Reverting back to original 1.8 version so I can manually merge in patch.
[llvm-complete.git] / lib / Transforms / LevelRaise.cpp
blob9cbe3b813eba1620bd070563ea545a309dcbe76a
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.
14 //===----------------------------------------------------------------------===//
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 #include <iostream>
28 using namespace llvm;
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!
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"));
38 static Statistic<>
39 NumLoadStorePeepholes("raise", "Number of load/store peepholes");
41 static Statistic<>
42 NumGEPInstFormed("raise", "Number of other getelementptr's formed");
44 static Statistic<>
45 NumExprTreesConv("raise", "Number of expression trees converted");
47 static Statistic<>
48 NumCastOfCast("raise", "Number of cast-of-self removed");
50 static Statistic<>
51 NumDCEorCP("raise", "Number of insts DCEd or constprop'd");
53 static Statistic<>
54 NumVarargCallChanges("raise", "Number of vararg call peepholes");
56 #define PRINT_PEEPHOLE(ID, NUM, I) \
57 DEBUG(std::cerr << "Inst P/H " << ID << "[" << NUM << "] " << I)
59 #define PRINT_PEEPHOLE1(ID, I1) do { PRINT_PEEPHOLE(ID, 0, I1); } while (0)
60 #define PRINT_PEEPHOLE2(ID, I1, I2) \
61 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); } while (0)
62 #define PRINT_PEEPHOLE3(ID, I1, I2, I3) \
63 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
64 PRINT_PEEPHOLE(ID, 2, I3); } while (0)
65 #define PRINT_PEEPHOLE4(ID, I1, I2, I3, I4) \
66 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
67 PRINT_PEEPHOLE(ID, 2, I3); PRINT_PEEPHOLE(ID, 3, I4); } while (0)
69 namespace {
70 struct RPR : public FunctionPass {
71 virtual bool runOnFunction(Function &F);
73 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
74 AU.setPreservesCFG();
75 AU.addRequired<TargetData>();
78 private:
79 bool DoRaisePass(Function &F);
80 bool PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI);
83 RegisterOpt<RPR> X("raise", "Raise Pointer References");
87 FunctionPass *llvm::createRaisePointerReferencesPass() {
88 return new RPR();
92 // isReinterpretingCast - Return true if the cast instruction specified will
93 // cause the operand to be "reinterpreted". A value is reinterpreted if the
94 // cast instruction would cause the underlying bits to change.
96 static inline bool isReinterpretingCast(const CastInst *CI) {
97 return!CI->getOperand(0)->getType()->isLosslesslyConvertibleTo(CI->getType());
100 bool RPR::PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI) {
101 Instruction *I = BI;
102 const TargetData &TD = getAnalysis<TargetData>();
104 if (CastInst *CI = dyn_cast<CastInst>(I)) {
105 Value *Src = CI->getOperand(0);
106 const Type *DestTy = CI->getType();
108 // Peephole optimize the following instruction:
109 // %V2 = cast <ty> %V to <ty>
111 // Into: <nothing>
113 if (DestTy == Src->getType()) { // Check for a cast to same type as src!!
114 PRINT_PEEPHOLE1("cast-of-self-ty", *CI);
115 CI->replaceAllUsesWith(Src);
116 if (!Src->hasName() && CI->hasName()) {
117 std::string Name = CI->getName();
118 CI->setName("");
119 Src->setName(Name);
122 // DCE the instruction now, to avoid having the iterative version of DCE
123 // have to worry about it.
125 BI = BB->getInstList().erase(BI);
127 ++NumCastOfCast;
128 return true;
131 // Check to see if it's a cast of an instruction that does not depend on the
132 // specific type of the operands to do it's job.
133 if (!isReinterpretingCast(CI)) {
134 ValueTypeCache ConvertedTypes;
136 // Check to see if we can convert the source of the cast to match the
137 // destination type of the cast...
139 ConvertedTypes[CI] = CI->getType(); // Make sure the cast doesn't change
140 if (ExpressionConvertibleToType(Src, DestTy, ConvertedTypes, TD)) {
141 PRINT_PEEPHOLE3("CAST-SRC-EXPR-CONV:in ", *Src, *CI, *BB->getParent());
143 DEBUG(std::cerr << "\nCONVERTING SRC EXPR TYPE:\n");
144 { // ValueMap must be destroyed before function verified!
145 ValueMapCache ValueMap;
146 Value *E = ConvertExpressionToType(Src, DestTy, ValueMap, TD);
148 if (Constant *CPV = dyn_cast<Constant>(E))
149 CI->replaceAllUsesWith(CPV);
151 PRINT_PEEPHOLE1("CAST-SRC-EXPR-CONV:out", *E);
152 DEBUG(std::cerr << "DONE CONVERTING SRC EXPR TYPE: \n"
153 << *BB->getParent());
156 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
157 ++NumExprTreesConv;
158 return true;
161 // Check to see if we can convert the users of the cast value to match the
162 // source type of the cast...
164 ConvertedTypes.clear();
165 // Make sure the source doesn't change type
166 ConvertedTypes[Src] = Src->getType();
167 if (ValueConvertibleToType(CI, Src->getType(), ConvertedTypes, TD)) {
168 //PRINT_PEEPHOLE3("CAST-DEST-EXPR-CONV:in ", *Src, *CI,
169 // *BB->getParent());
171 DEBUG(std::cerr << "\nCONVERTING EXPR TYPE:\n");
172 { // ValueMap must be destroyed before function verified!
173 ValueMapCache ValueMap;
174 ConvertValueToNewType(CI, Src, ValueMap, TD); // This will delete CI!
177 PRINT_PEEPHOLE1("CAST-DEST-EXPR-CONV:out", *Src);
178 DEBUG(std::cerr << "DONE CONVERTING EXPR TYPE: \n\n" <<
179 *BB->getParent());
181 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
182 ++NumExprTreesConv;
183 return true;
187 // Check to see if we are casting from a structure pointer to a pointer to
188 // the first element of the structure... to avoid munching other peepholes,
189 // we only let this happen if there are no add uses of the cast.
191 // Peephole optimize the following instructions:
192 // %t1 = cast {<...>} * %StructPtr to <ty> *
194 // Into: %t2 = getelementptr {<...>} * %StructPtr, <0, 0, 0, ...>
195 // %t1 = cast <eltype> * %t1 to <ty> *
197 if (const CompositeType *CTy = getPointedToComposite(Src->getType()))
198 if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
200 // Loop over uses of the cast, checking for add instructions. If an add
201 // exists, this is probably a part of a more complex GEP, so we don't
202 // want to mess around with the cast.
204 bool HasAddUse = false;
205 for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
206 I != E; ++I)
207 if (isa<Instruction>(*I) &&
208 cast<Instruction>(*I)->getOpcode() == Instruction::Add) {
209 HasAddUse = true; break;
212 // If it doesn't have an add use, check to see if the dest type is
213 // losslessly convertible to one of the types in the start of the struct
214 // type.
216 if (!HasAddUse) {
217 const Type *DestPointedTy = DestPTy->getElementType();
218 unsigned Depth = 1;
219 const CompositeType *CurCTy = CTy;
220 const Type *ElTy = 0;
222 // Build the index vector, full of all zeros
223 std::vector<Value*> Indices;
225 Indices.push_back(Constant::getNullValue(Type::UIntTy));
226 while (CurCTy && !isa<PointerType>(CurCTy)) {
227 if (const StructType *CurSTy = dyn_cast<StructType>(CurCTy)) {
228 // Check for a zero element struct type... if we have one, bail.
229 if (CurSTy->getNumElements() == 0) break;
231 // Grab the first element of the struct type, which must lie at
232 // offset zero in the struct.
234 ElTy = CurSTy->getElementType(0);
235 } else {
236 ElTy = cast<SequentialType>(CurCTy)->getElementType();
239 // Insert a zero to index through this type...
240 Indices.push_back(Constant::getNullValue(Type::UIntTy));
242 // Did we find what we're looking for?
243 if (ElTy->isLosslesslyConvertibleTo(DestPointedTy)) break;
245 // Nope, go a level deeper.
246 ++Depth;
247 CurCTy = dyn_cast<CompositeType>(ElTy);
248 ElTy = 0;
251 // Did we find what we were looking for? If so, do the transformation
252 if (ElTy) {
253 PRINT_PEEPHOLE1("cast-for-first:in", *CI);
255 std::string Name = CI->getName(); CI->setName("");
257 // Insert the new T cast instruction... stealing old T's name
258 GetElementPtrInst *GEP = new GetElementPtrInst(Src, Indices,
259 Name, BI);
261 // Make the old cast instruction reference the new GEP instead of
262 // the old src value.
264 CI->setOperand(0, GEP);
266 PRINT_PEEPHOLE2("cast-for-first:out", *GEP, *CI);
267 ++NumGEPInstFormed;
268 return true;
273 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
274 Value *Val = SI->getOperand(0);
275 Value *Pointer = SI->getPointerOperand();
277 // Peephole optimize the following instructions:
278 // %t = cast <T1>* %P to <T2> * ;; If T1 is losslessly convertible to T2
279 // store <T2> %V, <T2>* %t
281 // Into:
282 // %t = cast <T2> %V to <T1>
283 // store <T1> %t2, <T1>* %P
285 // Note: This is not taken care of by expr conversion because there might
286 // not be a cast available for the store to convert the incoming value of.
287 // This code is basically here to make sure that pointers don't have casts
288 // if possible.
290 if (CastInst *CI = dyn_cast<CastInst>(Pointer))
291 if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
292 if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
293 // convertible types?
294 if (Val->getType()->isLosslesslyConvertibleTo(CSPT->getElementType())) {
295 PRINT_PEEPHOLE3("st-src-cast:in ", *Pointer, *Val, *SI);
297 // Insert the new T cast instruction... stealing old T's name
298 std::string Name(CI->getName()); CI->setName("");
299 CastInst *NCI = new CastInst(Val, CSPT->getElementType(),
300 Name, BI);
302 // Replace the old store with a new one!
303 ReplaceInstWithInst(BB->getInstList(), BI,
304 SI = new StoreInst(NCI, CastSrc));
305 PRINT_PEEPHOLE3("st-src-cast:out", *NCI, *CastSrc, *SI);
306 ++NumLoadStorePeepholes;
307 return true;
310 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
311 Value *Pointer = LI->getOperand(0);
312 const Type *PtrElType =
313 cast<PointerType>(Pointer->getType())->getElementType();
315 // Peephole optimize the following instructions:
316 // %Val = cast <T1>* to <T2>* ;; If T1 is losslessly convertible to T2
317 // %t = load <T2>* %P
319 // Into:
320 // %t = load <T1>* %P
321 // %Val = cast <T1> to <T2>
323 // Note: This is not taken care of by expr conversion because there might
324 // not be a cast available for the store to convert the incoming value of.
325 // This code is basically here to make sure that pointers don't have casts
326 // if possible.
328 if (CastInst *CI = dyn_cast<CastInst>(Pointer))
329 if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
330 if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
331 // convertible types?
332 if (PtrElType->isLosslesslyConvertibleTo(CSPT->getElementType())) {
333 PRINT_PEEPHOLE2("load-src-cast:in ", *Pointer, *LI);
335 // Create the new load instruction... loading the pre-casted value
336 LoadInst *NewLI = new LoadInst(CastSrc, LI->getName(), BI);
338 // Insert the new T cast instruction... stealing old T's name
339 CastInst *NCI = new CastInst(NewLI, LI->getType(), CI->getName());
341 // Replace the old store with a new one!
342 ReplaceInstWithInst(BB->getInstList(), BI, NCI);
343 PRINT_PEEPHOLE3("load-src-cast:out", *NCI, *CastSrc, *NewLI);
344 ++NumLoadStorePeepholes;
345 return true;
348 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
349 // If we have a call with all varargs arguments, convert the call to use the
350 // actual argument types present...
352 const PointerType *PTy = cast<PointerType>(CI->getCalledValue()->getType());
353 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
355 // Is the call to a vararg variable with no real parameters?
356 if (FTy->isVarArg() && FTy->getNumParams() == 0 &&
357 !CI->getCalledFunction()) {
358 // If so, insert a new cast instruction, casting it to a function type
359 // that matches the current arguments...
361 std::vector<const Type *> Params; // Parameter types...
362 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
363 Params.push_back(CI->getOperand(i)->getType());
365 FunctionType *NewFT = FunctionType::get(FTy->getReturnType(),
366 Params, false);
367 PointerType *NewPFunTy = PointerType::get(NewFT);
369 // Create a new cast, inserting it right before the function call...
370 Value *NewCast;
371 Constant *ConstantCallSrc = 0;
372 if (Constant *CS = dyn_cast<Constant>(CI->getCalledValue()))
373 ConstantCallSrc = CS;
375 if (ConstantCallSrc)
376 NewCast = ConstantExpr::getCast(ConstantCallSrc, NewPFunTy);
377 else
378 NewCast = new CastInst(CI->getCalledValue(), NewPFunTy,
379 CI->getCalledValue()->getName()+"_c",CI);
381 // Create a new call instruction...
382 CallInst *NewCall = new CallInst(NewCast,
383 std::vector<Value*>(CI->op_begin()+1, CI->op_end()));
384 if (CI->isTailCall()) NewCall->setTailCall();
385 NewCall->setCallingConv(CI->getCallingConv());
386 ++BI;
387 ReplaceInstWithInst(CI, NewCall);
389 ++NumVarargCallChanges;
390 return true;
395 return false;
401 bool RPR::DoRaisePass(Function &F) {
402 bool Changed = false;
403 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
404 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
405 DEBUG(std::cerr << "LevelRaising: " << *BI);
406 if (dceInstruction(BI) || doConstantPropagation(BI)) {
407 Changed = true;
408 ++NumDCEorCP;
409 DEBUG(std::cerr << "***\t\t^^-- Dead code eliminated!\n");
410 } else if (PeepholeOptimize(BB, BI)) {
411 Changed = true;
412 } else {
413 ++BI;
417 return Changed;
421 // runOnFunction - Raise a function representation to a higher level.
422 bool RPR::runOnFunction(Function &F) {
423 DEBUG(std::cerr << "\n\n\nStarting to work on Function '" << F.getName()
424 << "'\n");
426 // Insert casts for all incoming pointer pointer values that are treated as
427 // arrays...
429 bool Changed = false, LocalChange;
431 // If the StartInst option was specified, then Peephole optimize that
432 // instruction first if it occurs in this function.
434 if (!StartInst.empty()) {
435 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
436 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI)
437 if (BI->getName() == StartInst) {
438 bool SavedDebug = DebugFlag; // Save the DEBUG() controlling flag.
439 DebugFlag = true; // Turn on DEBUG's
440 Changed |= PeepholeOptimize(BB, BI);
441 DebugFlag = SavedDebug; // Restore DebugFlag to previous state
445 do {
446 DEBUG(std::cerr << "Looping: \n" << F);
448 // Iterate over the function, refining it, until it converges on a stable
449 // state
450 LocalChange = false;
451 while (DoRaisePass(F)) LocalChange = true;
452 Changed |= LocalChange;
454 } while (LocalChange);
456 return Changed;