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