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/Optimizations/ConstantHandling.h"
16 #include "llvm/Optimizations/DCE.h"
17 #include "llvm/Optimizations/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());
56 // Peephole optimize the following instructions:
57 // %t1 = cast ulong <const int> to {<...>} *
58 // %t2 = add {<...>} * %SP, %t1 ;; Constant must be 2nd operand
61 // %t1 = cast {<...>}* %SP to int*
62 // %t5 = cast ulong <const int> to int*
63 // %t2 = add int* %t1, %t5 ;; int is same size as field
65 // Into: %t3 = getelementptr {<...>} * %SP, <element indices>
66 // %t2 = cast <eltype> * %t3 to {<...>}*
68 static bool PeepholeOptimizeAddCast(BasicBlock *BB, BasicBlock::iterator &BI,
69 Value *AddOp1, CastInst *AddOp2) {
70 const CompositeType *CompTy;
71 Value *OffsetVal = AddOp2->getOperand(0);
72 Value *SrcPtr; // Of type pointer to struct...
74 if ((CompTy = getPointedToComposite(AddOp1->getType()))) {
75 SrcPtr = AddOp1; // Handle the first case...
76 } else if (CastInst *AddOp1c = dyn_cast<CastInst>(AddOp1)) {
77 SrcPtr = AddOp1c->getOperand(0); // Handle the second case...
78 CompTy = getPointedToComposite(SrcPtr->getType());
81 // Only proceed if we have detected all of our conditions successfully...
82 if (!CompTy || !SrcPtr || !OffsetVal->getType()->isIntegral())
85 vector<Value*> Indices;
86 if (!ConvertableToGEP(SrcPtr->getType(), OffsetVal, Indices, &BI))
87 return false; // Not convertable... perhaps next time
89 if (getPointedToComposite(AddOp1->getType())) { // case 1
90 PRINT_PEEPHOLE2("add-to-gep1:in", AddOp2, *BI);
92 PRINT_PEEPHOLE3("add-to-gep2:in", AddOp1, AddOp2, *BI);
95 GetElementPtrInst *GEP = new GetElementPtrInst(SrcPtr, Indices,
97 BI = BB->getInstList().insert(BI, GEP)+1;
99 Instruction *NCI = new CastInst(GEP, AddOp1->getType());
100 ReplaceInstWithInst(BB->getInstList(), BI, NCI);
101 PRINT_PEEPHOLE2("add-to-gep:out", GEP, NCI);
105 static bool PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI) {
106 Instruction *I = *BI;
108 if (CastInst *CI = dyn_cast<CastInst>(I)) {
109 Value *Src = CI->getOperand(0);
110 Instruction *SrcI = dyn_cast<Instruction>(Src); // Nonnull if instr source
111 const Type *DestTy = CI->getType();
113 // Peephole optimize the following instruction:
114 // %V2 = cast <ty> %V to <ty>
118 if (DestTy == Src->getType()) { // Check for a cast to same type as src!!
119 PRINT_PEEPHOLE1("cast-of-self-ty", CI);
120 CI->replaceAllUsesWith(Src);
121 if (!Src->hasName() && CI->hasName()) {
122 string Name = CI->getName();
124 Src->setName(Name, BB->getParent()->getSymbolTable());
129 // Peephole optimize the following instructions:
130 // %tmp = cast <ty> %V to <ty2>
131 // %V = cast <ty2> %tmp to <ty3> ; Where ty & ty2 are same size
133 // Into: cast <ty> %V to <ty3>
136 if (CastInst *CSrc = dyn_cast<CastInst>(SrcI))
137 if (isReinterpretingCast(CI) + isReinterpretingCast(CSrc) < 2) {
138 // We can only do c-c elimination if, at most, one cast does a
139 // reinterpretation of the input data.
141 // If legal, make this cast refer the the original casts argument!
143 PRINT_PEEPHOLE2("cast-cast:in ", CI, CSrc);
144 CI->setOperand(0, CSrc->getOperand(0));
145 PRINT_PEEPHOLE1("cast-cast:out", CI);
149 // Check to see if it's a cast of an instruction that does not depend on the
150 // specific type of the operands to do it's job.
151 if (!isReinterpretingCast(CI)) {
152 ValueTypeCache ConvertedTypes;
153 if (ValueConvertableToType(CI, Src->getType(), ConvertedTypes)) {
154 PRINT_PEEPHOLE2("CAST-DEST-EXPR-CONV:in ", Src, CI);
156 #ifdef DEBUG_PEEPHOLE_INSTS
157 cerr << "\nCONVERTING EXPR TYPE:\n";
159 ValueMapCache ValueMap;
160 ConvertValueToNewType(CI, Src, ValueMap); // This will delete CI!
162 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
163 PRINT_PEEPHOLE1("CAST-DEST-EXPR-CONV:out", Src);
164 #ifdef DEBUG_PEEPHOLE_INSTS
165 cerr << "DONE CONVERTING EXPR TYPE: \n\n";// << BB->getParent();
169 ConvertedTypes.clear();
170 if (ExpressionConvertableToType(Src, DestTy, ConvertedTypes)) {
171 PRINT_PEEPHOLE2("CAST-SRC-EXPR-CONV:in ", Src, CI);
173 #ifdef DEBUG_PEEPHOLE_INSTS
174 cerr << "\nCONVERTING SRC EXPR TYPE:\n";
176 ValueMapCache ValueMap;
177 Value *E = ConvertExpressionToType(Src, DestTy, ValueMap);
178 if (Constant *CPV = dyn_cast<Constant>(E))
179 CI->replaceAllUsesWith(CPV);
181 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
182 PRINT_PEEPHOLE1("CAST-SRC-EXPR-CONV:out", E);
183 #ifdef DEBUG_PEEPHOLE_INSTS
184 cerr << "DONE CONVERTING SRC EXPR TYPE: \n\n";// << BB->getParent();
192 // Check to see if we are casting from a structure pointer to a pointer to
193 // the first element of the structure... to avoid munching other peepholes,
194 // we only let this happen if there are no add uses of the cast.
196 // Peephole optimize the following instructions:
197 // %t1 = cast {<...>} * %StructPtr to <ty> *
199 // Into: %t2 = getelementptr {<...>} * %StructPtr, <0, 0, 0, ...>
200 // %t1 = cast <eltype> * %t1 to <ty> *
203 if (const CompositeType *CTy = getPointedToComposite(Src->getType()))
204 if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
206 // Loop over uses of the cast, checking for add instructions. If an add
207 // exists, this is probably a part of a more complex GEP, so we don't
208 // want to mess around with the cast.
210 bool HasAddUse = false;
211 for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
213 if (isa<Instruction>(*I) &&
214 cast<Instruction>(*I)->getOpcode() == Instruction::Add) {
215 HasAddUse = true; break;
218 // If it doesn't have an add use, check to see if the dest type is
219 // losslessly convertable to one of the types in the start of the struct
223 const Type *DestPointedTy = DestPTy->getElementType();
225 const CompositeType *CurCTy = CTy;
226 const Type *ElTy = 0;
228 // Build the index vector, full of all zeros
229 vector<Value*> Indices;
232 if (const StructType *CurSTy = dyn_cast<StructType>(CurCTy)) {
233 // Check for a zero element struct type... if we have one, bail.
234 if (CurSTy->getElementTypes().size() == 0) break;
236 // Grab the first element of the struct type, which must lie at
237 // offset zero in the struct.
239 ElTy = CurSTy->getElementTypes()[0];
241 ElTy = cast<ArrayType>(CurCTy)->getElementType();
244 // Insert a zero to index through this type...
245 Indices.push_back(ConstantUInt::get(CurCTy->getIndexType(), 0));
247 // Did we find what we're looking for?
248 if (ElTy->isLosslesslyConvertableTo(DestPointedTy)) break;
250 // Nope, go a level deeper.
252 CurCTy = dyn_cast<CompositeType>(ElTy);
256 // Did we find what we were looking for? If so, do the transformation
258 PRINT_PEEPHOLE1("cast-for-first:in", CI);
260 // Insert the new T cast instruction... stealing old T's name
261 GetElementPtrInst *GEP = new GetElementPtrInst(Src, Indices,
264 BI = BB->getInstList().insert(BI, GEP)+1;
266 // Make the old cast instruction reference the new GEP instead of
267 // the old src value.
269 CI->setOperand(0, GEP);
271 PRINT_PEEPHOLE2("cast-for-first:out", GEP, CI);
279 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
280 Value *Val = SI->getOperand(0);
281 Value *Pointer = SI->getPointerOperand();
283 // Peephole optimize the following instructions:
284 // %t1 = getelementptr {<...>} * %StructPtr, <element indices>
285 // store <elementty> %v, <elementty> * %t1
287 // Into: store <elementty> %v, {<...>} * %StructPtr, <element indices>
289 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Pointer)) {
290 // Append any indices that the store instruction has onto the end of the
291 // ones that the GEP is carrying...
293 vector<Value*> Indices(GEP->copyIndices());
294 Indices.insert(Indices.end(), SI->idx_begin(), SI->idx_end());
296 PRINT_PEEPHOLE2("gep-store:in", GEP, SI);
297 ReplaceInstWithInst(BB->getInstList(), BI,
298 SI = new StoreInst(Val, GEP->getPointerOperand(),
300 PRINT_PEEPHOLE1("gep-store:out", SI);
304 // Peephole optimize the following instructions:
305 // %t = cast <T1>* %P to <T2> * ;; If T1 is losslessly convertable to T2
306 // store <T2> %V, <T2>* %t
309 // %t = cast <T2> %V to <T1>
310 // store <T1> %t2, <T1>* %P
312 if (CastInst *CI = dyn_cast<CastInst>(Pointer))
313 if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
314 if (PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
315 // convertable types?
316 if (Val->getType()->isLosslesslyConvertableTo(CSPT->getElementType()) &&
317 !SI->hasIndices()) { // No subscripts yet!
318 PRINT_PEEPHOLE3("st-src-cast:in ", Pointer, Val, SI);
320 // Insert the new T cast instruction... stealing old T's name
321 CastInst *NCI = new CastInst(Val, CSPT->getElementType(),
324 BI = BB->getInstList().insert(BI, NCI)+1;
326 // Replace the old store with a new one!
327 ReplaceInstWithInst(BB->getInstList(), BI,
328 SI = new StoreInst(NCI, CastSrc));
329 PRINT_PEEPHOLE3("st-src-cast:out", NCI, CastSrc, SI);
334 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
335 Value *Pointer = LI->getPointerOperand();
337 // Peephole optimize the following instructions:
338 // %t1 = getelementptr {<...>} * %StructPtr, <element indices>
339 // %V = load <elementty> * %t1
341 // Into: load {<...>} * %StructPtr, <element indices>
343 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Pointer)) {
344 // Append any indices that the load instruction has onto the end of the
345 // ones that the GEP is carrying...
347 vector<Value*> Indices(GEP->copyIndices());
348 Indices.insert(Indices.end(), LI->idx_begin(), LI->idx_end());
350 PRINT_PEEPHOLE2("gep-load:in", GEP, LI);
351 ReplaceInstWithInst(BB->getInstList(), BI,
352 LI = new LoadInst(GEP->getPointerOperand(),
354 PRINT_PEEPHOLE1("gep-load:out", LI);
359 // Peephole optimize the following instructions:
360 // %t1 = cast <ty> * %t0 to <ty2> *
361 // %V = load <ty2> * %t1
363 // Into: %t1 = load <ty> * %t0
364 // %V = cast <ty> %t1 to <ty2>
366 // The idea behind this transformation is that if the expression type
367 // conversion engine could not convert the cast into some other nice form,
368 // that there is something fundementally wrong with the current shape of
369 // the program. Move the cast through the load and try again. This will
370 // leave the original cast instruction, to presumably become dead.
372 if (CastInst *CI = dyn_cast<CastInst>(Pointer)) {
373 Value *SrcVal = CI->getOperand(0);
374 const PointerType *SrcTy = dyn_cast<PointerType>(SrcVal->getType());
375 const Type *ElTy = SrcTy ? SrcTy->getElementType() : 0;
377 // Make sure that nothing will be lost in the new cast...
378 if (!LI->hasIndices() && SrcTy &&
379 ElTy->isLosslesslyConvertableTo(LI->getType())) {
380 PRINT_PEEPHOLE2("CL-LoadCast:in ", CI, LI);
382 string CName = CI->getName(); CI->setName("");
383 LoadInst *NLI = new LoadInst(SrcVal, LI->getName());
384 LI->setName(""); // Take over the old load's name
386 // Insert the load before the old load
387 BI = BB->getInstList().insert(BI, NLI)+1;
389 // Replace the old load with a new cast...
390 ReplaceInstWithInst(BB->getInstList(), BI,
391 CI = new CastInst(NLI, LI->getType(), CName));
392 PRINT_PEEPHOLE2("CL-LoadCast:out", NLI, CI);
397 } else if (I->getOpcode() == Instruction::Add &&
398 isa<CastInst>(I->getOperand(1))) {
400 if (PeepholeOptimizeAddCast(BB, BI, I->getOperand(0),
401 cast<CastInst>(I->getOperand(1))))
413 static bool DoRaisePass(Method *M) {
414 bool Changed = false;
415 for (Method::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI) {
416 BasicBlock *BB = *MI;
417 BasicBlock::InstListType &BIL = BB->getInstList();
419 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
420 if (opt::DeadCodeElimination::dceInstruction(BIL, BI) ||
421 opt::ConstantPropogation::doConstantPropogation(BB, BI)) {
423 #ifdef DEBUG_PEEPHOLE_INSTS
424 cerr << "DeadCode Elinated!\n";
426 } else if (PeepholeOptimize(BB, BI))
438 // DoInsertArrayCast - If the argument value has a pointer type, and if the
439 // argument value is used as an array, insert a cast before the specified
440 // basic block iterator that casts the value to an array pointer. Return the
441 // new cast instruction (in the CastResult var), or null if no cast is inserted.
443 static bool DoInsertArrayCast(Value *V, BasicBlock *BB,
444 BasicBlock::iterator InsertBefore) {
445 const PointerType *ThePtrType = dyn_cast<PointerType>(V->getType());
446 if (!ThePtrType) return false;
448 const Type *ElTy = ThePtrType->getElementType();
449 if (isa<MethodType>(ElTy) || isa<ArrayType>(ElTy)) return false;
451 unsigned ElementSize = TD.getTypeSize(ElTy);
452 bool InsertCast = false;
454 for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
455 Instruction *Inst = cast<Instruction>(*I);
456 switch (Inst->getOpcode()) {
457 case Instruction::Cast: // There is already a cast instruction!
458 if (const PointerType *PT = dyn_cast<const PointerType>(Inst->getType()))
459 if (const ArrayType *AT = dyn_cast<const ArrayType>(PT->getElementType()))
460 if (AT->getElementType() == ThePtrType->getElementType()) {
461 // Cast already exists! Don't mess around with it.
462 return false; // No changes made to program though...
465 case Instruction::Add: { // Analyze pointer arithmetic...
466 Value *OtherOp = Inst->getOperand(Inst->getOperand(0) == V);
467 analysis::ExprType Expr = analysis::ClassifyExpression(OtherOp);
469 // This looks like array addressing iff:
470 // A. The constant of the index is larger than the size of the element
472 // B. The scale factor is >= the size of the type.
474 if (Expr.Offset && getConstantValue(Expr.Offset) >= (int)ElementSize) // A
477 if (Expr.Scale && getConstantValue(Expr.Scale) >= (int)ElementSize) // B
482 default: break; // Not an interesting use...
486 if (!InsertCast) return false; // There is no reason to insert a cast!
488 // Calculate the destination pointer type
489 const PointerType *DestTy = PointerType::get(ArrayType::get(ElTy));
491 // Check to make sure that all uses of the value can be converted over to use
492 // the newly typed value.
494 ValueTypeCache ConvertedTypes;
495 if (!ValueConvertableToType(V, DestTy, ConvertedTypes)) {
496 cerr << "FAILED to convert types of values for " << V << "\n";
497 ConvertedTypes.clear();
498 ValueConvertableToType(V, DestTy, ConvertedTypes);
501 ConvertedTypes.clear();
505 new CastInst(Constant::getNullConstant(V->getType()), DestTy, V->getName());
506 BB->getInstList().insert(InsertBefore, TheCast);
508 #ifdef DEBUG_PEEPHOLE_INSTS
509 cerr << "Inserting cast for " << V << endl;
512 // Convert users of the old value over to use the cast result...
514 ConvertValueToNewType(V, TheCast, VMC);
516 // The cast is the only thing that is allowed to reference the value...
517 TheCast->setOperand(0, V);
519 #ifdef DEBUG_PEEPHOLE_INSTS
520 cerr << "Inserted ptr-array cast: " << TheCast;
522 return true; // Made a change!
526 // DoInsertArrayCasts - Loop over all "incoming" values in the specified method,
527 // inserting a cast for pointer values that are used as arrays. For our
528 // purposes, an incoming value is considered to be either a value that is
529 // either a method parameter, or a pointer returned from a function call.
531 static bool DoInsertArrayCasts(Method *M) {
532 assert(!M->isExternal() && "Can't handle external methods!");
534 // Insert casts for all arguments to the function...
535 bool Changed = false;
536 BasicBlock *CurBB = M->front();
538 for (Method::ArgumentListType::iterator AI = M->getArgumentList().begin(),
539 AE = M->getArgumentList().end(); AI != AE; ++AI) {
541 Changed |= DoInsertArrayCast(*AI, CurBB, CurBB->begin());
544 // TODO: insert casts for alloca, malloc, and function call results. Also,
545 // look for pointers that already have casts, to add to the map.
553 // RaisePointerReferences::doit - Raise a method representation to a higher
556 bool RaisePointerReferences::doit(Method *M) {
557 if (M->isExternal()) return false;
559 #ifdef DEBUG_PEEPHOLE_INSTS
560 cerr << "\n\n\nStarting to work on Method '" << M->getName() << "'\n";
563 // Insert casts for all incoming pointer pointer values that are treated as
566 bool Changed = false, LocalChange;
567 Changed |= DoInsertArrayCasts(M);
570 // Iterate over the method, refining it, until it converges on a stable
572 bool LocalChange = false;
573 while (DoRaisePass(M)) LocalChange = true;
574 Changed |= LocalChange;
576 } while (LocalChange);