blob: f155c507097bda03703bb2a761c0a32bf008860f [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"
Chris Lattnere9bb2df2001-12-03 22:26:30 +000014#include "llvm/ConstantVals.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
Chris Lattnera8b6d432001-12-05 06:34:00 +000054#if 0 // Unneccesary code, handled by convert exprs
55// Peephole optimize the following instructions:
56// %t1 = cast ? to x *
57// %t2 = add x * %SP, %t1 ;; Constant must be 2nd operand
58//
59// Into: %t3 = getelementptr {<...>} * %SP, <element indices>
60// %t2 = cast <eltype> * %t3 to {<...>}*
61//
62static bool HandleCastToPointer(BasicBlock::iterator BI,
63 const PointerType *DestPTy) {
64 CastInst *CI = cast<CastInst>(*BI);
Chris Lattnerf3b976e2001-11-04 20:21:12 +000065
Chris Lattnera8b6d432001-12-05 06:34:00 +000066 // Scan all of the uses, looking for any uses that are not add
67 // instructions. If we have non-adds, do not make this transformation.
68 //
69 for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
70 I != E; ++I) {
71 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(*I)) {
72 if (BO->getOpcode() != Instruction::Add)
73 return false;
74 } else {
75 return false;
76 }
77 }
78
79 vector<Value*> Indices;
80 Value *Src = CI->getOperand(0);
81 const Type *Result = ConvertableToGEP(DestPTy, Src, Indices, &BI);
82 const PointerType *UsedType = DestPTy;
83
84 // If we fail, check to see if we have an pointer source type that, if
85 // converted to an unsized array type, would work. In this case, we propogate
86 // the cast forward to the input of the add instruction.
87 //
88 if (Result == 0 && getPointedToComposite(DestPTy) == 0) {
89 // Make an unsized array and try again...
90 UsedType = PointerType::get(ArrayType::get(DestPTy->getElementType()));
91 Result = ConvertableToGEP(UsedType, Src, Indices, &BI);
92 }
93
94 if (Result == 0) return false; // Not convertable...
95
96 PRINT_PEEPHOLE2("cast-add-to-gep:in", Src, CI);
97
98 // If we have a getelementptr capability... transform all of the
99 // add instruction uses into getelementptr's.
100 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
101 UI != E; ++UI) {
102 Instruction *I = cast<Instruction>(*UI);
103 assert(I->getOpcode() == Instruction::Add && I->getNumOperands() == 2 &&
104 "Use is not a valid add instruction!");
105
106 // Get the value added to the cast result pointer...
107 Value *OtherPtr = I->getOperand((I->getOperand(0) == CI) ? 1 : 0);
108
109 BasicBlock *BB = I->getParent();
110 BasicBlock::iterator AddIt = find(BB->getInstList().begin(),
111 BB->getInstList().end(), I);
112
113 if (UsedType != DestPTy) {
114 // Insert a cast of the incoming value to something addressable...
115 CastInst *C = new CastInst(OtherPtr, UsedType, OtherPtr->getName());
116 AddIt = BB->getInstList().insert(AddIt, C)+1;
117 OtherPtr = C;
118 }
119
120 GetElementPtrInst *GEP = new GetElementPtrInst(OtherPtr, Indices,
121 I->getName());
122
123 PRINT_PEEPHOLE1("cast-add-to-gep:i", I);
124
125 // Replace the old add instruction with the shiny new GEP inst
126 ReplaceInstWithInst(BB->getInstList(), AddIt, GEP);
127 PRINT_PEEPHOLE1("cast-add-to-gep:o", GEP);
128 }
129 return true;
130}
131#endif
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000132
133// Peephole optimize the following instructions:
134// %t1 = cast ulong <const int> to {<...>} *
135// %t2 = add {<...>} * %SP, %t1 ;; Constant must be 2nd operand
136//
137// or
138// %t1 = cast {<...>}* %SP to int*
139// %t5 = cast ulong <const int> to int*
140// %t2 = add int* %t1, %t5 ;; int is same size as field
141//
142// Into: %t3 = getelementptr {<...>} * %SP, <element indices>
143// %t2 = cast <eltype> * %t3 to {<...>}*
144//
145static bool PeepholeOptimizeAddCast(BasicBlock *BB, BasicBlock::iterator &BI,
146 Value *AddOp1, CastInst *AddOp2) {
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000147 const CompositeType *CompTy;
148 Value *OffsetVal = AddOp2->getOperand(0);
149 Value *SrcPtr; // Of type pointer to struct...
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000150
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000151 if ((CompTy = getPointedToComposite(AddOp1->getType()))) {
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000152 SrcPtr = AddOp1; // Handle the first case...
153 } else if (CastInst *AddOp1c = dyn_cast<CastInst>(AddOp1)) {
154 SrcPtr = AddOp1c->getOperand(0); // Handle the second case...
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000155 CompTy = getPointedToComposite(SrcPtr->getType());
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000156 }
157
158 // Only proceed if we have detected all of our conditions successfully...
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000159 if (!CompTy || !SrcPtr || !OffsetVal->getType()->isIntegral())
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000160 return false;
161
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000162 vector<Value*> Indices;
163 if (!ConvertableToGEP(SrcPtr->getType(), OffsetVal, Indices, &BI))
164 return false; // Not convertable... perhaps next time
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000165
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000166 if (getPointedToComposite(AddOp1->getType())) { // case 1
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000167 PRINT_PEEPHOLE2("add-to-gep1:in", AddOp2, *BI);
168 } else {
169 PRINT_PEEPHOLE3("add-to-gep2:in", AddOp1, AddOp2, *BI);
170 }
171
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000172 GetElementPtrInst *GEP = new GetElementPtrInst(SrcPtr, Indices,
173 AddOp2->getName());
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000174 BI = BB->getInstList().insert(BI, GEP)+1;
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000175
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000176 Instruction *NCI = new CastInst(GEP, AddOp1->getType());
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000177 ReplaceInstWithInst(BB->getInstList(), BI, NCI);
178 PRINT_PEEPHOLE2("add-to-gep:out", GEP, NCI);
179 return true;
180}
181
Chris Lattnerd32a9612001-11-01 02:42:08 +0000182static bool PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI) {
183 Instruction *I = *BI;
Chris Lattnerd32a9612001-11-01 02:42:08 +0000184
185 if (CastInst *CI = dyn_cast<CastInst>(I)) {
186 Value *Src = CI->getOperand(0);
187 Instruction *SrcI = dyn_cast<Instruction>(Src); // Nonnull if instr source
188 const Type *DestTy = CI->getType();
189
Chris Lattnere99c66b2001-11-01 17:05:27 +0000190 // Peephole optimize the following instruction:
191 // %V2 = cast <ty> %V to <ty>
192 //
193 // Into: <nothing>
194 //
195 if (DestTy == Src->getType()) { // Check for a cast to same type as src!!
Chris Lattnerd32a9612001-11-01 02:42:08 +0000196 PRINT_PEEPHOLE1("cast-of-self-ty", CI);
197 CI->replaceAllUsesWith(Src);
198 if (!Src->hasName() && CI->hasName()) {
199 string Name = CI->getName();
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000200 CI->setName("");
201 Src->setName(Name, BB->getParent()->getSymbolTable());
Chris Lattnerd32a9612001-11-01 02:42:08 +0000202 }
203 return true;
204 }
205
Chris Lattnere99c66b2001-11-01 17:05:27 +0000206 // Peephole optimize the following instructions:
207 // %tmp = cast <ty> %V to <ty2>
Chris Lattnera8b6d432001-12-05 06:34:00 +0000208 // %V = cast <ty2> %tmp to <ty3> ; Where ty & ty2 are same size
Chris Lattnere99c66b2001-11-01 17:05:27 +0000209 //
210 // Into: cast <ty> %V to <ty3>
211 //
Chris Lattnerd32a9612001-11-01 02:42:08 +0000212 if (SrcI)
213 if (CastInst *CSrc = dyn_cast<CastInst>(SrcI))
214 if (isReinterpretingCast(CI) + isReinterpretingCast(CSrc) < 2) {
215 // We can only do c-c elimination if, at most, one cast does a
216 // reinterpretation of the input data.
217 //
218 // If legal, make this cast refer the the original casts argument!
219 //
220 PRINT_PEEPHOLE2("cast-cast:in ", CI, CSrc);
221 CI->setOperand(0, CSrc->getOperand(0));
222 PRINT_PEEPHOLE1("cast-cast:out", CI);
223 return true;
224 }
225
226 // Check to see if it's a cast of an instruction that does not depend on the
227 // specific type of the operands to do it's job.
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000228 if (!isReinterpretingCast(CI)) {
Chris Lattnera8b6d432001-12-05 06:34:00 +0000229 // Check to see if we can convert the source of the cast to match the
230 // destination type of the cast...
231 //
Chris Lattnerb980e182001-11-04 21:32:11 +0000232 ValueTypeCache ConvertedTypes;
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000233 if (ValueConvertableToType(CI, Src->getType(), ConvertedTypes)) {
234 PRINT_PEEPHOLE2("CAST-DEST-EXPR-CONV:in ", Src, CI);
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000235
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000236#ifdef DEBUG_PEEPHOLE_INSTS
237 cerr << "\nCONVERTING EXPR TYPE:\n";
238#endif
Chris Lattnerb980e182001-11-04 21:32:11 +0000239 ValueMapCache ValueMap;
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000240 ConvertValueToNewType(CI, Src, ValueMap); // This will delete CI!
Chris Lattnere4f4d8c2001-11-05 18:30:53 +0000241
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000242 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
Chris Lattnere34443d2001-11-06 08:34:29 +0000243 PRINT_PEEPHOLE1("CAST-DEST-EXPR-CONV:out", Src);
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000244#ifdef DEBUG_PEEPHOLE_INSTS
245 cerr << "DONE CONVERTING EXPR TYPE: \n\n";// << BB->getParent();
246#endif
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000247 return true;
Chris Lattnera8b6d432001-12-05 06:34:00 +0000248 }
249
250 // Check to see if we can convert the users of the cast value to match the
251 // source type of the cast...
252 //
253 ConvertedTypes.clear();
254 if (ExpressionConvertableToType(Src, DestTy, ConvertedTypes)) {
255 PRINT_PEEPHOLE2("CAST-SRC-EXPR-CONV:in ", Src, CI);
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000256
257#ifdef DEBUG_PEEPHOLE_INSTS
Chris Lattnera8b6d432001-12-05 06:34:00 +0000258 cerr << "\nCONVERTING SRC EXPR TYPE:\n";
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000259#endif
Chris Lattnera8b6d432001-12-05 06:34:00 +0000260 ValueMapCache ValueMap;
261 Value *E = ConvertExpressionToType(Src, DestTy, ValueMap);
262 if (Constant *CPV = dyn_cast<Constant>(E))
263 CI->replaceAllUsesWith(CPV);
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000264
Chris Lattnera8b6d432001-12-05 06:34:00 +0000265 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
266 PRINT_PEEPHOLE1("CAST-SRC-EXPR-CONV:out", E);
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000267#ifdef DEBUG_PEEPHOLE_INSTS
Chris Lattnera8b6d432001-12-05 06:34:00 +0000268 cerr << "DONE CONVERTING SRC EXPR TYPE: \n\n";// << BB->getParent();
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000269#endif
Chris Lattnera8b6d432001-12-05 06:34:00 +0000270 return true;
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000271 }
Chris Lattnera8b6d432001-12-05 06:34:00 +0000272#if 0
273 // Otherwise find out it this cast is a cast to a pointer type, which is
274 // then added to some other pointer, then loaded or stored through. If
275 // so, convert the add into a getelementptr instruction...
276 //
277 if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
278 if (HandleCastToPointer(BI, DestPTy))
279 return true;
280 }
281#endif
Chris Lattnerd32a9612001-11-01 02:42:08 +0000282 }
283
Chris Lattnere99c66b2001-11-01 17:05:27 +0000284 // Check to see if we are casting from a structure pointer to a pointer to
285 // the first element of the structure... to avoid munching other peepholes,
286 // we only let this happen if there are no add uses of the cast.
287 //
288 // Peephole optimize the following instructions:
289 // %t1 = cast {<...>} * %StructPtr to <ty> *
290 //
291 // Into: %t2 = getelementptr {<...>} * %StructPtr, <0, 0, 0, ...>
292 // %t1 = cast <eltype> * %t1 to <ty> *
293 //
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000294#if 1
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000295 if (const CompositeType *CTy = getPointedToComposite(Src->getType()))
Chris Lattnere99c66b2001-11-01 17:05:27 +0000296 if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
297
298 // Loop over uses of the cast, checking for add instructions. If an add
299 // exists, this is probably a part of a more complex GEP, so we don't
300 // want to mess around with the cast.
301 //
302 bool HasAddUse = false;
303 for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
304 I != E; ++I)
305 if (isa<Instruction>(*I) &&
306 cast<Instruction>(*I)->getOpcode() == Instruction::Add) {
307 HasAddUse = true; break;
308 }
309
310 // If it doesn't have an add use, check to see if the dest type is
311 // losslessly convertable to one of the types in the start of the struct
312 // type.
313 //
314 if (!HasAddUse) {
Chris Lattner7a176752001-12-04 00:03:30 +0000315 const Type *DestPointedTy = DestPTy->getElementType();
Chris Lattnere99c66b2001-11-01 17:05:27 +0000316 unsigned Depth = 1;
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000317 const CompositeType *CurCTy = CTy;
Chris Lattnere99c66b2001-11-01 17:05:27 +0000318 const Type *ElTy = 0;
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000319
320 // Build the index vector, full of all zeros
321 vector<Value*> Indices;
322
323 while (CurCTy) {
324 if (const StructType *CurSTy = dyn_cast<StructType>(CurCTy)) {
325 // Check for a zero element struct type... if we have one, bail.
326 if (CurSTy->getElementTypes().size() == 0) break;
Chris Lattnere99c66b2001-11-01 17:05:27 +0000327
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000328 // Grab the first element of the struct type, which must lie at
329 // offset zero in the struct.
330 //
331 ElTy = CurSTy->getElementTypes()[0];
332 } else {
333 ElTy = cast<ArrayType>(CurCTy)->getElementType();
334 }
335
336 // Insert a zero to index through this type...
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000337 Indices.push_back(ConstantUInt::get(CurCTy->getIndexType(), 0));
Chris Lattnere99c66b2001-11-01 17:05:27 +0000338
339 // Did we find what we're looking for?
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000340 if (ElTy->isLosslesslyConvertableTo(DestPointedTy)) break;
Chris Lattnere99c66b2001-11-01 17:05:27 +0000341
342 // Nope, go a level deeper.
343 ++Depth;
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000344 CurCTy = dyn_cast<CompositeType>(ElTy);
Chris Lattnere99c66b2001-11-01 17:05:27 +0000345 ElTy = 0;
346 }
347
348 // Did we find what we were looking for? If so, do the transformation
349 if (ElTy) {
350 PRINT_PEEPHOLE1("cast-for-first:in", CI);
351
Chris Lattnere99c66b2001-11-01 17:05:27 +0000352 // Insert the new T cast instruction... stealing old T's name
353 GetElementPtrInst *GEP = new GetElementPtrInst(Src, Indices,
354 CI->getName());
355 CI->setName("");
356 BI = BB->getInstList().insert(BI, GEP)+1;
357
358 // Make the old cast instruction reference the new GEP instead of
359 // the old src value.
360 //
361 CI->setOperand(0, GEP);
362
363 PRINT_PEEPHOLE2("cast-for-first:out", GEP, CI);
364 return true;
365 }
366 }
367 }
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000368#endif
Chris Lattnere99c66b2001-11-01 17:05:27 +0000369
Chris Lattner3d775c32001-11-13 04:59:41 +0000370#if 1
Chris Lattner8d38e542001-11-01 03:12:34 +0000371 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
372 Value *Val = SI->getOperand(0);
Chris Lattner65ea1712001-11-14 11:27:58 +0000373 Value *Pointer = SI->getPointerOperand();
Chris Lattner8d38e542001-11-01 03:12:34 +0000374
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000375 // Peephole optimize the following instructions:
376 // %t1 = getelementptr {<...>} * %StructPtr, <element indices>
377 // store <elementty> %v, <elementty> * %t1
378 //
379 // Into: store <elementty> %v, {<...>} * %StructPtr, <element indices>
380 //
Chris Lattner8d38e542001-11-01 03:12:34 +0000381 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Pointer)) {
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000382 // Append any indices that the store instruction has onto the end of the
383 // ones that the GEP is carrying...
384 //
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000385 vector<Value*> Indices(GEP->copyIndices());
386 Indices.insert(Indices.end(), SI->idx_begin(), SI->idx_end());
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000387
Chris Lattner8d38e542001-11-01 03:12:34 +0000388 PRINT_PEEPHOLE2("gep-store:in", GEP, SI);
389 ReplaceInstWithInst(BB->getInstList(), BI,
Chris Lattner65ea1712001-11-14 11:27:58 +0000390 SI = new StoreInst(Val, GEP->getPointerOperand(),
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000391 Indices));
Chris Lattner8d38e542001-11-01 03:12:34 +0000392 PRINT_PEEPHOLE1("gep-store:out", SI);
393 return true;
394 }
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000395
396 // Peephole optimize the following instructions:
397 // %t = cast <T1>* %P to <T2> * ;; If T1 is losslessly convertable to T2
398 // store <T2> %V, <T2>* %t
399 //
400 // Into:
401 // %t = cast <T2> %V to <T1>
402 // store <T1> %t2, <T1>* %P
403 //
404 if (CastInst *CI = dyn_cast<CastInst>(Pointer))
405 if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
406 if (PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000407 // convertable types?
Chris Lattner7a176752001-12-04 00:03:30 +0000408 if (Val->getType()->isLosslesslyConvertableTo(CSPT->getElementType()) &&
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000409 !SI->hasIndices()) { // No subscripts yet!
410 PRINT_PEEPHOLE3("st-src-cast:in ", Pointer, Val, SI);
411
412 // Insert the new T cast instruction... stealing old T's name
Chris Lattner7a176752001-12-04 00:03:30 +0000413 CastInst *NCI = new CastInst(Val, CSPT->getElementType(),
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000414 CI->getName());
415 CI->setName("");
416 BI = BB->getInstList().insert(BI, NCI)+1;
417
418 // Replace the old store with a new one!
419 ReplaceInstWithInst(BB->getInstList(), BI,
420 SI = new StoreInst(NCI, CastSrc));
421 PRINT_PEEPHOLE3("st-src-cast:out", NCI, CastSrc, SI);
422 return true;
423 }
424
Chris Lattner8d38e542001-11-01 03:12:34 +0000425
426 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner65ea1712001-11-14 11:27:58 +0000427 Value *Pointer = LI->getPointerOperand();
Chris Lattner8d38e542001-11-01 03:12:34 +0000428
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000429 // Peephole optimize the following instructions:
430 // %t1 = getelementptr {<...>} * %StructPtr, <element indices>
431 // %V = load <elementty> * %t1
432 //
433 // Into: load {<...>} * %StructPtr, <element indices>
434 //
Chris Lattner8d38e542001-11-01 03:12:34 +0000435 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Pointer)) {
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000436 // Append any indices that the load instruction has onto the end of the
437 // ones that the GEP is carrying...
438 //
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000439 vector<Value*> Indices(GEP->copyIndices());
440 Indices.insert(Indices.end(), LI->idx_begin(), LI->idx_end());
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000441
Chris Lattner8d38e542001-11-01 03:12:34 +0000442 PRINT_PEEPHOLE2("gep-load:in", GEP, LI);
443 ReplaceInstWithInst(BB->getInstList(), BI,
Chris Lattner65ea1712001-11-14 11:27:58 +0000444 LI = new LoadInst(GEP->getPointerOperand(),
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000445 Indices));
Chris Lattner8d38e542001-11-01 03:12:34 +0000446 PRINT_PEEPHOLE1("gep-load:out", LI);
447 return true;
448 }
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000449
Chris Lattnera8b6d432001-12-05 06:34:00 +0000450#if 0
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000451 // Peephole optimize the following instructions:
452 // %t1 = cast <ty> * %t0 to <ty2> *
453 // %V = load <ty2> * %t1
454 //
455 // Into: %t1 = load <ty> * %t0
456 // %V = cast <ty> %t1 to <ty2>
457 //
458 // The idea behind this transformation is that if the expression type
459 // conversion engine could not convert the cast into some other nice form,
460 // that there is something fundementally wrong with the current shape of
461 // the program. Move the cast through the load and try again. This will
462 // leave the original cast instruction, to presumably become dead.
463 //
464 if (CastInst *CI = dyn_cast<CastInst>(Pointer)) {
465 Value *SrcVal = CI->getOperand(0);
466 const PointerType *SrcTy = dyn_cast<PointerType>(SrcVal->getType());
Chris Lattner7a176752001-12-04 00:03:30 +0000467 const Type *ElTy = SrcTy ? SrcTy->getElementType() : 0;
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000468
469 // Make sure that nothing will be lost in the new cast...
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000470 if (!LI->hasIndices() && SrcTy &&
471 ElTy->isLosslesslyConvertableTo(LI->getType())) {
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000472 PRINT_PEEPHOLE2("CL-LoadCast:in ", CI, LI);
473
474 string CName = CI->getName(); CI->setName("");
475 LoadInst *NLI = new LoadInst(SrcVal, LI->getName());
476 LI->setName(""); // Take over the old load's name
477
478 // Insert the load before the old load
479 BI = BB->getInstList().insert(BI, NLI)+1;
480
481 // Replace the old load with a new cast...
482 ReplaceInstWithInst(BB->getInstList(), BI,
483 CI = new CastInst(NLI, LI->getType(), CName));
484 PRINT_PEEPHOLE2("CL-LoadCast:out", NLI, CI);
485
486 return true;
487 }
488 }
Chris Lattnera8b6d432001-12-05 06:34:00 +0000489#endif
Chris Lattnerd32a9612001-11-01 02:42:08 +0000490 } else if (I->getOpcode() == Instruction::Add &&
491 isa<CastInst>(I->getOperand(1))) {
492
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000493 if (PeepholeOptimizeAddCast(BB, BI, I->getOperand(0),
494 cast<CastInst>(I->getOperand(1))))
Chris Lattnerd32a9612001-11-01 02:42:08 +0000495 return true;
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000496
Chris Lattner3d775c32001-11-13 04:59:41 +0000497#endif
Chris Lattnerd32a9612001-11-01 02:42:08 +0000498 }
499
500 return false;
501}
502
503
504
505
506static bool DoRaisePass(Method *M) {
507 bool Changed = false;
508 for (Method::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI) {
509 BasicBlock *BB = *MI;
510 BasicBlock::InstListType &BIL = BB->getInstList();
511
512 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
Chris Lattnerbd70bb92001-11-26 18:58:55 +0000513 if (opt::DeadCodeElimination::dceInstruction(BIL, BI) ||
514 opt::ConstantPropogation::doConstantPropogation(BB, BI)) {
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000515 Changed = true;
516#ifdef DEBUG_PEEPHOLE_INSTS
517 cerr << "DeadCode Elinated!\n";
518#endif
519 } else if (PeepholeOptimize(BB, BI))
Chris Lattnerd32a9612001-11-01 02:42:08 +0000520 Changed = true;
521 else
522 ++BI;
523 }
524 }
525 return Changed;
526}
527
528
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000529
530
531// DoInsertArrayCast - If the argument value has a pointer type, and if the
532// argument value is used as an array, insert a cast before the specified
533// basic block iterator that casts the value to an array pointer. Return the
534// new cast instruction (in the CastResult var), or null if no cast is inserted.
535//
536static bool DoInsertArrayCast(Value *V, BasicBlock *BB,
537 BasicBlock::iterator InsertBefore) {
538 const PointerType *ThePtrType = dyn_cast<PointerType>(V->getType());
539 if (!ThePtrType) return false;
540
Chris Lattner7a176752001-12-04 00:03:30 +0000541 const Type *ElTy = ThePtrType->getElementType();
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000542 if (isa<MethodType>(ElTy) || isa<ArrayType>(ElTy)) return false;
543
544 unsigned ElementSize = TD.getTypeSize(ElTy);
545 bool InsertCast = false;
546
547 for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
548 Instruction *Inst = cast<Instruction>(*I);
549 switch (Inst->getOpcode()) {
550 case Instruction::Cast: // There is already a cast instruction!
551 if (const PointerType *PT = dyn_cast<const PointerType>(Inst->getType()))
Chris Lattner7a176752001-12-04 00:03:30 +0000552 if (const ArrayType *AT = dyn_cast<const ArrayType>(PT->getElementType()))
553 if (AT->getElementType() == ThePtrType->getElementType()) {
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000554 // Cast already exists! Don't mess around with it.
555 return false; // No changes made to program though...
556 }
557 break;
558 case Instruction::Add: { // Analyze pointer arithmetic...
559 Value *OtherOp = Inst->getOperand(Inst->getOperand(0) == V);
560 analysis::ExprType Expr = analysis::ClassifyExpression(OtherOp);
561
562 // This looks like array addressing iff:
563 // A. The constant of the index is larger than the size of the element
564 // type.
565 // B. The scale factor is >= the size of the type.
566 //
567 if (Expr.Offset && getConstantValue(Expr.Offset) >= (int)ElementSize) // A
568 InsertCast = true;
569
570 if (Expr.Scale && getConstantValue(Expr.Scale) >= (int)ElementSize) // B
571 InsertCast = true;
572
573 break;
574 }
575 default: break; // Not an interesting use...
576 }
577 }
578
579 if (!InsertCast) return false; // There is no reason to insert a cast!
580
581 // Calculate the destination pointer type
582 const PointerType *DestTy = PointerType::get(ArrayType::get(ElTy));
583
584 // Check to make sure that all uses of the value can be converted over to use
585 // the newly typed value.
586 //
587 ValueTypeCache ConvertedTypes;
588 if (!ValueConvertableToType(V, DestTy, ConvertedTypes)) {
589 cerr << "FAILED to convert types of values for " << V << "\n";
590 ConvertedTypes.clear();
591 ValueConvertableToType(V, DestTy, ConvertedTypes);
592 return false;
593 }
594 ConvertedTypes.clear();
595
596 // Insert a cast!
597 CastInst *TheCast =
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000598 new CastInst(Constant::getNullConstant(V->getType()), DestTy, V->getName());
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000599 BB->getInstList().insert(InsertBefore, TheCast);
600
Chris Lattner4b770a32001-12-04 08:12:53 +0000601#ifdef DEBUG_PEEPHOLE_INSTS
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000602 cerr << "Inserting cast for " << V << endl;
Chris Lattner4b770a32001-12-04 08:12:53 +0000603#endif
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000604
605 // Convert users of the old value over to use the cast result...
606 ValueMapCache VMC;
607 ConvertValueToNewType(V, TheCast, VMC);
608
609 // The cast is the only thing that is allowed to reference the value...
610 TheCast->setOperand(0, V);
611
Chris Lattner4b770a32001-12-04 08:12:53 +0000612#ifdef DEBUG_PEEPHOLE_INSTS
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000613 cerr << "Inserted ptr-array cast: " << TheCast;
Chris Lattner4b770a32001-12-04 08:12:53 +0000614#endif
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000615 return true; // Made a change!
616}
617
618
619// DoInsertArrayCasts - Loop over all "incoming" values in the specified method,
620// inserting a cast for pointer values that are used as arrays. For our
621// purposes, an incoming value is considered to be either a value that is
622// either a method parameter, or a pointer returned from a function call.
623//
624static bool DoInsertArrayCasts(Method *M) {
625 assert(!M->isExternal() && "Can't handle external methods!");
626
627 // Insert casts for all arguments to the function...
628 bool Changed = false;
629 BasicBlock *CurBB = M->front();
630
631 for (Method::ArgumentListType::iterator AI = M->getArgumentList().begin(),
632 AE = M->getArgumentList().end(); AI != AE; ++AI) {
633
634 Changed |= DoInsertArrayCast(*AI, CurBB, CurBB->begin());
635 }
636
637 // TODO: insert casts for alloca, malloc, and function call results. Also,
638 // look for pointers that already have casts, to add to the map.
639
Chris Lattnerf1d65212001-12-05 06:40:17 +0000640#ifdef DEBUG_PEEPHOLE_INSTS
641 if (Changed) cerr << "Inserted casts:\n" << M;
642#endif
Chris Lattnera8b6d432001-12-05 06:34:00 +0000643
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000644 return Changed;
645}
646
647
648
649
Chris Lattnerd32a9612001-11-01 02:42:08 +0000650// RaisePointerReferences::doit - Raise a method representation to a higher
651// level.
652//
653bool RaisePointerReferences::doit(Method *M) {
654 if (M->isExternal()) return false;
Chris Lattnerd32a9612001-11-01 02:42:08 +0000655
Chris Lattner68b07b72001-11-01 07:00:51 +0000656#ifdef DEBUG_PEEPHOLE_INSTS
657 cerr << "\n\n\nStarting to work on Method '" << M->getName() << "'\n";
658#endif
659
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000660 // Insert casts for all incoming pointer pointer values that are treated as
661 // arrays...
Chris Lattnerd32a9612001-11-01 02:42:08 +0000662 //
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000663 bool Changed = false, LocalChange;
Chris Lattnera8b6d432001-12-05 06:34:00 +0000664
Chris Lattner4b770a32001-12-04 08:12:53 +0000665 do {
Chris Lattnera8b6d432001-12-05 06:34:00 +0000666#ifdef DEBUG_PEEPHOLE_INSTS
667 cerr << "Looping: \n" << M;
668#endif
669 LocalChange = DoInsertArrayCasts(M);
670
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000671 // Iterate over the method, refining it, until it converges on a stable
672 // state
673 while (DoRaisePass(M)) LocalChange = true;
674 Changed |= LocalChange;
675
676 } while (LocalChange);
Chris Lattnerd32a9612001-11-01 02:42:08 +0000677
678 return Changed;
679}