Add support for reading and writing pointersize/endianness to and from bytecode
[oota-llvm.git] / lib / Transforms / IPO / MutateStructTypes.cpp
1 //===- MutateStructTypes.cpp - Change struct defns --------------------------=//
2 //
3 // This pass is used to change structure accesses and type definitions in some
4 // way.  It can be used to arbitrarily permute structure fields, safely, without
5 // breaking code.  A transformation may only be done on a type if that type has
6 // been found to be "safe" by the 'FindUnsafePointerTypes' pass.  This pass will
7 // assert and die if you try to do an illegal transformation.
8 //
9 // This is an interprocedural pass that requires the entire program to do a
10 // transformation.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Transforms/MutateStructTypes.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/Module.h"
17 #include "llvm/SymbolTable.h"
18 #include "llvm/iPHINode.h"
19 #include "llvm/iMemory.h"
20 #include "llvm/iTerminators.h"
21 #include "llvm/iOther.h"
22 #include "llvm/Constants.h"
23 #include "Support/STLExtras.h"
24 #include "Support/Statistic.h"
25 #include <algorithm>
26
27 using std::map;
28 using std::vector;
29
30 // ValuePlaceHolder - A stupid little marker value.  It appears as an
31 // instruction of type Instruction::UserOp1.
32 //
33 struct ValuePlaceHolder : public Instruction {
34   ValuePlaceHolder(const Type *Ty) : Instruction(Ty, UserOp1, "") {}
35
36   virtual Instruction *clone() const { abort(); return 0; }
37   virtual const char *getOpcodeName() const { return "placeholder"; }
38 };
39
40
41 // ConvertType - Convert from the old type system to the new one...
42 const Type *MutateStructTypes::ConvertType(const Type *Ty) {
43   if (Ty->isPrimitiveType() ||
44       isa<OpaqueType>(Ty)) return Ty;  // Don't convert primitives
45
46   map<const Type *, PATypeHolder>::iterator I = TypeMap.find(Ty);
47   if (I != TypeMap.end()) return I->second;
48
49   const Type *DestTy = 0;
50
51   PATypeHolder PlaceHolder = OpaqueType::get();
52   TypeMap.insert(std::make_pair(Ty, PlaceHolder.get()));
53
54   switch (Ty->getPrimitiveID()) {
55   case Type::FunctionTyID: {
56     const FunctionType *MT = cast<FunctionType>(Ty);
57     const Type *RetTy = ConvertType(MT->getReturnType());
58     vector<const Type*> ArgTypes;
59
60     for (FunctionType::ParamTypes::const_iterator I = MT->getParamTypes().begin(),
61            E = MT->getParamTypes().end(); I != E; ++I)
62       ArgTypes.push_back(ConvertType(*I));
63     
64     DestTy = FunctionType::get(RetTy, ArgTypes, MT->isVarArg());
65     break;
66   }
67   case Type::StructTyID: {
68     const StructType *ST = cast<StructType>(Ty);
69     const StructType::ElementTypes &El = ST->getElementTypes();
70     vector<const Type *> Types;
71
72     for (StructType::ElementTypes::const_iterator I = El.begin(), E = El.end();
73          I != E; ++I)
74       Types.push_back(ConvertType(*I));
75     DestTy = StructType::get(Types);
76     break;
77   }
78   case Type::ArrayTyID:
79     DestTy = ArrayType::get(ConvertType(cast<ArrayType>(Ty)->getElementType()),
80                             cast<ArrayType>(Ty)->getNumElements());
81     break;
82
83   case Type::PointerTyID:
84     DestTy = PointerType::get(
85                  ConvertType(cast<PointerType>(Ty)->getElementType()));
86     break;
87   default:
88     assert(0 && "Unknown type!");
89     return 0;
90   }
91
92   assert(DestTy && "Type didn't get created!?!?");
93
94   // Refine our little placeholder value into a real type...
95   ((DerivedType*)PlaceHolder.get())->refineAbstractTypeTo(DestTy);
96   TypeMap.insert(std::make_pair(Ty, PlaceHolder.get()));
97
98   return PlaceHolder.get();
99 }
100
101
102 // AdjustIndices - Convert the indexes specifed by Idx to the new changed form
103 // using the specified OldTy as the base type being indexed into.
104 //
105 void MutateStructTypes::AdjustIndices(const CompositeType *OldTy,
106                                       vector<Value*> &Idx,
107                                       unsigned i) {
108   assert(i < Idx.size() && "i out of range!");
109   const CompositeType *NewCT = cast<CompositeType>(ConvertType(OldTy));
110   if (NewCT == OldTy) return;  // No adjustment unless type changes
111
112   if (const StructType *OldST = dyn_cast<StructType>(OldTy)) {
113     // Figure out what the current index is...
114     unsigned ElNum = cast<ConstantUInt>(Idx[i])->getValue();
115     assert(ElNum < OldST->getElementTypes().size());
116
117     map<const StructType*, TransformType>::iterator I = Transforms.find(OldST);
118     if (I != Transforms.end()) {
119       assert(ElNum < I->second.second.size());
120       // Apply the XForm specified by Transforms map...
121       unsigned NewElNum = I->second.second[ElNum];
122       Idx[i] = ConstantUInt::get(Type::UByteTy, NewElNum);
123     }
124   }
125
126   // Recursively process subtypes...
127   if (i+1 < Idx.size())
128     AdjustIndices(cast<CompositeType>(OldTy->getTypeAtIndex(Idx[i])), Idx, i+1);
129 }
130
131
132 // ConvertValue - Convert from the old value in the old type system to the new
133 // type system.
134 //
135 Value *MutateStructTypes::ConvertValue(const Value *V) {
136   // Ignore null values and simple constants..
137   if (V == 0) return 0;
138
139   if (const Constant *CPV = dyn_cast<Constant>(V)) {
140     if (V->getType()->isPrimitiveType())
141       return (Value*)CPV;
142
143     if (isa<ConstantPointerNull>(CPV))
144       return ConstantPointerNull::get(
145                       cast<PointerType>(ConvertType(V->getType())));
146     assert(0 && "Unable to convert constpool val of this type!");
147   }
148
149   // Check to see if this is an out of function reference first...
150   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
151     // Check to see if the value is in the map...
152     map<const GlobalValue*, GlobalValue*>::iterator I = GlobalMap.find(GV);
153     if (I == GlobalMap.end())
154       return (Value*)GV;  // Not mapped, just return value itself
155     return I->second;
156   }
157   
158   map<const Value*, Value*>::iterator I = LocalValueMap.find(V);
159   if (I != LocalValueMap.end()) return I->second;
160
161   if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
162     // Create placeholder block to represent the basic block we haven't seen yet
163     // This will be used when the block gets created.
164     //
165     return LocalValueMap[V] = new BasicBlock(BB->getName());
166   }
167
168   DEBUG(std::cerr << "NPH: " << V << "\n");
169
170   // Otherwise make a constant to represent it
171   return LocalValueMap[V] = new ValuePlaceHolder(ConvertType(V->getType()));
172 }
173
174
175 // setTransforms - Take a map that specifies what transformation to do for each
176 // field of the specified structure types.  There is one element of the vector
177 // for each field of the structure.  The value specified indicates which slot of
178 // the destination structure the field should end up in.  A negative value 
179 // indicates that the field should be deleted entirely.
180 //
181 void MutateStructTypes::setTransforms(const TransformsType &XForm) {
182
183   // Loop over the types and insert dummy entries into the type map so that 
184   // recursive types are resolved properly...
185   for (map<const StructType*, vector<int> >::const_iterator I = XForm.begin(),
186          E = XForm.end(); I != E; ++I) {
187     const StructType *OldTy = I->first;
188     TypeMap.insert(std::make_pair(OldTy, OpaqueType::get()));
189   }
190
191   // Loop over the type specified and figure out what types they should become
192   for (map<const StructType*, vector<int> >::const_iterator I = XForm.begin(),
193          E = XForm.end(); I != E; ++I) {
194     const StructType  *OldTy = I->first;
195     const vector<int> &InVec = I->second;
196
197     assert(OldTy->getElementTypes().size() == InVec.size() &&
198            "Action not specified for every element of structure type!");
199
200     vector<const Type *> NewType;
201
202     // Convert the elements of the type over, including the new position mapping
203     int Idx = 0;
204     vector<int>::const_iterator TI = find(InVec.begin(), InVec.end(), Idx);
205     while (TI != InVec.end()) {
206       unsigned Offset = TI-InVec.begin();
207       const Type *NewEl = ConvertType(OldTy->getContainedType(Offset));
208       assert(NewEl && "Element not found!");
209       NewType.push_back(NewEl);
210
211       TI = find(InVec.begin(), InVec.end(), ++Idx);
212     }
213
214     // Create a new type that corresponds to the destination type
215     PATypeHolder NSTy = StructType::get(NewType);
216
217     // Refine the old opaque type to the new type to properly handle recursive
218     // types...
219     //
220     const Type *OldTypeStub = TypeMap.find(OldTy)->second.get();
221     ((DerivedType*)OldTypeStub)->refineAbstractTypeTo(NSTy);
222
223     // Add the transformation to the Transforms map.
224     Transforms.insert(std::make_pair(OldTy,
225                        std::make_pair(cast<StructType>(NSTy.get()), InVec)));
226
227     DEBUG(std::cerr << "Mutate " << OldTy << "\nTo " << NSTy << "\n");
228   }
229 }
230
231 void MutateStructTypes::clearTransforms() {
232   Transforms.clear();
233   TypeMap.clear();
234   GlobalMap.clear();
235   assert(LocalValueMap.empty() &&
236          "Local Value Map should always be empty between transformations!");
237 }
238
239 // processGlobals - This loops over global constants defined in the
240 // module, converting them to their new type.
241 //
242 void MutateStructTypes::processGlobals(Module &M) {
243   // Loop through the functions in the module and create a new version of the
244   // function to contained the transformed code.  Also, be careful to not
245   // process the values that we add.
246   //
247   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
248     if (!I->isExternal()) {
249       const FunctionType *NewMTy = 
250         cast<FunctionType>(ConvertType(I->getFunctionType()));
251       
252       // Create a new function to put stuff into...
253       Function *NewMeth = new Function(NewMTy, I->getLinkage(), I->getName());
254       if (I->hasName())
255         I->setName("OLD."+I->getName());
256
257       // Insert the new function into the function list... to be filled in later
258       M.getFunctionList().push_back(NewMeth);
259       
260       // Keep track of the association...
261       GlobalMap[I] = NewMeth;
262     }
263
264   // TODO: HANDLE GLOBAL VARIABLES
265
266   // Remap the symbol table to refer to the types in a nice way
267   //
268   SymbolTable &ST = M.getSymbolTable();
269   SymbolTable::iterator I = ST.find(Type::TypeTy);
270   if (I != ST.end()) {    // Get the type plane for Type's
271     SymbolTable::VarMap &Plane = I->second;
272     for (SymbolTable::type_iterator TI = Plane.begin(), TE = Plane.end();
273          TI != TE; ++TI) {
274       // FIXME: This is gross, I'm reaching right into a symbol table and
275       // mucking around with it's internals... but oh well.
276       //
277       TI->second = (Value*)cast<Type>(ConvertType(cast<Type>(TI->second)));
278     }
279   }
280 }
281
282
283 // removeDeadGlobals - For this pass, all this does is remove the old versions
284 // of the functions and global variables that we no longer need.
285 void MutateStructTypes::removeDeadGlobals(Module &M) {
286   // Prepare for deletion of globals by dropping their interdependencies...
287   for(Module::iterator I = M.begin(); I != M.end(); ++I) {
288     if (GlobalMap.find(I) != GlobalMap.end())
289       I->dropAllReferences();
290   }
291
292   // Run through and delete the functions and global variables...
293 #if 0  // TODO: HANDLE GLOBAL VARIABLES
294   M->getGlobalList().delete_span(M.gbegin(), M.gbegin()+NumGVars/2);
295 #endif
296   for(Module::iterator I = M.begin(); I != M.end();) {
297     if (GlobalMap.find(I) != GlobalMap.end())
298       I = M.getFunctionList().erase(I);
299     else
300       ++I;
301   }
302 }
303
304
305
306 // transformFunction - This transforms the instructions of the function to use
307 // the new types.
308 //
309 void MutateStructTypes::transformFunction(Function *m) {
310   const Function *M = m;
311   map<const GlobalValue*, GlobalValue*>::iterator GMI = GlobalMap.find(M);
312   if (GMI == GlobalMap.end())
313     return;  // Do not affect one of our new functions that we are creating
314
315   Function *NewMeth = cast<Function>(GMI->second);
316
317   // Okay, first order of business, create the arguments...
318   for (Function::aiterator I = m->abegin(), E = m->aend(),
319          DI = NewMeth->abegin(); I != E; ++I, ++DI) {
320     DI->setName(I->getName());
321     LocalValueMap[I] = DI; // Keep track of value mapping
322   }
323
324
325   // Loop over all of the basic blocks copying instructions over...
326   for (Function::const_iterator BB = M->begin(), BBE = M->end(); BB != BBE;
327        ++BB) {
328     // Create a new basic block and establish a mapping between the old and new
329     BasicBlock *NewBB = cast<BasicBlock>(ConvertValue(BB));
330     NewMeth->getBasicBlockList().push_back(NewBB);  // Add block to function
331
332     // Copy over all of the instructions in the basic block...
333     for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
334          II != IE; ++II) {
335
336       const Instruction &I = *II;   // Get the current instruction...
337       Instruction *NewI = 0;
338
339       switch (I.getOpcode()) {
340         // Terminator Instructions
341       case Instruction::Ret:
342         NewI = new ReturnInst(
343                    ConvertValue(cast<ReturnInst>(I).getReturnValue()));
344         break;
345       case Instruction::Br: {
346         const BranchInst &BI = cast<BranchInst>(I);
347         if (BI.isConditional()) {
348           NewI =
349               new BranchInst(cast<BasicBlock>(ConvertValue(BI.getSuccessor(0))),
350                              cast<BasicBlock>(ConvertValue(BI.getSuccessor(1))),
351                              ConvertValue(BI.getCondition()));
352         } else {
353           NewI = 
354             new BranchInst(cast<BasicBlock>(ConvertValue(BI.getSuccessor(0))));
355         }
356         break;
357       }
358       case Instruction::Switch:
359       case Instruction::Invoke:
360         assert(0 && "Insn not implemented!");
361
362         // Binary Instructions
363       case Instruction::Add:
364       case Instruction::Sub:
365       case Instruction::Mul:
366       case Instruction::Div:
367       case Instruction::Rem:
368         // Logical Operations
369       case Instruction::And:
370       case Instruction::Or:
371       case Instruction::Xor:
372
373         // Binary Comparison Instructions
374       case Instruction::SetEQ:
375       case Instruction::SetNE:
376       case Instruction::SetLE:
377       case Instruction::SetGE:
378       case Instruction::SetLT:
379       case Instruction::SetGT:
380         NewI = BinaryOperator::create((Instruction::BinaryOps)I.getOpcode(),
381                                       ConvertValue(I.getOperand(0)),
382                                       ConvertValue(I.getOperand(1)));
383         break;
384
385       case Instruction::Shr:
386       case Instruction::Shl:
387         NewI = new ShiftInst(cast<ShiftInst>(I).getOpcode(),
388                              ConvertValue(I.getOperand(0)),
389                              ConvertValue(I.getOperand(1)));
390         break;
391
392
393         // Memory Instructions
394       case Instruction::Alloca:
395         NewI = 
396           new MallocInst(
397                   ConvertType(cast<PointerType>(I.getType())->getElementType()),
398                          I.getNumOperands() ? ConvertValue(I.getOperand(0)) :0);
399         break;
400       case Instruction::Malloc:
401         NewI = 
402           new MallocInst(
403                   ConvertType(cast<PointerType>(I.getType())->getElementType()),
404                          I.getNumOperands() ? ConvertValue(I.getOperand(0)) :0);
405         break;
406
407       case Instruction::Free:
408         NewI = new FreeInst(ConvertValue(I.getOperand(0)));
409         break;
410
411       case Instruction::Load:
412         NewI = new LoadInst(ConvertValue(I.getOperand(0)));
413         break;
414       case Instruction::Store:
415         NewI = new StoreInst(ConvertValue(I.getOperand(0)),
416                              ConvertValue(I.getOperand(1)));
417         break;
418       case Instruction::GetElementPtr: {
419         const GetElementPtrInst &GEP = cast<GetElementPtrInst>(I);
420         vector<Value*> Indices(GEP.idx_begin(), GEP.idx_end());
421         if (!Indices.empty()) {
422           const Type *PTy =
423             cast<PointerType>(GEP.getOperand(0)->getType())->getElementType();
424           AdjustIndices(cast<CompositeType>(PTy), Indices);
425         }
426
427         NewI = new GetElementPtrInst(ConvertValue(GEP.getOperand(0)), Indices);
428         break;
429       }
430
431         // Miscellaneous Instructions
432       case Instruction::PHINode: {
433         const PHINode &OldPN = cast<PHINode>(I);
434         PHINode *PN = new PHINode(ConvertType(OldPN.getType()));
435         for (unsigned i = 0; i < OldPN.getNumIncomingValues(); ++i)
436           PN->addIncoming(ConvertValue(OldPN.getIncomingValue(i)),
437                     cast<BasicBlock>(ConvertValue(OldPN.getIncomingBlock(i))));
438         NewI = PN;
439         break;
440       }
441       case Instruction::Cast:
442         NewI = new CastInst(ConvertValue(I.getOperand(0)),
443                             ConvertType(I.getType()));
444         break;
445       case Instruction::Call: {
446         Value *Meth = ConvertValue(I.getOperand(0));
447         vector<Value*> Operands;
448         for (unsigned i = 1; i < I.getNumOperands(); ++i)
449           Operands.push_back(ConvertValue(I.getOperand(i)));
450         NewI = new CallInst(Meth, Operands);
451         break;
452       }
453         
454       default:
455         assert(0 && "UNKNOWN INSTRUCTION ENCOUNTERED!\n");
456         break;
457       }
458
459       NewI->setName(I.getName());
460       NewBB->getInstList().push_back(NewI);
461
462       // Check to see if we had to make a placeholder for this value...
463       map<const Value*,Value*>::iterator LVMI = LocalValueMap.find(&I);
464       if (LVMI != LocalValueMap.end()) {
465         // Yup, make sure it's a placeholder...
466         Instruction *I = cast<Instruction>(LVMI->second);
467         assert(I->getOpcode() == Instruction::UserOp1 && "Not a placeholder!");
468
469         // Replace all uses of the place holder with the real deal...
470         I->replaceAllUsesWith(NewI);
471         delete I;                    // And free the placeholder memory
472       }
473
474       // Keep track of the fact the the local implementation of this instruction
475       // is NewI.
476       LocalValueMap[&I] = NewI;
477     }
478   }
479
480   LocalValueMap.clear();
481 }
482
483
484 bool MutateStructTypes::run(Module &M) {
485   processGlobals(M);
486
487   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
488     transformFunction(I);
489
490   removeDeadGlobals(M);
491   return true;
492 }
493