Handle more complex array indexing expressions
[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/Method.h"
10 #include "llvm/Type.h"
11 #include "llvm/ConstantVals.h"
12 #include "llvm/Analysis/Expressions.h"
13 #include "llvm/iOther.h"
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;
53
54   // Replace all uses of the old instruction, and delete it.
55   ReplaceInstWithValue(BIL, BI, I);
56
57   // Reexamine the instruction just inserted next time around the cleanup pass
58   // loop.
59   --BI;
60 }
61
62
63 // getStructOffsetType - Return a vector of offsets that are to be used to index
64 // into the specified struct type to get as close as possible to index as we
65 // can.  Note that it is possible that we cannot get exactly to Offset, in which
66 // case we update offset to be the offset we actually obtained.  The resultant
67 // leaf type is returned.
68 //
69 // If StopEarly is set to true (the default), the first object with the
70 // specified type is returned, even if it is a struct type itself.  In this
71 // case, this routine will not drill down to the leaf type.  Set StopEarly to
72 // false if you want a leaf
73 //
74 const Type *getStructOffsetType(const Type *Ty, unsigned &Offset,
75                                 vector<Value*> &Offsets,
76                                 bool StopEarly = true) {
77   if (!isa<CompositeType>(Ty) ||
78       (Offset == 0 && StopEarly && !Offsets.empty())) {
79     Offset = 0;   // Return the offset that we were able to acheive
80     return Ty;    // Return the leaf type
81   }
82
83   unsigned ThisOffset;
84   const Type *NextType;
85   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
86     assert(Offset < TD.getTypeSize(Ty) && "Offset not in composite!");
87     const StructLayout *SL = TD.getStructLayout(STy);
88
89     // This loop terminates always on a 0 <= i < MemberOffsets.size()
90     unsigned i;
91     for (i = 0; i < SL->MemberOffsets.size()-1; ++i)
92       if (Offset >= SL->MemberOffsets[i] && Offset <  SL->MemberOffsets[i+1])
93         break;
94   
95     assert(Offset >= SL->MemberOffsets[i] &&
96            (i == SL->MemberOffsets.size()-1 || Offset <SL->MemberOffsets[i+1]));
97     
98     // Make sure to save the current index...
99     Offsets.push_back(ConstantUInt::get(Type::UByteTy, i));
100     ThisOffset = SL->MemberOffsets[i];
101     NextType = STy->getElementTypes()[i];
102   } else {
103     const ArrayType *ATy = cast<ArrayType>(Ty);
104     assert(ATy->isUnsized() || Offset < TD.getTypeSize(Ty) &&
105            "Offset not in composite!");
106
107     NextType = ATy->getElementType();
108     unsigned ChildSize = TD.getTypeSize(NextType);
109     Offsets.push_back(ConstantUInt::get(Type::UIntTy, Offset/ChildSize));
110     ThisOffset = (Offset/ChildSize)*ChildSize;
111   }
112
113   unsigned SubOffs = Offset - ThisOffset;
114   const Type *LeafTy = getStructOffsetType(NextType, SubOffs, Offsets);
115   Offset = ThisOffset + SubOffs;
116   return LeafTy;
117 }
118
119 // ConvertableToGEP - This function returns true if the specified value V is
120 // a valid index into a pointer of type Ty.  If it is valid, Idx is filled in
121 // with the values that would be appropriate to make this a getelementptr
122 // instruction.  The type returned is the root type that the GEP would point to
123 //
124 const Type *ConvertableToGEP(const Type *Ty, Value *OffsetVal,
125                              vector<Value*> &Indices,
126                              BasicBlock::iterator *BI = 0) {
127   const CompositeType *CompTy = getPointedToComposite(Ty);
128   if (CompTy == 0) return 0;
129
130   // See if the cast is of an integer expression that is either a constant,
131   // or a value scaled by some amount with a possible offset.
132   //
133   analysis::ExprType Expr = analysis::ClassifyExpression(OffsetVal);
134
135   // The expression must either be a constant, or a scaled index to be useful
136   if (!Expr.Offset && !Expr.Scale)
137     return 0;
138
139   // Get the offset and scale now...
140   unsigned Offset = 0, Scale = Expr.Var != 0;
141
142   // Get the offset value if it exists...
143   if (Expr.Offset) {
144     int Val = getConstantValue(Expr.Offset);
145     if (Val < 0) return false;  // Don't mess with negative offsets
146     Offset = (unsigned)Val;
147   }
148
149   // Get the scale value if it exists...
150   if (Expr.Scale) {
151     int Val = getConstantValue(Expr.Scale);
152     if (Val < 0) return false;  // Don't mess with negative scales
153     Scale = (unsigned)Val;
154   }
155   
156   // Check to make sure the offset is not negative or really large, outside the
157   // scope of this structure...
158   //
159   if (!isa<ArrayType>(CompTy) || cast<ArrayType>(CompTy)->isSized())
160     if (Offset >= TD.getTypeSize(CompTy))
161       return 0;
162
163   // Loop over the Scale and Offset values, filling in the Indices vector for
164   // our final getelementptr instruction.
165   //
166   const Type *NextTy = CompTy;
167   do {
168     if (!isa<CompositeType>(NextTy))
169       return 0;  // Type must not be ready for processing...
170     CompTy = cast<CompositeType>(NextTy);
171
172     if (const StructType *StructTy = dyn_cast<StructType>(CompTy)) {
173       const StructLayout *SL = TD.getStructLayout(StructTy);
174       unsigned ActualOffset = Offset;
175       NextTy = getStructOffsetType(StructTy, ActualOffset, Indices);
176       Offset -= ActualOffset;
177     } else {
178       const ArrayType *AT = cast<ArrayType>(CompTy);
179       const Type *ElTy = AT->getElementType();
180       unsigned ElSize = TD.getTypeSize(ElTy);
181
182       // See if the user is indexing into a different cell of this array...
183       if (Scale && Scale >= ElSize) {
184         // A scale n*ElSize might occur if we are not stepping through
185         // array by one.  In this case, we will have to insert math to munge
186         // the index.
187         //
188         unsigned ScaleAmt = Scale/ElSize;
189         if (Scale-ScaleAmt*ElSize)
190           return 0;  // Didn't scale by a multiple of element size, bail out
191         Scale = ElSize;        
192
193         unsigned Index = Offset/ElSize;       // is zero unless Offset > ElSize
194         Offset -= Index*ElSize;               // Consume part of the offset
195
196         if (BI) {              // Generate code?
197           BasicBlock *BB = (**BI)->getParent();
198           if (Expr.Var->getType() != Type::UIntTy) {
199             CastInst *IdxCast = new CastInst(Expr.Var, Type::UIntTy);
200             if (Expr.Var->hasName())
201               IdxCast->setName(Expr.Var->getName()+"-idxcast");
202             *BI = BB->getInstList().insert(*BI, IdxCast)+1;
203             Expr.Var = IdxCast;
204           }
205
206           if (Scale > ElSize) {  // If we have to scale up our index, do so now
207             Value *ScaleAmtVal = ConstantUInt::get(Type::UIntTy, ScaleAmt);
208             Instruction *Scaler = BinaryOperator::create(Instruction::Mul,
209                                                          Expr.Var,ScaleAmtVal);
210             if (Expr.Var->hasName())
211               Scaler->setName(Expr.Var->getName()+"-scale");
212
213             *BI = BB->getInstList().insert(*BI, Scaler)+1;
214             Expr.Var = Scaler;
215           }
216
217           if (Index) {  // Add an offset to the index
218             Value *IndexAmt = ConstantUInt::get(Type::UIntTy, Index);
219             Instruction *Offseter = BinaryOperator::create(Instruction::Add,
220                                                            Expr.Var, IndexAmt);
221             if (Expr.Var->hasName())
222               Offseter->setName(Expr.Var->getName()+"-offset");
223             *BI = BB->getInstList().insert(*BI, Offseter)+1;
224             Expr.Var = Offseter;
225           }
226         }
227
228         Indices.push_back(Expr.Var);
229         Scale = 0;  // Consume scale factor!
230       } else if (Offset >= ElSize) {
231         // Calculate the index that we are entering into the array cell with
232         unsigned Index = Offset/ElSize;
233         Indices.push_back(ConstantUInt::get(Type::UIntTy, Index));
234         Offset -= Index*ElSize;               // Consume part of the offset
235
236       } else {
237         // Must be indexing a small amount into the first cell of the array
238         // Just index into element zero of the array here.
239         //
240         Indices.push_back(ConstantUInt::get(Type::UIntTy, 0));
241       }
242       NextTy = ElTy;
243     }
244   } while (Offset || Scale);    // Go until we're done!
245
246   return NextTy;
247 }