a75aa57bccd96ac1df59d73198152d74b7333fc1
[oota-llvm.git] / lib / Transforms / TransformInternals.cpp
1 //===-- 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"
9 #include "llvm/Type.h"
10 #include "llvm/ConstantVals.h"
11 #include "llvm/Analysis/Expressions.h"
12 #include "llvm/iOther.h"
13 #include <algorithm>
14
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 //
19 const TargetData TD("LevelRaise: Should be GCC though!");
20
21 // ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
22 // with a value, then remove and delete the original instruction.
23 //
24 void 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 //
46 void 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...
52   BI = BIL.insert(BI, I)+1;  // Increment BI to point to instruction to delete
53
54   // Replace all uses of the old instruction, and delete it.
55   ReplaceInstWithValue(BIL, BI, I);
56
57   // Move BI back to point to the newly inserted instruction
58   --BI;
59 }
60
61 void 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
69 // 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 //
74 BasicBlock::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
83
84
85 static 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
106 // 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 //
117 const Type *getStructOffsetType(const Type *Ty, unsigned &Offset,
118                                 std::vector<Value*> &Indices,
119                                 bool StopEarly = true) {
120   if (Offset == 0 && StopEarly && !Indices.empty())
121     return Ty;    // Return the leaf type
122
123   unsigned ThisOffset;
124   const Type *NextType;
125   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
126     ThisOffset = Offset;
127     NextType = getStructOffsetStep(STy, ThisOffset, Indices);
128   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
129     assert(Offset < TD.getTypeSize(ATy) && "Offset not in composite!");
130
131     NextType = ATy->getElementType();
132     unsigned ChildSize = TD.getTypeSize(NextType);
133     Indices.push_back(ConstantUInt::get(Type::UIntTy, Offset/ChildSize));
134     ThisOffset = (Offset/ChildSize)*ChildSize;
135   } else {
136     Offset = 0;   // Return the offset that we were able to acheive
137     return Ty;    // Return the leaf type
138   }
139
140   unsigned SubOffs = Offset - ThisOffset;
141   const Type *LeafTy = getStructOffsetType(NextType, SubOffs,
142                                            Indices, StopEarly);
143   Offset = ThisOffset + SubOffs;
144   return LeafTy;
145 }
146
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 //
152 const Type *ConvertableToGEP(const Type *Ty, Value *OffsetVal,
153                              std::vector<Value*> &Indices,
154                              BasicBlock::iterator *BI = 0) {
155   const CompositeType *CompTy = dyn_cast<CompositeType>(Ty);
156   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
163   // Get the offset and scale now...
164   // 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;
170
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...
179   if (Expr.Scale) Scale = getConstantValue(Expr.Scale);
180   if (Expr.Var && Scale == 0) Scale = 1;   // Scale != 0 if Expr.Var != 0
181  
182   // 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)) {
192       // Step into the appropriate element of the structure...
193       unsigned ActualOffset = Offset;
194       NextTy = getStructOffsetStep(StructTy, ActualOffset, Indices);
195       Offset -= ActualOffset;
196     } else {
197       const Type *ElTy = cast<SequentialType>(CompTy)->getElementType();
198       if (!ElTy->isSized())
199         return 0; // Type is unreasonable... escape!
200       unsigned ElSize = TD.getTypeSize(ElTy);
201       int ElSizeS = (int)ElSize;
202
203       // See if the user is indexing into a different cell of this array...
204       if (Scale && (Scale >= ElSizeS || -Scale >= ElSizeS)) {
205         // 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         //
209         int ScaleAmt = Scale/ElSizeS;
210         if (Scale-ScaleAmt*ElSizeS)
211           return 0;  // Didn't scale by a multiple of element size, bail out
212         Scale = 0;   // Scale is consumed
213
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
227           if (ScaleAmt && ScaleAmt != 1) {
228             // If we have to scale up our index, do so now
229             Value *ScaleAmtVal = ConstantUInt::get(Type::UIntTy,
230                                                    (unsigned)ScaleAmt);
231             Instruction *Scaler = BinaryOperator::create(Instruction::Mul,
232                                                          Expr.Var, ScaleAmtVal);
233             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);
252         Expr.Var = 0;
253       } else if (Offset >= ElSize) {
254         // Calculate the index that we are entering into the array cell with
255         unsigned Index = Offset/ElSize;
256         Indices.push_back(ConstantUInt::get(Type::UIntTy, Index));
257         Offset -= Index*ElSize;               // Consume part of the offset
258
259       } else if (isa<ArrayType>(CompTy) || Indices.empty()) {
260         // Must be indexing a small amount into the first cell of the array
261         // Just index into element zero of the array here.
262         //
263         Indices.push_back(ConstantUInt::get(Type::UIntTy, 0));
264       } else {
265         return 0;  // Hrm. wierd, can't handle this case.  Bail
266       }
267       NextTy = ElTy;
268     }
269   } while (Offset || Scale);    // Go until we're done!
270
271   return NextTy;
272 }