blob: 039bfd20d726be973de60131f43a01fd0c329270 [file] [log] [blame]
Chris Lattnerd32a9612001-11-01 02:42:08 +00001//===- LevelRaise.cpp - Code to change LLVM to higher level -----------------=//
2//
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
5// analyze. Note that it is good to run DCE after doing this transformation.
6//
7// Eliminate silly things in the source that do not effect the level, but do
8// clean up the code:
9// * Casts of casts
10// - getelementptr/load & getelementptr/store are folded into a direct
11// load or store
12// - Convert this code (for both alloca and malloc):
13// %reg110 = shl uint %n, ubyte 2 ;;<uint>
14// %reg108 = alloca ubyte, uint %reg110 ;;<ubyte*>
15// %cast76 = cast ubyte* %reg108 to uint* ;;<uint*>
16// To: %cast76 = alloca uint, uint %n
17// Convert explicit addressing to use getelementptr instruction where possible
18// - ...
19//
20// Convert explicit addressing on pointers to use getelementptr instruction.
21// - If a pointer is used by arithmetic operation, insert an array casted
22// version into the source program, only for the following pointer types:
23// * Method argument pointers
24// - Pointers returned by alloca or malloc
25// - Pointers returned by function calls
26// - If a pointer is indexed with a value scaled by a constant size equal
27// to the element size of the array, the expression is replaced with a
28// getelementptr instruction.
29//
30//===----------------------------------------------------------------------===//
31
32#include "llvm/Transforms/LevelChange.h"
33#include "llvm/Method.h"
34#include "llvm/Support/STLExtras.h"
35#include "llvm/iOther.h"
36#include "llvm/iMemory.h"
37#include "llvm/ConstPoolVals.h"
38#include "llvm/Target/TargetData.h"
Chris Lattnerdedee7b2001-11-01 05:57:59 +000039#include "llvm/Optimizations/ConstantHandling.h"
Chris Lattner68b07b72001-11-01 07:00:51 +000040#include "llvm/Optimizations/DCE.h"
Chris Lattnerd32a9612001-11-01 02:42:08 +000041#include <map>
42#include <algorithm>
43
44#include "llvm/Assembly/Writer.h"
45
46//#define DEBUG_PEEPHOLE_INSTS 1
47
48#ifdef DEBUG_PEEPHOLE_INSTS
49#define PRINT_PEEPHOLE(ID, NUM, I) \
50 cerr << "Inst P/H " << ID << "[" << NUM << "] " << I;
51#else
52#define PRINT_PEEPHOLE(ID, NUM, I)
53#endif
54
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
62
63// TargetData Hack: Eventually we will have annotations given to us by the
64// backend so that we know stuff about type size and alignments. For now
65// though, just use this, because it happens to match the model that GCC uses.
66//
67const TargetData TD("LevelRaise: Should be GCC though!");
68
69
70// losslessCastableTypes - Return true if the types are bitwise equivalent.
71// This predicate returns true if it is possible to cast from one type to
72// another without gaining or losing precision, or altering the bits in any way.
73//
74static bool losslessCastableTypes(const Type *T1, const Type *T2) {
Chris Lattnerdedee7b2001-11-01 05:57:59 +000075 if (!T1->isPrimitiveType() && !isa<PointerType>(T1)) return false;
76 if (!T2->isPrimitiveType() && !isa<PointerType>(T2)) return false;
Chris Lattnerd32a9612001-11-01 02:42:08 +000077
78 if (T1->getPrimitiveID() == T2->getPrimitiveID())
79 return true; // Handles identity cast, and cast of differing pointer types
80
81 // Now we know that they are two differing primitive or pointer types
82 switch (T1->getPrimitiveID()) {
83 case Type::UByteTyID: return T2 == Type::SByteTy;
84 case Type::SByteTyID: return T2 == Type::UByteTy;
85 case Type::UShortTyID: return T2 == Type::ShortTy;
86 case Type::ShortTyID: return T2 == Type::UShortTy;
87 case Type::UIntTyID: return T2 == Type::IntTy;
88 case Type::IntTyID: return T2 == Type::UIntTy;
89 case Type::ULongTyID:
90 case Type::LongTyID:
91 case Type::PointerTyID:
92 return T2 == Type::ULongTy || T2 == Type::LongTy ||
93 T2->getPrimitiveID() == Type::PointerTyID;
94 default:
95 return false; // Other types have no identity values
96 }
97}
98
99
100// isReinterpretingCast - Return true if the cast instruction specified will
101// cause the operand to be "reinterpreted". A value is reinterpreted if the
102// cast instruction would cause the underlying bits to change.
103//
104static inline bool isReinterpretingCast(const CastInst *CI) {
105 return !losslessCastableTypes(CI->getOperand(0)->getType(), CI->getType());
106}
107
108
109// getPointedToStruct - If the argument is a pointer type, and the pointed to
110// value is a struct type, return the struct type, else return null.
111//
112static const StructType *getPointedToStruct(const Type *Ty) {
113 const PointerType *PT = dyn_cast<PointerType>(Ty);
114 return PT ? dyn_cast<StructType>(PT->getValueType()) : 0;
115}
116
117
118// getStructOffsetType - Return a vector of offsets that are to be used to index
119// into the specified struct type to get as close as possible to index as we
120// can. Note that it is possible that we cannot get exactly to Offset, in which
121// case we update offset to be the offset we actually obtained. The resultant
122// leaf type is returned.
123//
124static const Type *getStructOffsetType(const Type *Ty, unsigned &Offset,
125 vector<ConstPoolVal*> &Offsets) {
126 if (!isa<StructType>(Ty)) {
127 Offset = 0; // Return the offset that we were able to acheive
128 return Ty; // Return the leaf type
129 }
130
131 assert(Offset < TD.getTypeSize(Ty) && "Offset not in struct!");
132 const StructType *STy = cast<StructType>(Ty);
133 const StructLayout *SL = TD.getStructLayout(STy);
134
135 // This loop terminates always on a 0 <= i < MemberOffsets.size()
136 unsigned i;
137 for (i = 0; i < SL->MemberOffsets.size()-1; ++i)
138 if (Offset >= SL->MemberOffsets[i] && Offset < SL->MemberOffsets[i+1])
139 break;
140
Chris Lattner68b07b72001-11-01 07:00:51 +0000141 assert(Offset >= SL->MemberOffsets[i] &&
142 (i == SL->MemberOffsets.size()-1 || Offset < SL->MemberOffsets[i+1]));
Chris Lattnerd32a9612001-11-01 02:42:08 +0000143
144 // Make sure to save the current index...
145 Offsets.push_back(ConstPoolUInt::get(Type::UByteTy, i));
146
147 unsigned SubOffs = Offset - SL->MemberOffsets[i];
148 const Type *LeafTy = getStructOffsetType(STy->getElementTypes()[i], SubOffs,
149 Offsets);
150 Offset = SL->MemberOffsets[i] + SubOffs;
151 return LeafTy;
152}
153
154
155
156// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
157// with a value, then remove and delete the original instruction.
158//
159static void ReplaceInstWithValue(BasicBlock::InstListType &BIL,
160 BasicBlock::iterator &BI, Value *V) {
161 Instruction *I = *BI;
162 // Replaces all of the uses of the instruction with uses of the value
163 I->replaceAllUsesWith(V);
164
165 // Remove the unneccesary instruction now...
166 BIL.remove(BI);
167
168 // Make sure to propogate a name if there is one already...
169 if (I->hasName() && !V->hasName())
170 V->setName(I->getName(), BIL.getParent()->getSymbolTable());
171
172 // Remove the dead instruction now...
173 delete I;
174}
175
176
177// ReplaceInstWithInst - Replace the instruction specified by BI with the
178// instruction specified by I. The original instruction is deleted and BI is
179// updated to point to the new instruction.
180//
181static void ReplaceInstWithInst(BasicBlock::InstListType &BIL,
182 BasicBlock::iterator &BI, Instruction *I) {
183 assert(I->getParent() == 0 &&
184 "ReplaceInstWithInst: Instruction already inserted into basic block!");
185
186 // Insert the new instruction into the basic block...
187 BI = BIL.insert(BI, I)+1;
188
189 // Replace all uses of the old instruction, and delete it.
190 ReplaceInstWithValue(BIL, BI, I);
191
192 // Reexamine the instruction just inserted next time around the cleanup pass
193 // loop.
194 --BI;
195}
196
197
198// ExpressionConvertableToType - Return true if it is possible
199static bool ExpressionConvertableToType(Value *V, const Type *Ty) {
200 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000201 if (I == 0) {
202 // It's not an instruction, check to see if it's a constant... all constants
203 // can be converted to an equivalent value (except pointers, they can't be
204 // const prop'd in general).
205 //
206 if (isa<ConstPoolVal>(V) &&
207 !isa<PointerType>(V->getType()) && !isa<PointerType>(Ty)) return true;
208
209 return false; // Otherwise, we can't convert!
210 }
Chris Lattnerd32a9612001-11-01 02:42:08 +0000211 if (I->getType() == Ty) return false; // Expression already correct type!
212
213 switch (I->getOpcode()) {
214 case Instruction::Cast:
215 // We can convert the expr if the cast destination type is losslessly
216 // convertable to the requested type.
217 return losslessCastableTypes(Ty, I->getType());
218
219 case Instruction::Add:
220 case Instruction::Sub:
221 return ExpressionConvertableToType(I->getOperand(0), Ty) &&
222 ExpressionConvertableToType(I->getOperand(1), Ty);
223 case Instruction::Shl:
224 case Instruction::Shr:
225 return ExpressionConvertableToType(I->getOperand(0), Ty);
226 }
227 return false;
228}
229
230
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000231static Value *ConvertExpressionToType(Value *V, const Type *Ty) {
232 assert(ExpressionConvertableToType(V, Ty) && "Value is not convertable!");
233 Instruction *I = dyn_cast<Instruction>(V);
234 if (I == 0)
235 if (ConstPoolVal *CPV = cast<ConstPoolVal>(V)) {
236 // Constants are converted by constant folding the cast that is required.
237 // We assume here that all casts are implemented for constant prop.
238 Value *Result = opt::ConstantFoldCastInstruction(CPV, Ty);
239 if (!Result) cerr << "Couldn't fold " << CPV << " to " << Ty << endl;
240 assert(Result && "ConstantFoldCastInstruction Failed!!!");
241 return Result;
242 }
243
244
Chris Lattnerd32a9612001-11-01 02:42:08 +0000245 BasicBlock *BB = I->getParent();
246 BasicBlock::InstListType &BIL = BB->getInstList();
247 string Name = I->getName(); if (!Name.empty()) I->setName("");
248 Instruction *Res; // Result of conversion
249
250 //cerr << endl << endl << "Type:\t" << Ty << "\nInst: " << I << "BB Before: " << BB << endl;
251
252 switch (I->getOpcode()) {
253 case Instruction::Cast:
254 Res = new CastInst(I->getOperand(0), Ty, Name);
255 break;
256
257 case Instruction::Add:
258 case Instruction::Sub:
259 Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
260 ConvertExpressionToType(I->getOperand(0), Ty),
261 ConvertExpressionToType(I->getOperand(1), Ty),
262 Name);
263 break;
264
265 case Instruction::Shl:
266 case Instruction::Shr:
267 Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(),
268 ConvertExpressionToType(I->getOperand(0), Ty),
269 I->getOperand(1), Name);
270 break;
271
272 default:
273 assert(0 && "Expression convertable, but don't know how to convert?");
274 return 0;
275 }
276
277 BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
278 assert(It != BIL.end() && "Instruction not in own basic block??");
279 BIL.insert(It, Res);
280
281 //cerr << "RInst: " << Res << "BB After: " << BB << endl << endl;
282
283 return Res;
284}
285
286
287
288// DoInsertArrayCast - If the argument value has a pointer type, and if the
289// argument value is used as an array, insert a cast before the specified
290// basic block iterator that casts the value to an array pointer. Return the
291// new cast instruction (in the CastResult var), or null if no cast is inserted.
292//
293static bool DoInsertArrayCast(Method *CurMeth, Value *V, BasicBlock *BB,
294 BasicBlock::iterator &InsertBefore,
295 CastInst *&CastResult) {
296 const PointerType *ThePtrType = dyn_cast<PointerType>(V->getType());
297 if (!ThePtrType) return false;
298 bool InsertCast = false;
299
300 for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
301 Instruction *Inst = cast<Instruction>(*I);
302 switch (Inst->getOpcode()) {
303 default: break; // Not an interesting use...
304 case Instruction::Add: // It's being used as an array index!
305 //case Instruction::Sub:
306 InsertCast = true;
307 break;
308 case Instruction::Cast: // There is already a cast instruction!
309 if (const PointerType *PT = dyn_cast<const PointerType>(Inst->getType()))
310 if (const ArrayType *AT = dyn_cast<const ArrayType>(PT->getValueType()))
311 if (AT->getElementType() == ThePtrType->getValueType()) {
312 // Cast already exists! Return the existing one!
313 CastResult = cast<CastInst>(Inst);
314 return false; // No changes made to program though...
315 }
316 break;
317 }
318 }
319
320 if (!InsertCast) return false; // There is no reason to insert a cast!
321
322 // Insert a cast!
323 const Type *ElTy = ThePtrType->getValueType();
324 const PointerType *DestTy = PointerType::get(ArrayType::get(ElTy));
325
326 CastResult = new CastInst(V, DestTy);
327 BB->getInstList().insert(InsertBefore, CastResult);
328 //cerr << "Inserted cast: " << CastResult;
329 return true; // Made a change!
330}
331
332
333// DoInsertArrayCasts - Loop over all "incoming" values in the specified method,
334// inserting a cast for pointer values that are used as arrays. For our
335// purposes, an incoming value is considered to be either a value that is
336// either a method parameter, a value created by alloca or malloc, or a value
337// returned from a function call. All casts are kept attached to their original
338// values through the PtrCasts map.
339//
340static bool DoInsertArrayCasts(Method *M, map<Value*, CastInst*> &PtrCasts) {
341 assert(!M->isExternal() && "Can't handle external methods!");
342
343 // Insert casts for all arguments to the function...
344 bool Changed = false;
345 BasicBlock *CurBB = M->front();
346 BasicBlock::iterator It = CurBB->begin();
347 for (Method::ArgumentListType::iterator AI = M->getArgumentList().begin(),
348 AE = M->getArgumentList().end(); AI != AE; ++AI) {
349 CastInst *TheCast = 0;
350 if (DoInsertArrayCast(M, *AI, CurBB, It, TheCast)) {
351 It = CurBB->begin(); // We might have just invalidated the iterator!
352 Changed = true; // Yes we made a change
353 ++It; // Insert next cast AFTER this one...
354 }
355
356 if (TheCast) // Is there a cast associated with this value?
357 PtrCasts[*AI] = TheCast; // Yes, add it to the map...
358 }
359
360 // TODO: insert casts for alloca, malloc, and function call results. Also,
361 // look for pointers that already have casts, to add to the map.
362
363 return Changed;
364}
365
366
367
368
369// DoElminatePointerArithmetic - Loop over each incoming pointer variable,
370// replacing indexing arithmetic with getelementptr calls.
371//
372static bool DoEliminatePointerArithmetic(const pair<Value*, CastInst*> &Val) {
373 Value *V = Val.first; // The original pointer
374 CastInst *CV = Val.second; // The array casted version of the pointer...
375
376 for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
377 Instruction *Inst = cast<Instruction>(*I);
378 if (Inst->getOpcode() != Instruction::Add)
379 continue; // We only care about add instructions
380
381 BinaryOperator *Add = cast<BinaryOperator>(Inst);
382
383 // Make sure the array is the first operand of the add expression...
384 if (Add->getOperand(0) != V)
385 Add->swapOperands();
386
387 // Get the amount added to the pointer value...
388 Value *AddAmount = Add->getOperand(1);
389
390
391 }
392 return false;
393}
394
395
396// Peephole Malloc instructions: we take a look at the use chain of the
397// malloc instruction, and try to find out if the following conditions hold:
398// 1. The malloc is of the form: 'malloc [sbyte], uint <constant>'
399// 2. The only users of the malloc are cast instructions
400// 3. Of the cast instructions, there is only one destination pointer type
401// [RTy] where the size of the pointed to object is equal to the number
402// of bytes allocated.
403//
404// If these conditions hold, we convert the malloc to allocate an [RTy]
405// element. This should be extended in the future to handle arrays. TODO
406//
407static bool PeepholeMallocInst(BasicBlock *BB, BasicBlock::iterator &BI) {
408 MallocInst *MI = cast<MallocInst>(*BI);
409 if (!MI->isArrayAllocation()) return false; // No array allocation?
410
411 ConstPoolUInt *Amt = dyn_cast<ConstPoolUInt>(MI->getArraySize());
412 if (Amt == 0 || MI->getAllocatedType() != ArrayType::get(Type::SByteTy))
413 return false;
414
415 // Get the number of bytes allocated...
416 unsigned Size = Amt->getValue();
417 const Type *ResultTy = 0;
418
419 // Loop over all of the uses of the malloc instruction, inspecting casts.
420 for (Value::use_iterator I = MI->use_begin(), E = MI->use_end();
421 I != E; ++I) {
422 if (!isa<CastInst>(*I)) {
423 //cerr << "\tnon" << *I;
424 return false; // A non cast user?
425 }
426 CastInst *CI = cast<CastInst>(*I);
427 //cerr << "\t" << CI;
428
429 // We only work on casts to pointer types for sure, be conservative
430 if (!isa<PointerType>(CI->getType())) {
431 cerr << "Found cast of malloc value to non pointer type:\n" << CI;
432 return false;
433 }
434
435 const Type *DestTy = cast<PointerType>(CI->getType())->getValueType();
436 if (TD.getTypeSize(DestTy) == Size && DestTy != ResultTy) {
437 // Does the size of the allocated type match the number of bytes
438 // allocated?
439 //
440 if (ResultTy == 0) {
441 ResultTy = DestTy; // Keep note of this for future uses...
442 } else {
443 // It's overdefined! We don't know which type to convert to!
444 return false;
445 }
446 }
447 }
448
449 // If we get this far, we have either found, or not, a type that is cast to
450 // that is of the same size as the malloc instruction.
451 if (!ResultTy) return false;
452
453 PRINT_PEEPHOLE1("mall-refine:in ", MI);
454 ReplaceInstWithInst(BB->getInstList(), BI,
455 MI = new MallocInst(PointerType::get(ResultTy)));
456 PRINT_PEEPHOLE1("mall-refine:out", MI);
457 return true;
458}
459
460
461
462static bool PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI) {
463 Instruction *I = *BI;
Chris Lattnerd32a9612001-11-01 02:42:08 +0000464
465 if (CastInst *CI = dyn_cast<CastInst>(I)) {
466 Value *Src = CI->getOperand(0);
467 Instruction *SrcI = dyn_cast<Instruction>(Src); // Nonnull if instr source
468 const Type *DestTy = CI->getType();
469
Chris Lattnere99c66b2001-11-01 17:05:27 +0000470 // Peephole optimize the following instruction:
471 // %V2 = cast <ty> %V to <ty>
472 //
473 // Into: <nothing>
474 //
475 if (DestTy == Src->getType()) { // Check for a cast to same type as src!!
Chris Lattnerd32a9612001-11-01 02:42:08 +0000476 PRINT_PEEPHOLE1("cast-of-self-ty", CI);
477 CI->replaceAllUsesWith(Src);
478 if (!Src->hasName() && CI->hasName()) {
479 string Name = CI->getName();
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000480 CI->setName(""); Src->setName(Name,
481 BB->getParent()->getSymbolTable());
Chris Lattnerd32a9612001-11-01 02:42:08 +0000482 }
483 return true;
484 }
485
Chris Lattnere99c66b2001-11-01 17:05:27 +0000486 // Peephole optimize the following instructions:
487 // %tmp = cast <ty> %V to <ty2>
488 // %V = cast <ty2> %tmp to <ty3> ; Where ty & ty2 are same size
489 //
490 // Into: cast <ty> %V to <ty3>
491 //
Chris Lattnerd32a9612001-11-01 02:42:08 +0000492 if (SrcI)
493 if (CastInst *CSrc = dyn_cast<CastInst>(SrcI))
494 if (isReinterpretingCast(CI) + isReinterpretingCast(CSrc) < 2) {
495 // We can only do c-c elimination if, at most, one cast does a
496 // reinterpretation of the input data.
497 //
498 // If legal, make this cast refer the the original casts argument!
499 //
500 PRINT_PEEPHOLE2("cast-cast:in ", CI, CSrc);
501 CI->setOperand(0, CSrc->getOperand(0));
502 PRINT_PEEPHOLE1("cast-cast:out", CI);
503 return true;
504 }
505
506 // Check to see if it's a cast of an instruction that does not depend on the
507 // specific type of the operands to do it's job.
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000508 if (!isReinterpretingCast(CI) &&
509 ExpressionConvertableToType(Src, DestTy)) {
510 PRINT_PEEPHOLE2("EXPR-CONV:in ", CI, Src);
511 CI->setOperand(0, ConvertExpressionToType(Src, DestTy));
Chris Lattnerd32a9612001-11-01 02:42:08 +0000512 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
513 PRINT_PEEPHOLE2("EXPR-CONV:out", CI, CI->getOperand(0));
514 return true;
515 }
516
Chris Lattnere99c66b2001-11-01 17:05:27 +0000517 // Check to see if we are casting from a structure pointer to a pointer to
518 // the first element of the structure... to avoid munching other peepholes,
519 // we only let this happen if there are no add uses of the cast.
520 //
521 // Peephole optimize the following instructions:
522 // %t1 = cast {<...>} * %StructPtr to <ty> *
523 //
524 // Into: %t2 = getelementptr {<...>} * %StructPtr, <0, 0, 0, ...>
525 // %t1 = cast <eltype> * %t1 to <ty> *
526 //
527 if (const StructType *STy = getPointedToStruct(Src->getType()))
528 if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
529
530 // Loop over uses of the cast, checking for add instructions. If an add
531 // exists, this is probably a part of a more complex GEP, so we don't
532 // want to mess around with the cast.
533 //
534 bool HasAddUse = false;
535 for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
536 I != E; ++I)
537 if (isa<Instruction>(*I) &&
538 cast<Instruction>(*I)->getOpcode() == Instruction::Add) {
539 HasAddUse = true; break;
540 }
541
542 // If it doesn't have an add use, check to see if the dest type is
543 // losslessly convertable to one of the types in the start of the struct
544 // type.
545 //
546 if (!HasAddUse) {
547 const Type *DestPointedTy = DestPTy->getValueType();
548 unsigned Depth = 1;
549 const StructType *CurSTy = STy;
550 const Type *ElTy = 0;
551 while (CurSTy) {
552
553 // Check for a zero element struct type... if we have one, bail.
554 if (CurSTy->getElementTypes().size() == 0) break;
555
556 // Grab the first element of the struct type, which must lie at
557 // offset zero in the struct.
558 //
559 ElTy = CurSTy->getElementTypes()[0];
560
561 // Did we find what we're looking for?
562 if (losslessCastableTypes(ElTy, DestPointedTy)) break;
563
564 // Nope, go a level deeper.
565 ++Depth;
566 CurSTy = dyn_cast<StructType>(ElTy);
567 ElTy = 0;
568 }
569
570 // Did we find what we were looking for? If so, do the transformation
571 if (ElTy) {
572 PRINT_PEEPHOLE1("cast-for-first:in", CI);
573
574 // Build the index vector, full of all zeros
575 vector<ConstPoolVal *> Indices(Depth,
576 ConstPoolUInt::get(Type::UByteTy,0));
577
578 // Insert the new T cast instruction... stealing old T's name
579 GetElementPtrInst *GEP = new GetElementPtrInst(Src, Indices,
580 CI->getName());
581 CI->setName("");
582 BI = BB->getInstList().insert(BI, GEP)+1;
583
584 // Make the old cast instruction reference the new GEP instead of
585 // the old src value.
586 //
587 CI->setOperand(0, GEP);
588
589 PRINT_PEEPHOLE2("cast-for-first:out", GEP, CI);
590 return true;
591 }
592 }
593 }
594
595
Chris Lattnerd32a9612001-11-01 02:42:08 +0000596 } else if (MallocInst *MI = dyn_cast<MallocInst>(I)) {
597 if (PeepholeMallocInst(BB, BI)) return true;
Chris Lattner8d38e542001-11-01 03:12:34 +0000598
599 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
600 Value *Val = SI->getOperand(0);
601 Value *Pointer = SI->getPtrOperand();
602
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000603 // Peephole optimize the following instructions:
604 // %t1 = getelementptr {<...>} * %StructPtr, <element indices>
605 // store <elementty> %v, <elementty> * %t1
606 //
607 // Into: store <elementty> %v, {<...>} * %StructPtr, <element indices>
608 //
Chris Lattner8d38e542001-11-01 03:12:34 +0000609 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Pointer)) {
610 PRINT_PEEPHOLE2("gep-store:in", GEP, SI);
611 ReplaceInstWithInst(BB->getInstList(), BI,
612 SI = new StoreInst(Val, GEP->getPtrOperand(),
613 GEP->getIndexVec()));
614 PRINT_PEEPHOLE1("gep-store:out", SI);
615 return true;
616 }
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000617
618 // Peephole optimize the following instructions:
619 // %t = cast <T1>* %P to <T2> * ;; If T1 is losslessly convertable to T2
620 // store <T2> %V, <T2>* %t
621 //
622 // Into:
623 // %t = cast <T2> %V to <T1>
624 // store <T1> %t2, <T1>* %P
625 //
626 if (CastInst *CI = dyn_cast<CastInst>(Pointer))
627 if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
628 if (PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
629 if (losslessCastableTypes(Val->getType(), // convertable types!
630 CSPT->getValueType()) &&
631 !SI->hasIndices()) { // No subscripts yet!
632 PRINT_PEEPHOLE3("st-src-cast:in ", Pointer, Val, SI);
633
634 // Insert the new T cast instruction... stealing old T's name
635 CastInst *NCI = new CastInst(Val, CSPT->getValueType(),
636 CI->getName());
637 CI->setName("");
638 BI = BB->getInstList().insert(BI, NCI)+1;
639
640 // Replace the old store with a new one!
641 ReplaceInstWithInst(BB->getInstList(), BI,
642 SI = new StoreInst(NCI, CastSrc));
643 PRINT_PEEPHOLE3("st-src-cast:out", NCI, CastSrc, SI);
644 return true;
645 }
646
Chris Lattner8d38e542001-11-01 03:12:34 +0000647
648 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
649 Value *Pointer = LI->getPtrOperand();
650
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000651 // Peephole optimize the following instructions:
652 // %t1 = getelementptr {<...>} * %StructPtr, <element indices>
653 // %V = load <elementty> * %t1
654 //
655 // Into: load {<...>} * %StructPtr, <element indices>
656 //
Chris Lattner8d38e542001-11-01 03:12:34 +0000657 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Pointer)) {
658 PRINT_PEEPHOLE2("gep-load:in", GEP, LI);
659 ReplaceInstWithInst(BB->getInstList(), BI,
660 LI = new LoadInst(GEP->getPtrOperand(),
661 GEP->getIndexVec()));
662 PRINT_PEEPHOLE1("gep-load:out", LI);
663 return true;
664 }
Chris Lattnerd32a9612001-11-01 02:42:08 +0000665 } else if (I->getOpcode() == Instruction::Add &&
666 isa<CastInst>(I->getOperand(1))) {
667
668 // Peephole optimize the following instructions:
669 // %t1 = cast ulong <const int> to {<...>} *
670 // %t2 = add {<...>} * %SP, %t1 ;; Constant must be 2nd operand
671 //
672 // or
673 // %t1 = cast {<...>}* %SP to int*
674 // %t5 = cast ulong <const int> to int*
675 // %t2 = add int* %t1, %t5 ;; int is same size as field
676 //
677 // Into: %t3 = getelementptr {<...>} * %SP, <element indices>
678 // %t2 = cast <eltype> * %t3 to {<...>}*
679 //
680 Value *AddOp1 = I->getOperand(0);
681 CastInst *AddOp2 = cast<CastInst>(I->getOperand(1));
682 ConstPoolUInt *OffsetV = dyn_cast<ConstPoolUInt>(AddOp2->getOperand(0));
683 unsigned Offset = OffsetV ? OffsetV->getValue() : 0;
684 Value *SrcPtr; // Of type pointer to struct...
685 const StructType *StructTy;
686
687 if ((StructTy = getPointedToStruct(AddOp1->getType()))) {
688 SrcPtr = AddOp1; // Handle the first case...
689 } else if (CastInst *AddOp1c = dyn_cast<CastInst>(AddOp1)) {
690 SrcPtr = AddOp1c->getOperand(0); // Handle the second case...
691 StructTy = getPointedToStruct(SrcPtr->getType());
692 }
693
694 // Only proceed if we have detected all of our conditions successfully...
695 if (Offset && StructTy && SrcPtr && Offset < TD.getTypeSize(StructTy)) {
696 const StructLayout *SL = TD.getStructLayout(StructTy);
697 vector<ConstPoolVal*> Offsets;
698 unsigned ActualOffset = Offset;
699 const Type *ElTy = getStructOffsetType(StructTy, ActualOffset, Offsets);
700
701 if (getPointedToStruct(AddOp1->getType())) { // case 1
702 PRINT_PEEPHOLE2("add-to-gep1:in", AddOp2, I);
703 } else {
704 PRINT_PEEPHOLE3("add-to-gep2:in", AddOp1, AddOp2, I);
705 }
706
707 GetElementPtrInst *GEP = new GetElementPtrInst(SrcPtr, Offsets);
708 BI = BB->getInstList().insert(BI, GEP)+1;
709
710 assert(Offset-ActualOffset == 0 &&
711 "GEP to middle of element not implemented yet!");
712
713 ReplaceInstWithInst(BB->getInstList(), BI,
714 I = new CastInst(GEP, I->getType()));
715 PRINT_PEEPHOLE2("add-to-gep:out", GEP, I);
716 return true;
717 }
718 }
719
720 return false;
721}
722
723
724
725
726static bool DoRaisePass(Method *M) {
727 bool Changed = false;
728 for (Method::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI) {
729 BasicBlock *BB = *MI;
730 BasicBlock::InstListType &BIL = BB->getInstList();
731
732 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
Chris Lattner68b07b72001-11-01 07:00:51 +0000733 if (opt::DeadCodeElimination::dceInstruction(BIL, BI) ||
734 PeepholeOptimize(BB, BI))
Chris Lattnerd32a9612001-11-01 02:42:08 +0000735 Changed = true;
736 else
737 ++BI;
738 }
739 }
740 return Changed;
741}
742
743
744// RaisePointerReferences::doit - Raise a method representation to a higher
745// level.
746//
747bool RaisePointerReferences::doit(Method *M) {
748 if (M->isExternal()) return false;
749 bool Changed = false;
750
Chris Lattner68b07b72001-11-01 07:00:51 +0000751#ifdef DEBUG_PEEPHOLE_INSTS
752 cerr << "\n\n\nStarting to work on Method '" << M->getName() << "'\n";
753#endif
754
Chris Lattnerd32a9612001-11-01 02:42:08 +0000755 while (DoRaisePass(M)) Changed = true;
756
757 // PtrCasts - Keep a mapping between the pointer values (the key of the
758 // map), and the cast to array pointer (the value) in this map. This is
759 // used when converting pointer math into array addressing.
760 //
761 map<Value*, CastInst*> PtrCasts;
762
763 // Insert casts for all incoming pointer values. Keep track of those casts
764 // and the identified incoming values in the PtrCasts map.
765 //
766 Changed |= DoInsertArrayCasts(M, PtrCasts);
767
768 // Loop over each incoming pointer variable, replacing indexing arithmetic
769 // with getelementptr calls.
770 //
771 Changed |= reduce_apply_bool(PtrCasts.begin(), PtrCasts.end(),
772 ptr_fun(DoEliminatePointerArithmetic));
773
774 return Changed;
775}