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 "TransformInternals.h"
11 #include "llvm/Method.h"
12 #include "llvm/iOther.h"
13 #include "llvm/iMemory.h"
14 #include "llvm/ConstantVals.h"
15 #include "llvm/Transforms/Scalar/DCE.h"
16 #include "llvm/Transforms/Scalar/ConstantHandling.h"
17 #include "llvm/Transforms/Scalar/ConstantProp.h"
18 #include "llvm/Analysis/Expressions.h"
19 #include "Support/STLExtras.h"
22 #include "llvm/Assembly/Writer.h"
24 //#define DEBUG_PEEPHOLE_INSTS 1
26 #ifdef DEBUG_PEEPHOLE_INSTS
27 #define PRINT_PEEPHOLE(ID, NUM, I) \
28 cerr << "Inst P/H " << ID << "[" << NUM << "] " << I;
30 #define PRINT_PEEPHOLE(ID, NUM, I)
33 #define PRINT_PEEPHOLE1(ID, I1) do { PRINT_PEEPHOLE(ID, 0, I1); } while (0)
34 #define PRINT_PEEPHOLE2(ID, I1, I2) \
35 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); } while (0)
36 #define PRINT_PEEPHOLE3(ID, I1, I2, I3) \
37 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
38 PRINT_PEEPHOLE(ID, 2, I3); } while (0)
39 #define PRINT_PEEPHOLE4(ID, I1, I2, I3, I4) \
40 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
41 PRINT_PEEPHOLE(ID, 2, I3); PRINT_PEEPHOLE(ID, 3, I4); } while (0)
44 // isReinterpretingCast - Return true if the cast instruction specified will
45 // cause the operand to be "reinterpreted". A value is reinterpreted if the
46 // cast instruction would cause the underlying bits to change.
48 static inline bool isReinterpretingCast(const CastInst *CI) {
49 return!CI->getOperand(0)->getType()->isLosslesslyConvertableTo(CI->getType());
54 // Peephole optimize the following instructions:
55 // %t1 = cast ? to x *
56 // %t2 = add x * %SP, %t1 ;; Constant must be 2nd operand
58 // Into: %t3 = getelementptr {<...>} * %SP, <element indices>
59 // %t2 = cast <eltype> * %t3 to {<...>}*
61 static bool HandleCastToPointer(BasicBlock::iterator BI,
62 const PointerType *DestPTy) {
63 CastInst *CI = cast<CastInst>(*BI);
65 // Scan all of the uses, looking for any uses that are not add
66 // instructions. If we have non-adds, do not make this transformation.
68 for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
70 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(*I)) {
71 if (BO->getOpcode() != Instruction::Add)
78 std::vector<Value*> Indices;
79 Value *Src = CI->getOperand(0);
80 const Type *Result = ConvertableToGEP(DestPTy, Src, Indices, &BI);
81 if (Result == 0) return false; // Not convertable...
83 PRINT_PEEPHOLE2("cast-add-to-gep:in", Src, CI);
85 // If we have a getelementptr capability... transform all of the
86 // add instruction uses into getelementptr's.
87 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
89 Instruction *I = cast<Instruction>(*UI);
90 assert(I->getOpcode() == Instruction::Add && I->getNumOperands() == 2 &&
91 "Use is not a valid add instruction!");
93 // Get the value added to the cast result pointer...
94 Value *OtherPtr = I->getOperand((I->getOperand(0) == CI) ? 1 : 0);
96 BasicBlock *BB = I->getParent();
97 BasicBlock::iterator AddIt = find(BB->getInstList().begin(),
98 BB->getInstList().end(), I);
100 GetElementPtrInst *GEP = new GetElementPtrInst(OtherPtr, Indices);
102 PRINT_PEEPHOLE1("cast-add-to-gep:i", I);
104 // Replace the old add instruction with the shiny new GEP inst
105 ReplaceInstWithInst(BB->getInstList(), AddIt, GEP);
106 PRINT_PEEPHOLE1("cast-add-to-gep:o", GEP);
111 // Peephole optimize the following instructions:
112 // %t1 = cast ulong <const int> to {<...>} *
113 // %t2 = add {<...>} * %SP, %t1 ;; Constant must be 2nd operand
116 // %t1 = cast {<...>}* %SP to int*
117 // %t5 = cast ulong <const int> to int*
118 // %t2 = add int* %t1, %t5 ;; int is same size as field
120 // Into: %t3 = getelementptr {<...>} * %SP, <element indices>
121 // %t2 = cast <eltype> * %t3 to {<...>}*
123 static bool PeepholeOptimizeAddCast(BasicBlock *BB, BasicBlock::iterator &BI,
124 Value *AddOp1, CastInst *AddOp2) {
125 const CompositeType *CompTy;
126 Value *OffsetVal = AddOp2->getOperand(0);
127 Value *SrcPtr; // Of type pointer to struct...
129 if ((CompTy = getPointedToComposite(AddOp1->getType()))) {
130 SrcPtr = AddOp1; // Handle the first case...
131 } else if (CastInst *AddOp1c = dyn_cast<CastInst>(AddOp1)) {
132 SrcPtr = AddOp1c->getOperand(0); // Handle the second case...
133 CompTy = getPointedToComposite(SrcPtr->getType());
136 // Only proceed if we have detected all of our conditions successfully...
137 if (!CompTy || !SrcPtr || !OffsetVal->getType()->isIntegral())
140 std::vector<Value*> Indices;
141 if (!ConvertableToGEP(SrcPtr->getType(), OffsetVal, Indices, &BI))
142 return false; // Not convertable... perhaps next time
144 if (getPointedToComposite(AddOp1->getType())) { // case 1
145 PRINT_PEEPHOLE2("add-to-gep1:in", AddOp2, *BI);
147 PRINT_PEEPHOLE3("add-to-gep2:in", AddOp1, AddOp2, *BI);
150 GetElementPtrInst *GEP = new GetElementPtrInst(SrcPtr, Indices,
152 BI = BB->getInstList().insert(BI, GEP)+1;
154 Instruction *NCI = new CastInst(GEP, AddOp1->getType());
155 ReplaceInstWithInst(BB->getInstList(), BI, NCI);
156 PRINT_PEEPHOLE2("add-to-gep:out", GEP, NCI);
160 static bool PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI) {
161 Instruction *I = *BI;
163 if (CastInst *CI = dyn_cast<CastInst>(I)) {
164 Value *Src = CI->getOperand(0);
165 Instruction *SrcI = dyn_cast<Instruction>(Src); // Nonnull if instr source
166 const Type *DestTy = CI->getType();
168 // Peephole optimize the following instruction:
169 // %V2 = cast <ty> %V to <ty>
173 if (DestTy == Src->getType()) { // Check for a cast to same type as src!!
174 PRINT_PEEPHOLE1("cast-of-self-ty", CI);
175 CI->replaceAllUsesWith(Src);
176 if (!Src->hasName() && CI->hasName()) {
177 std::string Name = CI->getName();
179 Src->setName(Name, BB->getParent()->getSymbolTable());
184 // Peephole optimize the following instructions:
185 // %tmp = cast <ty> %V to <ty2>
186 // %V = cast <ty2> %tmp to <ty3> ; Where ty & ty2 are same size
188 // Into: cast <ty> %V to <ty3>
191 if (CastInst *CSrc = dyn_cast<CastInst>(SrcI))
192 if (isReinterpretingCast(CI) + isReinterpretingCast(CSrc) < 2) {
193 // We can only do c-c elimination if, at most, one cast does a
194 // reinterpretation of the input data.
196 // If legal, make this cast refer the the original casts argument!
198 PRINT_PEEPHOLE2("cast-cast:in ", CI, CSrc);
199 CI->setOperand(0, CSrc->getOperand(0));
200 PRINT_PEEPHOLE1("cast-cast:out", CI);
204 // Check to see if it's a cast of an instruction that does not depend on the
205 // specific type of the operands to do it's job.
206 if (!isReinterpretingCast(CI)) {
207 ValueTypeCache ConvertedTypes;
209 // Check to see if we can convert the users of the cast value to match the
210 // source type of the cast...
212 ConvertedTypes[CI] = CI->getType(); // Make sure the cast doesn't change
213 if (ExpressionConvertableToType(Src, DestTy, ConvertedTypes)) {
214 PRINT_PEEPHOLE3("CAST-SRC-EXPR-CONV:in ", Src, CI, BB->getParent());
216 #ifdef DEBUG_PEEPHOLE_INSTS
217 cerr << "\nCONVERTING SRC EXPR TYPE:\n";
219 ValueMapCache ValueMap;
220 Value *E = ConvertExpressionToType(Src, DestTy, ValueMap);
221 if (Constant *CPV = dyn_cast<Constant>(E))
222 CI->replaceAllUsesWith(CPV);
224 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
225 PRINT_PEEPHOLE1("CAST-SRC-EXPR-CONV:out", E);
226 #ifdef DEBUG_PEEPHOLE_INSTS
227 cerr << "DONE CONVERTING SRC EXPR TYPE: \n" << BB->getParent();
232 // Check to see if we can convert the source of the cast to match the
233 // destination type of the cast...
235 ConvertedTypes.clear();
236 if (ValueConvertableToType(CI, Src->getType(), ConvertedTypes)) {
237 PRINT_PEEPHOLE3("CAST-DEST-EXPR-CONV:in ", Src, CI, BB->getParent());
239 #ifdef DEBUG_PEEPHOLE_INSTS
240 cerr << "\nCONVERTING EXPR TYPE:\n";
242 ValueMapCache ValueMap;
243 ConvertValueToNewType(CI, Src, ValueMap); // This will delete CI!
245 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
246 PRINT_PEEPHOLE1("CAST-DEST-EXPR-CONV:out", Src);
247 #ifdef DEBUG_PEEPHOLE_INSTS
248 cerr << "DONE CONVERTING EXPR TYPE: \n\n" << BB->getParent();
254 // Otherwise find out it this cast is a cast to a pointer type, which is
255 // then added to some other pointer, then loaded or stored through. If
256 // so, convert the add into a getelementptr instruction...
258 if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
259 if (HandleCastToPointer(BI, DestPTy)) {
260 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
265 // Check to see if we are casting from a structure pointer to a pointer to
266 // the first element of the structure... to avoid munching other peepholes,
267 // we only let this happen if there are no add uses of the cast.
269 // Peephole optimize the following instructions:
270 // %t1 = cast {<...>} * %StructPtr to <ty> *
272 // Into: %t2 = getelementptr {<...>} * %StructPtr, <0, 0, 0, ...>
273 // %t1 = cast <eltype> * %t1 to <ty> *
276 if (const CompositeType *CTy = getPointedToComposite(Src->getType()))
277 if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
279 // Loop over uses of the cast, checking for add instructions. If an add
280 // exists, this is probably a part of a more complex GEP, so we don't
281 // want to mess around with the cast.
283 bool HasAddUse = false;
284 for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
286 if (isa<Instruction>(*I) &&
287 cast<Instruction>(*I)->getOpcode() == Instruction::Add) {
288 HasAddUse = true; break;
291 // If it doesn't have an add use, check to see if the dest type is
292 // losslessly convertable to one of the types in the start of the struct
296 const Type *DestPointedTy = DestPTy->getElementType();
298 const CompositeType *CurCTy = CTy;
299 const Type *ElTy = 0;
301 // Build the index vector, full of all zeros
302 std::vector<Value*> Indices;
303 Indices.push_back(ConstantUInt::get(Type::UIntTy, 0));
304 while (CurCTy && !isa<PointerType>(CurCTy)) {
305 if (const StructType *CurSTy = dyn_cast<StructType>(CurCTy)) {
306 // Check for a zero element struct type... if we have one, bail.
307 if (CurSTy->getElementTypes().size() == 0) break;
309 // Grab the first element of the struct type, which must lie at
310 // offset zero in the struct.
312 ElTy = CurSTy->getElementTypes()[0];
314 ElTy = cast<ArrayType>(CurCTy)->getElementType();
317 // Insert a zero to index through this type...
318 Indices.push_back(ConstantUInt::get(CurCTy->getIndexType(), 0));
320 // Did we find what we're looking for?
321 if (ElTy->isLosslesslyConvertableTo(DestPointedTy)) break;
323 // Nope, go a level deeper.
325 CurCTy = dyn_cast<CompositeType>(ElTy);
329 // Did we find what we were looking for? If so, do the transformation
331 PRINT_PEEPHOLE1("cast-for-first:in", CI);
333 // Insert the new T cast instruction... stealing old T's name
334 GetElementPtrInst *GEP = new GetElementPtrInst(Src, Indices,
337 BI = BB->getInstList().insert(BI, GEP)+1;
339 // Make the old cast instruction reference the new GEP instead of
340 // the old src value.
342 CI->setOperand(0, GEP);
344 PRINT_PEEPHOLE2("cast-for-first:out", GEP, CI);
352 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
353 Value *Val = SI->getOperand(0);
354 Value *Pointer = SI->getPointerOperand();
356 // Peephole optimize the following instructions:
357 // %t = cast <T1>* %P to <T2> * ;; If T1 is losslessly convertable to T2
358 // store <T2> %V, <T2>* %t
361 // %t = cast <T2> %V to <T1>
362 // store <T1> %t2, <T1>* %P
364 // Note: This is not taken care of by expr conversion because there might
365 // not be a cast available for the store to convert the incoming value of.
366 // This code is basically here to make sure that pointers don't have casts
369 if (CastInst *CI = dyn_cast<CastInst>(Pointer))
370 if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
371 if (PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
372 // convertable types?
373 if (Val->getType()->isLosslesslyConvertableTo(CSPT->getElementType()) &&
374 !SI->hasIndices()) { // No subscripts yet!
375 PRINT_PEEPHOLE3("st-src-cast:in ", Pointer, Val, SI);
377 // Insert the new T cast instruction... stealing old T's name
378 CastInst *NCI = new CastInst(Val, CSPT->getElementType(),
381 BI = BB->getInstList().insert(BI, NCI)+1;
383 // Replace the old store with a new one!
384 ReplaceInstWithInst(BB->getInstList(), BI,
385 SI = new StoreInst(NCI, CastSrc));
386 PRINT_PEEPHOLE3("st-src-cast:out", NCI, CastSrc, SI);
390 } else if (I->getOpcode() == Instruction::Add &&
391 isa<CastInst>(I->getOperand(1))) {
393 if (PeepholeOptimizeAddCast(BB, BI, I->getOperand(0),
394 cast<CastInst>(I->getOperand(1))))
406 static bool DoRaisePass(Method *M) {
407 bool Changed = false;
408 for (Method::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI) {
409 BasicBlock *BB = *MI;
410 BasicBlock::InstListType &BIL = BB->getInstList();
412 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
413 #if DEBUG_PEEPHOLE_INSTS
414 cerr << "Processing: " << *BI;
416 if (DeadCodeElimination::dceInstruction(BIL, BI) ||
417 ConstantPropogation::doConstantPropogation(BB, BI)) {
419 #ifdef DEBUG_PEEPHOLE_INSTS
420 cerr << "DeadCode Elinated!\n";
422 } else if (PeepholeOptimize(BB, BI))
434 // RaisePointerReferences::doit - Raise a method representation to a higher
437 bool RaisePointerReferences::doit(Method *M) {
438 if (M->isExternal()) return false;
440 #ifdef DEBUG_PEEPHOLE_INSTS
441 cerr << "\n\n\nStarting to work on Method '" << M->getName() << "'\n";
444 // Insert casts for all incoming pointer pointer values that are treated as
447 bool Changed = false, LocalChange;
450 #ifdef DEBUG_PEEPHOLE_INSTS
451 cerr << "Looping: \n" << M;
454 // Iterate over the method, refining it, until it converges on a stable
457 while (DoRaisePass(M)) LocalChange = true;
458 Changed |= LocalChange;
460 } while (LocalChange);