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/RaisePointerReferences.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/STLExtras.h"
20 #include "Support/Statistic.h"
21 #include "Support/CommandLine.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()->isLosslesslyConvertableTo(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
111 // instructions. If we have non-adds, do not make this transformation.
113 for (Value::use_iterator I = CI.use_begin(), E = CI.use_end();
115 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(*I)) {
116 if (BO->getOpcode() != Instruction::Add ||
117 // Avoid add sbyte* %X, %X cases...
118 BO->getOperand(0) == BO->getOperand(1))
125 std::vector<Value*> Indices;
126 Value *Src = CI.getOperand(0);
127 const Type *Result = ConvertableToGEP(DestPTy, Src, Indices, TD, &BI);
128 if (Result == 0) return false; // Not convertable...
130 PRINT_PEEPHOLE2("cast-add-to-gep:in", Src, CI);
132 // If we have a getelementptr capability... transform all of the
133 // add instruction uses into getelementptr's.
134 while (!CI.use_empty()) {
135 BinaryOperator *I = cast<BinaryOperator>(*CI.use_begin());
136 assert(I->getOpcode() == Instruction::Add && I->getNumOperands() == 2 &&
137 "Use is not a valid add instruction!");
139 // Get the value added to the cast result pointer...
140 Value *OtherPtr = I->getOperand((I->getOperand(0) == &CI) ? 1 : 0);
142 Instruction *GEP = new GetElementPtrInst(OtherPtr, Indices, I->getName());
143 PRINT_PEEPHOLE1("cast-add-to-gep:i", I);
145 if (GEP->getType() == I->getType()) {
146 // Replace the old add instruction with the shiny new GEP inst
147 ReplaceInstWithInst(I, GEP);
149 // If the type produced by the gep instruction differs from the original
150 // add instruction type, insert a cast now.
153 // Insert the GEP instruction before the old add instruction...
154 I->getParent()->getInstList().insert(I, GEP);
156 PRINT_PEEPHOLE1("cast-add-to-gep:o", GEP);
157 GEP = new CastInst(GEP, I->getType());
159 // Replace the old add instruction with the shiny new GEP inst
160 ReplaceInstWithInst(I, GEP);
163 PRINT_PEEPHOLE1("cast-add-to-gep:o", GEP);
168 // Peephole optimize the following instructions:
169 // %t1 = cast ulong <const int> to {<...>} *
170 // %t2 = add {<...>} * %SP, %t1 ;; Constant must be 2nd operand
173 // %t1 = cast {<...>}* %SP to int*
174 // %t5 = cast ulong <const int> to int*
175 // %t2 = add int* %t1, %t5 ;; int is same size as field
177 // Into: %t3 = getelementptr {<...>} * %SP, <element indices>
178 // %t2 = cast <eltype> * %t3 to {<...>}*
180 static bool PeepholeOptimizeAddCast(BasicBlock *BB, BasicBlock::iterator &BI,
181 Value *AddOp1, CastInst *AddOp2,
182 const TargetData &TD) {
183 const CompositeType *CompTy;
184 Value *OffsetVal = AddOp2->getOperand(0);
185 Value *SrcPtr = 0; // Of type pointer to struct...
187 if ((CompTy = getPointedToComposite(AddOp1->getType()))) {
188 SrcPtr = AddOp1; // Handle the first case...
189 } else if (CastInst *AddOp1c = dyn_cast<CastInst>(AddOp1)) {
190 SrcPtr = AddOp1c->getOperand(0); // Handle the second case...
191 CompTy = getPointedToComposite(SrcPtr->getType());
194 // Only proceed if we have detected all of our conditions successfully...
195 if (!CompTy || !SrcPtr || !OffsetVal->getType()->isInteger())
198 std::vector<Value*> Indices;
199 if (!ConvertableToGEP(SrcPtr->getType(), OffsetVal, Indices, TD, &BI))
200 return false; // Not convertable... perhaps next time
202 if (getPointedToComposite(AddOp1->getType())) { // case 1
203 PRINT_PEEPHOLE2("add-to-gep1:in", AddOp2, *BI);
205 PRINT_PEEPHOLE3("add-to-gep2:in", AddOp1, AddOp2, *BI);
208 GetElementPtrInst *GEP = new GetElementPtrInst(SrcPtr, Indices,
209 AddOp2->getName(), BI);
211 Instruction *NCI = new CastInst(GEP, AddOp1->getType());
212 ReplaceInstWithInst(BB->getInstList(), BI, NCI);
213 PRINT_PEEPHOLE2("add-to-gep:out", GEP, NCI);
217 bool RPR::PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI) {
219 const TargetData &TD = getAnalysis<TargetData>();
221 if (CastInst *CI = dyn_cast<CastInst>(I)) {
222 Value *Src = CI->getOperand(0);
223 Instruction *SrcI = dyn_cast<Instruction>(Src); // Nonnull if instr source
224 const Type *DestTy = CI->getType();
226 // Peephole optimize the following instruction:
227 // %V2 = cast <ty> %V to <ty>
231 if (DestTy == Src->getType()) { // Check for a cast to same type as src!!
232 PRINT_PEEPHOLE1("cast-of-self-ty", CI);
233 CI->replaceAllUsesWith(Src);
234 if (!Src->hasName() && CI->hasName()) {
235 std::string Name = CI->getName();
237 Src->setName(Name, &BB->getParent()->getSymbolTable());
240 // DCE the instruction now, to avoid having the iterative version of DCE
241 // have to worry about it.
243 BI = BB->getInstList().erase(BI);
249 // Check to see if it's a cast of an instruction that does not depend on the
250 // specific type of the operands to do it's job.
251 if (!isReinterpretingCast(CI)) {
252 ValueTypeCache ConvertedTypes;
254 // Check to see if we can convert the source of the cast to match the
255 // destination type of the cast...
257 ConvertedTypes[CI] = CI->getType(); // Make sure the cast doesn't change
258 if (ExpressionConvertableToType(Src, DestTy, ConvertedTypes, TD)) {
259 PRINT_PEEPHOLE3("CAST-SRC-EXPR-CONV:in ", Src, CI, BB->getParent());
261 DEBUG(cerr << "\nCONVERTING SRC EXPR TYPE:\n");
262 { // ValueMap must be destroyed before function verified!
263 ValueMapCache ValueMap;
264 Value *E = ConvertExpressionToType(Src, DestTy, ValueMap, TD);
266 if (Constant *CPV = dyn_cast<Constant>(E))
267 CI->replaceAllUsesWith(CPV);
269 PRINT_PEEPHOLE1("CAST-SRC-EXPR-CONV:out", E);
270 DEBUG(cerr << "DONE CONVERTING SRC EXPR TYPE: \n" << BB->getParent());
273 DEBUG(assert(verifyFunction(*BB->getParent()) == false &&
274 "Function broken!"));
275 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
280 // Check to see if we can convert the users of the cast value to match the
281 // source type of the cast...
283 ConvertedTypes.clear();
284 // Make sure the source doesn't change type
285 ConvertedTypes[Src] = Src->getType();
286 if (ValueConvertableToType(CI, Src->getType(), ConvertedTypes, TD)) {
287 PRINT_PEEPHOLE3("CAST-DEST-EXPR-CONV:in ", Src, CI, BB->getParent());
289 DEBUG(cerr << "\nCONVERTING EXPR TYPE:\n");
290 { // ValueMap must be destroyed before function verified!
291 ValueMapCache ValueMap;
292 ConvertValueToNewType(CI, Src, ValueMap, TD); // This will delete CI!
295 PRINT_PEEPHOLE1("CAST-DEST-EXPR-CONV:out", Src);
296 DEBUG(cerr << "DONE CONVERTING EXPR TYPE: \n\n" << BB->getParent());
298 DEBUG(assert(verifyFunction(*BB->getParent()) == false &&
299 "Function broken!"));
300 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
306 // Otherwise find out it this cast is a cast to a pointer type, which is
307 // then added to some other pointer, then loaded or stored through. If
308 // so, convert the add into a getelementptr instruction...
310 if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
311 if (HandleCastToPointer(BI, DestPTy, TD)) {
312 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
318 // Check to see if we are casting from a structure pointer to a pointer to
319 // the first element of the structure... to avoid munching other peepholes,
320 // we only let this happen if there are no add uses of the cast.
322 // Peephole optimize the following instructions:
323 // %t1 = cast {<...>} * %StructPtr to <ty> *
325 // Into: %t2 = getelementptr {<...>} * %StructPtr, <0, 0, 0, ...>
326 // %t1 = cast <eltype> * %t1 to <ty> *
328 if (const CompositeType *CTy = getPointedToComposite(Src->getType()))
329 if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
331 // Loop over uses of the cast, checking for add instructions. If an add
332 // exists, this is probably a part of a more complex GEP, so we don't
333 // want to mess around with the cast.
335 bool HasAddUse = false;
336 for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
338 if (isa<Instruction>(*I) &&
339 cast<Instruction>(*I)->getOpcode() == Instruction::Add) {
340 HasAddUse = true; break;
343 // If it doesn't have an add use, check to see if the dest type is
344 // losslessly convertable to one of the types in the start of the struct
348 const Type *DestPointedTy = DestPTy->getElementType();
350 const CompositeType *CurCTy = CTy;
351 const Type *ElTy = 0;
353 // Build the index vector, full of all zeros
354 std::vector<Value*> Indices;
355 Indices.push_back(ConstantSInt::get(Type::LongTy, 0));
356 while (CurCTy && !isa<PointerType>(CurCTy)) {
357 if (const StructType *CurSTy = dyn_cast<StructType>(CurCTy)) {
358 // Check for a zero element struct type... if we have one, bail.
359 if (CurSTy->getElementTypes().size() == 0) break;
361 // Grab the first element of the struct type, which must lie at
362 // offset zero in the struct.
364 ElTy = CurSTy->getElementTypes()[0];
366 ElTy = cast<ArrayType>(CurCTy)->getElementType();
369 // Insert a zero to index through this type...
370 Indices.push_back(Constant::getNullValue(CurCTy->getIndexType()));
372 // Did we find what we're looking for?
373 if (ElTy->isLosslesslyConvertableTo(DestPointedTy)) break;
375 // Nope, go a level deeper.
377 CurCTy = dyn_cast<CompositeType>(ElTy);
381 // Did we find what we were looking for? If so, do the transformation
383 PRINT_PEEPHOLE1("cast-for-first:in", CI);
385 std::string Name = CI->getName(); CI->setName("");
387 // Insert the new T cast instruction... stealing old T's name
388 GetElementPtrInst *GEP = new GetElementPtrInst(Src, Indices,
391 // Make the old cast instruction reference the new GEP instead of
392 // the old src value.
394 CI->setOperand(0, GEP);
396 PRINT_PEEPHOLE2("cast-for-first:out", GEP, CI);
403 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
404 Value *Val = SI->getOperand(0);
405 Value *Pointer = SI->getPointerOperand();
407 // Peephole optimize the following instructions:
408 // %t = cast <T1>* %P to <T2> * ;; If T1 is losslessly convertable to T2
409 // store <T2> %V, <T2>* %t
412 // %t = cast <T2> %V to <T1>
413 // store <T1> %t2, <T1>* %P
415 // Note: This is not taken care of by expr conversion because there might
416 // not be a cast available for the store to convert the incoming value of.
417 // This code is basically here to make sure that pointers don't have casts
420 if (CastInst *CI = dyn_cast<CastInst>(Pointer))
421 if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
422 if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
423 // convertable types?
424 if (Val->getType()->isLosslesslyConvertableTo(CSPT->getElementType())) {
425 PRINT_PEEPHOLE3("st-src-cast:in ", Pointer, Val, SI);
427 // Insert the new T cast instruction... stealing old T's name
428 std::string Name(CI->getName()); CI->setName("");
429 CastInst *NCI = new CastInst(Val, CSPT->getElementType(),
432 // Replace the old store with a new one!
433 ReplaceInstWithInst(BB->getInstList(), BI,
434 SI = new StoreInst(NCI, CastSrc));
435 PRINT_PEEPHOLE3("st-src-cast:out", NCI, CastSrc, SI);
436 ++NumLoadStorePeepholes;
440 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
441 Value *Pointer = LI->getOperand(0);
442 const Type *PtrElType =
443 cast<PointerType>(Pointer->getType())->getElementType();
445 // Peephole optimize the following instructions:
446 // %Val = cast <T1>* to <T2>* ;; If T1 is losslessly convertable to T2
447 // %t = load <T2>* %P
450 // %t = load <T1>* %P
451 // %Val = cast <T1> to <T2>
453 // Note: This is not taken care of by expr conversion because there might
454 // not be a cast available for the store to convert the incoming value of.
455 // This code is basically here to make sure that pointers don't have casts
458 if (CastInst *CI = dyn_cast<CastInst>(Pointer))
459 if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
460 if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
461 // convertable types?
462 if (PtrElType->isLosslesslyConvertableTo(CSPT->getElementType())) {
463 PRINT_PEEPHOLE2("load-src-cast:in ", Pointer, LI);
465 // Create the new load instruction... loading the pre-casted value
466 LoadInst *NewLI = new LoadInst(CastSrc, LI->getName(), BI);
468 // Insert the new T cast instruction... stealing old T's name
469 CastInst *NCI = new CastInst(NewLI, LI->getType(), CI->getName());
471 // Replace the old store with a new one!
472 ReplaceInstWithInst(BB->getInstList(), BI, NCI);
473 PRINT_PEEPHOLE3("load-src-cast:out", NCI, CastSrc, NewLI);
474 ++NumLoadStorePeepholes;
478 } else if (I->getOpcode() == Instruction::Add &&
479 isa<CastInst>(I->getOperand(1))) {
481 if (PeepholeOptimizeAddCast(BB, BI, I->getOperand(0),
482 cast<CastInst>(I->getOperand(1)), TD)) {
486 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
487 // If we have a call with all varargs arguments, convert the call to use the
488 // actual argument types present...
490 const PointerType *PTy = cast<PointerType>(CI->getCalledValue()->getType());
491 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
493 // Is the call to a vararg variable with no real parameters?
494 if (FTy->isVarArg() && FTy->getNumParams() == 0) {
495 // If so, insert a new cast instruction, casting it to a function type
496 // that matches the current arguments...
498 std::vector<const Type *> Params; // Parameter types...
499 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
500 Params.push_back(CI->getOperand(i)->getType());
502 FunctionType *NewFT = FunctionType::get(FTy->getReturnType(),
504 PointerType *NewPFunTy = PointerType::get(NewFT);
506 // Create a new cast, inserting it right before the function call...
507 CastInst *NewCast = new CastInst(CI->getCalledValue(), NewPFunTy,
508 CI->getCalledValue()->getName()+"_c",CI);
510 // Create a new call instruction...
511 CallInst *NewCall = new CallInst(NewCast,
512 std::vector<Value*>(CI->op_begin()+1, CI->op_end()));
514 ReplaceInstWithInst(CI, NewCall);
516 ++NumVarargCallChanges;
528 bool RPR::DoRaisePass(Function &F) {
529 bool Changed = false;
530 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
531 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
532 DEBUG(cerr << "Processing: " << *BI);
533 if (dceInstruction(BI) || doConstantPropogation(BI)) {
536 DEBUG(cerr << "***\t\t^^-- Dead code eliminated!\n");
537 } else if (PeepholeOptimize(BB, BI)) {
548 // runOnFunction - Raise a function representation to a higher level.
549 bool RPR::runOnFunction(Function &F) {
550 DEBUG(cerr << "\n\n\nStarting to work on Function '" << F.getName() << "'\n");
552 // Insert casts for all incoming pointer pointer values that are treated as
555 bool Changed = false, LocalChange;
557 // If the StartInst option was specified, then Peephole optimize that
558 // instruction first if it occurs in this function.
560 if (!StartInst.empty()) {
561 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
562 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI)
563 if (BI->getName() == StartInst) {
564 bool SavedDebug = DebugFlag; // Save the DEBUG() controlling flag.
565 DebugFlag = true; // Turn on DEBUG's
566 Changed |= PeepholeOptimize(BB, BI);
567 DebugFlag = SavedDebug; // Restore DebugFlag to previous state
572 DEBUG(cerr << "Looping: \n" << F);
574 // Iterate over the function, refining it, until it converges on a stable
577 while (DoRaisePass(F)) LocalChange = true;
578 Changed |= LocalChange;
580 } while (LocalChange);