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