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