* Add support for different "PassType's"
[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/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"
22 #include <algorithm>
23 using std::cerr;
24
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
27 // debugging!
28 //
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"));
32
33 static Statistic<>
34 NumLoadStorePeepholes("raise\t\t- Number of load/store peepholes");
35
36 static Statistic<> 
37 NumGEPInstFormed("raise\t\t- Number of other getelementptr's formed");
38
39 static Statistic<>
40 NumExprTreesConv("raise\t\t- Number of expression trees converted");
41
42 static Statistic<>
43 NumCastOfCast("raise\t\t- Number of cast-of-self removed");
44
45 static Statistic<>
46 NumDCEorCP("raise\t\t- Number of insts DCEd or constprop'd");
47
48
49 #define PRINT_PEEPHOLE(ID, NUM, I)            \
50   DEBUG(std::cerr << "Inst P/H " << ID << "[" << NUM << "] " << I)
51
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)
61
62
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.
66 //
67 static inline bool isReinterpretingCast(const CastInst *CI) {
68   return!CI->getOperand(0)->getType()->isLosslesslyConvertableTo(CI->getType());
69 }
70
71
72 // Peephole optimize the following instructions:
73 // %t1 = cast ? to x *
74 // %t2 = add x * %SP, %t1              ;; Constant must be 2nd operand
75 //
76 // Into: %t3 = getelementptr {<...>} * %SP, <element indices>
77 //       %t2 = cast <eltype> * %t3 to {<...>}*
78 //
79 static bool HandleCastToPointer(BasicBlock::iterator BI,
80                                 const PointerType *DestPTy) {
81   CastInst &CI = cast<CastInst>(*BI);
82   if (CI.use_empty()) return false;
83
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.
86   //
87   for (Value::use_iterator I = CI.use_begin(), E = CI.use_end();
88        I != E; ++I) {
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))
93         return false;
94     } else {
95       return false;
96     }
97   }
98
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...
103
104   PRINT_PEEPHOLE2("cast-add-to-gep:in", Src, CI);
105
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!");
112     
113     // Get the value added to the cast result pointer...
114     Value *OtherPtr = I->getOperand((I->getOperand(0) == &CI) ? 1 : 0);
115
116     Instruction *GEP = new GetElementPtrInst(OtherPtr, Indices, I->getName());
117     PRINT_PEEPHOLE1("cast-add-to-gep:i", I);
118
119     if (GEP->getType() == I->getType()) {
120       // Replace the old add instruction with the shiny new GEP inst
121       ReplaceInstWithInst(I, GEP);
122     } else {
123       // If the type produced by the gep instruction differs from the original
124       // add instruction type, insert a cast now.
125       //
126
127       // Insert the GEP instruction before the old add instruction...
128       I->getParent()->getInstList().insert(I, GEP);
129
130       PRINT_PEEPHOLE1("cast-add-to-gep:o", GEP);
131       GEP = new CastInst(GEP, I->getType());
132
133       // Replace the old add instruction with the shiny new GEP inst
134       ReplaceInstWithInst(I, GEP);
135     }
136
137     PRINT_PEEPHOLE1("cast-add-to-gep:o", GEP);
138   }
139   return true;
140 }
141
142 // Peephole optimize the following instructions:
143 // %t1 = cast ulong <const int> to {<...>} *
144 // %t2 = add {<...>} * %SP, %t1              ;; Constant must be 2nd operand
145 //
146 //    or
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
150 //
151 // Into: %t3 = getelementptr {<...>} * %SP, <element indices>
152 //       %t2 = cast <eltype> * %t3 to {<...>}*
153 //
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...
159
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());
165   }
166
167   // Only proceed if we have detected all of our conditions successfully...
168   if (!CompTy || !SrcPtr || !OffsetVal->getType()->isIntegral())
169     return false;
170
171   std::vector<Value*> Indices;
172   if (!ConvertableToGEP(SrcPtr->getType(), OffsetVal, Indices, &BI))
173     return false;  // Not convertable... perhaps next time
174
175   if (getPointedToComposite(AddOp1->getType())) {  // case 1
176     PRINT_PEEPHOLE2("add-to-gep1:in", AddOp2, *BI);
177   } else {
178     PRINT_PEEPHOLE3("add-to-gep2:in", AddOp1, AddOp2, *BI);
179   }
180
181   GetElementPtrInst *GEP = new GetElementPtrInst(SrcPtr, Indices,
182                                                  AddOp2->getName());
183   BI = ++BB->getInstList().insert(BI, GEP);
184
185   Instruction *NCI = new CastInst(GEP, AddOp1->getType());
186   ReplaceInstWithInst(BB->getInstList(), BI, NCI);
187   PRINT_PEEPHOLE2("add-to-gep:out", GEP, NCI);
188   return true;
189 }
190
191 static bool PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI) {
192   Instruction *I = BI;
193
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();
198
199     // Peephole optimize the following instruction:
200     // %V2 = cast <ty> %V to <ty>
201     //
202     // Into: <nothing>
203     //
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();
209         CI->setName("");
210         Src->setName(Name, BB->getParent()->getSymbolTable());
211       }
212
213       // DCE the instruction now, to avoid having the iterative version of DCE
214       // have to worry about it.
215       //
216       BI = BB->getInstList().erase(BI);
217
218       ++NumCastOfCast;
219       return true;
220     }
221
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;
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[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());
233           
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);
238
239           if (Constant *CPV = dyn_cast<Constant>(E))
240             CI->replaceAllUsesWith(CPV);
241           
242           PRINT_PEEPHOLE1("CAST-SRC-EXPR-CONV:out", E);
243           DEBUG(cerr << "DONE CONVERTING SRC EXPR TYPE: \n" << BB->getParent());
244         }
245
246         DEBUG(assert(verifyFunction(*BB->getParent()) == false &&
247                      "Function broken!"));
248         BI = BB->begin();  // Rescan basic block.  BI might be invalidated.
249         ++NumExprTreesConv;
250         return true;
251       }
252
253       // Check to see if we can convert the users of the cast value to match the
254       // source type of the cast...
255       //
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());
260
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!
265         }
266
267         PRINT_PEEPHOLE1("CAST-DEST-EXPR-CONV:out", Src);
268         DEBUG(cerr << "DONE CONVERTING EXPR TYPE: \n\n" << BB->getParent());
269
270         DEBUG(assert(verifyFunction(*BB->getParent()) == false &&
271                      "Function broken!"));
272         BI = BB->begin();  // Rescan basic block.  BI might be invalidated.
273         ++NumExprTreesConv;
274         return true;
275       }
276     }
277
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...
281     //
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.
285         ++NumGEPInstFormed;
286         return true;
287       }
288     }
289
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.
293     //
294     // Peephole optimize the following instructions:
295     // %t1 = cast {<...>} * %StructPtr to <ty> *
296     //
297     // Into: %t2 = getelementptr {<...>} * %StructPtr, <0, 0, 0, ...>
298     //       %t1 = cast <eltype> * %t1 to <ty> *
299     //
300     if (const CompositeType *CTy = getPointedToComposite(Src->getType()))
301       if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
302
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.
306         //
307         bool HasAddUse = false;
308         for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
309              I != E; ++I)
310           if (isa<Instruction>(*I) &&
311               cast<Instruction>(*I)->getOpcode() == Instruction::Add) {
312             HasAddUse = true; break;
313           }
314
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
317         // type.
318         //
319         if (!HasAddUse) {
320           const Type *DestPointedTy = DestPTy->getElementType();
321           unsigned Depth = 1;
322           const CompositeType *CurCTy = CTy;
323           const Type *ElTy = 0;
324
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;
332             
333               // Grab the first element of the struct type, which must lie at
334               // offset zero in the struct.
335               //
336               ElTy = CurSTy->getElementTypes()[0];
337             } else {
338               ElTy = cast<ArrayType>(CurCTy)->getElementType();
339             }
340
341             // Insert a zero to index through this type...
342             Indices.push_back(ConstantUInt::get(CurCTy->getIndexType(), 0));
343
344             // Did we find what we're looking for?
345             if (ElTy->isLosslesslyConvertableTo(DestPointedTy)) break;
346             
347             // Nope, go a level deeper.
348             ++Depth;
349             CurCTy = dyn_cast<CompositeType>(ElTy);
350             ElTy = 0;
351           }
352           
353           // Did we find what we were looking for? If so, do the transformation
354           if (ElTy) {
355             PRINT_PEEPHOLE1("cast-for-first:in", CI);
356
357             // Insert the new T cast instruction... stealing old T's name
358             GetElementPtrInst *GEP = new GetElementPtrInst(Src, Indices,
359                                                            CI->getName());
360             CI->setName("");
361             BI = ++BB->getInstList().insert(BI, GEP);
362
363             // Make the old cast instruction reference the new GEP instead of
364             // the old src value.
365             //
366             CI->setOperand(0, GEP);
367             
368             PRINT_PEEPHOLE2("cast-for-first:out", GEP, CI);
369             ++NumGEPInstFormed;
370             return true;
371           }
372         }
373       }
374
375   } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
376     Value *Val     = SI->getOperand(0);
377     Value *Pointer = SI->getPointerOperand();
378     
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
382     //
383     // Into: 
384     // %t = cast <T2> %V to <T1>
385     // store <T1> %t2, <T1>* %P
386     //
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
390     // if possible.
391     //
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);
399
400             // Insert the new T cast instruction... stealing old T's name
401             CastInst *NCI = new CastInst(Val, CSPT->getElementType(),
402                                          CI->getName());
403             CI->setName("");
404             BI = ++BB->getInstList().insert(BI, NCI);
405
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;
411             return true;
412           }
413
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();
418     
419     // Peephole optimize the following instructions:
420     // %Val = cast <T1>* to <T2>*    ;; If T1 is losslessly convertable to T2
421     // %t = load <T2>* %P
422     //
423     // Into: 
424     // %t = load <T1>* %P
425     // %Val = cast <T1> to <T2>
426     //
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
430     // if possible.
431     //
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);
439
440             // Create the new load instruction... loading the pre-casted value
441             LoadInst *NewLI = new LoadInst(CastSrc, LI->getName());
442             
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);
446
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;
451             return true;
452           }
453
454   } else if (I->getOpcode() == Instruction::Add &&
455              isa<CastInst>(I->getOperand(1))) {
456
457     if (PeepholeOptimizeAddCast(BB, BI, I->getOperand(0),
458                                 cast<CastInst>(I->getOperand(1)))) {
459       ++NumGEPInstFormed;
460       return true;
461     }
462   }
463
464   return false;
465 }
466
467
468
469
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)) {
476         Changed = true; 
477         ++NumDCEorCP;
478         DEBUG(cerr << "***\t\t^^-- DeadCode Elinated!\n");
479       } else if (PeepholeOptimize(BB, BI)) {
480         Changed = true;
481       } else {
482         ++BI;
483       }
484     }
485
486   return Changed;
487 }
488
489
490 // RaisePointerReferences::doit - Raise a function representation to a higher
491 // level.
492 //
493 static bool doRPR(Function &F) {
494   DEBUG(cerr << "\n\n\nStarting to work on Function '" << F.getName() << "'\n");
495
496   // Insert casts for all incoming pointer pointer values that are treated as
497   // arrays...
498   //
499   bool Changed = false, LocalChange;
500   
501
502   // If the StartInst option was specified, then Peephole optimize that
503   // instruction first if it occurs in this function.
504   //
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
513         }
514   }
515
516   do {
517     DEBUG(cerr << "Looping: \n" << F);
518
519     // Iterate over the function, refining it, until it converges on a stable
520     // state
521     LocalChange = false;
522     while (DoRaisePass(F)) LocalChange = true;
523     Changed |= LocalChange;
524
525   } while (LocalChange);
526
527   return Changed;
528 }
529
530 namespace {
531   struct RaisePointerReferences : public FunctionPass {
532
533     // FIXME: constructor should save and use target data here!!
534     RaisePointerReferences(const TargetData &TD) {}
535
536     virtual bool runOnFunction(Function &F) { return doRPR(F); }
537
538     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
539       AU.preservesCFG();
540     }
541   };
542 }
543
544 Pass *createRaisePointerReferencesPass(const TargetData &TD) {
545   return new RaisePointerReferences(TD);
546 }
547
548 static RegisterOpt<RaisePointerReferences>
549 X("raise", "Raise Pointer References", createRaisePointerReferencesPass);