1 //===- LevelRaise.cpp - Code to change LLVM to higher level ---------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "llvm/Transforms/Scalar.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/CommandLine.h"
20 #include "Support/Debug.h"
21 #include "Support/Statistic.h"
22 #include "Support/STLExtras.h"
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
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"));
34 NumLoadStorePeepholes("raise", "Number of load/store peepholes");
37 NumGEPInstFormed("raise", "Number of other getelementptr's formed");
40 NumExprTreesConv("raise", "Number of expression trees converted");
43 NumCastOfCast("raise", "Number of cast-of-self removed");
46 NumDCEorCP("raise", "Number of insts DCEd or constprop'd");
49 NumVarargCallChanges("raise", "Number of vararg call peepholes");
52 #define PRINT_PEEPHOLE(ID, NUM, I) \
53 DEBUG(std::cerr << "Inst P/H " << ID << "[" << NUM << "] " << I)
55 #define PRINT_PEEPHOLE1(ID, I1) do { PRINT_PEEPHOLE(ID, 0, I1); } while (0)
56 #define PRINT_PEEPHOLE2(ID, I1, I2) \
57 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); } while (0)
58 #define PRINT_PEEPHOLE3(ID, I1, I2, I3) \
59 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
60 PRINT_PEEPHOLE(ID, 2, I3); } while (0)
61 #define PRINT_PEEPHOLE4(ID, I1, I2, I3, I4) \
62 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
63 PRINT_PEEPHOLE(ID, 2, I3); PRINT_PEEPHOLE(ID, 3, I4); } while (0)
66 struct RPR : public FunctionPass {
67 virtual bool runOnFunction(Function &F);
69 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
71 AU.addRequired<TargetData>();
75 bool DoRaisePass(Function &F);
76 bool PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI);
79 RegisterOpt<RPR> X("raise", "Raise Pointer References");
82 Pass *createRaisePointerReferencesPass() {
88 // isReinterpretingCast - Return true if the cast instruction specified will
89 // cause the operand to be "reinterpreted". A value is reinterpreted if the
90 // cast instruction would cause the underlying bits to change.
92 static inline bool isReinterpretingCast(const CastInst *CI) {
93 return!CI->getOperand(0)->getType()->isLosslesslyConvertibleTo(CI->getType());
97 // Peephole optimize the following instructions:
98 // %t1 = cast ? to x *
99 // %t2 = add x * %SP, %t1 ;; Constant must be 2nd operand
101 // Into: %t3 = getelementptr {<...>} * %SP, <element indices>
102 // %t2 = cast <eltype> * %t3 to {<...>}*
104 static bool HandleCastToPointer(BasicBlock::iterator BI,
105 const PointerType *DestPTy,
106 const TargetData &TD) {
107 CastInst &CI = cast<CastInst>(*BI);
108 if (CI.use_empty()) return false;
110 // Scan all of the uses, looking for any uses that are not add or sub
111 // instructions. If we have non-adds, do not make this transformation.
113 bool HasSubUse = false; // Keep track of any subtracts...
114 for (Value::use_iterator I = CI.use_begin(), E = CI.use_end();
116 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(*I)) {
117 if ((BO->getOpcode() != Instruction::Add &&
118 BO->getOpcode() != Instruction::Sub) ||
119 // Avoid add sbyte* %X, %X cases...
120 BO->getOperand(0) == BO->getOperand(1))
123 HasSubUse |= BO->getOpcode() == Instruction::Sub;
128 std::vector<Value*> Indices;
129 Value *Src = CI.getOperand(0);
130 const Type *Result = ConvertibleToGEP(DestPTy, Src, Indices, TD, &BI);
131 if (Result == 0) return false; // Not convertible...
133 // Cannot handle subtracts if there is more than one index required...
134 if (HasSubUse && Indices.size() != 1) return false;
136 PRINT_PEEPHOLE2("cast-add-to-gep:in", Src, CI);
138 // If we have a getelementptr capability... transform all of the
139 // add instruction uses into getelementptr's.
140 while (!CI.use_empty()) {
141 BinaryOperator *I = cast<BinaryOperator>(*CI.use_begin());
142 assert((I->getOpcode() == Instruction::Add ||
143 I->getOpcode() == Instruction::Sub) &&
144 "Use is not a valid add instruction!");
146 // Get the value added to the cast result pointer...
147 Value *OtherPtr = I->getOperand((I->getOperand(0) == &CI) ? 1 : 0);
149 Instruction *GEP = new GetElementPtrInst(OtherPtr, Indices, I->getName());
150 PRINT_PEEPHOLE1("cast-add-to-gep:i", I);
152 // If the instruction is actually a subtract, we are guaranteed to only have
153 // one index (from code above), so we just need to negate the pointer index
155 if (I->getOpcode() == Instruction::Sub) {
156 Instruction *Neg = BinaryOperator::createNeg(GEP->getOperand(1),
157 GEP->getOperand(1)->getName()+".neg", I);
158 GEP->setOperand(1, Neg);
161 if (GEP->getType() == I->getType()) {
162 // Replace the old add instruction with the shiny new GEP inst
163 ReplaceInstWithInst(I, GEP);
165 // If the type produced by the gep instruction differs from the original
166 // add instruction type, insert a cast now.
169 // Insert the GEP instruction before the old add instruction...
170 I->getParent()->getInstList().insert(I, GEP);
172 PRINT_PEEPHOLE1("cast-add-to-gep:o", GEP);
173 GEP = new CastInst(GEP, I->getType());
175 // Replace the old add instruction with the shiny new GEP inst
176 ReplaceInstWithInst(I, GEP);
179 PRINT_PEEPHOLE1("cast-add-to-gep:o", GEP);
184 // Peephole optimize the following instructions:
185 // %t1 = cast ulong <const int> to {<...>} *
186 // %t2 = add {<...>} * %SP, %t1 ;; Constant must be 2nd operand
189 // %t1 = cast {<...>}* %SP to int*
190 // %t5 = cast ulong <const int> to int*
191 // %t2 = add int* %t1, %t5 ;; int is same size as field
193 // Into: %t3 = getelementptr {<...>} * %SP, <element indices>
194 // %t2 = cast <eltype> * %t3 to {<...>}*
196 static bool PeepholeOptimizeAddCast(BasicBlock *BB, BasicBlock::iterator &BI,
197 Value *AddOp1, CastInst *AddOp2,
198 const TargetData &TD) {
199 const CompositeType *CompTy;
200 Value *OffsetVal = AddOp2->getOperand(0);
201 Value *SrcPtr = 0; // Of type pointer to struct...
203 if ((CompTy = getPointedToComposite(AddOp1->getType()))) {
204 SrcPtr = AddOp1; // Handle the first case...
205 } else if (CastInst *AddOp1c = dyn_cast<CastInst>(AddOp1)) {
206 SrcPtr = AddOp1c->getOperand(0); // Handle the second case...
207 CompTy = getPointedToComposite(SrcPtr->getType());
210 // Only proceed if we have detected all of our conditions successfully...
211 if (!CompTy || !SrcPtr || !OffsetVal->getType()->isInteger())
214 std::vector<Value*> Indices;
215 if (!ConvertibleToGEP(SrcPtr->getType(), OffsetVal, Indices, TD, &BI))
216 return false; // Not convertible... perhaps next time
218 if (getPointedToComposite(AddOp1->getType())) { // case 1
219 PRINT_PEEPHOLE2("add-to-gep1:in", AddOp2, *BI);
221 PRINT_PEEPHOLE3("add-to-gep2:in", AddOp1, AddOp2, *BI);
224 GetElementPtrInst *GEP = new GetElementPtrInst(SrcPtr, Indices,
225 AddOp2->getName(), BI);
227 Instruction *NCI = new CastInst(GEP, AddOp1->getType());
228 ReplaceInstWithInst(BB->getInstList(), BI, NCI);
229 PRINT_PEEPHOLE2("add-to-gep:out", GEP, NCI);
233 bool RPR::PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI) {
235 const TargetData &TD = getAnalysis<TargetData>();
237 if (CastInst *CI = dyn_cast<CastInst>(I)) {
238 Value *Src = CI->getOperand(0);
239 Instruction *SrcI = dyn_cast<Instruction>(Src); // Nonnull if instr source
240 const Type *DestTy = CI->getType();
242 // Peephole optimize the following instruction:
243 // %V2 = cast <ty> %V to <ty>
247 if (DestTy == Src->getType()) { // Check for a cast to same type as src!!
248 PRINT_PEEPHOLE1("cast-of-self-ty", CI);
249 CI->replaceAllUsesWith(Src);
250 if (!Src->hasName() && CI->hasName()) {
251 std::string Name = CI->getName();
253 Src->setName(Name, &BB->getParent()->getSymbolTable());
256 // DCE the instruction now, to avoid having the iterative version of DCE
257 // have to worry about it.
259 BI = BB->getInstList().erase(BI);
265 // Check to see if it's a cast of an instruction that does not depend on the
266 // specific type of the operands to do it's job.
267 if (!isReinterpretingCast(CI)) {
268 ValueTypeCache ConvertedTypes;
270 // Check to see if we can convert the source of the cast to match the
271 // destination type of the cast...
273 ConvertedTypes[CI] = CI->getType(); // Make sure the cast doesn't change
274 if (ExpressionConvertibleToType(Src, DestTy, ConvertedTypes, TD)) {
275 PRINT_PEEPHOLE3("CAST-SRC-EXPR-CONV:in ", Src, CI, BB->getParent());
277 DEBUG(std::cerr << "\nCONVERTING SRC EXPR TYPE:\n");
278 { // ValueMap must be destroyed before function verified!
279 ValueMapCache ValueMap;
280 Value *E = ConvertExpressionToType(Src, DestTy, ValueMap, TD);
282 if (Constant *CPV = dyn_cast<Constant>(E))
283 CI->replaceAllUsesWith(CPV);
285 PRINT_PEEPHOLE1("CAST-SRC-EXPR-CONV:out", E);
286 DEBUG(std::cerr << "DONE CONVERTING SRC EXPR TYPE: \n"
290 DEBUG(assert(verifyFunction(*BB->getParent()) == false &&
291 "Function broken!"));
292 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
297 // Check to see if we can convert the users of the cast value to match the
298 // source type of the cast...
300 ConvertedTypes.clear();
301 // Make sure the source doesn't change type
302 ConvertedTypes[Src] = Src->getType();
303 if (ValueConvertibleToType(CI, Src->getType(), ConvertedTypes, TD)) {
304 PRINT_PEEPHOLE3("CAST-DEST-EXPR-CONV:in ", Src, CI, BB->getParent());
306 DEBUG(std::cerr << "\nCONVERTING EXPR TYPE:\n");
307 { // ValueMap must be destroyed before function verified!
308 ValueMapCache ValueMap;
309 ConvertValueToNewType(CI, Src, ValueMap, TD); // This will delete CI!
312 PRINT_PEEPHOLE1("CAST-DEST-EXPR-CONV:out", Src);
313 DEBUG(std::cerr << "DONE CONVERTING EXPR TYPE: \n\n" << BB->getParent());
315 DEBUG(assert(verifyFunction(*BB->getParent()) == false &&
316 "Function broken!"));
317 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
323 // Otherwise find out it this cast is a cast to a pointer type, which is
324 // then added to some other pointer, then loaded or stored through. If
325 // so, convert the add into a getelementptr instruction...
327 if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
328 if (HandleCastToPointer(BI, DestPTy, TD)) {
329 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
335 // Check to see if we are casting from a structure pointer to a pointer to
336 // the first element of the structure... to avoid munching other peepholes,
337 // we only let this happen if there are no add uses of the cast.
339 // Peephole optimize the following instructions:
340 // %t1 = cast {<...>} * %StructPtr to <ty> *
342 // Into: %t2 = getelementptr {<...>} * %StructPtr, <0, 0, 0, ...>
343 // %t1 = cast <eltype> * %t1 to <ty> *
345 if (const CompositeType *CTy = getPointedToComposite(Src->getType()))
346 if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
348 // Loop over uses of the cast, checking for add instructions. If an add
349 // exists, this is probably a part of a more complex GEP, so we don't
350 // want to mess around with the cast.
352 bool HasAddUse = false;
353 for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
355 if (isa<Instruction>(*I) &&
356 cast<Instruction>(*I)->getOpcode() == Instruction::Add) {
357 HasAddUse = true; break;
360 // If it doesn't have an add use, check to see if the dest type is
361 // losslessly convertible to one of the types in the start of the struct
365 const Type *DestPointedTy = DestPTy->getElementType();
367 const CompositeType *CurCTy = CTy;
368 const Type *ElTy = 0;
370 // Build the index vector, full of all zeros
371 std::vector<Value*> Indices;
372 Indices.push_back(ConstantSInt::get(Type::LongTy, 0));
373 while (CurCTy && !isa<PointerType>(CurCTy)) {
374 if (const StructType *CurSTy = dyn_cast<StructType>(CurCTy)) {
375 // Check for a zero element struct type... if we have one, bail.
376 if (CurSTy->getElementTypes().size() == 0) break;
378 // Grab the first element of the struct type, which must lie at
379 // offset zero in the struct.
381 ElTy = CurSTy->getElementTypes()[0];
383 ElTy = cast<ArrayType>(CurCTy)->getElementType();
386 // Insert a zero to index through this type...
387 Indices.push_back(Constant::getNullValue(CurCTy->getIndexType()));
389 // Did we find what we're looking for?
390 if (ElTy->isLosslesslyConvertibleTo(DestPointedTy)) break;
392 // Nope, go a level deeper.
394 CurCTy = dyn_cast<CompositeType>(ElTy);
398 // Did we find what we were looking for? If so, do the transformation
400 PRINT_PEEPHOLE1("cast-for-first:in", CI);
402 std::string Name = CI->getName(); CI->setName("");
404 // Insert the new T cast instruction... stealing old T's name
405 GetElementPtrInst *GEP = new GetElementPtrInst(Src, Indices,
408 // Make the old cast instruction reference the new GEP instead of
409 // the old src value.
411 CI->setOperand(0, GEP);
413 PRINT_PEEPHOLE2("cast-for-first:out", GEP, CI);
420 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
421 Value *Val = SI->getOperand(0);
422 Value *Pointer = SI->getPointerOperand();
424 // Peephole optimize the following instructions:
425 // %t = cast <T1>* %P to <T2> * ;; If T1 is losslessly convertible to T2
426 // store <T2> %V, <T2>* %t
429 // %t = cast <T2> %V to <T1>
430 // store <T1> %t2, <T1>* %P
432 // Note: This is not taken care of by expr conversion because there might
433 // not be a cast available for the store to convert the incoming value of.
434 // This code is basically here to make sure that pointers don't have casts
437 if (CastInst *CI = dyn_cast<CastInst>(Pointer))
438 if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
439 if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
440 // convertible types?
441 if (Val->getType()->isLosslesslyConvertibleTo(CSPT->getElementType())) {
442 PRINT_PEEPHOLE3("st-src-cast:in ", Pointer, Val, SI);
444 // Insert the new T cast instruction... stealing old T's name
445 std::string Name(CI->getName()); CI->setName("");
446 CastInst *NCI = new CastInst(Val, CSPT->getElementType(),
449 // Replace the old store with a new one!
450 ReplaceInstWithInst(BB->getInstList(), BI,
451 SI = new StoreInst(NCI, CastSrc));
452 PRINT_PEEPHOLE3("st-src-cast:out", NCI, CastSrc, SI);
453 ++NumLoadStorePeepholes;
457 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
458 Value *Pointer = LI->getOperand(0);
459 const Type *PtrElType =
460 cast<PointerType>(Pointer->getType())->getElementType();
462 // Peephole optimize the following instructions:
463 // %Val = cast <T1>* to <T2>* ;; If T1 is losslessly convertible to T2
464 // %t = load <T2>* %P
467 // %t = load <T1>* %P
468 // %Val = cast <T1> to <T2>
470 // Note: This is not taken care of by expr conversion because there might
471 // not be a cast available for the store to convert the incoming value of.
472 // This code is basically here to make sure that pointers don't have casts
475 if (CastInst *CI = dyn_cast<CastInst>(Pointer))
476 if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
477 if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
478 // convertible types?
479 if (PtrElType->isLosslesslyConvertibleTo(CSPT->getElementType())) {
480 PRINT_PEEPHOLE2("load-src-cast:in ", Pointer, LI);
482 // Create the new load instruction... loading the pre-casted value
483 LoadInst *NewLI = new LoadInst(CastSrc, LI->getName(), BI);
485 // Insert the new T cast instruction... stealing old T's name
486 CastInst *NCI = new CastInst(NewLI, LI->getType(), CI->getName());
488 // Replace the old store with a new one!
489 ReplaceInstWithInst(BB->getInstList(), BI, NCI);
490 PRINT_PEEPHOLE3("load-src-cast:out", NCI, CastSrc, NewLI);
491 ++NumLoadStorePeepholes;
495 } else if (I->getOpcode() == Instruction::Add &&
496 isa<CastInst>(I->getOperand(1))) {
498 if (PeepholeOptimizeAddCast(BB, BI, I->getOperand(0),
499 cast<CastInst>(I->getOperand(1)), TD)) {
503 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
504 // If we have a call with all varargs arguments, convert the call to use the
505 // actual argument types present...
507 const PointerType *PTy = cast<PointerType>(CI->getCalledValue()->getType());
508 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
510 // Is the call to a vararg variable with no real parameters?
511 if (FTy->isVarArg() && FTy->getNumParams() == 0 &&
512 !CI->getCalledFunction()) {
513 // If so, insert a new cast instruction, casting it to a function type
514 // that matches the current arguments...
516 std::vector<const Type *> Params; // Parameter types...
517 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
518 Params.push_back(CI->getOperand(i)->getType());
520 FunctionType *NewFT = FunctionType::get(FTy->getReturnType(),
522 PointerType *NewPFunTy = PointerType::get(NewFT);
524 // Create a new cast, inserting it right before the function call...
526 Constant *ConstantCallSrc = 0;
527 if (Constant *CS = dyn_cast<Constant>(CI->getCalledValue()))
528 ConstantCallSrc = CS;
529 else if (GlobalValue *GV = dyn_cast<GlobalValue>(CI->getCalledValue()))
530 ConstantCallSrc = ConstantPointerRef::get(GV);
533 NewCast = ConstantExpr::getCast(ConstantCallSrc, NewPFunTy);
535 NewCast = new CastInst(CI->getCalledValue(), NewPFunTy,
536 CI->getCalledValue()->getName()+"_c",CI);
538 // Create a new call instruction...
539 CallInst *NewCall = new CallInst(NewCast,
540 std::vector<Value*>(CI->op_begin()+1, CI->op_end()));
542 ReplaceInstWithInst(CI, NewCall);
544 ++NumVarargCallChanges;
556 bool RPR::DoRaisePass(Function &F) {
557 bool Changed = false;
558 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
559 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
560 DEBUG(std::cerr << "Processing: " << *BI);
561 if (dceInstruction(BI) || doConstantPropagation(BI)) {
564 DEBUG(std::cerr << "***\t\t^^-- Dead code eliminated!\n");
565 } else if (PeepholeOptimize(BB, BI)) {
576 // runOnFunction - Raise a function representation to a higher level.
577 bool RPR::runOnFunction(Function &F) {
578 DEBUG(std::cerr << "\n\n\nStarting to work on Function '" << F.getName()
581 // Insert casts for all incoming pointer pointer values that are treated as
584 bool Changed = false, LocalChange;
586 // If the StartInst option was specified, then Peephole optimize that
587 // instruction first if it occurs in this function.
589 if (!StartInst.empty()) {
590 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
591 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI)
592 if (BI->getName() == StartInst) {
593 bool SavedDebug = DebugFlag; // Save the DEBUG() controlling flag.
594 DebugFlag = true; // Turn on DEBUG's
595 Changed |= PeepholeOptimize(BB, BI);
596 DebugFlag = SavedDebug; // Restore DebugFlag to previous state
601 DEBUG(std::cerr << "Looping: \n" << F);
603 // Iterate over the function, refining it, until it converges on a stable
606 while (DoRaisePass(F)) LocalChange = true;
607 Changed |= LocalChange;
609 } while (LocalChange);