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/LevelChange.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/Transforms/Utils/BasicBlockUtils.h"
18 #include "Support/STLExtras.h"
19 #include "Support/StatisticReporter.h"
22 static Statistic<> NumLoadStorePeepholes("raise\t\t- Number of load/store peepholes");
23 static Statistic<> NumGEPInstFormed("raise\t\t- Number of other getelementptr's formed");
24 static Statistic<> NumExprTreesConv("raise\t\t- Number of expression trees converted");
25 static Statistic<> NumCastOfCast("raise\t\t- Number of cast-of-self removed");
26 static Statistic<> NumDCEorCP("raise\t\t- Number of insts DCE'd or constprop'd");
29 //#define DEBUG_PEEPHOLE_INSTS 1
31 #ifdef DEBUG_PEEPHOLE_INSTS
32 #define PRINT_PEEPHOLE(ID, NUM, I) \
33 std::cerr << "Inst P/H " << ID << "[" << NUM << "] " << I;
35 #define PRINT_PEEPHOLE(ID, NUM, I)
38 #define PRINT_PEEPHOLE1(ID, I1) do { PRINT_PEEPHOLE(ID, 0, I1); } while (0)
39 #define PRINT_PEEPHOLE2(ID, I1, I2) \
40 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); } while (0)
41 #define PRINT_PEEPHOLE3(ID, I1, I2, I3) \
42 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
43 PRINT_PEEPHOLE(ID, 2, I3); } while (0)
44 #define PRINT_PEEPHOLE4(ID, I1, I2, I3, I4) \
45 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
46 PRINT_PEEPHOLE(ID, 2, I3); PRINT_PEEPHOLE(ID, 3, I4); } while (0)
49 // isReinterpretingCast - Return true if the cast instruction specified will
50 // cause the operand to be "reinterpreted". A value is reinterpreted if the
51 // cast instruction would cause the underlying bits to change.
53 static inline bool isReinterpretingCast(const CastInst *CI) {
54 return!CI->getOperand(0)->getType()->isLosslesslyConvertableTo(CI->getType());
58 // Peephole optimize the following instructions:
59 // %t1 = cast ? to x *
60 // %t2 = add x * %SP, %t1 ;; Constant must be 2nd operand
62 // Into: %t3 = getelementptr {<...>} * %SP, <element indices>
63 // %t2 = cast <eltype> * %t3 to {<...>}*
65 static bool HandleCastToPointer(BasicBlock::iterator BI,
66 const PointerType *DestPTy) {
67 CastInst *CI = cast<CastInst>(*BI);
68 if (CI->use_empty()) return false;
70 // Scan all of the uses, looking for any uses that are not add
71 // instructions. If we have non-adds, do not make this transformation.
73 for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
75 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(*I)) {
76 if (BO->getOpcode() != Instruction::Add)
83 std::vector<Value*> Indices;
84 Value *Src = CI->getOperand(0);
85 const Type *Result = ConvertableToGEP(DestPTy, Src, Indices, &BI);
86 if (Result == 0) return false; // Not convertable...
88 PRINT_PEEPHOLE2("cast-add-to-gep:in", Src, CI);
90 // If we have a getelementptr capability... transform all of the
91 // add instruction uses into getelementptr's.
92 while (!CI->use_empty()) {
93 BinaryOperator *I = cast<BinaryOperator>(*CI->use_begin());
94 assert(I->getOpcode() == Instruction::Add && I->getNumOperands() == 2 &&
95 "Use is not a valid add instruction!");
97 // Get the value added to the cast result pointer...
98 Value *OtherPtr = I->getOperand((I->getOperand(0) == CI) ? 1 : 0);
100 Instruction *GEP = new GetElementPtrInst(OtherPtr, Indices, I->getName());
101 PRINT_PEEPHOLE1("cast-add-to-gep:i", I);
103 if (GEP->getType() == I->getType()) {
104 // Replace the old add instruction with the shiny new GEP inst
105 ReplaceInstWithInst(I, GEP);
107 // If the type produced by the gep instruction differs from the original
108 // add instruction type, insert a cast now.
111 // Insert the GEP instruction before the old add instruction... and get an
112 // iterator to point at the add instruction...
113 BasicBlock::iterator GEPI = InsertInstBeforeInst(GEP, I)+1;
115 PRINT_PEEPHOLE1("cast-add-to-gep:o", GEP);
116 CastInst *CI = new CastInst(GEP, I->getType());
119 // Replace the old add instruction with the shiny new GEP inst
120 ReplaceInstWithInst(I->getParent()->getInstList(), GEPI, GEP);
123 PRINT_PEEPHOLE1("cast-add-to-gep:o", GEP);
128 // Peephole optimize the following instructions:
129 // %t1 = cast ulong <const int> to {<...>} *
130 // %t2 = add {<...>} * %SP, %t1 ;; Constant must be 2nd operand
133 // %t1 = cast {<...>}* %SP to int*
134 // %t5 = cast ulong <const int> to int*
135 // %t2 = add int* %t1, %t5 ;; int is same size as field
137 // Into: %t3 = getelementptr {<...>} * %SP, <element indices>
138 // %t2 = cast <eltype> * %t3 to {<...>}*
140 static bool PeepholeOptimizeAddCast(BasicBlock *BB, BasicBlock::iterator &BI,
141 Value *AddOp1, CastInst *AddOp2) {
142 const CompositeType *CompTy;
143 Value *OffsetVal = AddOp2->getOperand(0);
144 Value *SrcPtr; // Of type pointer to struct...
146 if ((CompTy = getPointedToComposite(AddOp1->getType()))) {
147 SrcPtr = AddOp1; // Handle the first case...
148 } else if (CastInst *AddOp1c = dyn_cast<CastInst>(AddOp1)) {
149 SrcPtr = AddOp1c->getOperand(0); // Handle the second case...
150 CompTy = getPointedToComposite(SrcPtr->getType());
153 // Only proceed if we have detected all of our conditions successfully...
154 if (!CompTy || !SrcPtr || !OffsetVal->getType()->isIntegral())
157 std::vector<Value*> Indices;
158 if (!ConvertableToGEP(SrcPtr->getType(), OffsetVal, Indices, &BI))
159 return false; // Not convertable... perhaps next time
161 if (getPointedToComposite(AddOp1->getType())) { // case 1
162 PRINT_PEEPHOLE2("add-to-gep1:in", AddOp2, *BI);
164 PRINT_PEEPHOLE3("add-to-gep2:in", AddOp1, AddOp2, *BI);
167 GetElementPtrInst *GEP = new GetElementPtrInst(SrcPtr, Indices,
169 BI = BB->getInstList().insert(BI, GEP)+1;
171 Instruction *NCI = new CastInst(GEP, AddOp1->getType());
172 ReplaceInstWithInst(BB->getInstList(), BI, NCI);
173 PRINT_PEEPHOLE2("add-to-gep:out", GEP, NCI);
177 static bool PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI) {
178 Instruction *I = *BI;
180 if (CastInst *CI = dyn_cast<CastInst>(I)) {
181 Value *Src = CI->getOperand(0);
182 Instruction *SrcI = dyn_cast<Instruction>(Src); // Nonnull if instr source
183 const Type *DestTy = CI->getType();
185 // Peephole optimize the following instruction:
186 // %V2 = cast <ty> %V to <ty>
190 if (DestTy == Src->getType()) { // Check for a cast to same type as src!!
191 PRINT_PEEPHOLE1("cast-of-self-ty", CI);
192 CI->replaceAllUsesWith(Src);
193 if (!Src->hasName() && CI->hasName()) {
194 std::string Name = CI->getName();
196 Src->setName(Name, BB->getParent()->getSymbolTable());
199 // DCE the instruction now, to avoid having the iterative version of DCE
200 // have to worry about it.
202 delete BB->getInstList().remove(BI);
208 // Check to see if it's a cast of an instruction that does not depend on the
209 // specific type of the operands to do it's job.
210 if (!isReinterpretingCast(CI)) {
211 ValueTypeCache ConvertedTypes;
213 // Check to see if we can convert the users of the cast value to match the
214 // source type of the cast...
216 ConvertedTypes[CI] = CI->getType(); // Make sure the cast doesn't change
217 if (ExpressionConvertableToType(Src, DestTy, ConvertedTypes)) {
218 PRINT_PEEPHOLE3("CAST-SRC-EXPR-CONV:in ", Src, CI, BB->getParent());
220 #ifdef DEBUG_PEEPHOLE_INSTS
221 cerr << "\nCONVERTING SRC EXPR TYPE:\n";
223 ValueMapCache ValueMap;
224 Value *E = ConvertExpressionToType(Src, DestTy, ValueMap);
225 if (Constant *CPV = dyn_cast<Constant>(E))
226 CI->replaceAllUsesWith(CPV);
228 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
229 PRINT_PEEPHOLE1("CAST-SRC-EXPR-CONV:out", E);
230 #ifdef DEBUG_PEEPHOLE_INSTS
231 cerr << "DONE CONVERTING SRC EXPR TYPE: \n" << BB->getParent();
237 // Check to see if we can convert the source of the cast to match the
238 // destination type of the cast...
240 ConvertedTypes.clear();
241 if (ValueConvertableToType(CI, Src->getType(), ConvertedTypes)) {
242 PRINT_PEEPHOLE3("CAST-DEST-EXPR-CONV:in ", Src, CI, BB->getParent());
244 #ifdef DEBUG_PEEPHOLE_INSTS
245 cerr << "\nCONVERTING EXPR TYPE:\n";
247 ValueMapCache ValueMap;
248 ConvertValueToNewType(CI, Src, ValueMap); // This will delete CI!
250 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
251 PRINT_PEEPHOLE1("CAST-DEST-EXPR-CONV:out", Src);
252 #ifdef DEBUG_PEEPHOLE_INSTS
253 cerr << "DONE CONVERTING EXPR TYPE: \n\n" << BB->getParent();
260 // Otherwise find out it this cast is a cast to a pointer type, which is
261 // then added to some other pointer, then loaded or stored through. If
262 // so, convert the add into a getelementptr instruction...
264 if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
265 if (HandleCastToPointer(BI, DestPTy)) {
266 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
272 // Check to see if we are casting from a structure pointer to a pointer to
273 // the first element of the structure... to avoid munching other peepholes,
274 // we only let this happen if there are no add uses of the cast.
276 // Peephole optimize the following instructions:
277 // %t1 = cast {<...>} * %StructPtr to <ty> *
279 // Into: %t2 = getelementptr {<...>} * %StructPtr, <0, 0, 0, ...>
280 // %t1 = cast <eltype> * %t1 to <ty> *
283 if (const CompositeType *CTy = getPointedToComposite(Src->getType()))
284 if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
286 // Loop over uses of the cast, checking for add instructions. If an add
287 // exists, this is probably a part of a more complex GEP, so we don't
288 // want to mess around with the cast.
290 bool HasAddUse = false;
291 for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
293 if (isa<Instruction>(*I) &&
294 cast<Instruction>(*I)->getOpcode() == Instruction::Add) {
295 HasAddUse = true; break;
298 // If it doesn't have an add use, check to see if the dest type is
299 // losslessly convertable to one of the types in the start of the struct
303 const Type *DestPointedTy = DestPTy->getElementType();
305 const CompositeType *CurCTy = CTy;
306 const Type *ElTy = 0;
308 // Build the index vector, full of all zeros
309 std::vector<Value*> Indices;
310 Indices.push_back(ConstantUInt::get(Type::UIntTy, 0));
311 while (CurCTy && !isa<PointerType>(CurCTy)) {
312 if (const StructType *CurSTy = dyn_cast<StructType>(CurCTy)) {
313 // Check for a zero element struct type... if we have one, bail.
314 if (CurSTy->getElementTypes().size() == 0) break;
316 // Grab the first element of the struct type, which must lie at
317 // offset zero in the struct.
319 ElTy = CurSTy->getElementTypes()[0];
321 ElTy = cast<ArrayType>(CurCTy)->getElementType();
324 // Insert a zero to index through this type...
325 Indices.push_back(ConstantUInt::get(CurCTy->getIndexType(), 0));
327 // Did we find what we're looking for?
328 if (ElTy->isLosslesslyConvertableTo(DestPointedTy)) break;
330 // Nope, go a level deeper.
332 CurCTy = dyn_cast<CompositeType>(ElTy);
336 // Did we find what we were looking for? If so, do the transformation
338 PRINT_PEEPHOLE1("cast-for-first:in", CI);
340 // Insert the new T cast instruction... stealing old T's name
341 GetElementPtrInst *GEP = new GetElementPtrInst(Src, Indices,
344 BI = BB->getInstList().insert(BI, GEP)+1;
346 // Make the old cast instruction reference the new GEP instead of
347 // the old src value.
349 CI->setOperand(0, GEP);
351 PRINT_PEEPHOLE2("cast-for-first:out", GEP, CI);
360 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
361 Value *Val = SI->getOperand(0);
362 Value *Pointer = SI->getPointerOperand();
364 // Peephole optimize the following instructions:
365 // %t = cast <T1>* %P to <T2> * ;; If T1 is losslessly convertable to T2
366 // store <T2> %V, <T2>* %t
369 // %t = cast <T2> %V to <T1>
370 // store <T1> %t2, <T1>* %P
372 // Note: This is not taken care of by expr conversion because there might
373 // not be a cast available for the store to convert the incoming value of.
374 // This code is basically here to make sure that pointers don't have casts
377 if (CastInst *CI = dyn_cast<CastInst>(Pointer))
378 if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
379 if (PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
380 // convertable types?
381 if (Val->getType()->isLosslesslyConvertableTo(CSPT->getElementType()) &&
382 !SI->hasIndices()) { // No subscripts yet!
383 PRINT_PEEPHOLE3("st-src-cast:in ", Pointer, Val, SI);
385 // Insert the new T cast instruction... stealing old T's name
386 CastInst *NCI = new CastInst(Val, CSPT->getElementType(),
389 BI = BB->getInstList().insert(BI, NCI)+1;
391 // Replace the old store with a new one!
392 ReplaceInstWithInst(BB->getInstList(), BI,
393 SI = new StoreInst(NCI, CastSrc));
394 PRINT_PEEPHOLE3("st-src-cast:out", NCI, CastSrc, SI);
395 ++NumLoadStorePeepholes;
399 } else if (I->getOpcode() == Instruction::Add &&
400 isa<CastInst>(I->getOperand(1))) {
402 if (PeepholeOptimizeAddCast(BB, BI, I->getOperand(0),
403 cast<CastInst>(I->getOperand(1)))) {
416 static bool DoRaisePass(Function *F) {
417 bool Changed = false;
418 for (Function::iterator MI = F->begin(), ME = F->end(); MI != ME; ++MI) {
419 BasicBlock *BB = *MI;
420 BasicBlock::InstListType &BIL = BB->getInstList();
422 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
423 #if DEBUG_PEEPHOLE_INSTS
424 cerr << "Processing: " << *BI;
426 if (dceInstruction(BIL, BI) || doConstantPropogation(BB, BI)) {
429 #ifdef DEBUG_PEEPHOLE_INSTS
430 cerr << "***\t\t^^-- DeadCode Elinated!\n";
432 } else if (PeepholeOptimize(BB, BI))
442 // RaisePointerReferences::doit - Raise a function representation to a higher
445 static bool doRPR(Function *F) {
446 #ifdef DEBUG_PEEPHOLE_INSTS
447 cerr << "\n\n\nStarting to work on Function '" << F->getName() << "'\n";
450 // Insert casts for all incoming pointer pointer values that are treated as
453 bool Changed = false, LocalChange;
456 #ifdef DEBUG_PEEPHOLE_INSTS
457 cerr << "Looping: \n" << F;
460 // Iterate over the function, refining it, until it converges on a stable
463 while (DoRaisePass(F)) LocalChange = true;
464 Changed |= LocalChange;
466 } while (LocalChange);
472 struct RaisePointerReferences : public FunctionPass {
473 const char *getPassName() const { return "Raise Pointer References"; }
475 virtual bool runOnFunction(Function *F) { return doRPR(F); }
477 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
483 Pass *createRaisePointerReferencesPass() {
484 return new RaisePointerReferences();