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