blob: a75aa57bccd96ac1df59d73198152d74b7333fc1 [file] [log] [blame]
Chris Lattner59cd9f12001-11-04 23:24:06 +00001//===-- TransformInternals.cpp - Implement shared functions for transforms --=//
2//
3// This file defines shared functions used by the different components of the
4// Transforms library.
5//
6//===----------------------------------------------------------------------===//
7
8#include "TransformInternals.h"
Chris Lattner59cd9f12001-11-04 23:24:06 +00009#include "llvm/Type.h"
Chris Lattnere9bb2df2001-12-03 22:26:30 +000010#include "llvm/ConstantVals.h"
Chris Lattner89a1c802001-11-26 16:59:47 +000011#include "llvm/Analysis/Expressions.h"
12#include "llvm/iOther.h"
Chris Lattner7991c282001-12-14 16:38:59 +000013#include <algorithm>
Chris Lattner59cd9f12001-11-04 23:24:06 +000014
15// TargetData Hack: Eventually we will have annotations given to us by the
16// backend so that we know stuff about type size and alignments. For now
17// though, just use this, because it happens to match the model that GCC uses.
18//
19const TargetData TD("LevelRaise: Should be GCC though!");
20
Chris Lattner59cd9f12001-11-04 23:24:06 +000021// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
22// with a value, then remove and delete the original instruction.
23//
24void ReplaceInstWithValue(BasicBlock::InstListType &BIL,
25 BasicBlock::iterator &BI, Value *V) {
26 Instruction *I = *BI;
27 // Replaces all of the uses of the instruction with uses of the value
28 I->replaceAllUsesWith(V);
29
30 // Remove the unneccesary instruction now...
31 BIL.remove(BI);
32
33 // Make sure to propogate a name if there is one already...
34 if (I->hasName() && !V->hasName())
35 V->setName(I->getName(), BIL.getParent()->getSymbolTable());
36
37 // Remove the dead instruction now...
38 delete I;
39}
40
41
42// ReplaceInstWithInst - Replace the instruction specified by BI with the
43// instruction specified by I. The original instruction is deleted and BI is
44// updated to point to the new instruction.
45//
46void ReplaceInstWithInst(BasicBlock::InstListType &BIL,
47 BasicBlock::iterator &BI, Instruction *I) {
48 assert(I->getParent() == 0 &&
49 "ReplaceInstWithInst: Instruction already inserted into basic block!");
50
51 // Insert the new instruction into the basic block...
Chris Lattnerc4db7542002-03-11 22:21:04 +000052 BI = BIL.insert(BI, I)+1; // Increment BI to point to instruction to delete
Chris Lattner59cd9f12001-11-04 23:24:06 +000053
54 // Replace all uses of the old instruction, and delete it.
55 ReplaceInstWithValue(BIL, BI, I);
56
Chris Lattnerc4db7542002-03-11 22:21:04 +000057 // Move BI back to point to the newly inserted instruction
Chris Lattner59cd9f12001-11-04 23:24:06 +000058 --BI;
59}
60
Chris Lattner7991c282001-12-14 16:38:59 +000061void ReplaceInstWithInst(Instruction *From, Instruction *To) {
62 BasicBlock *BB = From->getParent();
63 BasicBlock::InstListType &BIL = BB->getInstList();
64 BasicBlock::iterator BI = find(BIL.begin(), BIL.end(), From);
65 assert(BI != BIL.end() && "Inst not in it's parents BB!");
66 ReplaceInstWithInst(BIL, BI, To);
67}
68
Chris Lattner8e865422002-03-21 06:24:00 +000069// InsertInstBeforeInst - Insert 'NewInst' into the basic block that 'Existing'
70// is already in, and put it right before 'Existing'. This instruction should
71// only be used when there is no iterator to Existing already around. The
72// returned iterator points to the new instruction.
73//
74BasicBlock::iterator InsertInstBeforeInst(Instruction *NewInst,
75 Instruction *Existing) {
76 BasicBlock *BB = Existing->getParent();
77 BasicBlock::InstListType &BIL = BB->getInstList();
78 BasicBlock::iterator BI = find(BIL.begin(), BIL.end(), Existing);
79 assert(BI != BIL.end() && "Inst not in it's parents BB!");
80 return BIL.insert(BI, NewInst);
81}
82
Chris Lattner7991c282001-12-14 16:38:59 +000083
Chris Lattner59cd9f12001-11-04 23:24:06 +000084
Chris Lattner9e77f7e2002-03-21 06:27:20 +000085static const Type *getStructOffsetStep(const StructType *STy, unsigned &Offset,
86 std::vector<Value*> &Indices) {
87 assert(Offset < TD.getTypeSize(STy) && "Offset not in composite!");
88 const StructLayout *SL = TD.getStructLayout(STy);
89
90 // This loop terminates always on a 0 <= i < MemberOffsets.size()
91 unsigned i;
92 for (i = 0; i < SL->MemberOffsets.size()-1; ++i)
93 if (Offset >= SL->MemberOffsets[i] && Offset < SL->MemberOffsets[i+1])
94 break;
95
96 assert(Offset >= SL->MemberOffsets[i] &&
97 (i == SL->MemberOffsets.size()-1 || Offset < SL->MemberOffsets[i+1]));
98
99 // Make sure to save the current index...
100 Indices.push_back(ConstantUInt::get(Type::UByteTy, i));
101 Offset = SL->MemberOffsets[i];
102 return STy->getContainedType(i);
103}
104
105
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000106// getStructOffsetType - Return a vector of offsets that are to be used to index
107// into the specified struct type to get as close as possible to index as we
108// can. Note that it is possible that we cannot get exactly to Offset, in which
109// case we update offset to be the offset we actually obtained. The resultant
110// leaf type is returned.
111//
112// If StopEarly is set to true (the default), the first object with the
113// specified type is returned, even if it is a struct type itself. In this
114// case, this routine will not drill down to the leaf type. Set StopEarly to
115// false if you want a leaf
116//
117const Type *getStructOffsetType(const Type *Ty, unsigned &Offset,
Chris Lattner9e77f7e2002-03-21 06:27:20 +0000118 std::vector<Value*> &Indices,
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000119 bool StopEarly = true) {
Chris Lattner9e77f7e2002-03-21 06:27:20 +0000120 if (Offset == 0 && StopEarly && !Indices.empty())
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000121 return Ty; // Return the leaf type
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000122
Chris Lattner89a1c802001-11-26 16:59:47 +0000123 unsigned ThisOffset;
124 const Type *NextType;
125 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattner9e77f7e2002-03-21 06:27:20 +0000126 ThisOffset = Offset;
127 NextType = getStructOffsetStep(STy, ThisOffset, Indices);
Chris Lattner7991c282001-12-14 16:38:59 +0000128 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
129 assert(Offset < TD.getTypeSize(ATy) && "Offset not in composite!");
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000130
Chris Lattner89a1c802001-11-26 16:59:47 +0000131 NextType = ATy->getElementType();
132 unsigned ChildSize = TD.getTypeSize(NextType);
Chris Lattner9e77f7e2002-03-21 06:27:20 +0000133 Indices.push_back(ConstantUInt::get(Type::UIntTy, Offset/ChildSize));
Chris Lattner89a1c802001-11-26 16:59:47 +0000134 ThisOffset = (Offset/ChildSize)*ChildSize;
Chris Lattner7991c282001-12-14 16:38:59 +0000135 } else {
136 Offset = 0; // Return the offset that we were able to acheive
137 return Ty; // Return the leaf type
Chris Lattner89a1c802001-11-26 16:59:47 +0000138 }
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000139
Chris Lattner89a1c802001-11-26 16:59:47 +0000140 unsigned SubOffs = Offset - ThisOffset;
Chris Lattner4736d062002-03-07 21:18:00 +0000141 const Type *LeafTy = getStructOffsetType(NextType, SubOffs,
Chris Lattner9e77f7e2002-03-21 06:27:20 +0000142 Indices, StopEarly);
Chris Lattner89a1c802001-11-26 16:59:47 +0000143 Offset = ThisOffset + SubOffs;
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000144 return LeafTy;
145}
Chris Lattner89a1c802001-11-26 16:59:47 +0000146
147// ConvertableToGEP - This function returns true if the specified value V is
148// a valid index into a pointer of type Ty. If it is valid, Idx is filled in
149// with the values that would be appropriate to make this a getelementptr
150// instruction. The type returned is the root type that the GEP would point to
151//
152const Type *ConvertableToGEP(const Type *Ty, Value *OffsetVal,
Chris Lattner697954c2002-01-20 22:54:45 +0000153 std::vector<Value*> &Indices,
Chris Lattner89a1c802001-11-26 16:59:47 +0000154 BasicBlock::iterator *BI = 0) {
Chris Lattner7991c282001-12-14 16:38:59 +0000155 const CompositeType *CompTy = dyn_cast<CompositeType>(Ty);
Chris Lattner89a1c802001-11-26 16:59:47 +0000156 if (CompTy == 0) return 0;
157
158 // See if the cast is of an integer expression that is either a constant,
159 // or a value scaled by some amount with a possible offset.
160 //
161 analysis::ExprType Expr = analysis::ClassifyExpression(OffsetVal);
162
Chris Lattner89a1c802001-11-26 16:59:47 +0000163 // Get the offset and scale now...
Chris Lattner99fb91c2002-03-21 03:04:38 +0000164 // A scale of zero with Expr.Var != 0 means a scale of 1.
165 //
166 // TODO: Handle negative offsets for C code like this:
167 // for (unsigned i = 12; i < 14; ++i) x[j*i-12] = ...
168 unsigned Offset = 0;
169 int Scale = 0;
Chris Lattner89a1c802001-11-26 16:59:47 +0000170
171 // Get the offset value if it exists...
172 if (Expr.Offset) {
173 int Val = getConstantValue(Expr.Offset);
174 if (Val < 0) return false; // Don't mess with negative offsets
175 Offset = (unsigned)Val;
176 }
177
178 // Get the scale value if it exists...
Chris Lattner99fb91c2002-03-21 03:04:38 +0000179 if (Expr.Scale) Scale = getConstantValue(Expr.Scale);
180 if (Expr.Var && Scale == 0) Scale = 1; // Scale != 0 if Expr.Var != 0
181
Chris Lattner89a1c802001-11-26 16:59:47 +0000182 // Loop over the Scale and Offset values, filling in the Indices vector for
183 // our final getelementptr instruction.
184 //
185 const Type *NextTy = CompTy;
186 do {
187 if (!isa<CompositeType>(NextTy))
188 return 0; // Type must not be ready for processing...
189 CompTy = cast<CompositeType>(NextTy);
190
191 if (const StructType *StructTy = dyn_cast<StructType>(CompTy)) {
Chris Lattner9e77f7e2002-03-21 06:27:20 +0000192 // Step into the appropriate element of the structure...
Chris Lattner89a1c802001-11-26 16:59:47 +0000193 unsigned ActualOffset = Offset;
Chris Lattner9e77f7e2002-03-21 06:27:20 +0000194 NextTy = getStructOffsetStep(StructTy, ActualOffset, Indices);
Chris Lattner89a1c802001-11-26 16:59:47 +0000195 Offset -= ActualOffset;
196 } else {
Chris Lattner7991c282001-12-14 16:38:59 +0000197 const Type *ElTy = cast<SequentialType>(CompTy)->getElementType();
Chris Lattner99fb91c2002-03-21 03:04:38 +0000198 if (!ElTy->isSized())
199 return 0; // Type is unreasonable... escape!
Chris Lattner89a1c802001-11-26 16:59:47 +0000200 unsigned ElSize = TD.getTypeSize(ElTy);
Chris Lattner99fb91c2002-03-21 03:04:38 +0000201 int ElSizeS = (int)ElSize;
Chris Lattner89a1c802001-11-26 16:59:47 +0000202
203 // See if the user is indexing into a different cell of this array...
Chris Lattner99fb91c2002-03-21 03:04:38 +0000204 if (Scale && (Scale >= ElSizeS || -Scale >= ElSizeS)) {
Chris Lattner2dc48bd2001-12-05 19:41:16 +0000205 // A scale n*ElSize might occur if we are not stepping through
206 // array by one. In this case, we will have to insert math to munge
207 // the index.
208 //
Chris Lattner99fb91c2002-03-21 03:04:38 +0000209 int ScaleAmt = Scale/ElSizeS;
210 if (Scale-ScaleAmt*ElSizeS)
Chris Lattner2dc48bd2001-12-05 19:41:16 +0000211 return 0; // Didn't scale by a multiple of element size, bail out
Chris Lattner7991c282001-12-14 16:38:59 +0000212 Scale = 0; // Scale is consumed
Chris Lattner2dc48bd2001-12-05 19:41:16 +0000213
214 unsigned Index = Offset/ElSize; // is zero unless Offset > ElSize
215 Offset -= Index*ElSize; // Consume part of the offset
216
217 if (BI) { // Generate code?
218 BasicBlock *BB = (**BI)->getParent();
219 if (Expr.Var->getType() != Type::UIntTy) {
220 CastInst *IdxCast = new CastInst(Expr.Var, Type::UIntTy);
221 if (Expr.Var->hasName())
222 IdxCast->setName(Expr.Var->getName()+"-idxcast");
223 *BI = BB->getInstList().insert(*BI, IdxCast)+1;
224 Expr.Var = IdxCast;
225 }
226
Chris Lattner7c3f4152001-12-07 04:26:02 +0000227 if (ScaleAmt && ScaleAmt != 1) {
228 // If we have to scale up our index, do so now
Chris Lattner99fb91c2002-03-21 03:04:38 +0000229 Value *ScaleAmtVal = ConstantUInt::get(Type::UIntTy,
230 (unsigned)ScaleAmt);
Chris Lattner2dc48bd2001-12-05 19:41:16 +0000231 Instruction *Scaler = BinaryOperator::create(Instruction::Mul,
Chris Lattner99fb91c2002-03-21 03:04:38 +0000232 Expr.Var, ScaleAmtVal);
Chris Lattner2dc48bd2001-12-05 19:41:16 +0000233 if (Expr.Var->hasName())
234 Scaler->setName(Expr.Var->getName()+"-scale");
235
236 *BI = BB->getInstList().insert(*BI, Scaler)+1;
237 Expr.Var = Scaler;
238 }
239
240 if (Index) { // Add an offset to the index
241 Value *IndexAmt = ConstantUInt::get(Type::UIntTy, Index);
242 Instruction *Offseter = BinaryOperator::create(Instruction::Add,
243 Expr.Var, IndexAmt);
244 if (Expr.Var->hasName())
245 Offseter->setName(Expr.Var->getName()+"-offset");
246 *BI = BB->getInstList().insert(*BI, Offseter)+1;
247 Expr.Var = Offseter;
248 }
249 }
250
251 Indices.push_back(Expr.Var);
Chris Lattner99fb91c2002-03-21 03:04:38 +0000252 Expr.Var = 0;
Chris Lattner2dc48bd2001-12-05 19:41:16 +0000253 } else if (Offset >= ElSize) {
Chris Lattner89a1c802001-11-26 16:59:47 +0000254 // Calculate the index that we are entering into the array cell with
255 unsigned Index = Offset/ElSize;
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000256 Indices.push_back(ConstantUInt::get(Type::UIntTy, Index));
Chris Lattner89a1c802001-11-26 16:59:47 +0000257 Offset -= Index*ElSize; // Consume part of the offset
258
Chris Lattner754cf412002-03-14 16:37:04 +0000259 } else if (isa<ArrayType>(CompTy) || Indices.empty()) {
Chris Lattner89a1c802001-11-26 16:59:47 +0000260 // Must be indexing a small amount into the first cell of the array
261 // Just index into element zero of the array here.
262 //
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000263 Indices.push_back(ConstantUInt::get(Type::UIntTy, 0));
Chris Lattner7991c282001-12-14 16:38:59 +0000264 } else {
265 return 0; // Hrm. wierd, can't handle this case. Bail
Chris Lattner89a1c802001-11-26 16:59:47 +0000266 }
267 NextTy = ElTy;
268 }
269 } while (Offset || Scale); // Go until we're done!
270
271 return NextTy;
272}