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/Support/STLExtras.h"
13 #include "llvm/iOther.h"
14 #include "llvm/iMemory.h"
15 #include "llvm/ConstPoolVals.h"
16 #include "llvm/Optimizations/ConstantHandling.h"
17 #include "llvm/Optimizations/DCE.h"
18 #include "llvm/Analysis/Expressions.h"
21 #include "llvm/Assembly/Writer.h"
23 #define DEBUG_PEEPHOLE_INSTS 1
25 #ifdef DEBUG_PEEPHOLE_INSTS
26 #define PRINT_PEEPHOLE(ID, NUM, I) \
27 cerr << "Inst P/H " << ID << "[" << NUM << "] " << I;
29 #define PRINT_PEEPHOLE(ID, NUM, I)
32 #define PRINT_PEEPHOLE1(ID, I1) do { PRINT_PEEPHOLE(ID, 0, I1); } while (0)
33 #define PRINT_PEEPHOLE2(ID, I1, I2) \
34 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); } while (0)
35 #define PRINT_PEEPHOLE3(ID, I1, I2, I3) \
36 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
37 PRINT_PEEPHOLE(ID, 2, I3); } while (0)
38 #define PRINT_PEEPHOLE4(ID, I1, I2, I3, I4) \
39 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
40 PRINT_PEEPHOLE(ID, 2, I3); PRINT_PEEPHOLE(ID, 3, I4); } while (0)
43 // isReinterpretingCast - Return true if the cast instruction specified will
44 // cause the operand to be "reinterpreted". A value is reinterpreted if the
45 // cast instruction would cause the underlying bits to change.
47 static inline bool isReinterpretingCast(const CastInst *CI) {
48 return!CI->getOperand(0)->getType()->isLosslesslyConvertableTo(CI->getType());
55 // Peephole optimize the following instructions:
56 // %t1 = cast ulong <const int> to {<...>} *
57 // %t2 = add {<...>} * %SP, %t1 ;; Constant must be 2nd operand
60 // %t1 = cast {<...>}* %SP to int*
61 // %t5 = cast ulong <const int> to int*
62 // %t2 = add int* %t1, %t5 ;; int is same size as field
64 // Into: %t3 = getelementptr {<...>} * %SP, <element indices>
65 // %t2 = cast <eltype> * %t3 to {<...>}*
67 static bool PeepholeOptimizeAddCast(BasicBlock *BB, BasicBlock::iterator &BI,
68 Value *AddOp1, CastInst *AddOp2) {
69 const CompositeType *CompTy;
70 Value *OffsetVal = AddOp2->getOperand(0);
71 Value *SrcPtr; // Of type pointer to struct...
73 if ((CompTy = getPointedToComposite(AddOp1->getType()))) {
74 SrcPtr = AddOp1; // Handle the first case...
75 } else if (CastInst *AddOp1c = dyn_cast<CastInst>(AddOp1)) {
76 SrcPtr = AddOp1c->getOperand(0); // Handle the second case...
77 CompTy = getPointedToComposite(SrcPtr->getType());
80 // Only proceed if we have detected all of our conditions successfully...
81 if (!CompTy || !SrcPtr || !OffsetVal->getType()->isIntegral())
84 vector<Value*> Indices;
85 if (!ConvertableToGEP(SrcPtr->getType(), OffsetVal, Indices, &BI))
86 return false; // Not convertable... perhaps next time
88 if (getPointedToComposite(AddOp1->getType())) { // case 1
89 PRINT_PEEPHOLE2("add-to-gep1:in", AddOp2, *BI);
91 PRINT_PEEPHOLE3("add-to-gep2:in", AddOp1, AddOp2, *BI);
94 GetElementPtrInst *GEP = new GetElementPtrInst(SrcPtr, Indices,
96 BI = BB->getInstList().insert(BI, GEP)+1;
98 Instruction *NCI = new CastInst(GEP, AddOp1->getType());
99 ReplaceInstWithInst(BB->getInstList(), BI, NCI);
100 PRINT_PEEPHOLE2("add-to-gep:out", GEP, NCI);
104 static bool PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI) {
105 Instruction *I = *BI;
107 if (CastInst *CI = dyn_cast<CastInst>(I)) {
108 Value *Src = CI->getOperand(0);
109 Instruction *SrcI = dyn_cast<Instruction>(Src); // Nonnull if instr source
110 const Type *DestTy = CI->getType();
112 // Peephole optimize the following instruction:
113 // %V2 = cast <ty> %V to <ty>
117 if (DestTy == Src->getType()) { // Check for a cast to same type as src!!
118 PRINT_PEEPHOLE1("cast-of-self-ty", CI);
119 CI->replaceAllUsesWith(Src);
120 if (!Src->hasName() && CI->hasName()) {
121 string Name = CI->getName();
123 Src->setName(Name, BB->getParent()->getSymbolTable());
128 // Peephole optimize the following instructions:
129 // %tmp = cast <ty> %V to <ty2>
130 // %V = cast <ty2> %tmp to <ty3> ; Where ty & ty2 are same size
132 // Into: cast <ty> %V to <ty3>
135 if (CastInst *CSrc = dyn_cast<CastInst>(SrcI))
136 if (isReinterpretingCast(CI) + isReinterpretingCast(CSrc) < 2) {
137 // We can only do c-c elimination if, at most, one cast does a
138 // reinterpretation of the input data.
140 // If legal, make this cast refer the the original casts argument!
142 PRINT_PEEPHOLE2("cast-cast:in ", CI, CSrc);
143 CI->setOperand(0, CSrc->getOperand(0));
144 PRINT_PEEPHOLE1("cast-cast:out", CI);
148 // Check to see if it's a cast of an instruction that does not depend on the
149 // specific type of the operands to do it's job.
150 if (!isReinterpretingCast(CI)) {
151 ValueTypeCache ConvertedTypes;
152 if (ValueConvertableToType(CI, Src->getType(), ConvertedTypes)) {
153 PRINT_PEEPHOLE2("CAST-DEST-EXPR-CONV:in ", Src, CI);
155 #ifdef DEBUG_PEEPHOLE_INSTS
156 cerr << "\nCONVERTING EXPR TYPE:\n";
158 ValueMapCache ValueMap;
159 ConvertValueToNewType(CI, Src, ValueMap); // This will delete CI!
161 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
162 PRINT_PEEPHOLE1("CAST-DEST-EXPR-CONV:out", Src);
163 #ifdef DEBUG_PEEPHOLE_INSTS
164 cerr << "DONE CONVERTING EXPR TYPE: \n\n";// << BB->getParent();
168 ConvertedTypes.clear();
169 if (ExpressionConvertableToType(Src, DestTy, ConvertedTypes)) {
170 PRINT_PEEPHOLE2("CAST-SRC-EXPR-CONV:in ", Src, CI);
172 #ifdef DEBUG_PEEPHOLE_INSTS
173 cerr << "\nCONVERTING SRC EXPR TYPE:\n";
175 ValueMapCache ValueMap;
176 Value *E = ConvertExpressionToType(Src, DestTy, ValueMap);
177 if (ConstPoolVal *CPV = dyn_cast<ConstPoolVal>(E))
178 CI->replaceAllUsesWith(CPV);
180 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
181 PRINT_PEEPHOLE1("CAST-SRC-EXPR-CONV:out", E);
182 #ifdef DEBUG_PEEPHOLE_INSTS
183 cerr << "DONE CONVERTING SRC EXPR TYPE: \n\n";// << BB->getParent();
191 // Check to see if we are casting from a structure pointer to a pointer to
192 // the first element of the structure... to avoid munching other peepholes,
193 // we only let this happen if there are no add uses of the cast.
195 // Peephole optimize the following instructions:
196 // %t1 = cast {<...>} * %StructPtr to <ty> *
198 // Into: %t2 = getelementptr {<...>} * %StructPtr, <0, 0, 0, ...>
199 // %t1 = cast <eltype> * %t1 to <ty> *
202 if (const CompositeType *CTy = getPointedToComposite(Src->getType()))
203 if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
205 // Loop over uses of the cast, checking for add instructions. If an add
206 // exists, this is probably a part of a more complex GEP, so we don't
207 // want to mess around with the cast.
209 bool HasAddUse = false;
210 for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
212 if (isa<Instruction>(*I) &&
213 cast<Instruction>(*I)->getOpcode() == Instruction::Add) {
214 HasAddUse = true; break;
217 // If it doesn't have an add use, check to see if the dest type is
218 // losslessly convertable to one of the types in the start of the struct
222 const Type *DestPointedTy = DestPTy->getValueType();
224 const CompositeType *CurCTy = CTy;
225 const Type *ElTy = 0;
227 // Build the index vector, full of all zeros
228 vector<Value*> Indices;
231 if (const StructType *CurSTy = dyn_cast<StructType>(CurCTy)) {
232 // Check for a zero element struct type... if we have one, bail.
233 if (CurSTy->getElementTypes().size() == 0) break;
235 // Grab the first element of the struct type, which must lie at
236 // offset zero in the struct.
238 ElTy = CurSTy->getElementTypes()[0];
240 ElTy = cast<ArrayType>(CurCTy)->getElementType();
243 // Insert a zero to index through this type...
244 Indices.push_back(ConstPoolUInt::get(CurCTy->getIndexType(), 0));
246 // Did we find what we're looking for?
247 if (ElTy->isLosslesslyConvertableTo(DestPointedTy)) break;
249 // Nope, go a level deeper.
251 CurCTy = dyn_cast<CompositeType>(ElTy);
255 // Did we find what we were looking for? If so, do the transformation
257 PRINT_PEEPHOLE1("cast-for-first:in", CI);
259 // Insert the new T cast instruction... stealing old T's name
260 GetElementPtrInst *GEP = new GetElementPtrInst(Src, Indices,
263 BI = BB->getInstList().insert(BI, GEP)+1;
265 // Make the old cast instruction reference the new GEP instead of
266 // the old src value.
268 CI->setOperand(0, GEP);
270 PRINT_PEEPHOLE2("cast-for-first:out", GEP, CI);
278 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
279 Value *Val = SI->getOperand(0);
280 Value *Pointer = SI->getPointerOperand();
282 // Peephole optimize the following instructions:
283 // %t1 = getelementptr {<...>} * %StructPtr, <element indices>
284 // store <elementty> %v, <elementty> * %t1
286 // Into: store <elementty> %v, {<...>} * %StructPtr, <element indices>
288 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Pointer)) {
289 // Append any indices that the store instruction has onto the end of the
290 // ones that the GEP is carrying...
292 vector<Value*> Indices(GEP->copyIndices());
293 Indices.insert(Indices.end(), SI->idx_begin(), SI->idx_end());
295 PRINT_PEEPHOLE2("gep-store:in", GEP, SI);
296 ReplaceInstWithInst(BB->getInstList(), BI,
297 SI = new StoreInst(Val, GEP->getPointerOperand(),
299 PRINT_PEEPHOLE1("gep-store:out", SI);
303 // Peephole optimize the following instructions:
304 // %t = cast <T1>* %P to <T2> * ;; If T1 is losslessly convertable to T2
305 // store <T2> %V, <T2>* %t
308 // %t = cast <T2> %V to <T1>
309 // store <T1> %t2, <T1>* %P
311 if (CastInst *CI = dyn_cast<CastInst>(Pointer))
312 if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
313 if (PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
314 // convertable types?
315 if (Val->getType()->isLosslesslyConvertableTo(CSPT->getValueType()) &&
316 !SI->hasIndices()) { // No subscripts yet!
317 PRINT_PEEPHOLE3("st-src-cast:in ", Pointer, Val, SI);
319 // Insert the new T cast instruction... stealing old T's name
320 CastInst *NCI = new CastInst(Val, CSPT->getValueType(),
323 BI = BB->getInstList().insert(BI, NCI)+1;
325 // Replace the old store with a new one!
326 ReplaceInstWithInst(BB->getInstList(), BI,
327 SI = new StoreInst(NCI, CastSrc));
328 PRINT_PEEPHOLE3("st-src-cast:out", NCI, CastSrc, SI);
333 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
334 Value *Pointer = LI->getPointerOperand();
336 // Peephole optimize the following instructions:
337 // %t1 = getelementptr {<...>} * %StructPtr, <element indices>
338 // %V = load <elementty> * %t1
340 // Into: load {<...>} * %StructPtr, <element indices>
342 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Pointer)) {
343 // Append any indices that the load instruction has onto the end of the
344 // ones that the GEP is carrying...
346 vector<Value*> Indices(GEP->copyIndices());
347 Indices.insert(Indices.end(), LI->idx_begin(), LI->idx_end());
349 PRINT_PEEPHOLE2("gep-load:in", GEP, LI);
350 ReplaceInstWithInst(BB->getInstList(), BI,
351 LI = new LoadInst(GEP->getPointerOperand(),
353 PRINT_PEEPHOLE1("gep-load:out", LI);
358 // Peephole optimize the following instructions:
359 // %t1 = cast <ty> * %t0 to <ty2> *
360 // %V = load <ty2> * %t1
362 // Into: %t1 = load <ty> * %t0
363 // %V = cast <ty> %t1 to <ty2>
365 // The idea behind this transformation is that if the expression type
366 // conversion engine could not convert the cast into some other nice form,
367 // that there is something fundementally wrong with the current shape of
368 // the program. Move the cast through the load and try again. This will
369 // leave the original cast instruction, to presumably become dead.
371 if (CastInst *CI = dyn_cast<CastInst>(Pointer)) {
372 Value *SrcVal = CI->getOperand(0);
373 const PointerType *SrcTy = dyn_cast<PointerType>(SrcVal->getType());
374 const Type *ElTy = SrcTy ? SrcTy->getValueType() : 0;
376 // Make sure that nothing will be lost in the new cast...
377 if (!LI->hasIndices() && SrcTy &&
378 ElTy->isLosslesslyConvertableTo(LI->getType())) {
379 PRINT_PEEPHOLE2("CL-LoadCast:in ", CI, LI);
381 string CName = CI->getName(); CI->setName("");
382 LoadInst *NLI = new LoadInst(SrcVal, LI->getName());
383 LI->setName(""); // Take over the old load's name
385 // Insert the load before the old load
386 BI = BB->getInstList().insert(BI, NLI)+1;
388 // Replace the old load with a new cast...
389 ReplaceInstWithInst(BB->getInstList(), BI,
390 CI = new CastInst(NLI, LI->getType(), CName));
391 PRINT_PEEPHOLE2("CL-LoadCast:out", NLI, CI);
396 } else if (I->getOpcode() == Instruction::Add &&
397 isa<CastInst>(I->getOperand(1))) {
399 if (PeepholeOptimizeAddCast(BB, BI, I->getOperand(0),
400 cast<CastInst>(I->getOperand(1))))
412 static bool DoRaisePass(Method *M) {
413 bool Changed = false;
414 for (Method::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI) {
415 BasicBlock *BB = *MI;
416 BasicBlock::InstListType &BIL = BB->getInstList();
418 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
419 if (opt::DeadCodeElimination::dceInstruction(BIL, BI)) {
421 #ifdef DEBUG_PEEPHOLE_INSTS
422 cerr << "DeadCode Elinated!\n";
424 } else if (PeepholeOptimize(BB, BI))
436 // DoInsertArrayCast - If the argument value has a pointer type, and if the
437 // argument value is used as an array, insert a cast before the specified
438 // basic block iterator that casts the value to an array pointer. Return the
439 // new cast instruction (in the CastResult var), or null if no cast is inserted.
441 static bool DoInsertArrayCast(Value *V, BasicBlock *BB,
442 BasicBlock::iterator InsertBefore) {
443 const PointerType *ThePtrType = dyn_cast<PointerType>(V->getType());
444 if (!ThePtrType) return false;
446 const Type *ElTy = ThePtrType->getValueType();
447 if (isa<MethodType>(ElTy) || isa<ArrayType>(ElTy)) return false;
449 unsigned ElementSize = TD.getTypeSize(ElTy);
450 bool InsertCast = false;
452 for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
453 Instruction *Inst = cast<Instruction>(*I);
454 switch (Inst->getOpcode()) {
455 case Instruction::Cast: // There is already a cast instruction!
456 if (const PointerType *PT = dyn_cast<const PointerType>(Inst->getType()))
457 if (const ArrayType *AT = dyn_cast<const ArrayType>(PT->getValueType()))
458 if (AT->getElementType() == ThePtrType->getValueType()) {
459 // Cast already exists! Don't mess around with it.
460 return false; // No changes made to program though...
463 case Instruction::Add: { // Analyze pointer arithmetic...
464 Value *OtherOp = Inst->getOperand(Inst->getOperand(0) == V);
465 analysis::ExprType Expr = analysis::ClassifyExpression(OtherOp);
467 // This looks like array addressing iff:
468 // A. The constant of the index is larger than the size of the element
470 // B. The scale factor is >= the size of the type.
472 if (Expr.Offset && getConstantValue(Expr.Offset) >= (int)ElementSize) // A
475 if (Expr.Scale && getConstantValue(Expr.Scale) >= (int)ElementSize) // B
480 default: break; // Not an interesting use...
484 if (!InsertCast) return false; // There is no reason to insert a cast!
486 // Calculate the destination pointer type
487 const PointerType *DestTy = PointerType::get(ArrayType::get(ElTy));
489 // Check to make sure that all uses of the value can be converted over to use
490 // the newly typed value.
492 ValueTypeCache ConvertedTypes;
493 if (!ValueConvertableToType(V, DestTy, ConvertedTypes)) {
494 cerr << "FAILED to convert types of values for " << V << "\n";
495 ConvertedTypes.clear();
496 ValueConvertableToType(V, DestTy, ConvertedTypes);
499 ConvertedTypes.clear();
503 new CastInst(ConstPoolVal::getNullConstant(V->getType()), DestTy,
505 BB->getInstList().insert(InsertBefore, TheCast);
507 cerr << "Inserting cast for " << V << endl;
509 // Convert users of the old value over to use the cast result...
511 ConvertValueToNewType(V, TheCast, VMC);
513 // The cast is the only thing that is allowed to reference the value...
514 TheCast->setOperand(0, V);
516 cerr << "Inserted ptr-array cast: " << TheCast;
517 return true; // Made a change!
521 // DoInsertArrayCasts - Loop over all "incoming" values in the specified method,
522 // inserting a cast for pointer values that are used as arrays. For our
523 // purposes, an incoming value is considered to be either a value that is
524 // either a method parameter, or a pointer returned from a function call.
526 static bool DoInsertArrayCasts(Method *M) {
527 assert(!M->isExternal() && "Can't handle external methods!");
529 // Insert casts for all arguments to the function...
530 bool Changed = false;
531 BasicBlock *CurBB = M->front();
533 for (Method::ArgumentListType::iterator AI = M->getArgumentList().begin(),
534 AE = M->getArgumentList().end(); AI != AE; ++AI) {
536 Changed |= DoInsertArrayCast(*AI, CurBB, CurBB->begin());
539 // TODO: insert casts for alloca, malloc, and function call results. Also,
540 // look for pointers that already have casts, to add to the map.
548 // RaisePointerReferences::doit - Raise a method representation to a higher
551 bool RaisePointerReferences::doit(Method *M) {
552 if (M->isExternal()) return false;
554 #ifdef DEBUG_PEEPHOLE_INSTS
555 cerr << "\n\n\nStarting to work on Method '" << M->getName() << "'\n";
558 // Insert casts for all incoming pointer pointer values that are treated as
561 bool Changed = false, LocalChange;
563 LocalChange = DoInsertArrayCasts(M);
565 // Iterate over the method, refining it, until it converges on a stable
567 while (DoRaisePass(M)) LocalChange = true;
568 Changed |= LocalChange;
570 } while (LocalChange);