4828f753e862cf7a8a9930b39caad497631b9bf0
[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/Support/STLExtras.h"
13 #include "llvm/iOther.h"
14 #include "llvm/iMemory.h"
15 #include "llvm/ConstPoolVals.h"
16 #include "llvm/Optimizations/ConstantHandling.h"
17 #include "llvm/Optimizations/DCE.h"
18 #include "llvm/Optimizations/ConstantProp.h"
19 #include "llvm/Analysis/Expressions.h"
20 #include <algorithm>
21
22 #include "llvm/Assembly/Writer.h"
23
24 #define DEBUG_PEEPHOLE_INSTS 1
25
26 #ifdef DEBUG_PEEPHOLE_INSTS
27 #define PRINT_PEEPHOLE(ID, NUM, I)            \
28   cerr << "Inst P/H " << ID << "[" << NUM << "] " << I;
29 #else
30 #define PRINT_PEEPHOLE(ID, NUM, I)
31 #endif
32
33 #define PRINT_PEEPHOLE1(ID, I1) do { PRINT_PEEPHOLE(ID, 0, I1); } while (0)
34 #define PRINT_PEEPHOLE2(ID, I1, I2) \
35   do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); } while (0)
36 #define PRINT_PEEPHOLE3(ID, I1, I2, I3) \
37   do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
38        PRINT_PEEPHOLE(ID, 2, I3); } while (0)
39 #define PRINT_PEEPHOLE4(ID, I1, I2, I3, I4) \
40   do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
41        PRINT_PEEPHOLE(ID, 2, I3); PRINT_PEEPHOLE(ID, 3, I4); } while (0)
42
43
44 // isReinterpretingCast - Return true if the cast instruction specified will
45 // cause the operand to be "reinterpreted".  A value is reinterpreted if the
46 // cast instruction would cause the underlying bits to change.
47 //
48 static inline bool isReinterpretingCast(const CastInst *CI) {
49   return!CI->getOperand(0)->getType()->isLosslesslyConvertableTo(CI->getType());
50 }
51
52
53
54
55
56 // Peephole optimize the following instructions:
57 // %t1 = cast ulong <const int> to {<...>} *
58 // %t2 = add {<...>} * %SP, %t1              ;; Constant must be 2nd operand
59 //
60 //    or
61 // %t1 = cast {<...>}* %SP to int*
62 // %t5 = cast ulong <const int> to int*
63 // %t2 = add int* %t1, %t5                   ;; int is same size as field
64 //
65 // Into: %t3 = getelementptr {<...>} * %SP, <element indices>
66 //       %t2 = cast <eltype> * %t3 to {<...>}*
67 //
68 static bool PeepholeOptimizeAddCast(BasicBlock *BB, BasicBlock::iterator &BI,
69                                     Value *AddOp1, CastInst *AddOp2) {
70   const CompositeType *CompTy;
71   Value *OffsetVal = AddOp2->getOperand(0);
72   Value *SrcPtr;  // Of type pointer to struct...
73
74   if ((CompTy = getPointedToComposite(AddOp1->getType()))) {
75     SrcPtr = AddOp1;                      // Handle the first case...
76   } else if (CastInst *AddOp1c = dyn_cast<CastInst>(AddOp1)) {
77     SrcPtr = AddOp1c->getOperand(0);      // Handle the second case...
78     CompTy = getPointedToComposite(SrcPtr->getType());
79   }
80
81   // Only proceed if we have detected all of our conditions successfully...
82   if (!CompTy || !SrcPtr || !OffsetVal->getType()->isIntegral())
83     return false;
84
85   vector<Value*> Indices;
86   if (!ConvertableToGEP(SrcPtr->getType(), OffsetVal, Indices, &BI))
87     return false;  // Not convertable... perhaps next time
88
89   if (getPointedToComposite(AddOp1->getType())) {  // case 1
90     PRINT_PEEPHOLE2("add-to-gep1:in", AddOp2, *BI);
91   } else {
92     PRINT_PEEPHOLE3("add-to-gep2:in", AddOp1, AddOp2, *BI);
93   }
94
95   GetElementPtrInst *GEP = new GetElementPtrInst(SrcPtr, Indices,
96                                                  AddOp2->getName());
97   BI = BB->getInstList().insert(BI, GEP)+1;
98
99   Instruction *NCI = new CastInst(GEP, AddOp1->getType());
100   ReplaceInstWithInst(BB->getInstList(), BI, NCI);
101   PRINT_PEEPHOLE2("add-to-gep:out", GEP, NCI);
102   return true;
103 }
104
105 static bool PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI) {
106   Instruction *I = *BI;
107
108   if (CastInst *CI = dyn_cast<CastInst>(I)) {
109     Value       *Src    = CI->getOperand(0);
110     Instruction *SrcI   = dyn_cast<Instruction>(Src); // Nonnull if instr source
111     const Type  *DestTy = CI->getType();
112
113     // Peephole optimize the following instruction:
114     // %V2 = cast <ty> %V to <ty>
115     //
116     // Into: <nothing>
117     //
118     if (DestTy == Src->getType()) {   // Check for a cast to same type as src!!
119       PRINT_PEEPHOLE1("cast-of-self-ty", CI);
120       CI->replaceAllUsesWith(Src);
121       if (!Src->hasName() && CI->hasName()) {
122         string Name = CI->getName();
123         CI->setName("");
124         Src->setName(Name, BB->getParent()->getSymbolTable());
125       }
126       return true;
127     }
128
129     // Peephole optimize the following instructions:
130     // %tmp = cast <ty> %V to <ty2>
131     // %V  = cast <ty2> %tmp to <ty3>     ; Where ty & ty2 are same size
132     //
133     // Into: cast <ty> %V to <ty3>
134     //
135     if (SrcI)
136       if (CastInst *CSrc = dyn_cast<CastInst>(SrcI))
137         if (isReinterpretingCast(CI) + isReinterpretingCast(CSrc) < 2) {
138           // We can only do c-c elimination if, at most, one cast does a
139           // reinterpretation of the input data.
140           //
141           // If legal, make this cast refer the the original casts argument!
142           //
143           PRINT_PEEPHOLE2("cast-cast:in ", CI, CSrc);
144           CI->setOperand(0, CSrc->getOperand(0));
145           PRINT_PEEPHOLE1("cast-cast:out", CI);
146           return true;
147         }
148
149     // Check to see if it's a cast of an instruction that does not depend on the
150     // specific type of the operands to do it's job.
151     if (!isReinterpretingCast(CI)) {
152       ValueTypeCache ConvertedTypes;
153       if (ValueConvertableToType(CI, Src->getType(), ConvertedTypes)) {
154         PRINT_PEEPHOLE2("CAST-DEST-EXPR-CONV:in ", Src, CI);
155
156 #ifdef DEBUG_PEEPHOLE_INSTS
157         cerr << "\nCONVERTING EXPR TYPE:\n";
158 #endif
159         ValueMapCache ValueMap;
160         ConvertValueToNewType(CI, Src, ValueMap);  // This will delete CI!
161
162         BI = BB->begin();  // Rescan basic block.  BI might be invalidated.
163         PRINT_PEEPHOLE1("CAST-DEST-EXPR-CONV:out", Src);
164 #ifdef DEBUG_PEEPHOLE_INSTS
165         cerr << "DONE CONVERTING EXPR TYPE: \n\n";// << BB->getParent();
166 #endif
167         return true;
168       } else {
169         ConvertedTypes.clear();
170         if (ExpressionConvertableToType(Src, DestTy, ConvertedTypes)) {
171           PRINT_PEEPHOLE2("CAST-SRC-EXPR-CONV:in ", Src, CI);
172           
173 #ifdef DEBUG_PEEPHOLE_INSTS
174           cerr << "\nCONVERTING SRC EXPR TYPE:\n";
175 #endif
176           ValueMapCache ValueMap;
177           Value *E = ConvertExpressionToType(Src, DestTy, ValueMap);
178           if (ConstPoolVal *CPV = dyn_cast<ConstPoolVal>(E))
179             CI->replaceAllUsesWith(CPV);
180
181           BI = BB->begin();  // Rescan basic block.  BI might be invalidated.
182           PRINT_PEEPHOLE1("CAST-SRC-EXPR-CONV:out", E);
183 #ifdef DEBUG_PEEPHOLE_INSTS
184           cerr << "DONE CONVERTING SRC EXPR TYPE: \n\n";// << BB->getParent();
185 #endif
186           return true;
187         }
188       }
189       
190     }
191
192     // Check to see if we are casting from a structure pointer to a pointer to
193     // the first element of the structure... to avoid munching other peepholes,
194     // we only let this happen if there are no add uses of the cast.
195     //
196     // Peephole optimize the following instructions:
197     // %t1 = cast {<...>} * %StructPtr to <ty> *
198     //
199     // Into: %t2 = getelementptr {<...>} * %StructPtr, <0, 0, 0, ...>
200     //       %t1 = cast <eltype> * %t1 to <ty> *
201     //
202 #if 1
203     if (const CompositeType *CTy = getPointedToComposite(Src->getType()))
204       if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
205
206         // Loop over uses of the cast, checking for add instructions.  If an add
207         // exists, this is probably a part of a more complex GEP, so we don't
208         // want to mess around with the cast.
209         //
210         bool HasAddUse = false;
211         for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
212              I != E; ++I)
213           if (isa<Instruction>(*I) &&
214               cast<Instruction>(*I)->getOpcode() == Instruction::Add) {
215             HasAddUse = true; break;
216           }
217
218         // If it doesn't have an add use, check to see if the dest type is
219         // losslessly convertable to one of the types in the start of the struct
220         // type.
221         //
222         if (!HasAddUse) {
223           const Type *DestPointedTy = DestPTy->getValueType();
224           unsigned Depth = 1;
225           const CompositeType *CurCTy = CTy;
226           const Type *ElTy = 0;
227
228           // Build the index vector, full of all zeros
229           vector<Value*> Indices;
230
231           while (CurCTy) {
232             if (const StructType *CurSTy = dyn_cast<StructType>(CurCTy)) {
233               // Check for a zero element struct type... if we have one, bail.
234               if (CurSTy->getElementTypes().size() == 0) break;
235             
236               // Grab the first element of the struct type, which must lie at
237               // offset zero in the struct.
238               //
239               ElTy = CurSTy->getElementTypes()[0];
240             } else {
241               ElTy = cast<ArrayType>(CurCTy)->getElementType();
242             }
243
244             // Insert a zero to index through this type...
245             Indices.push_back(ConstPoolUInt::get(CurCTy->getIndexType(), 0));
246
247             // Did we find what we're looking for?
248             if (ElTy->isLosslesslyConvertableTo(DestPointedTy)) break;
249             
250             // Nope, go a level deeper.
251             ++Depth;
252             CurCTy = dyn_cast<CompositeType>(ElTy);
253             ElTy = 0;
254           }
255           
256           // Did we find what we were looking for? If so, do the transformation
257           if (ElTy) {
258             PRINT_PEEPHOLE1("cast-for-first:in", CI);
259
260             // Insert the new T cast instruction... stealing old T's name
261             GetElementPtrInst *GEP = new GetElementPtrInst(Src, Indices,
262                                                            CI->getName());
263             CI->setName("");
264             BI = BB->getInstList().insert(BI, GEP)+1;
265
266             // Make the old cast instruction reference the new GEP instead of
267             // the old src value.
268             //
269             CI->setOperand(0, GEP);
270             
271             PRINT_PEEPHOLE2("cast-for-first:out", GEP, CI);
272             return true;
273           }
274         }
275       }
276 #endif
277
278 #if 1
279   } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
280     Value *Val     = SI->getOperand(0);
281     Value *Pointer = SI->getPointerOperand();
282     
283     // Peephole optimize the following instructions:
284     // %t1 = getelementptr {<...>} * %StructPtr, <element indices>
285     // store <elementty> %v, <elementty> * %t1
286     //
287     // Into: store <elementty> %v, {<...>} * %StructPtr, <element indices>
288     //
289     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Pointer)) {
290       // Append any indices that the store instruction has onto the end of the
291       // ones that the GEP is carrying...
292       //
293       vector<Value*> Indices(GEP->copyIndices());
294       Indices.insert(Indices.end(), SI->idx_begin(), SI->idx_end());
295
296       PRINT_PEEPHOLE2("gep-store:in", GEP, SI);
297       ReplaceInstWithInst(BB->getInstList(), BI,
298                           SI = new StoreInst(Val, GEP->getPointerOperand(),
299                                              Indices));
300       PRINT_PEEPHOLE1("gep-store:out", SI);
301       return true;
302     }
303     
304     // Peephole optimize the following instructions:
305     // %t = cast <T1>* %P to <T2> * ;; If T1 is losslessly convertable to T2
306     // store <T2> %V, <T2>* %t
307     //
308     // Into: 
309     // %t = cast <T2> %V to <T1>
310     // store <T1> %t2, <T1>* %P
311     //
312     if (CastInst *CI = dyn_cast<CastInst>(Pointer))
313       if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
314         if (PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
315           // convertable types?
316           if (Val->getType()->isLosslesslyConvertableTo(CSPT->getValueType()) &&
317               !SI->hasIndices()) {      // No subscripts yet!
318             PRINT_PEEPHOLE3("st-src-cast:in ", Pointer, Val, SI);
319
320             // Insert the new T cast instruction... stealing old T's name
321             CastInst *NCI = new CastInst(Val, CSPT->getValueType(),
322                                          CI->getName());
323             CI->setName("");
324             BI = BB->getInstList().insert(BI, NCI)+1;
325
326             // Replace the old store with a new one!
327             ReplaceInstWithInst(BB->getInstList(), BI,
328                                 SI = new StoreInst(NCI, CastSrc));
329             PRINT_PEEPHOLE3("st-src-cast:out", NCI, CastSrc, SI);
330             return true;
331           }
332
333
334   } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
335     Value *Pointer = LI->getPointerOperand();
336     
337     // Peephole optimize the following instructions:
338     // %t1 = getelementptr {<...>} * %StructPtr, <element indices>
339     // %V  = load <elementty> * %t1
340     //
341     // Into: load {<...>} * %StructPtr, <element indices>
342     //
343     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Pointer)) {
344       // Append any indices that the load instruction has onto the end of the
345       // ones that the GEP is carrying...
346       //
347       vector<Value*> Indices(GEP->copyIndices());
348       Indices.insert(Indices.end(), LI->idx_begin(), LI->idx_end());
349
350       PRINT_PEEPHOLE2("gep-load:in", GEP, LI);
351       ReplaceInstWithInst(BB->getInstList(), BI,
352                           LI = new LoadInst(GEP->getPointerOperand(),
353                                             Indices));
354       PRINT_PEEPHOLE1("gep-load:out", LI);
355       return true;
356     }
357
358
359     // Peephole optimize the following instructions:
360     // %t1 = cast <ty> * %t0 to <ty2> *
361     // %V  = load <ty2> * %t1
362     //
363     // Into: %t1 = load <ty> * %t0
364     //       %V  = cast <ty> %t1 to <ty2>
365     //
366     // The idea behind this transformation is that if the expression type
367     // conversion engine could not convert the cast into some other nice form,
368     // that there is something fundementally wrong with the current shape of
369     // the program.  Move the cast through the load and try again.  This will
370     // leave the original cast instruction, to presumably become dead.
371     //
372     if (CastInst *CI = dyn_cast<CastInst>(Pointer)) {
373       Value *SrcVal = CI->getOperand(0);
374       const PointerType *SrcTy = dyn_cast<PointerType>(SrcVal->getType());
375       const Type *ElTy = SrcTy ? SrcTy->getValueType() : 0;
376
377       // Make sure that nothing will be lost in the new cast...
378       if (!LI->hasIndices() && SrcTy &&
379           ElTy->isLosslesslyConvertableTo(LI->getType())) {
380         PRINT_PEEPHOLE2("CL-LoadCast:in ", CI, LI);
381
382         string CName = CI->getName(); CI->setName("");
383         LoadInst *NLI = new LoadInst(SrcVal, LI->getName());
384         LI->setName("");  // Take over the old load's name
385
386         // Insert the load before the old load
387         BI = BB->getInstList().insert(BI, NLI)+1;
388
389         // Replace the old load with a new cast...
390         ReplaceInstWithInst(BB->getInstList(), BI, 
391                             CI = new CastInst(NLI, LI->getType(), CName));
392         PRINT_PEEPHOLE2("CL-LoadCast:out", NLI, CI);
393
394         return true;
395       }
396     }
397   } else if (I->getOpcode() == Instruction::Add &&
398              isa<CastInst>(I->getOperand(1))) {
399
400     if (PeepholeOptimizeAddCast(BB, BI, I->getOperand(0),
401                                 cast<CastInst>(I->getOperand(1))))
402       return true;
403
404 #endif
405   }
406
407   return false;
408 }
409
410
411
412
413 static bool DoRaisePass(Method *M) {
414   bool Changed = false;
415   for (Method::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI) {
416     BasicBlock *BB = *MI;
417     BasicBlock::InstListType &BIL = BB->getInstList();
418
419     for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
420       if (opt::DeadCodeElimination::dceInstruction(BIL, BI) ||
421           opt::ConstantPropogation::doConstantPropogation(BB, BI)) {
422         Changed = true; 
423 #ifdef DEBUG_PEEPHOLE_INSTS
424         cerr << "DeadCode Elinated!\n";
425 #endif
426       } else if (PeepholeOptimize(BB, BI))
427         Changed = true;
428       else
429         ++BI;
430     }
431   }
432   return Changed;
433 }
434
435
436
437
438 // DoInsertArrayCast - If the argument value has a pointer type, and if the
439 // argument value is used as an array, insert a cast before the specified 
440 // basic block iterator that casts the value to an array pointer.  Return the
441 // new cast instruction (in the CastResult var), or null if no cast is inserted.
442 //
443 static bool DoInsertArrayCast(Value *V, BasicBlock *BB,
444                               BasicBlock::iterator InsertBefore) {
445   const PointerType *ThePtrType = dyn_cast<PointerType>(V->getType());
446   if (!ThePtrType) return false;
447
448   const Type *ElTy = ThePtrType->getValueType();
449   if (isa<MethodType>(ElTy) || isa<ArrayType>(ElTy)) return false;
450
451   unsigned ElementSize = TD.getTypeSize(ElTy);
452   bool InsertCast = false;
453
454   for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
455     Instruction *Inst = cast<Instruction>(*I);
456     switch (Inst->getOpcode()) {
457     case Instruction::Cast:          // There is already a cast instruction!
458       if (const PointerType *PT = dyn_cast<const PointerType>(Inst->getType()))
459         if (const ArrayType *AT = dyn_cast<const ArrayType>(PT->getValueType()))
460           if (AT->getElementType() == ThePtrType->getValueType()) {
461             // Cast already exists! Don't mess around with it.
462             return false;       // No changes made to program though...
463           }
464       break;
465     case Instruction::Add: {         // Analyze pointer arithmetic...
466       Value *OtherOp = Inst->getOperand(Inst->getOperand(0) == V);
467       analysis::ExprType Expr = analysis::ClassifyExpression(OtherOp);
468
469       // This looks like array addressing iff:
470       //   A. The constant of the index is larger than the size of the element
471       //      type.
472       //   B. The scale factor is >= the size of the type.
473       //
474       if (Expr.Offset && getConstantValue(Expr.Offset) >= (int)ElementSize) // A
475         InsertCast = true;
476
477       if (Expr.Scale && getConstantValue(Expr.Scale) >= (int)ElementSize) // B
478         InsertCast = true;
479
480       break;
481     }
482     default: break;                  // Not an interesting use...
483     }
484   }
485
486   if (!InsertCast) return false;  // There is no reason to insert a cast!
487
488   // Calculate the destination pointer type
489   const PointerType *DestTy = PointerType::get(ArrayType::get(ElTy));
490
491   // Check to make sure that all uses of the value can be converted over to use
492   // the newly typed value.
493   //
494   ValueTypeCache ConvertedTypes;
495   if (!ValueConvertableToType(V, DestTy, ConvertedTypes)) {
496     cerr << "FAILED to convert types of values for " << V << "\n";
497     ConvertedTypes.clear();
498     ValueConvertableToType(V, DestTy, ConvertedTypes);
499     return false;
500   }
501   ConvertedTypes.clear();
502
503   // Insert a cast!
504   CastInst *TheCast = 
505     new CastInst(ConstPoolVal::getNullConstant(V->getType()), DestTy,
506                  V->getName());
507   BB->getInstList().insert(InsertBefore, TheCast);
508
509   cerr << "Inserting cast for " << V << endl;
510
511   // Convert users of the old value over to use the cast result...
512   ValueMapCache VMC;
513   ConvertValueToNewType(V, TheCast, VMC);
514
515   // The cast is the only thing that is allowed to reference the value...
516   TheCast->setOperand(0, V);
517
518   cerr << "Inserted ptr-array cast: " << TheCast;
519   return true;            // Made a change!
520 }
521
522
523 // DoInsertArrayCasts - Loop over all "incoming" values in the specified method,
524 // inserting a cast for pointer values that are used as arrays. For our
525 // purposes, an incoming value is considered to be either a value that is 
526 // either a method parameter, or a pointer returned from a function call.
527 //
528 static bool DoInsertArrayCasts(Method *M) {
529   assert(!M->isExternal() && "Can't handle external methods!");
530
531   // Insert casts for all arguments to the function...
532   bool Changed = false;
533   BasicBlock *CurBB = M->front();
534
535   for (Method::ArgumentListType::iterator AI = M->getArgumentList().begin(), 
536          AE = M->getArgumentList().end(); AI != AE; ++AI) {
537
538     Changed |= DoInsertArrayCast(*AI, CurBB, CurBB->begin());
539   }
540
541   // TODO: insert casts for alloca, malloc, and function call results.  Also, 
542   // look for pointers that already have casts, to add to the map.
543
544   return Changed;
545 }
546
547
548
549
550 // RaisePointerReferences::doit - Raise a method representation to a higher
551 // level.
552 //
553 bool RaisePointerReferences::doit(Method *M) {
554   if (M->isExternal()) return false;
555
556 #ifdef DEBUG_PEEPHOLE_INSTS
557   cerr << "\n\n\nStarting to work on Method '" << M->getName() << "'\n";
558 #endif
559
560   // Insert casts for all incoming pointer pointer values that are treated as
561   // arrays...
562   //
563   bool Changed = false, LocalChange;
564   do {
565     LocalChange = DoInsertArrayCasts(M);
566
567     // Iterate over the method, refining it, until it converges on a stable
568     // state
569     while (DoRaisePass(M)) LocalChange = true;
570     Changed |= LocalChange;
571
572   } while (LocalChange);
573
574   return Changed;
575 }