Removed #include <iostream> and used the llvm_cerr/DOUT streams instead.
[oota-llvm.git] / lib / Transforms / LevelRaise.cpp
1 //===- LevelRaise.cpp - Code to change LLVM to higher level ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the 'raising' part of the LevelChange API.  This is
11 // useful because, in general, it makes the LLVM code terser and easier to
12 // analyze.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/Transforms/Scalar.h"
17 #include "llvm/Transforms/Utils/Local.h"
18 #include "TransformInternals.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Pass.h"
21 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include <algorithm>
27 using namespace llvm;
28
29 // StartInst - This enables the -raise-start-inst=foo option to cause the level
30 // raising pass to start at instruction "foo", which is immensely useful for
31 // debugging!
32 //
33 static cl::opt<std::string>
34 StartInst("raise-start-inst", cl::Hidden, cl::value_desc("inst name"),
35        cl::desc("Start raise pass at the instruction with the specified name"));
36
37 static Statistic<>
38 NumLoadStorePeepholes("raise", "Number of load/store peepholes");
39
40 static Statistic<>
41 NumGEPInstFormed("raise", "Number of other getelementptr's formed");
42
43 static Statistic<>
44 NumExprTreesConv("raise", "Number of expression trees converted");
45
46 static Statistic<>
47 NumCastOfCast("raise", "Number of cast-of-self removed");
48
49 static Statistic<>
50 NumDCEorCP("raise", "Number of insts DCEd or constprop'd");
51
52 static Statistic<>
53 NumVarargCallChanges("raise", "Number of vararg call peepholes");
54
55 #define PRINT_PEEPHOLE(ID, NUM, I)            \
56   DOUT << "Inst P/H " << ID << "[" << NUM << "] " << I
57
58 #define PRINT_PEEPHOLE1(ID, I1) do { PRINT_PEEPHOLE(ID, 0, I1); } while (0)
59 #define PRINT_PEEPHOLE2(ID, I1, I2) \
60   do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); } while (0)
61 #define PRINT_PEEPHOLE3(ID, I1, I2, I3) \
62   do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
63        PRINT_PEEPHOLE(ID, 2, I3); } while (0)
64 #define PRINT_PEEPHOLE4(ID, I1, I2, I3, I4) \
65   do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
66        PRINT_PEEPHOLE(ID, 2, I3); PRINT_PEEPHOLE(ID, 3, I4); } while (0)
67
68 namespace {
69   struct RPR : public FunctionPass {
70     virtual bool runOnFunction(Function &F);
71
72     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
73       AU.setPreservesCFG();
74       AU.addRequired<TargetData>();
75     }
76
77   private:
78     bool DoRaisePass(Function &F);
79     bool PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI);
80   };
81
82   RegisterPass<RPR> X("raise", "Raise Pointer References");
83 }
84
85
86 FunctionPass *llvm::createRaisePointerReferencesPass() {
87   return new RPR();
88 }
89
90
91 // isReinterpretingCast - Return true if the cast instruction specified will
92 // cause the operand to be "reinterpreted".  A value is reinterpreted if the
93 // cast instruction would cause the underlying bits to change.
94 //
95 static inline bool isReinterpretingCast(const CastInst *CI) {
96   return!CI->getOperand(0)->getType()->isLosslesslyConvertibleTo(CI->getType());
97 }
98
99 bool RPR::PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI) {
100   Instruction *I = BI;
101   const TargetData &TD = getAnalysis<TargetData>();
102
103   if (CastInst *CI = dyn_cast<CastInst>(I)) {
104     Value       *Src    = CI->getOperand(0);
105     const Type  *DestTy = CI->getType();
106
107     // Peephole optimize the following instruction:
108     // %V2 = cast <ty> %V to <ty>
109     //
110     // Into: <nothing>
111     //
112     if (DestTy == Src->getType()) {   // Check for a cast to same type as src!!
113       PRINT_PEEPHOLE1("cast-of-self-ty", *CI);
114       CI->replaceAllUsesWith(Src);
115       if (!Src->hasName() && CI->hasName()) {
116         std::string Name = CI->getName();
117         CI->setName("");
118         Src->setName(Name);
119       }
120
121       // DCE the instruction now, to avoid having the iterative version of DCE
122       // have to worry about it.
123       //
124       BI = BB->getInstList().erase(BI);
125
126       ++NumCastOfCast;
127       return true;
128     }
129
130     // Check to see if it's a cast of an instruction that does not depend on the
131     // specific type of the operands to do it's job.
132     if (!isReinterpretingCast(CI)) {
133       ValueTypeCache ConvertedTypes;
134
135       // Check to see if we can convert the source of the cast to match the
136       // destination type of the cast...
137       //
138       ConvertedTypes[CI] = CI->getType();  // Make sure the cast doesn't change
139       if (ExpressionConvertibleToType(Src, DestTy, ConvertedTypes, TD)) {
140         PRINT_PEEPHOLE3("CAST-SRC-EXPR-CONV:in ", *Src, *CI, *BB->getParent());
141
142         DOUT << "\nCONVERTING SRC EXPR TYPE:\n";
143         { // ValueMap must be destroyed before function verified!
144           ValueMapCache ValueMap;
145           Value *E = ConvertExpressionToType(Src, DestTy, ValueMap, TD);
146
147           if (Constant *CPV = dyn_cast<Constant>(E))
148             CI->replaceAllUsesWith(CPV);
149
150           PRINT_PEEPHOLE1("CAST-SRC-EXPR-CONV:out", *E);
151           DOUT << "DONE CONVERTING SRC EXPR TYPE: \n"
152                << *BB->getParent();
153         }
154
155         BI = BB->begin();  // Rescan basic block.  BI might be invalidated.
156         ++NumExprTreesConv;
157         return true;
158       }
159
160       // Check to see if we can convert the users of the cast value to match the
161       // source type of the cast...
162       //
163       ConvertedTypes.clear();
164       // Make sure the source doesn't change type
165       ConvertedTypes[Src] = Src->getType();
166       if (ValueConvertibleToType(CI, Src->getType(), ConvertedTypes, TD)) {
167         //PRINT_PEEPHOLE3("CAST-DEST-EXPR-CONV:in ", *Src, *CI,
168         //                *BB->getParent());
169
170         DOUT << "\nCONVERTING EXPR TYPE:\n";
171         { // ValueMap must be destroyed before function verified!
172           ValueMapCache ValueMap;
173           ConvertValueToNewType(CI, Src, ValueMap, TD);  // This will delete CI!
174         }
175
176         PRINT_PEEPHOLE1("CAST-DEST-EXPR-CONV:out", *Src);
177         DOUT << "DONE CONVERTING EXPR TYPE: \n\n" << *BB->getParent();
178
179         BI = BB->begin();  // Rescan basic block.  BI might be invalidated.
180         ++NumExprTreesConv;
181         return true;
182       }
183     }
184
185     // Check to see if we are casting from a structure pointer to a pointer to
186     // the first element of the structure... to avoid munching other peepholes,
187     // we only let this happen if there are no add uses of the cast.
188     //
189     // Peephole optimize the following instructions:
190     // %t1 = cast {<...>} * %StructPtr to <ty> *
191     //
192     // Into: %t2 = getelementptr {<...>} * %StructPtr, <0, 0, 0, ...>
193     //       %t1 = cast <eltype> * %t1 to <ty> *
194     //
195     if (const CompositeType *CTy = getPointedToComposite(Src->getType()))
196       if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
197
198         // Loop over uses of the cast, checking for add instructions.  If an add
199         // exists, this is probably a part of a more complex GEP, so we don't
200         // want to mess around with the cast.
201         //
202         bool HasAddUse = false;
203         for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
204              I != E; ++I)
205           if (isa<Instruction>(*I) &&
206               cast<Instruction>(*I)->getOpcode() == Instruction::Add) {
207             HasAddUse = true; break;
208           }
209
210         // If it doesn't have an add use, check to see if the dest type is
211         // losslessly convertible to one of the types in the start of the struct
212         // type.
213         //
214         if (!HasAddUse) {
215           const Type *DestPointedTy = DestPTy->getElementType();
216           unsigned Depth = 1;
217           const CompositeType *CurCTy = CTy;
218           const Type *ElTy = 0;
219
220           // Build the index vector, full of all zeros
221           std::vector<Value*> Indices;
222
223           Indices.push_back(Constant::getNullValue(Type::UIntTy));
224           while (CurCTy && !isa<PointerType>(CurCTy)) {
225             if (const StructType *CurSTy = dyn_cast<StructType>(CurCTy)) {
226               // Check for a zero element struct type... if we have one, bail.
227               if (CurSTy->getNumElements() == 0) break;
228
229               // Grab the first element of the struct type, which must lie at
230               // offset zero in the struct.
231               //
232               ElTy = CurSTy->getElementType(0);
233             } else {
234               ElTy = cast<SequentialType>(CurCTy)->getElementType();
235             }
236
237             // Insert a zero to index through this type...
238             Indices.push_back(Constant::getNullValue(Type::UIntTy));
239
240             // Did we find what we're looking for?
241             if (ElTy->isLosslesslyConvertibleTo(DestPointedTy)) break;
242
243             // Nope, go a level deeper.
244             ++Depth;
245             CurCTy = dyn_cast<CompositeType>(ElTy);
246             ElTy = 0;
247           }
248
249           // Did we find what we were looking for? If so, do the transformation
250           if (ElTy) {
251             PRINT_PEEPHOLE1("cast-for-first:in", *CI);
252
253             std::string Name = CI->getName(); CI->setName("");
254
255             // Insert the new T cast instruction... stealing old T's name
256             GetElementPtrInst *GEP = new GetElementPtrInst(Src, Indices,
257                                                            Name, BI);
258
259             // Make the old cast instruction reference the new GEP instead of
260             // the old src value.
261             //
262             CI->setOperand(0, GEP);
263
264             PRINT_PEEPHOLE2("cast-for-first:out", *GEP, *CI);
265             ++NumGEPInstFormed;
266             return true;
267           }
268         }
269       }
270
271   } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
272     Value *Val     = SI->getOperand(0);
273     Value *Pointer = SI->getPointerOperand();
274
275     // Peephole optimize the following instructions:
276     // %t = cast <T1>* %P to <T2> * ;; If T1 is losslessly convertible to T2
277     // store <T2> %V, <T2>* %t
278     //
279     // Into:
280     // %t = cast <T2> %V to <T1>
281     // store <T1> %t2, <T1>* %P
282     //
283     // Note: This is not taken care of by expr conversion because there might
284     // not be a cast available for the store to convert the incoming value of.
285     // This code is basically here to make sure that pointers don't have casts
286     // if possible.
287     //
288     if (CastInst *CI = dyn_cast<CastInst>(Pointer))
289       if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
290         if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
291           // convertible types?
292           if (Val->getType()->isLosslesslyConvertibleTo(CSPT->getElementType())) {
293             PRINT_PEEPHOLE3("st-src-cast:in ", *Pointer, *Val, *SI);
294
295             // Insert the new T cast instruction... stealing old T's name
296             std::string Name(CI->getName()); CI->setName("");
297             CastInst *NCI = new CastInst(Val, CSPT->getElementType(),
298                                          Name, BI);
299
300             // Replace the old store with a new one!
301             ReplaceInstWithInst(BB->getInstList(), BI,
302                                 SI = new StoreInst(NCI, CastSrc));
303             PRINT_PEEPHOLE3("st-src-cast:out", *NCI, *CastSrc, *SI);
304             ++NumLoadStorePeepholes;
305             return true;
306           }
307
308   } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
309     Value *Pointer = LI->getOperand(0);
310     const Type *PtrElType =
311       cast<PointerType>(Pointer->getType())->getElementType();
312
313     // Peephole optimize the following instructions:
314     // %Val = cast <T1>* to <T2>*    ;; If T1 is losslessly convertible to T2
315     // %t = load <T2>* %P
316     //
317     // Into:
318     // %t = load <T1>* %P
319     // %Val = cast <T1> to <T2>
320     //
321     // Note: This is not taken care of by expr conversion because there might
322     // not be a cast available for the store to convert the incoming value of.
323     // This code is basically here to make sure that pointers don't have casts
324     // if possible.
325     //
326     if (CastInst *CI = dyn_cast<CastInst>(Pointer))
327       if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
328         if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
329           // convertible types?
330           if (PtrElType->isLosslesslyConvertibleTo(CSPT->getElementType())) {
331             PRINT_PEEPHOLE2("load-src-cast:in ", *Pointer, *LI);
332
333             // Create the new load instruction... loading the pre-casted value
334             LoadInst *NewLI = new LoadInst(CastSrc, LI->getName(), BI);
335
336             // Insert the new T cast instruction... stealing old T's name
337             CastInst *NCI = new CastInst(NewLI, LI->getType(), CI->getName());
338
339             // Replace the old store with a new one!
340             ReplaceInstWithInst(BB->getInstList(), BI, NCI);
341             PRINT_PEEPHOLE3("load-src-cast:out", *NCI, *CastSrc, *NewLI);
342             ++NumLoadStorePeepholes;
343             return true;
344           }
345
346   } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
347     // If we have a call with all varargs arguments, convert the call to use the
348     // actual argument types present...
349     //
350     const PointerType *PTy = cast<PointerType>(CI->getCalledValue()->getType());
351     const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
352
353     // Is the call to a vararg variable with no real parameters?
354     if (FTy->isVarArg() && FTy->getNumParams() == 0 &&
355         !CI->getCalledFunction()) {
356       // If so, insert a new cast instruction, casting it to a function type
357       // that matches the current arguments...
358       //
359       std::vector<const Type *> Params;  // Parameter types...
360       for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
361         Params.push_back(CI->getOperand(i)->getType());
362
363       FunctionType *NewFT = FunctionType::get(FTy->getReturnType(),
364                                               Params, false);
365       PointerType *NewPFunTy = PointerType::get(NewFT);
366
367       // Create a new cast, inserting it right before the function call...
368       Value *NewCast;
369       Constant *ConstantCallSrc = 0;
370       if (Constant *CS = dyn_cast<Constant>(CI->getCalledValue()))
371         ConstantCallSrc = CS;
372
373       if (ConstantCallSrc)
374         NewCast = ConstantExpr::getCast(ConstantCallSrc, NewPFunTy);
375       else
376         NewCast = new CastInst(CI->getCalledValue(), NewPFunTy,
377                                CI->getCalledValue()->getName()+"_c",CI);
378
379       // Create a new call instruction...
380       CallInst *NewCall = new CallInst(NewCast,
381                            std::vector<Value*>(CI->op_begin()+1, CI->op_end()));
382       if (CI->isTailCall()) NewCall->setTailCall();
383       NewCall->setCallingConv(CI->getCallingConv());
384       ++BI;
385       ReplaceInstWithInst(CI, NewCall);
386
387       ++NumVarargCallChanges;
388       return true;
389     }
390
391   }
392
393   return false;
394 }
395
396
397
398
399 bool RPR::DoRaisePass(Function &F) {
400   bool Changed = false;
401   for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
402     for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
403       DOUT << "LevelRaising: " << *BI;
404       if (dceInstruction(BI) || doConstantPropagation(BI)) {
405         Changed = true;
406         ++NumDCEorCP;
407         DOUT << "***\t\t^^-- Dead code eliminated!\n";
408       } else if (PeepholeOptimize(BB, BI)) {
409         Changed = true;
410       } else {
411         ++BI;
412       }
413     }
414
415   return Changed;
416 }
417
418
419 // runOnFunction - Raise a function representation to a higher level.
420 bool RPR::runOnFunction(Function &F) {
421   DOUT << "\n\n\nStarting to work on Function '" << F.getName() << "'\n";
422
423   // Insert casts for all incoming pointer pointer values that are treated as
424   // arrays...
425   //
426   bool Changed = false, LocalChange;
427
428   // If the StartInst option was specified, then Peephole optimize that
429   // instruction first if it occurs in this function.
430   //
431   if (!StartInst.empty()) {
432     for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
433       for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI)
434         if (BI->getName() == StartInst) {
435           bool SavedDebug = DebugFlag;  // Save the DEBUG() controlling flag.
436           DebugFlag = true;             // Turn on DEBUG's
437           Changed |= PeepholeOptimize(BB, BI);
438           DebugFlag = SavedDebug;       // Restore DebugFlag to previous state
439         }
440   }
441
442   do {
443     DOUT << "Looping: \n" << F;
444
445     // Iterate over the function, refining it, until it converges on a stable
446     // state
447     LocalChange = false;
448     while (DoRaisePass(F)) LocalChange = true;
449     Changed |= LocalChange;
450
451   } while (LocalChange);
452
453   return Changed;
454 }
455