c3100347680a9e02e618b6f6c1c625e34fdf3115
[oota-llvm.git] / lib / Transforms / LevelRaise.cpp
1 //===- LevelRaise.cpp - Code to change LLVM to higher level -----------------=//
2 //
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
5 // analyze.
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "llvm/Transforms/LevelChange.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/Transforms/Utils/BasicBlockUtils.h"
18 #include "Support/STLExtras.h"
19 #include "Support/StatisticReporter.h"
20 #include <algorithm>
21
22 static Statistic<> NumLoadStorePeepholes("raise\t\t- Number of load/store peepholes");
23 static Statistic<> NumGEPInstFormed("raise\t\t- Number of other getelementptr's formed");
24 static Statistic<> NumExprTreesConv("raise\t\t- Number of expression trees converted");
25 static Statistic<> NumCastOfCast("raise\t\t- Number of cast-of-self removed");
26 static Statistic<> NumDCEorCP("raise\t\t- Number of insts DCE'd or constprop'd");
27
28
29 #define PRINT_PEEPHOLE(ID, NUM, I)            \
30   DEBUG(std::cerr << "Inst P/H " << ID << "[" << NUM << "] " << I)
31
32 #define PRINT_PEEPHOLE1(ID, I1) do { PRINT_PEEPHOLE(ID, 0, I1); } while (0)
33 #define PRINT_PEEPHOLE2(ID, I1, I2) \
34   do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); } while (0)
35 #define PRINT_PEEPHOLE3(ID, I1, I2, I3) \
36   do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
37        PRINT_PEEPHOLE(ID, 2, I3); } while (0)
38 #define PRINT_PEEPHOLE4(ID, I1, I2, I3, I4) \
39   do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
40        PRINT_PEEPHOLE(ID, 2, I3); PRINT_PEEPHOLE(ID, 3, I4); } while (0)
41
42
43 // isReinterpretingCast - Return true if the cast instruction specified will
44 // cause the operand to be "reinterpreted".  A value is reinterpreted if the
45 // cast instruction would cause the underlying bits to change.
46 //
47 static inline bool isReinterpretingCast(const CastInst *CI) {
48   return!CI->getOperand(0)->getType()->isLosslesslyConvertableTo(CI->getType());
49 }
50
51
52 // Peephole optimize the following instructions:
53 // %t1 = cast ? to x *
54 // %t2 = add x * %SP, %t1              ;; Constant must be 2nd operand
55 //
56 // Into: %t3 = getelementptr {<...>} * %SP, <element indices>
57 //       %t2 = cast <eltype> * %t3 to {<...>}*
58 //
59 static bool HandleCastToPointer(BasicBlock::iterator BI,
60                                 const PointerType *DestPTy) {
61   CastInst &CI = cast<CastInst>(*BI);
62   if (CI.use_empty()) return false;
63
64   // Scan all of the uses, looking for any uses that are not add
65   // instructions.  If we have non-adds, do not make this transformation.
66   //
67   for (Value::use_iterator I = CI.use_begin(), E = CI.use_end();
68        I != E; ++I) {
69     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(*I)) {
70       if (BO->getOpcode() != Instruction::Add)
71         return false;
72     } else {
73       return false;
74     }
75   }
76
77   std::vector<Value*> Indices;
78   Value *Src = CI.getOperand(0);
79   const Type *Result = ConvertableToGEP(DestPTy, Src, Indices, &BI);
80   if (Result == 0) return false;  // Not convertable...
81
82   PRINT_PEEPHOLE2("cast-add-to-gep:in", Src, CI);
83
84   // If we have a getelementptr capability... transform all of the 
85   // add instruction uses into getelementptr's.
86   while (!CI.use_empty()) {
87     BinaryOperator *I = cast<BinaryOperator>(*CI.use_begin());
88     assert(I->getOpcode() == Instruction::Add && I->getNumOperands() == 2 &&
89            "Use is not a valid add instruction!");
90     
91     // Get the value added to the cast result pointer...
92     Value *OtherPtr = I->getOperand((I->getOperand(0) == &CI) ? 1 : 0);
93
94     Instruction *GEP = new GetElementPtrInst(OtherPtr, Indices, I->getName());
95     PRINT_PEEPHOLE1("cast-add-to-gep:i", I);
96
97     if (GEP->getType() == I->getType()) {
98       // Replace the old add instruction with the shiny new GEP inst
99       ReplaceInstWithInst(I, GEP);
100     } else {
101       // If the type produced by the gep instruction differs from the original
102       // add instruction type, insert a cast now.
103       //
104
105       // Insert the GEP instruction before the old add instruction...
106       I->getParent()->getInstList().insert(I, GEP);
107
108       PRINT_PEEPHOLE1("cast-add-to-gep:o", GEP);
109       GEP = new CastInst(GEP, I->getType());
110
111       // Replace the old add instruction with the shiny new GEP inst
112       ReplaceInstWithInst(I, GEP);
113     }
114
115     PRINT_PEEPHOLE1("cast-add-to-gep:o", GEP);
116   }
117   return true;
118 }
119
120 // Peephole optimize the following instructions:
121 // %t1 = cast ulong <const int> to {<...>} *
122 // %t2 = add {<...>} * %SP, %t1              ;; Constant must be 2nd operand
123 //
124 //    or
125 // %t1 = cast {<...>}* %SP to int*
126 // %t5 = cast ulong <const int> to int*
127 // %t2 = add int* %t1, %t5                   ;; int is same size as field
128 //
129 // Into: %t3 = getelementptr {<...>} * %SP, <element indices>
130 //       %t2 = cast <eltype> * %t3 to {<...>}*
131 //
132 static bool PeepholeOptimizeAddCast(BasicBlock *BB, BasicBlock::iterator &BI,
133                                     Value *AddOp1, CastInst *AddOp2) {
134   const CompositeType *CompTy;
135   Value *OffsetVal = AddOp2->getOperand(0);
136   Value *SrcPtr;  // Of type pointer to struct...
137
138   if ((CompTy = getPointedToComposite(AddOp1->getType()))) {
139     SrcPtr = AddOp1;                      // Handle the first case...
140   } else if (CastInst *AddOp1c = dyn_cast<CastInst>(AddOp1)) {
141     SrcPtr = AddOp1c->getOperand(0);      // Handle the second case...
142     CompTy = getPointedToComposite(SrcPtr->getType());
143   }
144
145   // Only proceed if we have detected all of our conditions successfully...
146   if (!CompTy || !SrcPtr || !OffsetVal->getType()->isIntegral())
147     return false;
148
149   std::vector<Value*> Indices;
150   if (!ConvertableToGEP(SrcPtr->getType(), OffsetVal, Indices, &BI))
151     return false;  // Not convertable... perhaps next time
152
153   if (getPointedToComposite(AddOp1->getType())) {  // case 1
154     PRINT_PEEPHOLE2("add-to-gep1:in", AddOp2, *BI);
155   } else {
156     PRINT_PEEPHOLE3("add-to-gep2:in", AddOp1, AddOp2, *BI);
157   }
158
159   GetElementPtrInst *GEP = new GetElementPtrInst(SrcPtr, Indices,
160                                                  AddOp2->getName());
161   BI = ++BB->getInstList().insert(BI, GEP);
162
163   Instruction *NCI = new CastInst(GEP, AddOp1->getType());
164   ReplaceInstWithInst(BB->getInstList(), BI, NCI);
165   PRINT_PEEPHOLE2("add-to-gep:out", GEP, NCI);
166   return true;
167 }
168
169 static bool PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI) {
170   Instruction *I = BI;
171
172   if (CastInst *CI = dyn_cast<CastInst>(I)) {
173     Value       *Src    = CI->getOperand(0);
174     Instruction *SrcI   = dyn_cast<Instruction>(Src); // Nonnull if instr source
175     const Type  *DestTy = CI->getType();
176
177     // Peephole optimize the following instruction:
178     // %V2 = cast <ty> %V to <ty>
179     //
180     // Into: <nothing>
181     //
182     if (DestTy == Src->getType()) {   // Check for a cast to same type as src!!
183       PRINT_PEEPHOLE1("cast-of-self-ty", CI);
184       CI->replaceAllUsesWith(Src);
185       if (!Src->hasName() && CI->hasName()) {
186         std::string Name = CI->getName();
187         CI->setName("");
188         Src->setName(Name, BB->getParent()->getSymbolTable());
189       }
190
191       // DCE the instruction now, to avoid having the iterative version of DCE
192       // have to worry about it.
193       //
194       BI = BB->getInstList().erase(BI);
195
196       ++NumCastOfCast;
197       return true;
198     }
199
200     // Check to see if it's a cast of an instruction that does not depend on the
201     // specific type of the operands to do it's job.
202     if (!isReinterpretingCast(CI)) {
203       ValueTypeCache ConvertedTypes;
204
205       // Check to see if we can convert the source of the cast to match the
206       // destination type of the cast...
207       //
208       ConvertedTypes[CI] = CI->getType();  // Make sure the cast doesn't change
209       if (ExpressionConvertableToType(Src, DestTy, ConvertedTypes)) {
210         PRINT_PEEPHOLE3("CAST-SRC-EXPR-CONV:in ", Src, CI, BB->getParent());
211           
212         DEBUG(cerr << "\nCONVERTING SRC EXPR TYPE:\n");
213         ValueMapCache ValueMap;
214         Value *E = ConvertExpressionToType(Src, DestTy, ValueMap);
215         if (Constant *CPV = dyn_cast<Constant>(E))
216           CI->replaceAllUsesWith(CPV);
217
218         BI = BB->begin();  // Rescan basic block.  BI might be invalidated.
219         PRINT_PEEPHOLE1("CAST-SRC-EXPR-CONV:out", E);
220         DEBUG(cerr << "DONE CONVERTING SRC EXPR TYPE: \n" << BB->getParent());
221         ++NumExprTreesConv;
222         return true;
223       }
224
225       // Check to see if we can convert the users of the cast value to match the
226       // source type of the cast...
227       //
228       ConvertedTypes.clear();
229       if (ValueConvertableToType(CI, Src->getType(), ConvertedTypes)) {
230         PRINT_PEEPHOLE3("CAST-DEST-EXPR-CONV:in ", Src, CI, BB->getParent());
231
232         DEBUG(cerr << "\nCONVERTING EXPR TYPE:\n");
233         ValueMapCache ValueMap;
234         ConvertValueToNewType(CI, Src, ValueMap);  // This will delete CI!
235
236         BI = BB->begin();  // Rescan basic block.  BI might be invalidated.
237         PRINT_PEEPHOLE1("CAST-DEST-EXPR-CONV:out", Src);
238         DEBUG(cerr << "DONE CONVERTING EXPR TYPE: \n\n" << BB->getParent());
239         ++NumExprTreesConv;
240         return true;
241       }
242     }
243
244     // Otherwise find out it this cast is a cast to a pointer type, which is
245     // then added to some other pointer, then loaded or stored through.  If
246     // so, convert the add into a getelementptr instruction...
247     //
248     if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
249       if (HandleCastToPointer(BI, DestPTy)) {
250         BI = BB->begin();  // Rescan basic block.  BI might be invalidated.
251         ++NumGEPInstFormed;
252         return true;
253       }
254     }
255
256     // Check to see if we are casting from a structure pointer to a pointer to
257     // the first element of the structure... to avoid munching other peepholes,
258     // we only let this happen if there are no add uses of the cast.
259     //
260     // Peephole optimize the following instructions:
261     // %t1 = cast {<...>} * %StructPtr to <ty> *
262     //
263     // Into: %t2 = getelementptr {<...>} * %StructPtr, <0, 0, 0, ...>
264     //       %t1 = cast <eltype> * %t1 to <ty> *
265     //
266     if (const CompositeType *CTy = getPointedToComposite(Src->getType()))
267       if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
268
269         // Loop over uses of the cast, checking for add instructions.  If an add
270         // exists, this is probably a part of a more complex GEP, so we don't
271         // want to mess around with the cast.
272         //
273         bool HasAddUse = false;
274         for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
275              I != E; ++I)
276           if (isa<Instruction>(*I) &&
277               cast<Instruction>(*I)->getOpcode() == Instruction::Add) {
278             HasAddUse = true; break;
279           }
280
281         // If it doesn't have an add use, check to see if the dest type is
282         // losslessly convertable to one of the types in the start of the struct
283         // type.
284         //
285         if (!HasAddUse) {
286           const Type *DestPointedTy = DestPTy->getElementType();
287           unsigned Depth = 1;
288           const CompositeType *CurCTy = CTy;
289           const Type *ElTy = 0;
290
291           // Build the index vector, full of all zeros
292           std::vector<Value*> Indices;
293           Indices.push_back(ConstantUInt::get(Type::UIntTy, 0));
294           while (CurCTy && !isa<PointerType>(CurCTy)) {
295             if (const StructType *CurSTy = dyn_cast<StructType>(CurCTy)) {
296               // Check for a zero element struct type... if we have one, bail.
297               if (CurSTy->getElementTypes().size() == 0) break;
298             
299               // Grab the first element of the struct type, which must lie at
300               // offset zero in the struct.
301               //
302               ElTy = CurSTy->getElementTypes()[0];
303             } else {
304               ElTy = cast<ArrayType>(CurCTy)->getElementType();
305             }
306
307             // Insert a zero to index through this type...
308             Indices.push_back(ConstantUInt::get(CurCTy->getIndexType(), 0));
309
310             // Did we find what we're looking for?
311             if (ElTy->isLosslesslyConvertableTo(DestPointedTy)) break;
312             
313             // Nope, go a level deeper.
314             ++Depth;
315             CurCTy = dyn_cast<CompositeType>(ElTy);
316             ElTy = 0;
317           }
318           
319           // Did we find what we were looking for? If so, do the transformation
320           if (ElTy) {
321             PRINT_PEEPHOLE1("cast-for-first:in", CI);
322
323             // Insert the new T cast instruction... stealing old T's name
324             GetElementPtrInst *GEP = new GetElementPtrInst(Src, Indices,
325                                                            CI->getName());
326             CI->setName("");
327             BI = ++BB->getInstList().insert(BI, GEP);
328
329             // Make the old cast instruction reference the new GEP instead of
330             // the old src value.
331             //
332             CI->setOperand(0, GEP);
333             
334             PRINT_PEEPHOLE2("cast-for-first:out", GEP, CI);
335             ++NumGEPInstFormed;
336             return true;
337           }
338         }
339       }
340
341   } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
342     Value *Val     = SI->getOperand(0);
343     Value *Pointer = SI->getPointerOperand();
344     
345     // Peephole optimize the following instructions:
346     // %t = cast <T1>* %P to <T2> * ;; If T1 is losslessly convertable to T2
347     // store <T2> %V, <T2>* %t
348     //
349     // Into: 
350     // %t = cast <T2> %V to <T1>
351     // store <T1> %t2, <T1>* %P
352     //
353     // Note: This is not taken care of by expr conversion because there might
354     // not be a cast available for the store to convert the incoming value of.
355     // This code is basically here to make sure that pointers don't have casts
356     // if possible.
357     //
358     if (CastInst *CI = dyn_cast<CastInst>(Pointer))
359       if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
360         if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
361           // convertable types?
362           if (Val->getType()->isLosslesslyConvertableTo(CSPT->getElementType()) &&
363               !SI->hasIndices()) {      // No subscripts yet!
364             PRINT_PEEPHOLE3("st-src-cast:in ", Pointer, Val, SI);
365
366             // Insert the new T cast instruction... stealing old T's name
367             CastInst *NCI = new CastInst(Val, CSPT->getElementType(),
368                                          CI->getName());
369             CI->setName("");
370             BI = ++BB->getInstList().insert(BI, NCI);
371
372             // Replace the old store with a new one!
373             ReplaceInstWithInst(BB->getInstList(), BI,
374                                 SI = new StoreInst(NCI, CastSrc));
375             PRINT_PEEPHOLE3("st-src-cast:out", NCI, CastSrc, SI);
376             ++NumLoadStorePeepholes;
377             return true;
378           }
379
380   } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
381     Value *Pointer = LI->getOperand(0);
382     const Type *PtrElType =
383       cast<PointerType>(Pointer->getType())->getElementType();
384     
385     // Peephole optimize the following instructions:
386     // %Val = cast <T1>* to <T2>*    ;; If T1 is losslessly convertable to T2
387     // %t = load <T2>* %P
388     //
389     // Into: 
390     // %t = load <T1>* %P
391     // %Val = cast <T1> to <T2>
392     //
393     // Note: This is not taken care of by expr conversion because there might
394     // not be a cast available for the store to convert the incoming value of.
395     // This code is basically here to make sure that pointers don't have casts
396     // if possible.
397     //
398     if (CastInst *CI = dyn_cast<CastInst>(Pointer))
399       if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
400         if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
401           // convertable types?
402           if (PtrElType->isLosslesslyConvertableTo(CSPT->getElementType()) &&
403               !LI->hasIndices()) {      // No subscripts yet!
404             PRINT_PEEPHOLE2("load-src-cast:in ", Pointer, LI);
405
406             // Create the new load instruction... loading the pre-casted value
407             LoadInst *NewLI = new LoadInst(CastSrc, LI->getName());
408             
409             // Insert the new T cast instruction... stealing old T's name
410             CastInst *NCI = new CastInst(NewLI, LI->getType(), CI->getName());
411             BI = ++BB->getInstList().insert(BI, NewLI);
412
413             // Replace the old store with a new one!
414             ReplaceInstWithInst(BB->getInstList(), BI, NCI);
415             PRINT_PEEPHOLE3("load-src-cast:out", NCI, CastSrc, NewLI);
416             ++NumLoadStorePeepholes;
417             return true;
418           }
419
420   } else if (I->getOpcode() == Instruction::Add &&
421              isa<CastInst>(I->getOperand(1))) {
422
423     if (PeepholeOptimizeAddCast(BB, BI, I->getOperand(0),
424                                 cast<CastInst>(I->getOperand(1)))) {
425       ++NumGEPInstFormed;
426       return true;
427     }
428   }
429
430   return false;
431 }
432
433
434
435
436 static bool DoRaisePass(Function &F) {
437   bool Changed = false;
438   for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
439     for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
440       DEBUG(cerr << "Processing: " << *BI);
441       if (dceInstruction(BI) || doConstantPropogation(BI)) {
442         Changed = true; 
443         ++NumDCEorCP;
444         DEBUG(cerr << "***\t\t^^-- DeadCode Elinated!\n");
445       } else if (PeepholeOptimize(BB, BI)) {
446         Changed = true;
447       } else {
448         ++BI;
449       }
450     }
451
452   return Changed;
453 }
454
455
456 // RaisePointerReferences::doit - Raise a function representation to a higher
457 // level.
458 //
459 static bool doRPR(Function &F) {
460   DEBUG(cerr << "\n\n\nStarting to work on Function '" << F.getName() << "'\n");
461
462   // Insert casts for all incoming pointer pointer values that are treated as
463   // arrays...
464   //
465   bool Changed = false, LocalChange;
466   
467   do {
468     DEBUG(cerr << "Looping: \n" << F);
469
470     // Iterate over the function, refining it, until it converges on a stable
471     // state
472     LocalChange = false;
473     while (DoRaisePass(F)) LocalChange = true;
474     Changed |= LocalChange;
475
476   } while (LocalChange);
477
478   return Changed;
479 }
480
481 namespace {
482   struct RaisePointerReferences : public FunctionPass {
483     const char *getPassName() const { return "Raise Pointer References"; }
484
485     virtual bool runOnFunction(Function &F) { return doRPR(F); }
486
487     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
488       AU.preservesCFG();
489     }
490   };
491 }
492
493 Pass *createRaisePointerReferencesPass() {
494   return new RaisePointerReferences();
495 }
496
497