1 //===- LevelRaise.cpp - Code to change LLVM to higher level ---------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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
14 //===----------------------------------------------------------------------===//
16 #include "llvm/Transforms/Scalar.h"
17 #include "llvm/Transforms/Utils/Local.h"
18 #include "TransformInternals.h"
19 #include "llvm/iOther.h"
20 #include "llvm/iMemory.h"
21 #include "llvm/Pass.h"
22 #include "llvm/ConstantHandling.h"
23 #include "llvm/Analysis/Expressions.h"
24 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
25 #include "Support/CommandLine.h"
26 #include "Support/Debug.h"
27 #include "Support/Statistic.h"
28 #include "Support/STLExtras.h"
33 // StartInst - This enables the -raise-start-inst=foo option to cause the level
34 // raising pass to start at instruction "foo", which is immensely useful for
37 static cl::opt<std::string>
38 StartInst("raise-start-inst", cl::Hidden, cl::value_desc("inst name"),
39 cl::desc("Start raise pass at the instruction with the specified name"));
42 NumLoadStorePeepholes("raise", "Number of load/store peepholes");
45 NumGEPInstFormed("raise", "Number of other getelementptr's formed");
48 NumExprTreesConv("raise", "Number of expression trees converted");
51 NumCastOfCast("raise", "Number of cast-of-self removed");
54 NumDCEorCP("raise", "Number of insts DCEd or constprop'd");
57 NumVarargCallChanges("raise", "Number of vararg call peepholes");
59 #define PRINT_PEEPHOLE(ID, NUM, I) \
60 DEBUG(std::cerr << "Inst P/H " << ID << "[" << NUM << "] " << I)
62 #define PRINT_PEEPHOLE1(ID, I1) do { PRINT_PEEPHOLE(ID, 0, I1); } while (0)
63 #define PRINT_PEEPHOLE2(ID, I1, I2) \
64 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); } while (0)
65 #define PRINT_PEEPHOLE3(ID, I1, I2, I3) \
66 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
67 PRINT_PEEPHOLE(ID, 2, I3); } while (0)
68 #define PRINT_PEEPHOLE4(ID, I1, I2, I3, I4) \
69 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
70 PRINT_PEEPHOLE(ID, 2, I3); PRINT_PEEPHOLE(ID, 3, I4); } while (0)
73 struct RPR : public FunctionPass {
74 virtual bool runOnFunction(Function &F);
76 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
78 AU.addRequired<TargetData>();
82 bool DoRaisePass(Function &F);
83 bool PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI);
86 RegisterOpt<RPR> X("raise", "Raise Pointer References");
90 Pass *createRaisePointerReferencesPass() {
95 // isReinterpretingCast - Return true if the cast instruction specified will
96 // cause the operand to be "reinterpreted". A value is reinterpreted if the
97 // cast instruction would cause the underlying bits to change.
99 static inline bool isReinterpretingCast(const CastInst *CI) {
100 return!CI->getOperand(0)->getType()->isLosslesslyConvertibleTo(CI->getType());
104 // Peephole optimize the following instructions:
105 // %t1 = cast ? to x *
106 // %t2 = add x * %SP, %t1 ;; Constant must be 2nd operand
108 // Into: %t3 = getelementptr {<...>} * %SP, <element indices>
109 // %t2 = cast <eltype> * %t3 to {<...>}*
111 static bool HandleCastToPointer(BasicBlock::iterator BI,
112 const PointerType *DestPTy,
113 const TargetData &TD) {
114 CastInst &CI = cast<CastInst>(*BI);
115 if (CI.use_empty()) return false;
117 // Scan all of the uses, looking for any uses that are not add or sub
118 // instructions. If we have non-adds, do not make this transformation.
120 bool HasSubUse = false; // Keep track of any subtracts...
121 for (Value::use_iterator I = CI.use_begin(), E = CI.use_end();
123 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(*I)) {
124 if ((BO->getOpcode() != Instruction::Add &&
125 BO->getOpcode() != Instruction::Sub) ||
126 // Avoid add sbyte* %X, %X cases...
127 BO->getOperand(0) == BO->getOperand(1))
130 HasSubUse |= BO->getOpcode() == Instruction::Sub;
135 std::vector<Value*> Indices;
136 Value *Src = CI.getOperand(0);
137 const Type *Result = ConvertibleToGEP(DestPTy, Src, Indices, TD, &BI);
138 if (Result == 0) return false; // Not convertible...
140 // Cannot handle subtracts if there is more than one index required...
141 if (HasSubUse && Indices.size() != 1) return false;
143 PRINT_PEEPHOLE2("cast-add-to-gep:in", Src, CI);
145 // If we have a getelementptr capability... transform all of the
146 // add instruction uses into getelementptr's.
147 while (!CI.use_empty()) {
148 BinaryOperator *I = cast<BinaryOperator>(*CI.use_begin());
149 assert((I->getOpcode() == Instruction::Add ||
150 I->getOpcode() == Instruction::Sub) &&
151 "Use is not a valid add instruction!");
153 // Get the value added to the cast result pointer...
154 Value *OtherPtr = I->getOperand((I->getOperand(0) == &CI) ? 1 : 0);
156 Instruction *GEP = new GetElementPtrInst(OtherPtr, Indices, I->getName());
157 PRINT_PEEPHOLE1("cast-add-to-gep:i", I);
159 // If the instruction is actually a subtract, we are guaranteed to only have
160 // one index (from code above), so we just need to negate the pointer index
162 if (I->getOpcode() == Instruction::Sub) {
163 Instruction *Neg = BinaryOperator::createNeg(GEP->getOperand(1),
164 GEP->getOperand(1)->getName()+".neg", I);
165 GEP->setOperand(1, Neg);
168 if (GEP->getType() == I->getType()) {
169 // Replace the old add instruction with the shiny new GEP inst
170 ReplaceInstWithInst(I, GEP);
172 // If the type produced by the gep instruction differs from the original
173 // add instruction type, insert a cast now.
176 // Insert the GEP instruction before the old add instruction...
177 I->getParent()->getInstList().insert(I, GEP);
179 PRINT_PEEPHOLE1("cast-add-to-gep:o", GEP);
180 GEP = new CastInst(GEP, I->getType());
182 // Replace the old add instruction with the shiny new GEP inst
183 ReplaceInstWithInst(I, GEP);
186 PRINT_PEEPHOLE1("cast-add-to-gep:o", GEP);
191 // Peephole optimize the following instructions:
192 // %t1 = cast ulong <const int> to {<...>} *
193 // %t2 = add {<...>} * %SP, %t1 ;; Constant must be 2nd operand
196 // %t1 = cast {<...>}* %SP to int*
197 // %t5 = cast ulong <const int> to int*
198 // %t2 = add int* %t1, %t5 ;; int is same size as field
200 // Into: %t3 = getelementptr {<...>} * %SP, <element indices>
201 // %t2 = cast <eltype> * %t3 to {<...>}*
203 static bool PeepholeOptimizeAddCast(BasicBlock *BB, BasicBlock::iterator &BI,
204 Value *AddOp1, CastInst *AddOp2,
205 const TargetData &TD) {
206 const CompositeType *CompTy;
207 Value *OffsetVal = AddOp2->getOperand(0);
208 Value *SrcPtr = 0; // Of type pointer to struct...
210 if ((CompTy = getPointedToComposite(AddOp1->getType()))) {
211 SrcPtr = AddOp1; // Handle the first case...
212 } else if (CastInst *AddOp1c = dyn_cast<CastInst>(AddOp1)) {
213 SrcPtr = AddOp1c->getOperand(0); // Handle the second case...
214 CompTy = getPointedToComposite(SrcPtr->getType());
217 // Only proceed if we have detected all of our conditions successfully...
218 if (!CompTy || !SrcPtr || !OffsetVal->getType()->isInteger())
221 std::vector<Value*> Indices;
222 if (!ConvertibleToGEP(SrcPtr->getType(), OffsetVal, Indices, TD, &BI))
223 return false; // Not convertible... perhaps next time
225 if (getPointedToComposite(AddOp1->getType())) { // case 1
226 PRINT_PEEPHOLE2("add-to-gep1:in", AddOp2, *BI);
228 PRINT_PEEPHOLE3("add-to-gep2:in", AddOp1, AddOp2, *BI);
231 GetElementPtrInst *GEP = new GetElementPtrInst(SrcPtr, Indices,
232 AddOp2->getName(), BI);
234 Instruction *NCI = new CastInst(GEP, AddOp1->getType());
235 ReplaceInstWithInst(BB->getInstList(), BI, NCI);
236 PRINT_PEEPHOLE2("add-to-gep:out", GEP, NCI);
240 bool RPR::PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI) {
242 const TargetData &TD = getAnalysis<TargetData>();
244 if (CastInst *CI = dyn_cast<CastInst>(I)) {
245 Value *Src = CI->getOperand(0);
246 Instruction *SrcI = dyn_cast<Instruction>(Src); // Nonnull if instr source
247 const Type *DestTy = CI->getType();
249 // Peephole optimize the following instruction:
250 // %V2 = cast <ty> %V to <ty>
254 if (DestTy == Src->getType()) { // Check for a cast to same type as src!!
255 PRINT_PEEPHOLE1("cast-of-self-ty", CI);
256 CI->replaceAllUsesWith(Src);
257 if (!Src->hasName() && CI->hasName()) {
258 std::string Name = CI->getName();
260 Src->setName(Name, &BB->getParent()->getSymbolTable());
263 // DCE the instruction now, to avoid having the iterative version of DCE
264 // have to worry about it.
266 BI = BB->getInstList().erase(BI);
272 // Check to see if it's a cast of an instruction that does not depend on the
273 // specific type of the operands to do it's job.
274 if (!isReinterpretingCast(CI)) {
275 ValueTypeCache ConvertedTypes;
277 // Check to see if we can convert the source of the cast to match the
278 // destination type of the cast...
280 ConvertedTypes[CI] = CI->getType(); // Make sure the cast doesn't change
281 if (ExpressionConvertibleToType(Src, DestTy, ConvertedTypes, TD)) {
282 PRINT_PEEPHOLE3("CAST-SRC-EXPR-CONV:in ", Src, CI, BB->getParent());
284 DEBUG(std::cerr << "\nCONVERTING SRC EXPR TYPE:\n");
285 { // ValueMap must be destroyed before function verified!
286 ValueMapCache ValueMap;
287 Value *E = ConvertExpressionToType(Src, DestTy, ValueMap, TD);
289 if (Constant *CPV = dyn_cast<Constant>(E))
290 CI->replaceAllUsesWith(CPV);
292 PRINT_PEEPHOLE1("CAST-SRC-EXPR-CONV:out", E);
293 DEBUG(std::cerr << "DONE CONVERTING SRC EXPR TYPE: \n"
297 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
302 // Check to see if we can convert the users of the cast value to match the
303 // source type of the cast...
305 ConvertedTypes.clear();
306 // Make sure the source doesn't change type
307 ConvertedTypes[Src] = Src->getType();
308 if (ValueConvertibleToType(CI, Src->getType(), ConvertedTypes, TD)) {
309 PRINT_PEEPHOLE3("CAST-DEST-EXPR-CONV:in ", Src, CI, BB->getParent());
311 DEBUG(std::cerr << "\nCONVERTING EXPR TYPE:\n");
312 { // ValueMap must be destroyed before function verified!
313 ValueMapCache ValueMap;
314 ConvertValueToNewType(CI, Src, ValueMap, TD); // This will delete CI!
317 PRINT_PEEPHOLE1("CAST-DEST-EXPR-CONV:out", Src);
318 DEBUG(std::cerr << "DONE CONVERTING EXPR TYPE: \n\n" << BB->getParent());
320 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
326 // Otherwise find out it this cast is a cast to a pointer type, which is
327 // then added to some other pointer, then loaded or stored through. If
328 // so, convert the add into a getelementptr instruction...
330 if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
331 if (HandleCastToPointer(BI, DestPTy, TD)) {
332 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
338 // Check to see if we are casting from a structure pointer to a pointer to
339 // the first element of the structure... to avoid munching other peepholes,
340 // we only let this happen if there are no add uses of the cast.
342 // Peephole optimize the following instructions:
343 // %t1 = cast {<...>} * %StructPtr to <ty> *
345 // Into: %t2 = getelementptr {<...>} * %StructPtr, <0, 0, 0, ...>
346 // %t1 = cast <eltype> * %t1 to <ty> *
348 if (const CompositeType *CTy = getPointedToComposite(Src->getType()))
349 if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
351 // Loop over uses of the cast, checking for add instructions. If an add
352 // exists, this is probably a part of a more complex GEP, so we don't
353 // want to mess around with the cast.
355 bool HasAddUse = false;
356 for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
358 if (isa<Instruction>(*I) &&
359 cast<Instruction>(*I)->getOpcode() == Instruction::Add) {
360 HasAddUse = true; break;
363 // If it doesn't have an add use, check to see if the dest type is
364 // losslessly convertible to one of the types in the start of the struct
368 const Type *DestPointedTy = DestPTy->getElementType();
370 const CompositeType *CurCTy = CTy;
371 const Type *ElTy = 0;
373 // Build the index vector, full of all zeros
374 std::vector<Value*> Indices;
375 Indices.push_back(ConstantSInt::get(Type::LongTy, 0));
376 while (CurCTy && !isa<PointerType>(CurCTy)) {
377 if (const StructType *CurSTy = dyn_cast<StructType>(CurCTy)) {
378 // Check for a zero element struct type... if we have one, bail.
379 if (CurSTy->getElementTypes().size() == 0) break;
381 // Grab the first element of the struct type, which must lie at
382 // offset zero in the struct.
384 ElTy = CurSTy->getElementTypes()[0];
386 ElTy = cast<ArrayType>(CurCTy)->getElementType();
389 // Insert a zero to index through this type...
390 Indices.push_back(Constant::getNullValue(CurCTy->getIndexType()));
392 // Did we find what we're looking for?
393 if (ElTy->isLosslesslyConvertibleTo(DestPointedTy)) break;
395 // Nope, go a level deeper.
397 CurCTy = dyn_cast<CompositeType>(ElTy);
401 // Did we find what we were looking for? If so, do the transformation
403 PRINT_PEEPHOLE1("cast-for-first:in", CI);
405 std::string Name = CI->getName(); CI->setName("");
407 // Insert the new T cast instruction... stealing old T's name
408 GetElementPtrInst *GEP = new GetElementPtrInst(Src, Indices,
411 // Make the old cast instruction reference the new GEP instead of
412 // the old src value.
414 CI->setOperand(0, GEP);
416 PRINT_PEEPHOLE2("cast-for-first:out", GEP, CI);
423 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
424 Value *Val = SI->getOperand(0);
425 Value *Pointer = SI->getPointerOperand();
427 // Peephole optimize the following instructions:
428 // %t = cast <T1>* %P to <T2> * ;; If T1 is losslessly convertible to T2
429 // store <T2> %V, <T2>* %t
432 // %t = cast <T2> %V to <T1>
433 // store <T1> %t2, <T1>* %P
435 // Note: This is not taken care of by expr conversion because there might
436 // not be a cast available for the store to convert the incoming value of.
437 // This code is basically here to make sure that pointers don't have casts
440 if (CastInst *CI = dyn_cast<CastInst>(Pointer))
441 if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
442 if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
443 // convertible types?
444 if (Val->getType()->isLosslesslyConvertibleTo(CSPT->getElementType())) {
445 PRINT_PEEPHOLE3("st-src-cast:in ", Pointer, Val, SI);
447 // Insert the new T cast instruction... stealing old T's name
448 std::string Name(CI->getName()); CI->setName("");
449 CastInst *NCI = new CastInst(Val, CSPT->getElementType(),
452 // Replace the old store with a new one!
453 ReplaceInstWithInst(BB->getInstList(), BI,
454 SI = new StoreInst(NCI, CastSrc));
455 PRINT_PEEPHOLE3("st-src-cast:out", NCI, CastSrc, SI);
456 ++NumLoadStorePeepholes;
460 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
461 Value *Pointer = LI->getOperand(0);
462 const Type *PtrElType =
463 cast<PointerType>(Pointer->getType())->getElementType();
465 // Peephole optimize the following instructions:
466 // %Val = cast <T1>* to <T2>* ;; If T1 is losslessly convertible to T2
467 // %t = load <T2>* %P
470 // %t = load <T1>* %P
471 // %Val = cast <T1> to <T2>
473 // Note: This is not taken care of by expr conversion because there might
474 // not be a cast available for the store to convert the incoming value of.
475 // This code is basically here to make sure that pointers don't have casts
478 if (CastInst *CI = dyn_cast<CastInst>(Pointer))
479 if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
480 if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
481 // convertible types?
482 if (PtrElType->isLosslesslyConvertibleTo(CSPT->getElementType())) {
483 PRINT_PEEPHOLE2("load-src-cast:in ", Pointer, LI);
485 // Create the new load instruction... loading the pre-casted value
486 LoadInst *NewLI = new LoadInst(CastSrc, LI->getName(), BI);
488 // Insert the new T cast instruction... stealing old T's name
489 CastInst *NCI = new CastInst(NewLI, LI->getType(), CI->getName());
491 // Replace the old store with a new one!
492 ReplaceInstWithInst(BB->getInstList(), BI, NCI);
493 PRINT_PEEPHOLE3("load-src-cast:out", NCI, CastSrc, NewLI);
494 ++NumLoadStorePeepholes;
498 } else if (I->getOpcode() == Instruction::Add &&
499 isa<CastInst>(I->getOperand(1))) {
501 if (PeepholeOptimizeAddCast(BB, BI, I->getOperand(0),
502 cast<CastInst>(I->getOperand(1)), TD)) {
506 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
507 // If we have a call with all varargs arguments, convert the call to use the
508 // actual argument types present...
510 const PointerType *PTy = cast<PointerType>(CI->getCalledValue()->getType());
511 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
513 // Is the call to a vararg variable with no real parameters?
514 if (FTy->isVarArg() && FTy->getNumParams() == 0 &&
515 !CI->getCalledFunction()) {
516 // If so, insert a new cast instruction, casting it to a function type
517 // that matches the current arguments...
519 std::vector<const Type *> Params; // Parameter types...
520 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
521 Params.push_back(CI->getOperand(i)->getType());
523 FunctionType *NewFT = FunctionType::get(FTy->getReturnType(),
525 PointerType *NewPFunTy = PointerType::get(NewFT);
527 // Create a new cast, inserting it right before the function call...
529 Constant *ConstantCallSrc = 0;
530 if (Constant *CS = dyn_cast<Constant>(CI->getCalledValue()))
531 ConstantCallSrc = CS;
532 else if (GlobalValue *GV = dyn_cast<GlobalValue>(CI->getCalledValue()))
533 ConstantCallSrc = ConstantPointerRef::get(GV);
536 NewCast = ConstantExpr::getCast(ConstantCallSrc, NewPFunTy);
538 NewCast = new CastInst(CI->getCalledValue(), NewPFunTy,
539 CI->getCalledValue()->getName()+"_c",CI);
541 // Create a new call instruction...
542 CallInst *NewCall = new CallInst(NewCast,
543 std::vector<Value*>(CI->op_begin()+1, CI->op_end()));
545 ReplaceInstWithInst(CI, NewCall);
547 ++NumVarargCallChanges;
559 bool RPR::DoRaisePass(Function &F) {
560 bool Changed = false;
561 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
562 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
563 DEBUG(std::cerr << "Processing: " << *BI);
564 if (dceInstruction(BI) || doConstantPropagation(BI)) {
567 DEBUG(std::cerr << "***\t\t^^-- Dead code eliminated!\n");
568 } else if (PeepholeOptimize(BB, BI)) {
579 // runOnFunction - Raise a function representation to a higher level.
580 bool RPR::runOnFunction(Function &F) {
581 DEBUG(std::cerr << "\n\n\nStarting to work on Function '" << F.getName()
584 // Insert casts for all incoming pointer pointer values that are treated as
587 bool Changed = false, LocalChange;
589 // If the StartInst option was specified, then Peephole optimize that
590 // instruction first if it occurs in this function.
592 if (!StartInst.empty()) {
593 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
594 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI)
595 if (BI->getName() == StartInst) {
596 bool SavedDebug = DebugFlag; // Save the DEBUG() controlling flag.
597 DebugFlag = true; // Turn on DEBUG's
598 Changed |= PeepholeOptimize(BB, BI);
599 DebugFlag = SavedDebug; // Restore DebugFlag to previous state
604 DEBUG(std::cerr << "Looping: \n" << F);
606 // Iterate over the function, refining it, until it converges on a stable
609 while (DoRaisePass(F)) LocalChange = true;
610 Changed |= LocalChange;
612 } while (LocalChange);
617 } // End llvm namespace