blob: f80270567d397dcc08272a886c47272139d584a3 [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
Chris Lattner3cc7dde2001-11-26 16:58:14 +00005// analyze.
Chris Lattnerd32a9612001-11-01 02:42:08 +00006//
7//===----------------------------------------------------------------------===//
8
9#include "llvm/Transforms/LevelChange.h"
Chris Lattner59cd9f12001-11-04 23:24:06 +000010#include "TransformInternals.h"
Chris Lattnerd32a9612001-11-01 02:42:08 +000011#include "llvm/Method.h"
Chris Lattnerd32a9612001-11-01 02:42:08 +000012#include "llvm/iOther.h"
13#include "llvm/iMemory.h"
14#include "llvm/ConstPoolVals.h"
Chris Lattnerdedee7b2001-11-01 05:57:59 +000015#include "llvm/Optimizations/ConstantHandling.h"
Chris Lattner68b07b72001-11-01 07:00:51 +000016#include "llvm/Optimizations/DCE.h"
Chris Lattnerbd70bb92001-11-26 18:58:55 +000017#include "llvm/Optimizations/ConstantProp.h"
Chris Lattnerd5b48ca2001-11-14 11:02:49 +000018#include "llvm/Analysis/Expressions.h"
Chris Lattnercee8f9a2001-11-27 00:03:19 +000019#include "Support/STLExtras.h"
Chris Lattnerd32a9612001-11-01 02:42:08 +000020#include <algorithm>
21
22#include "llvm/Assembly/Writer.h"
23
Chris Lattner09009802001-11-26 19:36:58 +000024//#define DEBUG_PEEPHOLE_INSTS 1
Chris Lattnerd32a9612001-11-01 02:42:08 +000025
26#ifdef DEBUG_PEEPHOLE_INSTS
27#define PRINT_PEEPHOLE(ID, NUM, I) \
28 cerr << "Inst P/H " << ID << "[" << NUM << "] " << I;
29#else
30#define PRINT_PEEPHOLE(ID, NUM, I)
31#endif
32
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)
Chris Lattnerd5b48ca2001-11-14 11:02:49 +000039#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)
Chris Lattnerd32a9612001-11-01 02:42:08 +000042
43
Chris Lattnerd32a9612001-11-01 02:42:08 +000044// 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.
47//
48static inline bool isReinterpretingCast(const CastInst *CI) {
Chris Lattner3cc7dde2001-11-26 16:58:14 +000049 return!CI->getOperand(0)->getType()->isLosslesslyConvertableTo(CI->getType());
Chris Lattnerd32a9612001-11-01 02:42:08 +000050}
51
52
Chris Lattnerf3b976e2001-11-04 20:21:12 +000053
54
Chris Lattnerd5b48ca2001-11-14 11:02:49 +000055
56// Peephole optimize the following instructions:
57// %t1 = cast ulong <const int> to {<...>} *
58// %t2 = add {<...>} * %SP, %t1 ;; Constant must be 2nd operand
59//
60// or
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
64//
65// Into: %t3 = getelementptr {<...>} * %SP, <element indices>
66// %t2 = cast <eltype> * %t3 to {<...>}*
67//
68static bool PeepholeOptimizeAddCast(BasicBlock *BB, BasicBlock::iterator &BI,
69 Value *AddOp1, CastInst *AddOp2) {
Chris Lattner3cc7dde2001-11-26 16:58:14 +000070 const CompositeType *CompTy;
71 Value *OffsetVal = AddOp2->getOperand(0);
72 Value *SrcPtr; // Of type pointer to struct...
Chris Lattnerd5b48ca2001-11-14 11:02:49 +000073
Chris Lattner3cc7dde2001-11-26 16:58:14 +000074 if ((CompTy = getPointedToComposite(AddOp1->getType()))) {
Chris Lattnerd5b48ca2001-11-14 11:02:49 +000075 SrcPtr = AddOp1; // Handle the first case...
76 } else if (CastInst *AddOp1c = dyn_cast<CastInst>(AddOp1)) {
77 SrcPtr = AddOp1c->getOperand(0); // Handle the second case...
Chris Lattner3cc7dde2001-11-26 16:58:14 +000078 CompTy = getPointedToComposite(SrcPtr->getType());
Chris Lattnerd5b48ca2001-11-14 11:02:49 +000079 }
80
81 // Only proceed if we have detected all of our conditions successfully...
Chris Lattner3cc7dde2001-11-26 16:58:14 +000082 if (!CompTy || !SrcPtr || !OffsetVal->getType()->isIntegral())
Chris Lattnerd5b48ca2001-11-14 11:02:49 +000083 return false;
84
Chris Lattner3cc7dde2001-11-26 16:58:14 +000085 vector<Value*> Indices;
86 if (!ConvertableToGEP(SrcPtr->getType(), OffsetVal, Indices, &BI))
87 return false; // Not convertable... perhaps next time
Chris Lattnerd5b48ca2001-11-14 11:02:49 +000088
Chris Lattner3cc7dde2001-11-26 16:58:14 +000089 if (getPointedToComposite(AddOp1->getType())) { // case 1
Chris Lattnerd5b48ca2001-11-14 11:02:49 +000090 PRINT_PEEPHOLE2("add-to-gep1:in", AddOp2, *BI);
91 } else {
92 PRINT_PEEPHOLE3("add-to-gep2:in", AddOp1, AddOp2, *BI);
93 }
94
Chris Lattner3cc7dde2001-11-26 16:58:14 +000095 GetElementPtrInst *GEP = new GetElementPtrInst(SrcPtr, Indices,
96 AddOp2->getName());
Chris Lattnerd5b48ca2001-11-14 11:02:49 +000097 BI = BB->getInstList().insert(BI, GEP)+1;
Chris Lattnerd5b48ca2001-11-14 11:02:49 +000098
Chris Lattner3cc7dde2001-11-26 16:58:14 +000099 Instruction *NCI = new CastInst(GEP, AddOp1->getType());
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000100 ReplaceInstWithInst(BB->getInstList(), BI, NCI);
101 PRINT_PEEPHOLE2("add-to-gep:out", GEP, NCI);
102 return true;
103}
104
Chris Lattnerd32a9612001-11-01 02:42:08 +0000105static bool PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI) {
106 Instruction *I = *BI;
Chris Lattnerd32a9612001-11-01 02:42:08 +0000107
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();
112
Chris Lattnere99c66b2001-11-01 17:05:27 +0000113 // Peephole optimize the following instruction:
114 // %V2 = cast <ty> %V to <ty>
115 //
116 // Into: <nothing>
117 //
118 if (DestTy == Src->getType()) { // Check for a cast to same type as src!!
Chris Lattnerd32a9612001-11-01 02:42:08 +0000119 PRINT_PEEPHOLE1("cast-of-self-ty", CI);
120 CI->replaceAllUsesWith(Src);
121 if (!Src->hasName() && CI->hasName()) {
122 string Name = CI->getName();
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000123 CI->setName("");
124 Src->setName(Name, BB->getParent()->getSymbolTable());
Chris Lattnerd32a9612001-11-01 02:42:08 +0000125 }
126 return true;
127 }
128
Chris Lattnere99c66b2001-11-01 17:05:27 +0000129 // 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
132 //
133 // Into: cast <ty> %V to <ty3>
134 //
Chris Lattnerd32a9612001-11-01 02:42:08 +0000135 if (SrcI)
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.
140 //
141 // If legal, make this cast refer the the original casts argument!
142 //
143 PRINT_PEEPHOLE2("cast-cast:in ", CI, CSrc);
144 CI->setOperand(0, CSrc->getOperand(0));
145 PRINT_PEEPHOLE1("cast-cast:out", CI);
146 return true;
147 }
148
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.
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000151 if (!isReinterpretingCast(CI)) {
Chris Lattnerb980e182001-11-04 21:32:11 +0000152 ValueTypeCache ConvertedTypes;
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000153 if (ValueConvertableToType(CI, Src->getType(), ConvertedTypes)) {
154 PRINT_PEEPHOLE2("CAST-DEST-EXPR-CONV:in ", Src, CI);
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000155
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000156#ifdef DEBUG_PEEPHOLE_INSTS
157 cerr << "\nCONVERTING EXPR TYPE:\n";
158#endif
Chris Lattnerb980e182001-11-04 21:32:11 +0000159 ValueMapCache ValueMap;
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000160 ConvertValueToNewType(CI, Src, ValueMap); // This will delete CI!
Chris Lattnere4f4d8c2001-11-05 18:30:53 +0000161
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000162 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
Chris Lattnere34443d2001-11-06 08:34:29 +0000163 PRINT_PEEPHOLE1("CAST-DEST-EXPR-CONV:out", Src);
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000164#ifdef DEBUG_PEEPHOLE_INSTS
165 cerr << "DONE CONVERTING EXPR TYPE: \n\n";// << BB->getParent();
166#endif
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000167 return true;
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000168 } else {
169 ConvertedTypes.clear();
170 if (ExpressionConvertableToType(Src, DestTy, ConvertedTypes)) {
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000171 PRINT_PEEPHOLE2("CAST-SRC-EXPR-CONV:in ", Src, CI);
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000172
173#ifdef DEBUG_PEEPHOLE_INSTS
174 cerr << "\nCONVERTING SRC EXPR TYPE:\n";
175#endif
176 ValueMapCache ValueMap;
177 Value *E = ConvertExpressionToType(Src, DestTy, ValueMap);
178 if (ConstPoolVal *CPV = dyn_cast<ConstPoolVal>(E))
179 CI->replaceAllUsesWith(CPV);
180
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();
185#endif
186 return true;
187 }
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000188 }
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000189
Chris Lattnerd32a9612001-11-01 02:42:08 +0000190 }
191
Chris Lattnere99c66b2001-11-01 17:05:27 +0000192 // 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.
195 //
196 // Peephole optimize the following instructions:
197 // %t1 = cast {<...>} * %StructPtr to <ty> *
198 //
199 // Into: %t2 = getelementptr {<...>} * %StructPtr, <0, 0, 0, ...>
200 // %t1 = cast <eltype> * %t1 to <ty> *
201 //
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000202#if 1
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000203 if (const CompositeType *CTy = getPointedToComposite(Src->getType()))
Chris Lattnere99c66b2001-11-01 17:05:27 +0000204 if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
205
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.
209 //
210 bool HasAddUse = false;
211 for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
212 I != E; ++I)
213 if (isa<Instruction>(*I) &&
214 cast<Instruction>(*I)->getOpcode() == Instruction::Add) {
215 HasAddUse = true; break;
216 }
217
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
220 // type.
221 //
222 if (!HasAddUse) {
223 const Type *DestPointedTy = DestPTy->getValueType();
224 unsigned Depth = 1;
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000225 const CompositeType *CurCTy = CTy;
Chris Lattnere99c66b2001-11-01 17:05:27 +0000226 const Type *ElTy = 0;
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000227
228 // Build the index vector, full of all zeros
229 vector<Value*> Indices;
230
231 while (CurCTy) {
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;
Chris Lattnere99c66b2001-11-01 17:05:27 +0000235
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000236 // Grab the first element of the struct type, which must lie at
237 // offset zero in the struct.
238 //
239 ElTy = CurSTy->getElementTypes()[0];
240 } else {
241 ElTy = cast<ArrayType>(CurCTy)->getElementType();
242 }
243
244 // Insert a zero to index through this type...
245 Indices.push_back(ConstPoolUInt::get(CurCTy->getIndexType(), 0));
Chris Lattnere99c66b2001-11-01 17:05:27 +0000246
247 // Did we find what we're looking for?
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000248 if (ElTy->isLosslesslyConvertableTo(DestPointedTy)) break;
Chris Lattnere99c66b2001-11-01 17:05:27 +0000249
250 // Nope, go a level deeper.
251 ++Depth;
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000252 CurCTy = dyn_cast<CompositeType>(ElTy);
Chris Lattnere99c66b2001-11-01 17:05:27 +0000253 ElTy = 0;
254 }
255
256 // Did we find what we were looking for? If so, do the transformation
257 if (ElTy) {
258 PRINT_PEEPHOLE1("cast-for-first:in", CI);
259
Chris Lattnere99c66b2001-11-01 17:05:27 +0000260 // Insert the new T cast instruction... stealing old T's name
261 GetElementPtrInst *GEP = new GetElementPtrInst(Src, Indices,
262 CI->getName());
263 CI->setName("");
264 BI = BB->getInstList().insert(BI, GEP)+1;
265
266 // Make the old cast instruction reference the new GEP instead of
267 // the old src value.
268 //
269 CI->setOperand(0, GEP);
270
271 PRINT_PEEPHOLE2("cast-for-first:out", GEP, CI);
272 return true;
273 }
274 }
275 }
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000276#endif
Chris Lattnere99c66b2001-11-01 17:05:27 +0000277
Chris Lattner3d775c32001-11-13 04:59:41 +0000278#if 1
Chris Lattner8d38e542001-11-01 03:12:34 +0000279 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
280 Value *Val = SI->getOperand(0);
Chris Lattner65ea1712001-11-14 11:27:58 +0000281 Value *Pointer = SI->getPointerOperand();
Chris Lattner8d38e542001-11-01 03:12:34 +0000282
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000283 // Peephole optimize the following instructions:
284 // %t1 = getelementptr {<...>} * %StructPtr, <element indices>
285 // store <elementty> %v, <elementty> * %t1
286 //
287 // Into: store <elementty> %v, {<...>} * %StructPtr, <element indices>
288 //
Chris Lattner8d38e542001-11-01 03:12:34 +0000289 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Pointer)) {
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000290 // Append any indices that the store instruction has onto the end of the
291 // ones that the GEP is carrying...
292 //
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000293 vector<Value*> Indices(GEP->copyIndices());
294 Indices.insert(Indices.end(), SI->idx_begin(), SI->idx_end());
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000295
Chris Lattner8d38e542001-11-01 03:12:34 +0000296 PRINT_PEEPHOLE2("gep-store:in", GEP, SI);
297 ReplaceInstWithInst(BB->getInstList(), BI,
Chris Lattner65ea1712001-11-14 11:27:58 +0000298 SI = new StoreInst(Val, GEP->getPointerOperand(),
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000299 Indices));
Chris Lattner8d38e542001-11-01 03:12:34 +0000300 PRINT_PEEPHOLE1("gep-store:out", SI);
301 return true;
302 }
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000303
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
307 //
308 // Into:
309 // %t = cast <T2> %V to <T1>
310 // store <T1> %t2, <T1>* %P
311 //
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()))
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000315 // convertable types?
316 if (Val->getType()->isLosslesslyConvertableTo(CSPT->getValueType()) &&
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000317 !SI->hasIndices()) { // No subscripts yet!
318 PRINT_PEEPHOLE3("st-src-cast:in ", Pointer, Val, SI);
319
320 // Insert the new T cast instruction... stealing old T's name
321 CastInst *NCI = new CastInst(Val, CSPT->getValueType(),
322 CI->getName());
323 CI->setName("");
324 BI = BB->getInstList().insert(BI, NCI)+1;
325
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);
330 return true;
331 }
332
Chris Lattner8d38e542001-11-01 03:12:34 +0000333
334 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner65ea1712001-11-14 11:27:58 +0000335 Value *Pointer = LI->getPointerOperand();
Chris Lattner8d38e542001-11-01 03:12:34 +0000336
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000337 // Peephole optimize the following instructions:
338 // %t1 = getelementptr {<...>} * %StructPtr, <element indices>
339 // %V = load <elementty> * %t1
340 //
341 // Into: load {<...>} * %StructPtr, <element indices>
342 //
Chris Lattner8d38e542001-11-01 03:12:34 +0000343 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Pointer)) {
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000344 // Append any indices that the load instruction has onto the end of the
345 // ones that the GEP is carrying...
346 //
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000347 vector<Value*> Indices(GEP->copyIndices());
348 Indices.insert(Indices.end(), LI->idx_begin(), LI->idx_end());
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000349
Chris Lattner8d38e542001-11-01 03:12:34 +0000350 PRINT_PEEPHOLE2("gep-load:in", GEP, LI);
351 ReplaceInstWithInst(BB->getInstList(), BI,
Chris Lattner65ea1712001-11-14 11:27:58 +0000352 LI = new LoadInst(GEP->getPointerOperand(),
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000353 Indices));
Chris Lattner8d38e542001-11-01 03:12:34 +0000354 PRINT_PEEPHOLE1("gep-load:out", LI);
355 return true;
356 }
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000357
358
359 // Peephole optimize the following instructions:
360 // %t1 = cast <ty> * %t0 to <ty2> *
361 // %V = load <ty2> * %t1
362 //
363 // Into: %t1 = load <ty> * %t0
364 // %V = cast <ty> %t1 to <ty2>
365 //
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.
371 //
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->getValueType() : 0;
376
377 // Make sure that nothing will be lost in the new cast...
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000378 if (!LI->hasIndices() && SrcTy &&
379 ElTy->isLosslesslyConvertableTo(LI->getType())) {
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000380 PRINT_PEEPHOLE2("CL-LoadCast:in ", CI, LI);
381
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
385
386 // Insert the load before the old load
387 BI = BB->getInstList().insert(BI, NLI)+1;
388
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);
393
394 return true;
395 }
396 }
Chris Lattnerd32a9612001-11-01 02:42:08 +0000397 } else if (I->getOpcode() == Instruction::Add &&
398 isa<CastInst>(I->getOperand(1))) {
399
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000400 if (PeepholeOptimizeAddCast(BB, BI, I->getOperand(0),
401 cast<CastInst>(I->getOperand(1))))
Chris Lattnerd32a9612001-11-01 02:42:08 +0000402 return true;
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000403
Chris Lattner3d775c32001-11-13 04:59:41 +0000404#endif
Chris Lattnerd32a9612001-11-01 02:42:08 +0000405 }
406
407 return false;
408}
409
410
411
412
413static 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();
418
419 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
Chris Lattnerbd70bb92001-11-26 18:58:55 +0000420 if (opt::DeadCodeElimination::dceInstruction(BIL, BI) ||
421 opt::ConstantPropogation::doConstantPropogation(BB, BI)) {
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000422 Changed = true;
423#ifdef DEBUG_PEEPHOLE_INSTS
424 cerr << "DeadCode Elinated!\n";
425#endif
426 } else if (PeepholeOptimize(BB, BI))
Chris Lattnerd32a9612001-11-01 02:42:08 +0000427 Changed = true;
428 else
429 ++BI;
430 }
431 }
432 return Changed;
433}
434
435
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000436
437
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.
442//
443static bool DoInsertArrayCast(Value *V, BasicBlock *BB,
444 BasicBlock::iterator InsertBefore) {
445 const PointerType *ThePtrType = dyn_cast<PointerType>(V->getType());
446 if (!ThePtrType) return false;
447
448 const Type *ElTy = ThePtrType->getValueType();
449 if (isa<MethodType>(ElTy) || isa<ArrayType>(ElTy)) return false;
450
451 unsigned ElementSize = TD.getTypeSize(ElTy);
452 bool InsertCast = false;
453
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->getValueType()))
460 if (AT->getElementType() == ThePtrType->getValueType()) {
461 // Cast already exists! Don't mess around with it.
462 return false; // No changes made to program though...
463 }
464 break;
465 case Instruction::Add: { // Analyze pointer arithmetic...
466 Value *OtherOp = Inst->getOperand(Inst->getOperand(0) == V);
467 analysis::ExprType Expr = analysis::ClassifyExpression(OtherOp);
468
469 // This looks like array addressing iff:
470 // A. The constant of the index is larger than the size of the element
471 // type.
472 // B. The scale factor is >= the size of the type.
473 //
474 if (Expr.Offset && getConstantValue(Expr.Offset) >= (int)ElementSize) // A
475 InsertCast = true;
476
477 if (Expr.Scale && getConstantValue(Expr.Scale) >= (int)ElementSize) // B
478 InsertCast = true;
479
480 break;
481 }
482 default: break; // Not an interesting use...
483 }
484 }
485
486 if (!InsertCast) return false; // There is no reason to insert a cast!
487
488 // Calculate the destination pointer type
489 const PointerType *DestTy = PointerType::get(ArrayType::get(ElTy));
490
491 // Check to make sure that all uses of the value can be converted over to use
492 // the newly typed value.
493 //
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);
499 return false;
500 }
501 ConvertedTypes.clear();
502
503 // Insert a cast!
504 CastInst *TheCast =
505 new CastInst(ConstPoolVal::getNullConstant(V->getType()), DestTy,
506 V->getName());
507 BB->getInstList().insert(InsertBefore, TheCast);
508
509 cerr << "Inserting cast for " << V << endl;
510
511 // Convert users of the old value over to use the cast result...
512 ValueMapCache VMC;
513 ConvertValueToNewType(V, TheCast, VMC);
514
515 // The cast is the only thing that is allowed to reference the value...
516 TheCast->setOperand(0, V);
517
518 cerr << "Inserted ptr-array cast: " << TheCast;
519 return true; // Made a change!
520}
521
522
523// DoInsertArrayCasts - Loop over all "incoming" values in the specified method,
524// inserting a cast for pointer values that are used as arrays. For our
525// purposes, an incoming value is considered to be either a value that is
526// either a method parameter, or a pointer returned from a function call.
527//
528static bool DoInsertArrayCasts(Method *M) {
529 assert(!M->isExternal() && "Can't handle external methods!");
530
531 // Insert casts for all arguments to the function...
532 bool Changed = false;
533 BasicBlock *CurBB = M->front();
534
535 for (Method::ArgumentListType::iterator AI = M->getArgumentList().begin(),
536 AE = M->getArgumentList().end(); AI != AE; ++AI) {
537
538 Changed |= DoInsertArrayCast(*AI, CurBB, CurBB->begin());
539 }
540
541 // TODO: insert casts for alloca, malloc, and function call results. Also,
542 // look for pointers that already have casts, to add to the map.
543
544 return Changed;
545}
546
547
548
549
Chris Lattnerd32a9612001-11-01 02:42:08 +0000550// RaisePointerReferences::doit - Raise a method representation to a higher
551// level.
552//
553bool RaisePointerReferences::doit(Method *M) {
554 if (M->isExternal()) return false;
Chris Lattnerd32a9612001-11-01 02:42:08 +0000555
Chris Lattner68b07b72001-11-01 07:00:51 +0000556#ifdef DEBUG_PEEPHOLE_INSTS
557 cerr << "\n\n\nStarting to work on Method '" << M->getName() << "'\n";
558#endif
559
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000560 // Insert casts for all incoming pointer pointer values that are treated as
561 // arrays...
Chris Lattnerd32a9612001-11-01 02:42:08 +0000562 //
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000563 bool Changed = false, LocalChange;
564 do {
565 LocalChange = DoInsertArrayCasts(M);
Chris Lattnerd32a9612001-11-01 02:42:08 +0000566
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000567 // Iterate over the method, refining it, until it converges on a stable
568 // state
569 while (DoRaisePass(M)) LocalChange = true;
570 Changed |= LocalChange;
571
572 } while (LocalChange);
Chris Lattnerd32a9612001-11-01 02:42:08 +0000573
574 return Changed;
575}