b18095027bd4fe314d2128e1a8e00436fea41e79
[oota-llvm.git] / lib / Transforms / Scalar / DecomposeMultiDimRefs.cpp
1 //===- llvm/Transforms/DecomposeMultiDimRefs.cpp - Lower array refs to 1D -===//
2 //
3 // DecomposeMultiDimRefs - Convert multi-dimensional references consisting of
4 // any combination of 2 or more array and structure indices into a sequence of
5 // instructions (using getelementpr and cast) so that each instruction has at
6 // most one index (except structure references, which need an extra leading
7 // index of [0]).
8 //
9 //===----------------------------------------------------------------------===//
10
11 #include "llvm/Transforms/Scalar.h"
12 #include "llvm/DerivedTypes.h"
13 #include "llvm/Constant.h"
14 #include "llvm/iMemory.h"
15 #include "llvm/iOther.h"
16 #include "llvm/BasicBlock.h"
17 #include "llvm/Pass.h"
18 #include "Support/StatisticReporter.h"
19
20 static Statistic<> NumAdded("lowerrefs\t\t- New instructions added");
21
22 namespace {
23   struct DecomposePass : public BasicBlockPass {
24     const char *getPassName() const { return "Decompose Subscripting Exps"; }
25
26     virtual bool runOnBasicBlock(BasicBlock &BB);
27
28   private:
29     static void decomposeArrayRef(BasicBlock::iterator &BBI);
30   };
31 }
32
33 Pass *createDecomposeMultiDimRefsPass() {
34   return new DecomposePass();
35 }
36
37
38 // runOnBasicBlock - Entry point for array or structure references with multiple
39 // indices.
40 //
41 bool DecomposePass::runOnBasicBlock(BasicBlock &BB) {
42   bool Changed = false;
43   for (BasicBlock::iterator II = BB.begin(); II != BB.end(); ) {
44     if (MemAccessInst *MAI = dyn_cast<MemAccessInst>(&*II)) {
45       if (MAI->getNumOperands() > MAI->getFirstIndexOperandNumber()+1) {
46         decomposeArrayRef(II);
47         Changed = true;
48       } else {
49         ++II;
50       }
51     } else {
52       ++II;
53     }
54   }
55   
56   return Changed;
57 }
58
59 // 
60 // For any combination of 2 or more array and structure indices,
61 // this function repeats the foll. until we have a one-dim. reference: {
62 //      ptr1 = getElementPtr [CompositeType-N] * lastPtr, uint firstIndex
63 //      ptr2 = cast [CompositeType-N] * ptr1 to [CompositeType-N] *
64 // }
65 // Then it replaces the original instruction with an equivalent one that
66 // uses the last ptr2 generated in the loop and a single index.
67 // If any index is (uint) 0, we omit the getElementPtr instruction.
68 // 
69
70 void DecomposePass::decomposeArrayRef(BasicBlock::iterator &BBI) {
71   MemAccessInst &MAI = cast<MemAccessInst>(*BBI);
72   BasicBlock *BB = MAI.getParent();
73   Value *LastPtr = MAI.getPointerOperand();
74
75   // Remove the instruction from the stream
76   BB->getInstList().remove(BBI);
77
78   std::vector<Instruction*> NewInsts;
79   
80   // Process each index except the last one.
81   // 
82
83   User::const_op_iterator OI = MAI.idx_begin(), OE = MAI.idx_end();
84   for (; OI+1 != OE; ++OI) {
85     assert(isa<PointerType>(LastPtr->getType()));
86       
87     // Check for a zero index.  This will need a cast instead of
88     // a getElementPtr, or it may need neither.
89     bool indexIsZero = isa<Constant>(*OI) && 
90                        cast<Constant>(OI->get())->isNullValue() &&
91                        OI->get()->getType() == Type::UIntTy;
92       
93     // Extract the first index.  If the ptr is a pointer to a structure
94     // and the next index is a structure offset (i.e., not an array offset), 
95     // we need to include an initial [0] to index into the pointer.
96     //
97
98     std::vector<Value*> Indices;
99     const PointerType *PtrTy = cast<PointerType>(LastPtr->getType());
100
101     if (isa<StructType>(PtrTy->getElementType())
102         && !PtrTy->indexValid(*OI))
103       Indices.push_back(Constant::getNullValue(Type::UIntTy));
104     Indices.push_back(*OI);
105
106     // Get the type obtained by applying the first index.
107     // It must be a structure or array.
108     const Type *NextTy = MemAccessInst::getIndexedType(LastPtr->getType(),
109                                                        Indices, true);
110     assert(isa<CompositeType>(NextTy));
111     
112     // Get a pointer to the structure or to the elements of the array.
113     const Type *NextPtrTy =
114       PointerType::get(isa<StructType>(NextTy) ? NextTy
115                        : cast<ArrayType>(NextTy)->getElementType());
116       
117     // Instruction 1: nextPtr1 = GetElementPtr LastPtr, Indices
118     // This is not needed if the index is zero.
119     if (!indexIsZero) {
120       LastPtr = new GetElementPtrInst(LastPtr, Indices, "ptr1");
121       NewInsts.push_back(cast<Instruction>(LastPtr));
122       ++NumAdded;
123     }
124
125       
126     // Instruction 2: nextPtr2 = cast nextPtr1 to NextPtrTy
127     // This is not needed if the two types are identical.
128     //
129     if (LastPtr->getType() != NextPtrTy) {
130       LastPtr = new CastInst(LastPtr, NextPtrTy, "ptr2");
131       NewInsts.push_back(cast<Instruction>(LastPtr));
132       ++NumAdded;
133     }
134   }
135   
136   // 
137   // Now create a new instruction to replace the original one
138   //
139   const PointerType *PtrTy = cast<PointerType>(LastPtr->getType());
140
141   // First, get the final index vector.  As above, we may need an initial [0].
142
143   std::vector<Value*> Indices;
144   if (isa<StructType>(PtrTy->getElementType())
145       && !PtrTy->indexValid(*OI))
146     Indices.push_back(Constant::getNullValue(Type::UIntTy));
147
148   Indices.push_back(*OI);
149
150   Instruction *NewI = 0;
151   switch(MAI.getOpcode()) {
152   case Instruction::Load:
153     NewI = new LoadInst(LastPtr, Indices, MAI.getName());
154     break;
155   case Instruction::Store:
156     NewI = new StoreInst(MAI.getOperand(0), LastPtr, Indices);
157     break;
158   case Instruction::GetElementPtr:
159     NewI = new GetElementPtrInst(LastPtr, Indices, MAI.getName());
160     break;
161   default:
162     assert(0 && "Unrecognized memory access instruction");
163   }
164   NewInsts.push_back(NewI);
165
166   
167   // Replace all uses of the old instruction with the new
168   MAI.replaceAllUsesWith(NewI);
169
170   // Now delete the old instruction...
171   delete &MAI;
172
173   // Insert all of the new instructions...
174   BB->getInstList().insert(BBI, NewInsts.begin(), NewInsts.end());
175   
176   // Advance the iterator to the instruction following the one just inserted...
177   BBI = NewInsts.back();
178   ++BBI;
179 }