blob: a40d865fa632c77c380e9c948aecc4df77d4b86f [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"
Chris Lattner59cd9f12001-11-04 23:24:06 +000033#include "TransformInternals.h"
Chris Lattnerd32a9612001-11-01 02:42:08 +000034#include "llvm/Method.h"
35#include "llvm/Support/STLExtras.h"
36#include "llvm/iOther.h"
37#include "llvm/iMemory.h"
38#include "llvm/ConstPoolVals.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 <algorithm>
42
43#include "llvm/Assembly/Writer.h"
44
Chris Lattnere4f4d8c2001-11-05 18:30:53 +000045//#define DEBUG_PEEPHOLE_INSTS 1
Chris Lattnerd32a9612001-11-01 02:42:08 +000046
47#ifdef DEBUG_PEEPHOLE_INSTS
48#define PRINT_PEEPHOLE(ID, NUM, I) \
49 cerr << "Inst P/H " << ID << "[" << NUM << "] " << I;
50#else
51#define PRINT_PEEPHOLE(ID, NUM, I)
52#endif
53
54#define PRINT_PEEPHOLE1(ID, I1) do { PRINT_PEEPHOLE(ID, 0, I1); } while (0)
55#define PRINT_PEEPHOLE2(ID, I1, I2) \
56 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); } while (0)
57#define PRINT_PEEPHOLE3(ID, I1, I2, I3) \
58 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
59 PRINT_PEEPHOLE(ID, 2, I3); } while (0)
60
61
Chris Lattnerd32a9612001-11-01 02:42:08 +000062// isReinterpretingCast - Return true if the cast instruction specified will
63// cause the operand to be "reinterpreted". A value is reinterpreted if the
64// cast instruction would cause the underlying bits to change.
65//
66static inline bool isReinterpretingCast(const CastInst *CI) {
67 return !losslessCastableTypes(CI->getOperand(0)->getType(), CI->getType());
68}
69
70
71// getPointedToStruct - If the argument is a pointer type, and the pointed to
72// value is a struct type, return the struct type, else return null.
73//
74static const StructType *getPointedToStruct(const Type *Ty) {
75 const PointerType *PT = dyn_cast<PointerType>(Ty);
76 return PT ? dyn_cast<StructType>(PT->getValueType()) : 0;
77}
78
79
80// getStructOffsetType - Return a vector of offsets that are to be used to index
81// into the specified struct type to get as close as possible to index as we
82// can. Note that it is possible that we cannot get exactly to Offset, in which
83// case we update offset to be the offset we actually obtained. The resultant
84// leaf type is returned.
85//
86static const Type *getStructOffsetType(const Type *Ty, unsigned &Offset,
87 vector<ConstPoolVal*> &Offsets) {
88 if (!isa<StructType>(Ty)) {
89 Offset = 0; // Return the offset that we were able to acheive
90 return Ty; // Return the leaf type
91 }
92
93 assert(Offset < TD.getTypeSize(Ty) && "Offset not in struct!");
94 const StructType *STy = cast<StructType>(Ty);
95 const StructLayout *SL = TD.getStructLayout(STy);
96
97 // This loop terminates always on a 0 <= i < MemberOffsets.size()
98 unsigned i;
99 for (i = 0; i < SL->MemberOffsets.size()-1; ++i)
100 if (Offset >= SL->MemberOffsets[i] && Offset < SL->MemberOffsets[i+1])
101 break;
102
Chris Lattner68b07b72001-11-01 07:00:51 +0000103 assert(Offset >= SL->MemberOffsets[i] &&
104 (i == SL->MemberOffsets.size()-1 || Offset < SL->MemberOffsets[i+1]));
Chris Lattnerd32a9612001-11-01 02:42:08 +0000105
106 // Make sure to save the current index...
107 Offsets.push_back(ConstPoolUInt::get(Type::UByteTy, i));
108
109 unsigned SubOffs = Offset - SL->MemberOffsets[i];
110 const Type *LeafTy = getStructOffsetType(STy->getElementTypes()[i], SubOffs,
111 Offsets);
112 Offset = SL->MemberOffsets[i] + SubOffs;
113 return LeafTy;
114}
115
116
117
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000118
119
Chris Lattnerd32a9612001-11-01 02:42:08 +0000120// DoInsertArrayCast - If the argument value has a pointer type, and if the
121// argument value is used as an array, insert a cast before the specified
122// basic block iterator that casts the value to an array pointer. Return the
123// new cast instruction (in the CastResult var), or null if no cast is inserted.
124//
125static bool DoInsertArrayCast(Method *CurMeth, Value *V, BasicBlock *BB,
126 BasicBlock::iterator &InsertBefore,
127 CastInst *&CastResult) {
128 const PointerType *ThePtrType = dyn_cast<PointerType>(V->getType());
129 if (!ThePtrType) return false;
130 bool InsertCast = false;
131
132 for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
133 Instruction *Inst = cast<Instruction>(*I);
134 switch (Inst->getOpcode()) {
135 default: break; // Not an interesting use...
136 case Instruction::Add: // It's being used as an array index!
137 //case Instruction::Sub:
138 InsertCast = true;
139 break;
140 case Instruction::Cast: // There is already a cast instruction!
141 if (const PointerType *PT = dyn_cast<const PointerType>(Inst->getType()))
142 if (const ArrayType *AT = dyn_cast<const ArrayType>(PT->getValueType()))
143 if (AT->getElementType() == ThePtrType->getValueType()) {
144 // Cast already exists! Return the existing one!
145 CastResult = cast<CastInst>(Inst);
146 return false; // No changes made to program though...
147 }
148 break;
149 }
150 }
151
152 if (!InsertCast) return false; // There is no reason to insert a cast!
153
154 // Insert a cast!
155 const Type *ElTy = ThePtrType->getValueType();
156 const PointerType *DestTy = PointerType::get(ArrayType::get(ElTy));
157
158 CastResult = new CastInst(V, DestTy);
159 BB->getInstList().insert(InsertBefore, CastResult);
160 //cerr << "Inserted cast: " << CastResult;
161 return true; // Made a change!
162}
163
164
165// DoInsertArrayCasts - Loop over all "incoming" values in the specified method,
166// inserting a cast for pointer values that are used as arrays. For our
167// purposes, an incoming value is considered to be either a value that is
168// either a method parameter, a value created by alloca or malloc, or a value
169// returned from a function call. All casts are kept attached to their original
170// values through the PtrCasts map.
171//
172static bool DoInsertArrayCasts(Method *M, map<Value*, CastInst*> &PtrCasts) {
173 assert(!M->isExternal() && "Can't handle external methods!");
174
175 // Insert casts for all arguments to the function...
176 bool Changed = false;
177 BasicBlock *CurBB = M->front();
178 BasicBlock::iterator It = CurBB->begin();
179 for (Method::ArgumentListType::iterator AI = M->getArgumentList().begin(),
180 AE = M->getArgumentList().end(); AI != AE; ++AI) {
181 CastInst *TheCast = 0;
182 if (DoInsertArrayCast(M, *AI, CurBB, It, TheCast)) {
183 It = CurBB->begin(); // We might have just invalidated the iterator!
184 Changed = true; // Yes we made a change
185 ++It; // Insert next cast AFTER this one...
186 }
187
188 if (TheCast) // Is there a cast associated with this value?
189 PtrCasts[*AI] = TheCast; // Yes, add it to the map...
190 }
191
192 // TODO: insert casts for alloca, malloc, and function call results. Also,
193 // look for pointers that already have casts, to add to the map.
194
195 return Changed;
196}
197
198
199
200
201// DoElminatePointerArithmetic - Loop over each incoming pointer variable,
202// replacing indexing arithmetic with getelementptr calls.
203//
204static bool DoEliminatePointerArithmetic(const pair<Value*, CastInst*> &Val) {
205 Value *V = Val.first; // The original pointer
206 CastInst *CV = Val.second; // The array casted version of the pointer...
207
208 for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
209 Instruction *Inst = cast<Instruction>(*I);
210 if (Inst->getOpcode() != Instruction::Add)
211 continue; // We only care about add instructions
212
213 BinaryOperator *Add = cast<BinaryOperator>(Inst);
214
215 // Make sure the array is the first operand of the add expression...
216 if (Add->getOperand(0) != V)
217 Add->swapOperands();
218
219 // Get the amount added to the pointer value...
220 Value *AddAmount = Add->getOperand(1);
221
222
223 }
224 return false;
225}
226
227
228// Peephole Malloc instructions: we take a look at the use chain of the
229// malloc instruction, and try to find out if the following conditions hold:
230// 1. The malloc is of the form: 'malloc [sbyte], uint <constant>'
Chris Lattnerbacec7b2001-11-04 22:11:10 +0000231// 2. The only users of the malloc are cast & add instructions
Chris Lattnerd32a9612001-11-01 02:42:08 +0000232// 3. Of the cast instructions, there is only one destination pointer type
233// [RTy] where the size of the pointed to object is equal to the number
234// of bytes allocated.
235//
236// If these conditions hold, we convert the malloc to allocate an [RTy]
237// element. This should be extended in the future to handle arrays. TODO
238//
239static bool PeepholeMallocInst(BasicBlock *BB, BasicBlock::iterator &BI) {
240 MallocInst *MI = cast<MallocInst>(*BI);
241 if (!MI->isArrayAllocation()) return false; // No array allocation?
242
243 ConstPoolUInt *Amt = dyn_cast<ConstPoolUInt>(MI->getArraySize());
244 if (Amt == 0 || MI->getAllocatedType() != ArrayType::get(Type::SByteTy))
245 return false;
246
247 // Get the number of bytes allocated...
248 unsigned Size = Amt->getValue();
249 const Type *ResultTy = 0;
250
251 // Loop over all of the uses of the malloc instruction, inspecting casts.
252 for (Value::use_iterator I = MI->use_begin(), E = MI->use_end();
253 I != E; ++I) {
Chris Lattnerbacec7b2001-11-04 22:11:10 +0000254 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
255 //cerr << "\t" << CI;
Chris Lattnerd32a9612001-11-01 02:42:08 +0000256
Chris Lattnerbacec7b2001-11-04 22:11:10 +0000257 // We only work on casts to pointer types for sure, be conservative
258 if (!isa<PointerType>(CI->getType())) {
259 cerr << "Found cast of malloc value to non pointer type:\n" << CI;
Chris Lattnerd32a9612001-11-01 02:42:08 +0000260 return false;
261 }
Chris Lattnerbacec7b2001-11-04 22:11:10 +0000262
263 const Type *DestTy = cast<PointerType>(CI->getType())->getValueType();
264 if (TD.getTypeSize(DestTy) == Size && DestTy != ResultTy) {
265 // Does the size of the allocated type match the number of bytes
266 // allocated?
267 //
268 if (ResultTy == 0) {
269 ResultTy = DestTy; // Keep note of this for future uses...
270 } else {
271 // It's overdefined! We don't know which type to convert to!
272 return false;
273 }
274 }
Chris Lattnerd32a9612001-11-01 02:42:08 +0000275 }
276 }
277
278 // If we get this far, we have either found, or not, a type that is cast to
279 // that is of the same size as the malloc instruction.
280 if (!ResultTy) return false;
281
Chris Lattnerc109d302001-11-05 21:13:30 +0000282 // Now we check to see if we can convert the return value of malloc to the
283 // specified pointer type. All this is moot if we can't.
284 //
285 ValueTypeCache ConvertedTypes;
286 if (RetValConvertableToType(MI, PointerType::get(ResultTy), ConvertedTypes)) {
287 // Yup, it's convertable, do the transformation now!
288 PRINT_PEEPHOLE1("mall-refine:in ", MI);
289
290 // Create a new malloc instruction, and insert it into the method...
291 MallocInst *NewMI = new MallocInst(PointerType::get(ResultTy));
292 NewMI->setName(MI->getName());
293 MI->setName("");
294 BI = BB->getInstList().insert(BI, NewMI)+1;
295
296 // Create a new cast instruction to cast it to the old type...
297 CastInst *NewCI = new CastInst(NewMI, MI->getType());
298 BB->getInstList().insert(BI, NewCI);
299
300 // Move all users of the old malloc instruction over to use the new cast...
301 MI->replaceAllUsesWith(NewCI);
302
303 ValueMapCache ValueMap;
304 ConvertUsersType(NewCI, NewMI, ValueMap); // This will delete MI!
305
306 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
307 PRINT_PEEPHOLE1("mall-refine:out", NewMI);
308 return true;
309 }
310 return false;
Chris Lattnerd32a9612001-11-01 02:42:08 +0000311}
312
313
Chris Lattnerb9693952001-11-04 07:42:17 +0000314// Peephole optimize the following instructions:
315// %t1 = cast int (uint) * %reg111 to uint (...) *
316// %t2 = call uint (...) * %cast111( uint %key )
317//
318// Into: %t3 = call int (uint) * %reg111( uint %key )
319// %t2 = cast int %t3 to uint
320//
321static bool PeepholeCallInst(BasicBlock *BB, BasicBlock::iterator &BI) {
322 CallInst *CI = cast<CallInst>(*BI);
323 return false;
324}
325
Chris Lattnerd32a9612001-11-01 02:42:08 +0000326
327static bool PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI) {
328 Instruction *I = *BI;
Chris Lattnerd32a9612001-11-01 02:42:08 +0000329
330 if (CastInst *CI = dyn_cast<CastInst>(I)) {
331 Value *Src = CI->getOperand(0);
332 Instruction *SrcI = dyn_cast<Instruction>(Src); // Nonnull if instr source
333 const Type *DestTy = CI->getType();
334
Chris Lattnere99c66b2001-11-01 17:05:27 +0000335 // Peephole optimize the following instruction:
336 // %V2 = cast <ty> %V to <ty>
337 //
338 // Into: <nothing>
339 //
340 if (DestTy == Src->getType()) { // Check for a cast to same type as src!!
Chris Lattnerd32a9612001-11-01 02:42:08 +0000341 PRINT_PEEPHOLE1("cast-of-self-ty", CI);
342 CI->replaceAllUsesWith(Src);
343 if (!Src->hasName() && CI->hasName()) {
344 string Name = CI->getName();
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000345 CI->setName("");
346 Src->setName(Name, BB->getParent()->getSymbolTable());
Chris Lattnerd32a9612001-11-01 02:42:08 +0000347 }
348 return true;
349 }
350
Chris Lattnere99c66b2001-11-01 17:05:27 +0000351 // Peephole optimize the following instructions:
352 // %tmp = cast <ty> %V to <ty2>
353 // %V = cast <ty2> %tmp to <ty3> ; Where ty & ty2 are same size
354 //
355 // Into: cast <ty> %V to <ty3>
356 //
Chris Lattnerd32a9612001-11-01 02:42:08 +0000357 if (SrcI)
358 if (CastInst *CSrc = dyn_cast<CastInst>(SrcI))
359 if (isReinterpretingCast(CI) + isReinterpretingCast(CSrc) < 2) {
360 // We can only do c-c elimination if, at most, one cast does a
361 // reinterpretation of the input data.
362 //
363 // If legal, make this cast refer the the original casts argument!
364 //
365 PRINT_PEEPHOLE2("cast-cast:in ", CI, CSrc);
366 CI->setOperand(0, CSrc->getOperand(0));
367 PRINT_PEEPHOLE1("cast-cast:out", CI);
368 return true;
369 }
370
371 // Check to see if it's a cast of an instruction that does not depend on the
372 // specific type of the operands to do it's job.
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000373 if (!isReinterpretingCast(CI)) {
Chris Lattnerb980e182001-11-04 21:32:11 +0000374 ValueTypeCache ConvertedTypes;
375 if (RetValConvertableToType(CI, Src->getType(), ConvertedTypes)) {
Chris Lattnerbacec7b2001-11-04 22:11:10 +0000376 PRINT_PEEPHOLE2("CAST-DEST-EXPR-CONV:in ", CI, Src);
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000377
Chris Lattnerb980e182001-11-04 21:32:11 +0000378 ValueMapCache ValueMap;
Chris Lattnere4f4d8c2001-11-05 18:30:53 +0000379 ConvertUsersType(CI, Src, ValueMap); // This will delete CI!
380
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000381 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
Chris Lattnerbacec7b2001-11-04 22:11:10 +0000382 PRINT_PEEPHOLE1("CAST-DEST-EXPR-CONV:out", I);
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000383 return true;
384 }
Chris Lattnerd32a9612001-11-01 02:42:08 +0000385 }
386
Chris Lattnere99c66b2001-11-01 17:05:27 +0000387 // Check to see if we are casting from a structure pointer to a pointer to
388 // the first element of the structure... to avoid munching other peepholes,
389 // we only let this happen if there are no add uses of the cast.
390 //
391 // Peephole optimize the following instructions:
392 // %t1 = cast {<...>} * %StructPtr to <ty> *
393 //
394 // Into: %t2 = getelementptr {<...>} * %StructPtr, <0, 0, 0, ...>
395 // %t1 = cast <eltype> * %t1 to <ty> *
396 //
397 if (const StructType *STy = getPointedToStruct(Src->getType()))
398 if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
399
400 // Loop over uses of the cast, checking for add instructions. If an add
401 // exists, this is probably a part of a more complex GEP, so we don't
402 // want to mess around with the cast.
403 //
404 bool HasAddUse = false;
405 for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
406 I != E; ++I)
407 if (isa<Instruction>(*I) &&
408 cast<Instruction>(*I)->getOpcode() == Instruction::Add) {
409 HasAddUse = true; break;
410 }
411
412 // If it doesn't have an add use, check to see if the dest type is
413 // losslessly convertable to one of the types in the start of the struct
414 // type.
415 //
416 if (!HasAddUse) {
417 const Type *DestPointedTy = DestPTy->getValueType();
418 unsigned Depth = 1;
419 const StructType *CurSTy = STy;
420 const Type *ElTy = 0;
421 while (CurSTy) {
422
423 // Check for a zero element struct type... if we have one, bail.
424 if (CurSTy->getElementTypes().size() == 0) break;
425
426 // Grab the first element of the struct type, which must lie at
427 // offset zero in the struct.
428 //
429 ElTy = CurSTy->getElementTypes()[0];
430
431 // Did we find what we're looking for?
432 if (losslessCastableTypes(ElTy, DestPointedTy)) break;
433
434 // Nope, go a level deeper.
435 ++Depth;
436 CurSTy = dyn_cast<StructType>(ElTy);
437 ElTy = 0;
438 }
439
440 // Did we find what we were looking for? If so, do the transformation
441 if (ElTy) {
442 PRINT_PEEPHOLE1("cast-for-first:in", CI);
443
444 // Build the index vector, full of all zeros
445 vector<ConstPoolVal *> Indices(Depth,
446 ConstPoolUInt::get(Type::UByteTy,0));
447
448 // Insert the new T cast instruction... stealing old T's name
449 GetElementPtrInst *GEP = new GetElementPtrInst(Src, Indices,
450 CI->getName());
451 CI->setName("");
452 BI = BB->getInstList().insert(BI, GEP)+1;
453
454 // Make the old cast instruction reference the new GEP instead of
455 // the old src value.
456 //
457 CI->setOperand(0, GEP);
458
459 PRINT_PEEPHOLE2("cast-for-first:out", GEP, CI);
460 return true;
461 }
462 }
463 }
464
465
Chris Lattnerd32a9612001-11-01 02:42:08 +0000466 } else if (MallocInst *MI = dyn_cast<MallocInst>(I)) {
467 if (PeepholeMallocInst(BB, BI)) return true;
Chris Lattner8d38e542001-11-01 03:12:34 +0000468
Chris Lattnerb9693952001-11-04 07:42:17 +0000469 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
470 if (PeepholeCallInst(BB, BI)) return true;
471
Chris Lattner8d38e542001-11-01 03:12:34 +0000472 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
473 Value *Val = SI->getOperand(0);
474 Value *Pointer = SI->getPtrOperand();
475
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000476 // Peephole optimize the following instructions:
477 // %t1 = getelementptr {<...>} * %StructPtr, <element indices>
478 // store <elementty> %v, <elementty> * %t1
479 //
480 // Into: store <elementty> %v, {<...>} * %StructPtr, <element indices>
481 //
Chris Lattner8d38e542001-11-01 03:12:34 +0000482 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Pointer)) {
483 PRINT_PEEPHOLE2("gep-store:in", GEP, SI);
484 ReplaceInstWithInst(BB->getInstList(), BI,
485 SI = new StoreInst(Val, GEP->getPtrOperand(),
Chris Lattner8e7f4092001-11-04 08:08:34 +0000486 GEP->getIndices()));
Chris Lattner8d38e542001-11-01 03:12:34 +0000487 PRINT_PEEPHOLE1("gep-store:out", SI);
488 return true;
489 }
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000490
491 // Peephole optimize the following instructions:
492 // %t = cast <T1>* %P to <T2> * ;; If T1 is losslessly convertable to T2
493 // store <T2> %V, <T2>* %t
494 //
495 // Into:
496 // %t = cast <T2> %V to <T1>
497 // store <T1> %t2, <T1>* %P
498 //
499 if (CastInst *CI = dyn_cast<CastInst>(Pointer))
500 if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
501 if (PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
502 if (losslessCastableTypes(Val->getType(), // convertable types!
503 CSPT->getValueType()) &&
504 !SI->hasIndices()) { // No subscripts yet!
505 PRINT_PEEPHOLE3("st-src-cast:in ", Pointer, Val, SI);
506
507 // Insert the new T cast instruction... stealing old T's name
508 CastInst *NCI = new CastInst(Val, CSPT->getValueType(),
509 CI->getName());
510 CI->setName("");
511 BI = BB->getInstList().insert(BI, NCI)+1;
512
513 // Replace the old store with a new one!
514 ReplaceInstWithInst(BB->getInstList(), BI,
515 SI = new StoreInst(NCI, CastSrc));
516 PRINT_PEEPHOLE3("st-src-cast:out", NCI, CastSrc, SI);
517 return true;
518 }
519
Chris Lattner8d38e542001-11-01 03:12:34 +0000520
521 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
522 Value *Pointer = LI->getPtrOperand();
523
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000524 // Peephole optimize the following instructions:
525 // %t1 = getelementptr {<...>} * %StructPtr, <element indices>
526 // %V = load <elementty> * %t1
527 //
528 // Into: load {<...>} * %StructPtr, <element indices>
529 //
Chris Lattner8d38e542001-11-01 03:12:34 +0000530 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Pointer)) {
531 PRINT_PEEPHOLE2("gep-load:in", GEP, LI);
532 ReplaceInstWithInst(BB->getInstList(), BI,
533 LI = new LoadInst(GEP->getPtrOperand(),
Chris Lattner8e7f4092001-11-04 08:08:34 +0000534 GEP->getIndices()));
Chris Lattner8d38e542001-11-01 03:12:34 +0000535 PRINT_PEEPHOLE1("gep-load:out", LI);
536 return true;
537 }
Chris Lattnerd32a9612001-11-01 02:42:08 +0000538 } else if (I->getOpcode() == Instruction::Add &&
539 isa<CastInst>(I->getOperand(1))) {
540
541 // Peephole optimize the following instructions:
542 // %t1 = cast ulong <const int> to {<...>} *
543 // %t2 = add {<...>} * %SP, %t1 ;; Constant must be 2nd operand
544 //
545 // or
546 // %t1 = cast {<...>}* %SP to int*
547 // %t5 = cast ulong <const int> to int*
548 // %t2 = add int* %t1, %t5 ;; int is same size as field
549 //
550 // Into: %t3 = getelementptr {<...>} * %SP, <element indices>
551 // %t2 = cast <eltype> * %t3 to {<...>}*
552 //
553 Value *AddOp1 = I->getOperand(0);
554 CastInst *AddOp2 = cast<CastInst>(I->getOperand(1));
555 ConstPoolUInt *OffsetV = dyn_cast<ConstPoolUInt>(AddOp2->getOperand(0));
556 unsigned Offset = OffsetV ? OffsetV->getValue() : 0;
557 Value *SrcPtr; // Of type pointer to struct...
558 const StructType *StructTy;
559
560 if ((StructTy = getPointedToStruct(AddOp1->getType()))) {
561 SrcPtr = AddOp1; // Handle the first case...
562 } else if (CastInst *AddOp1c = dyn_cast<CastInst>(AddOp1)) {
563 SrcPtr = AddOp1c->getOperand(0); // Handle the second case...
564 StructTy = getPointedToStruct(SrcPtr->getType());
565 }
566
567 // Only proceed if we have detected all of our conditions successfully...
568 if (Offset && StructTy && SrcPtr && Offset < TD.getTypeSize(StructTy)) {
569 const StructLayout *SL = TD.getStructLayout(StructTy);
570 vector<ConstPoolVal*> Offsets;
571 unsigned ActualOffset = Offset;
572 const Type *ElTy = getStructOffsetType(StructTy, ActualOffset, Offsets);
573
574 if (getPointedToStruct(AddOp1->getType())) { // case 1
575 PRINT_PEEPHOLE2("add-to-gep1:in", AddOp2, I);
576 } else {
577 PRINT_PEEPHOLE3("add-to-gep2:in", AddOp1, AddOp2, I);
578 }
579
580 GetElementPtrInst *GEP = new GetElementPtrInst(SrcPtr, Offsets);
581 BI = BB->getInstList().insert(BI, GEP)+1;
582
583 assert(Offset-ActualOffset == 0 &&
584 "GEP to middle of element not implemented yet!");
585
586 ReplaceInstWithInst(BB->getInstList(), BI,
587 I = new CastInst(GEP, I->getType()));
588 PRINT_PEEPHOLE2("add-to-gep:out", GEP, I);
589 return true;
590 }
591 }
592
593 return false;
594}
595
596
597
598
599static bool DoRaisePass(Method *M) {
600 bool Changed = false;
601 for (Method::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI) {
602 BasicBlock *BB = *MI;
603 BasicBlock::InstListType &BIL = BB->getInstList();
604
605 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
Chris Lattner68b07b72001-11-01 07:00:51 +0000606 if (opt::DeadCodeElimination::dceInstruction(BIL, BI) ||
607 PeepholeOptimize(BB, BI))
Chris Lattnerd32a9612001-11-01 02:42:08 +0000608 Changed = true;
609 else
610 ++BI;
611 }
612 }
613 return Changed;
614}
615
616
617// RaisePointerReferences::doit - Raise a method representation to a higher
618// level.
619//
620bool RaisePointerReferences::doit(Method *M) {
621 if (M->isExternal()) return false;
622 bool Changed = false;
623
Chris Lattner68b07b72001-11-01 07:00:51 +0000624#ifdef DEBUG_PEEPHOLE_INSTS
625 cerr << "\n\n\nStarting to work on Method '" << M->getName() << "'\n";
626#endif
627
Chris Lattnerd32a9612001-11-01 02:42:08 +0000628 while (DoRaisePass(M)) Changed = true;
629
630 // PtrCasts - Keep a mapping between the pointer values (the key of the
631 // map), and the cast to array pointer (the value) in this map. This is
632 // used when converting pointer math into array addressing.
633 //
634 map<Value*, CastInst*> PtrCasts;
635
636 // Insert casts for all incoming pointer values. Keep track of those casts
637 // and the identified incoming values in the PtrCasts map.
638 //
639 Changed |= DoInsertArrayCasts(M, PtrCasts);
640
641 // Loop over each incoming pointer variable, replacing indexing arithmetic
642 // with getelementptr calls.
643 //
644 Changed |= reduce_apply_bool(PtrCasts.begin(), PtrCasts.end(),
645 ptr_fun(DoEliminatePointerArithmetic));
646
647 return Changed;
648}