1 //===- LevelRaise.cpp - Code to change LLVM to higher level -----------------=//
3 // This file implements the 'raising' part of the LevelChange API. This is
4 // useful because, in general, it makes the LLVM code terser and easier to
7 //===----------------------------------------------------------------------===//
9 #include "llvm/Transforms/RaisePointerReferences.h"
10 #include "llvm/Transforms/Utils/Local.h"
11 #include "TransformInternals.h"
12 #include "llvm/iOther.h"
13 #include "llvm/iMemory.h"
14 #include "llvm/Pass.h"
15 #include "llvm/ConstantHandling.h"
16 #include "llvm/Analysis/Expressions.h"
17 #include "llvm/Analysis/Verifier.h"
18 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
19 #include "Support/STLExtras.h"
20 #include "Support/StatisticReporter.h"
21 #include "Support/CommandLine.h"
25 // StartInst - This enables the -raise-start-inst=foo option to cause the level
26 // raising pass to start at instruction "foo", which is immensely useful for
29 static cl::opt<std::string>
30 StartInst("raise-start-inst", cl::Hidden, cl::value_desc("inst name"),
31 cl::desc("Start raise pass at the instruction with the specified name"));
34 NumLoadStorePeepholes("raise\t\t- Number of load/store peepholes");
37 NumGEPInstFormed("raise\t\t- Number of other getelementptr's formed");
40 NumExprTreesConv("raise\t\t- Number of expression trees converted");
43 NumCastOfCast("raise\t\t- Number of cast-of-self removed");
46 NumDCEorCP("raise\t\t- Number of insts DCEd or constprop'd");
49 #define PRINT_PEEPHOLE(ID, NUM, I) \
50 DEBUG(std::cerr << "Inst P/H " << ID << "[" << NUM << "] " << I)
52 #define PRINT_PEEPHOLE1(ID, I1) do { PRINT_PEEPHOLE(ID, 0, I1); } while (0)
53 #define PRINT_PEEPHOLE2(ID, I1, I2) \
54 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); } while (0)
55 #define PRINT_PEEPHOLE3(ID, I1, I2, I3) \
56 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
57 PRINT_PEEPHOLE(ID, 2, I3); } while (0)
58 #define PRINT_PEEPHOLE4(ID, I1, I2, I3, I4) \
59 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
60 PRINT_PEEPHOLE(ID, 2, I3); PRINT_PEEPHOLE(ID, 3, I4); } while (0)
63 // isReinterpretingCast - Return true if the cast instruction specified will
64 // cause the operand to be "reinterpreted". A value is reinterpreted if the
65 // cast instruction would cause the underlying bits to change.
67 static inline bool isReinterpretingCast(const CastInst *CI) {
68 return!CI->getOperand(0)->getType()->isLosslesslyConvertableTo(CI->getType());
72 // Peephole optimize the following instructions:
73 // %t1 = cast ? to x *
74 // %t2 = add x * %SP, %t1 ;; Constant must be 2nd operand
76 // Into: %t3 = getelementptr {<...>} * %SP, <element indices>
77 // %t2 = cast <eltype> * %t3 to {<...>}*
79 static bool HandleCastToPointer(BasicBlock::iterator BI,
80 const PointerType *DestPTy) {
81 CastInst &CI = cast<CastInst>(*BI);
82 if (CI.use_empty()) return false;
84 // Scan all of the uses, looking for any uses that are not add
85 // instructions. If we have non-adds, do not make this transformation.
87 for (Value::use_iterator I = CI.use_begin(), E = CI.use_end();
89 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(*I)) {
90 if (BO->getOpcode() != Instruction::Add ||
91 // Avoid add sbyte* %X, %X cases...
92 BO->getOperand(0) == BO->getOperand(1))
99 std::vector<Value*> Indices;
100 Value *Src = CI.getOperand(0);
101 const Type *Result = ConvertableToGEP(DestPTy, Src, Indices, &BI);
102 if (Result == 0) return false; // Not convertable...
104 PRINT_PEEPHOLE2("cast-add-to-gep:in", Src, CI);
106 // If we have a getelementptr capability... transform all of the
107 // add instruction uses into getelementptr's.
108 while (!CI.use_empty()) {
109 BinaryOperator *I = cast<BinaryOperator>(*CI.use_begin());
110 assert(I->getOpcode() == Instruction::Add && I->getNumOperands() == 2 &&
111 "Use is not a valid add instruction!");
113 // Get the value added to the cast result pointer...
114 Value *OtherPtr = I->getOperand((I->getOperand(0) == &CI) ? 1 : 0);
116 Instruction *GEP = new GetElementPtrInst(OtherPtr, Indices, I->getName());
117 PRINT_PEEPHOLE1("cast-add-to-gep:i", I);
119 if (GEP->getType() == I->getType()) {
120 // Replace the old add instruction with the shiny new GEP inst
121 ReplaceInstWithInst(I, GEP);
123 // If the type produced by the gep instruction differs from the original
124 // add instruction type, insert a cast now.
127 // Insert the GEP instruction before the old add instruction...
128 I->getParent()->getInstList().insert(I, GEP);
130 PRINT_PEEPHOLE1("cast-add-to-gep:o", GEP);
131 GEP = new CastInst(GEP, I->getType());
133 // Replace the old add instruction with the shiny new GEP inst
134 ReplaceInstWithInst(I, GEP);
137 PRINT_PEEPHOLE1("cast-add-to-gep:o", GEP);
142 // Peephole optimize the following instructions:
143 // %t1 = cast ulong <const int> to {<...>} *
144 // %t2 = add {<...>} * %SP, %t1 ;; Constant must be 2nd operand
147 // %t1 = cast {<...>}* %SP to int*
148 // %t5 = cast ulong <const int> to int*
149 // %t2 = add int* %t1, %t5 ;; int is same size as field
151 // Into: %t3 = getelementptr {<...>} * %SP, <element indices>
152 // %t2 = cast <eltype> * %t3 to {<...>}*
154 static bool PeepholeOptimizeAddCast(BasicBlock *BB, BasicBlock::iterator &BI,
155 Value *AddOp1, CastInst *AddOp2) {
156 const CompositeType *CompTy;
157 Value *OffsetVal = AddOp2->getOperand(0);
158 Value *SrcPtr; // Of type pointer to struct...
160 if ((CompTy = getPointedToComposite(AddOp1->getType()))) {
161 SrcPtr = AddOp1; // Handle the first case...
162 } else if (CastInst *AddOp1c = dyn_cast<CastInst>(AddOp1)) {
163 SrcPtr = AddOp1c->getOperand(0); // Handle the second case...
164 CompTy = getPointedToComposite(SrcPtr->getType());
167 // Only proceed if we have detected all of our conditions successfully...
168 if (!CompTy || !SrcPtr || !OffsetVal->getType()->isIntegral())
171 std::vector<Value*> Indices;
172 if (!ConvertableToGEP(SrcPtr->getType(), OffsetVal, Indices, &BI))
173 return false; // Not convertable... perhaps next time
175 if (getPointedToComposite(AddOp1->getType())) { // case 1
176 PRINT_PEEPHOLE2("add-to-gep1:in", AddOp2, *BI);
178 PRINT_PEEPHOLE3("add-to-gep2:in", AddOp1, AddOp2, *BI);
181 GetElementPtrInst *GEP = new GetElementPtrInst(SrcPtr, Indices,
183 BI = ++BB->getInstList().insert(BI, GEP);
185 Instruction *NCI = new CastInst(GEP, AddOp1->getType());
186 ReplaceInstWithInst(BB->getInstList(), BI, NCI);
187 PRINT_PEEPHOLE2("add-to-gep:out", GEP, NCI);
191 static bool PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI) {
194 if (CastInst *CI = dyn_cast<CastInst>(I)) {
195 Value *Src = CI->getOperand(0);
196 Instruction *SrcI = dyn_cast<Instruction>(Src); // Nonnull if instr source
197 const Type *DestTy = CI->getType();
199 // Peephole optimize the following instruction:
200 // %V2 = cast <ty> %V to <ty>
204 if (DestTy == Src->getType()) { // Check for a cast to same type as src!!
205 PRINT_PEEPHOLE1("cast-of-self-ty", CI);
206 CI->replaceAllUsesWith(Src);
207 if (!Src->hasName() && CI->hasName()) {
208 std::string Name = CI->getName();
210 Src->setName(Name, BB->getParent()->getSymbolTable());
213 // DCE the instruction now, to avoid having the iterative version of DCE
214 // have to worry about it.
216 BI = BB->getInstList().erase(BI);
222 // Check to see if it's a cast of an instruction that does not depend on the
223 // specific type of the operands to do it's job.
224 if (!isReinterpretingCast(CI)) {
225 ValueTypeCache ConvertedTypes;
227 // Check to see if we can convert the source of the cast to match the
228 // destination type of the cast...
230 ConvertedTypes[CI] = CI->getType(); // Make sure the cast doesn't change
231 if (ExpressionConvertableToType(Src, DestTy, ConvertedTypes)) {
232 PRINT_PEEPHOLE3("CAST-SRC-EXPR-CONV:in ", Src, CI, BB->getParent());
234 DEBUG(cerr << "\nCONVERTING SRC EXPR TYPE:\n");
235 { // ValueMap must be destroyed before function verified!
236 ValueMapCache ValueMap;
237 Value *E = ConvertExpressionToType(Src, DestTy, ValueMap);
239 if (Constant *CPV = dyn_cast<Constant>(E))
240 CI->replaceAllUsesWith(CPV);
242 PRINT_PEEPHOLE1("CAST-SRC-EXPR-CONV:out", E);
243 DEBUG(cerr << "DONE CONVERTING SRC EXPR TYPE: \n" << BB->getParent());
246 DEBUG(assert(verifyFunction(*BB->getParent()) == false &&
247 "Function broken!"));
248 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
253 // Check to see if we can convert the users of the cast value to match the
254 // source type of the cast...
256 ConvertedTypes.clear();
257 ConvertedTypes[Src] = Src->getType(); // Make sure the source doesn't change type
258 if (ValueConvertableToType(CI, Src->getType(), ConvertedTypes)) {
259 PRINT_PEEPHOLE3("CAST-DEST-EXPR-CONV:in ", Src, CI, BB->getParent());
261 DEBUG(cerr << "\nCONVERTING EXPR TYPE:\n");
262 { // ValueMap must be destroyed before function verified!
263 ValueMapCache ValueMap;
264 ConvertValueToNewType(CI, Src, ValueMap); // This will delete CI!
267 PRINT_PEEPHOLE1("CAST-DEST-EXPR-CONV:out", Src);
268 DEBUG(cerr << "DONE CONVERTING EXPR TYPE: \n\n" << BB->getParent());
270 DEBUG(assert(verifyFunction(*BB->getParent()) == false &&
271 "Function broken!"));
272 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
278 // Otherwise find out it this cast is a cast to a pointer type, which is
279 // then added to some other pointer, then loaded or stored through. If
280 // so, convert the add into a getelementptr instruction...
282 if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
283 if (HandleCastToPointer(BI, DestPTy)) {
284 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
290 // Check to see if we are casting from a structure pointer to a pointer to
291 // the first element of the structure... to avoid munching other peepholes,
292 // we only let this happen if there are no add uses of the cast.
294 // Peephole optimize the following instructions:
295 // %t1 = cast {<...>} * %StructPtr to <ty> *
297 // Into: %t2 = getelementptr {<...>} * %StructPtr, <0, 0, 0, ...>
298 // %t1 = cast <eltype> * %t1 to <ty> *
300 if (const CompositeType *CTy = getPointedToComposite(Src->getType()))
301 if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
303 // Loop over uses of the cast, checking for add instructions. If an add
304 // exists, this is probably a part of a more complex GEP, so we don't
305 // want to mess around with the cast.
307 bool HasAddUse = false;
308 for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
310 if (isa<Instruction>(*I) &&
311 cast<Instruction>(*I)->getOpcode() == Instruction::Add) {
312 HasAddUse = true; break;
315 // If it doesn't have an add use, check to see if the dest type is
316 // losslessly convertable to one of the types in the start of the struct
320 const Type *DestPointedTy = DestPTy->getElementType();
322 const CompositeType *CurCTy = CTy;
323 const Type *ElTy = 0;
325 // Build the index vector, full of all zeros
326 std::vector<Value*> Indices;
327 Indices.push_back(ConstantUInt::get(Type::UIntTy, 0));
328 while (CurCTy && !isa<PointerType>(CurCTy)) {
329 if (const StructType *CurSTy = dyn_cast<StructType>(CurCTy)) {
330 // Check for a zero element struct type... if we have one, bail.
331 if (CurSTy->getElementTypes().size() == 0) break;
333 // Grab the first element of the struct type, which must lie at
334 // offset zero in the struct.
336 ElTy = CurSTy->getElementTypes()[0];
338 ElTy = cast<ArrayType>(CurCTy)->getElementType();
341 // Insert a zero to index through this type...
342 Indices.push_back(ConstantUInt::get(CurCTy->getIndexType(), 0));
344 // Did we find what we're looking for?
345 if (ElTy->isLosslesslyConvertableTo(DestPointedTy)) break;
347 // Nope, go a level deeper.
349 CurCTy = dyn_cast<CompositeType>(ElTy);
353 // Did we find what we were looking for? If so, do the transformation
355 PRINT_PEEPHOLE1("cast-for-first:in", CI);
357 // Insert the new T cast instruction... stealing old T's name
358 GetElementPtrInst *GEP = new GetElementPtrInst(Src, Indices,
361 BI = ++BB->getInstList().insert(BI, GEP);
363 // Make the old cast instruction reference the new GEP instead of
364 // the old src value.
366 CI->setOperand(0, GEP);
368 PRINT_PEEPHOLE2("cast-for-first:out", GEP, CI);
375 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
376 Value *Val = SI->getOperand(0);
377 Value *Pointer = SI->getPointerOperand();
379 // Peephole optimize the following instructions:
380 // %t = cast <T1>* %P to <T2> * ;; If T1 is losslessly convertable to T2
381 // store <T2> %V, <T2>* %t
384 // %t = cast <T2> %V to <T1>
385 // store <T1> %t2, <T1>* %P
387 // Note: This is not taken care of by expr conversion because there might
388 // not be a cast available for the store to convert the incoming value of.
389 // This code is basically here to make sure that pointers don't have casts
392 if (CastInst *CI = dyn_cast<CastInst>(Pointer))
393 if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
394 if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
395 // convertable types?
396 if (Val->getType()->isLosslesslyConvertableTo(CSPT->getElementType()) &&
397 !SI->hasIndices()) { // No subscripts yet!
398 PRINT_PEEPHOLE3("st-src-cast:in ", Pointer, Val, SI);
400 // Insert the new T cast instruction... stealing old T's name
401 CastInst *NCI = new CastInst(Val, CSPT->getElementType(),
404 BI = ++BB->getInstList().insert(BI, NCI);
406 // Replace the old store with a new one!
407 ReplaceInstWithInst(BB->getInstList(), BI,
408 SI = new StoreInst(NCI, CastSrc));
409 PRINT_PEEPHOLE3("st-src-cast:out", NCI, CastSrc, SI);
410 ++NumLoadStorePeepholes;
414 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
415 Value *Pointer = LI->getOperand(0);
416 const Type *PtrElType =
417 cast<PointerType>(Pointer->getType())->getElementType();
419 // Peephole optimize the following instructions:
420 // %Val = cast <T1>* to <T2>* ;; If T1 is losslessly convertable to T2
421 // %t = load <T2>* %P
424 // %t = load <T1>* %P
425 // %Val = cast <T1> to <T2>
427 // Note: This is not taken care of by expr conversion because there might
428 // not be a cast available for the store to convert the incoming value of.
429 // This code is basically here to make sure that pointers don't have casts
432 if (CastInst *CI = dyn_cast<CastInst>(Pointer))
433 if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
434 if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
435 // convertable types?
436 if (PtrElType->isLosslesslyConvertableTo(CSPT->getElementType()) &&
437 !LI->hasIndices()) { // No subscripts yet!
438 PRINT_PEEPHOLE2("load-src-cast:in ", Pointer, LI);
440 // Create the new load instruction... loading the pre-casted value
441 LoadInst *NewLI = new LoadInst(CastSrc, LI->getName());
443 // Insert the new T cast instruction... stealing old T's name
444 CastInst *NCI = new CastInst(NewLI, LI->getType(), CI->getName());
445 BI = ++BB->getInstList().insert(BI, NewLI);
447 // Replace the old store with a new one!
448 ReplaceInstWithInst(BB->getInstList(), BI, NCI);
449 PRINT_PEEPHOLE3("load-src-cast:out", NCI, CastSrc, NewLI);
450 ++NumLoadStorePeepholes;
454 } else if (I->getOpcode() == Instruction::Add &&
455 isa<CastInst>(I->getOperand(1))) {
457 if (PeepholeOptimizeAddCast(BB, BI, I->getOperand(0),
458 cast<CastInst>(I->getOperand(1)))) {
470 static bool DoRaisePass(Function &F) {
471 bool Changed = false;
472 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
473 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
474 DEBUG(cerr << "Processing: " << *BI);
475 if (dceInstruction(BI) || doConstantPropogation(BI)) {
478 DEBUG(cerr << "***\t\t^^-- DeadCode Elinated!\n");
479 } else if (PeepholeOptimize(BB, BI)) {
490 // RaisePointerReferences::doit - Raise a function representation to a higher
493 static bool doRPR(Function &F) {
494 DEBUG(cerr << "\n\n\nStarting to work on Function '" << F.getName() << "'\n");
496 // Insert casts for all incoming pointer pointer values that are treated as
499 bool Changed = false, LocalChange;
502 // If the StartInst option was specified, then Peephole optimize that
503 // instruction first if it occurs in this function.
505 if (!StartInst.empty()) {
506 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
507 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI)
508 if (BI->getName() == StartInst) {
509 bool SavedDebug = DebugFlag; // Save the DEBUG() controlling flag.
510 DebugFlag = true; // Turn on DEBUG's
511 Changed |= PeepholeOptimize(BB, BI);
512 DebugFlag = SavedDebug; // Restore DebugFlag to previous state
517 DEBUG(cerr << "Looping: \n" << F);
519 // Iterate over the function, refining it, until it converges on a stable
522 while (DoRaisePass(F)) LocalChange = true;
523 Changed |= LocalChange;
525 } while (LocalChange);
531 struct RaisePointerReferences : public FunctionPass {
533 // FIXME: constructor should save and use target data here!!
534 RaisePointerReferences(const TargetData &TD) {}
536 virtual bool runOnFunction(Function &F) { return doRPR(F); }
538 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
544 Pass *createRaisePointerReferencesPass(const TargetData &TD) {
545 return new RaisePointerReferences(TD);
548 static RegisterPass<RaisePointerReferences>
549 X("raise", "Raise Pointer References", createRaisePointerReferencesPass);