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