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