1 //===- MutateStructTypes.cpp - Change struct defns --------------------------=//
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.
9 // This is an interprocedural pass that requires the entire program to do a
12 //===----------------------------------------------------------------------===//
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 "llvm/Constants.h"
27 #include "Support/STLExtras.h"
28 #include "Support/StatisticReporter.h"
33 // ValuePlaceHolder - A stupid little marker value. It appears as an
34 // instruction of type Instruction::UserOp1.
36 struct ValuePlaceHolder : public Instruction {
37 ValuePlaceHolder(const Type *Ty) : Instruction(Ty, UserOp1, "") {}
39 virtual Instruction *clone() const { abort(); return 0; }
40 virtual const char *getOpcodeName() const { return "placeholder"; }
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
49 map<const Type *, PATypeHolder>::iterator I = TypeMap.find(Ty);
50 if (I != TypeMap.end()) return I->second;
52 const Type *DestTy = 0;
54 PATypeHolder PlaceHolder = OpaqueType::get();
55 TypeMap.insert(std::make_pair(Ty, PlaceHolder.get()));
57 switch (Ty->getPrimitiveID()) {
58 case Type::FunctionTyID: {
59 const FunctionType *MT = cast<FunctionType>(Ty);
60 const Type *RetTy = ConvertType(MT->getReturnType());
61 vector<const Type*> ArgTypes;
63 for (FunctionType::ParamTypes::const_iterator I = MT->getParamTypes().begin(),
64 E = MT->getParamTypes().end(); I != E; ++I)
65 ArgTypes.push_back(ConvertType(*I));
67 DestTy = FunctionType::get(RetTy, ArgTypes, MT->isVarArg());
70 case Type::StructTyID: {
71 const StructType *ST = cast<StructType>(Ty);
72 const StructType::ElementTypes &El = ST->getElementTypes();
73 vector<const Type *> Types;
75 for (StructType::ElementTypes::const_iterator I = El.begin(), E = El.end();
77 Types.push_back(ConvertType(*I));
78 DestTy = StructType::get(Types);
82 DestTy = ArrayType::get(ConvertType(cast<ArrayType>(Ty)->getElementType()),
83 cast<ArrayType>(Ty)->getNumElements());
86 case Type::PointerTyID:
87 DestTy = PointerType::get(
88 ConvertType(cast<PointerType>(Ty)->getElementType()));
91 assert(0 && "Unknown type!");
95 assert(DestTy && "Type didn't get created!?!?");
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()));
101 return PlaceHolder.get();
105 // AdjustIndices - Convert the indexes specifed by Idx to the new changed form
106 // using the specified OldTy as the base type being indexed into.
108 void MutateStructTypes::AdjustIndices(const CompositeType *OldTy,
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
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());
120 map<const StructType*, TransformType>::iterator I = Transforms.find(OldST);
121 if (I != Transforms.end()) {
122 assert(ElNum < I->second.second.size());
123 // Apply the XForm specified by Transforms map...
124 unsigned NewElNum = I->second.second[ElNum];
125 Idx[i] = ConstantUInt::get(Type::UByteTy, NewElNum);
129 // Recursively process subtypes...
130 if (i+1 < Idx.size())
131 AdjustIndices(cast<CompositeType>(OldTy->getTypeAtIndex(Idx[i])), Idx, i+1);
135 // ConvertValue - Convert from the old value in the old type system to the new
138 Value *MutateStructTypes::ConvertValue(const Value *V) {
139 // Ignore null values and simple constants..
140 if (V == 0) return 0;
142 if (const Constant *CPV = dyn_cast<Constant>(V)) {
143 if (V->getType()->isPrimitiveType())
146 if (isa<ConstantPointerNull>(CPV))
147 return ConstantPointerNull::get(
148 cast<PointerType>(ConvertType(V->getType())));
149 assert(0 && "Unable to convert constpool val of this type!");
152 // Check to see if this is an out of function reference first...
153 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
154 // Check to see if the value is in the map...
155 map<const GlobalValue*, GlobalValue*>::iterator I = GlobalMap.find(GV);
156 if (I == GlobalMap.end())
157 return (Value*)GV; // Not mapped, just return value itself
161 map<const Value*, Value*>::iterator I = LocalValueMap.find(V);
162 if (I != LocalValueMap.end()) return I->second;
164 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
165 // Create placeholder block to represent the basic block we haven't seen yet
166 // This will be used when the block gets created.
168 return LocalValueMap[V] = new BasicBlock(BB->getName());
171 DEBUG(cerr << "NPH: " << V << "\n");
173 // Otherwise make a constant to represent it
174 return LocalValueMap[V] = new ValuePlaceHolder(ConvertType(V->getType()));
178 // setTransforms - Take a map that specifies what transformation to do for each
179 // field of the specified structure types. There is one element of the vector
180 // for each field of the structure. The value specified indicates which slot of
181 // the destination structure the field should end up in. A negative value
182 // indicates that the field should be deleted entirely.
184 void MutateStructTypes::setTransforms(const TransformsType &XForm) {
186 // Loop over the types and insert dummy entries into the type map so that
187 // recursive types are resolved properly...
188 for (map<const StructType*, vector<int> >::const_iterator I = XForm.begin(),
189 E = XForm.end(); I != E; ++I) {
190 const StructType *OldTy = I->first;
191 TypeMap.insert(std::make_pair(OldTy, OpaqueType::get()));
194 // Loop over the type specified and figure out what types they should become
195 for (map<const StructType*, vector<int> >::const_iterator I = XForm.begin(),
196 E = XForm.end(); I != E; ++I) {
197 const StructType *OldTy = I->first;
198 const vector<int> &InVec = I->second;
200 assert(OldTy->getElementTypes().size() == InVec.size() &&
201 "Action not specified for every element of structure type!");
203 vector<const Type *> NewType;
205 // Convert the elements of the type over, including the new position mapping
207 vector<int>::const_iterator TI = find(InVec.begin(), InVec.end(), Idx);
208 while (TI != InVec.end()) {
209 unsigned Offset = TI-InVec.begin();
210 const Type *NewEl = ConvertType(OldTy->getContainedType(Offset));
211 assert(NewEl && "Element not found!");
212 NewType.push_back(NewEl);
214 TI = find(InVec.begin(), InVec.end(), ++Idx);
217 // Create a new type that corresponds to the destination type
218 PATypeHolder NSTy = StructType::get(NewType);
220 // Refine the old opaque type to the new type to properly handle recursive
223 const Type *OldTypeStub = TypeMap.find(OldTy)->second.get();
224 ((DerivedType*)OldTypeStub)->refineAbstractTypeTo(NSTy);
226 // Add the transformation to the Transforms map.
227 Transforms.insert(std::make_pair(OldTy,
228 std::make_pair(cast<StructType>(NSTy.get()), InVec)));
230 DEBUG(cerr << "Mutate " << OldTy << "\nTo " << NSTy << "\n");
234 void MutateStructTypes::clearTransforms() {
238 assert(LocalValueMap.empty() &&
239 "Local Value Map should always be empty between transformations!");
242 // processGlobals - This loops over global constants defined in the
243 // module, converting them to their new type.
245 void MutateStructTypes::processGlobals(Module &M) {
246 // Loop through the functions in the module and create a new version of the
247 // function to contained the transformed code. Also, be careful to not
248 // process the values that we add.
250 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
251 if (!I->isExternal()) {
252 const FunctionType *NewMTy =
253 cast<FunctionType>(ConvertType(I->getFunctionType()));
255 // Create a new function to put stuff into...
256 Function *NewMeth = new Function(NewMTy, I->hasInternalLinkage(),
259 I->setName("OLD."+I->getName());
261 // Insert the new function into the function list... to be filled in later
262 M.getFunctionList().push_back(NewMeth);
264 // Keep track of the association...
265 GlobalMap[I] = NewMeth;
268 // TODO: HANDLE GLOBAL VARIABLES
270 // Remap the symbol table to refer to the types in a nice way
272 if (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();
278 // FIXME: This is gross, I'm reaching right into a symbol table and
279 // mucking around with it's internals... but oh well.
281 TI->second = (Value*)cast<Type>(ConvertType(cast<Type>(TI->second)));
288 // removeDeadGlobals - For this pass, all this does is remove the old versions
289 // of the functions and global variables that we no longer need.
290 void MutateStructTypes::removeDeadGlobals(Module &M) {
291 // Prepare for deletion of globals by dropping their interdependencies...
292 for(Module::iterator I = M.begin(); I != M.end(); ++I) {
293 if (GlobalMap.find(I) != GlobalMap.end())
294 I->dropAllReferences();
297 // Run through and delete the functions and global variables...
298 #if 0 // TODO: HANDLE GLOBAL VARIABLES
299 M->getGlobalList().delete_span(M.gbegin(), M.gbegin()+NumGVars/2);
301 for(Module::iterator I = M.begin(); I != M.end();) {
302 if (GlobalMap.find(I) != GlobalMap.end())
303 I = M.getFunctionList().erase(I);
311 // transformFunction - This transforms the instructions of the function to use
314 void MutateStructTypes::transformFunction(Function *m) {
315 const Function *M = m;
316 map<const GlobalValue*, GlobalValue*>::iterator GMI = GlobalMap.find(M);
317 if (GMI == GlobalMap.end())
318 return; // Do not affect one of our new functions that we are creating
320 Function *NewMeth = cast<Function>(GMI->second);
322 // Okay, first order of business, create the arguments...
323 for (Function::aiterator I = m->abegin(), E = m->aend(); I != E; ++I) {
324 Argument *NFA = new Argument(ConvertType(I->getType()), I->getName());
325 NewMeth->getArgumentList().push_back(NFA);
326 LocalValueMap[I] = NFA; // Keep track of value mapping
330 // Loop over all of the basic blocks copying instructions over...
331 for (Function::const_iterator BB = M->begin(), BBE = M->end(); BB != BBE;
333 // Create a new basic block and establish a mapping between the old and new
334 BasicBlock *NewBB = cast<BasicBlock>(ConvertValue(BB));
335 NewMeth->getBasicBlockList().push_back(NewBB); // Add block to function
337 // Copy over all of the instructions in the basic block...
338 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
341 const Instruction &I = *II; // Get the current instruction...
342 Instruction *NewI = 0;
344 switch (I.getOpcode()) {
345 // Terminator Instructions
346 case Instruction::Ret:
347 NewI = new ReturnInst(
348 ConvertValue(cast<ReturnInst>(I).getReturnValue()));
350 case Instruction::Br: {
351 const BranchInst &BI = cast<BranchInst>(I);
352 if (BI.isConditional()) {
354 new BranchInst(cast<BasicBlock>(ConvertValue(BI.getSuccessor(0))),
355 cast<BasicBlock>(ConvertValue(BI.getSuccessor(1))),
356 ConvertValue(BI.getCondition()));
359 new BranchInst(cast<BasicBlock>(ConvertValue(BI.getSuccessor(0))));
363 case Instruction::Switch:
364 case Instruction::Invoke:
365 assert(0 && "Insn not implemented!");
367 // Unary Instructions
368 case Instruction::Not:
369 NewI = UnaryOperator::create((Instruction::UnaryOps)I.getOpcode(),
370 ConvertValue(I.getOperand(0)));
373 // Binary Instructions
374 case Instruction::Add:
375 case Instruction::Sub:
376 case Instruction::Mul:
377 case Instruction::Div:
378 case Instruction::Rem:
379 // Logical Operations
380 case Instruction::And:
381 case Instruction::Or:
382 case Instruction::Xor:
384 // Binary Comparison Instructions
385 case Instruction::SetEQ:
386 case Instruction::SetNE:
387 case Instruction::SetLE:
388 case Instruction::SetGE:
389 case Instruction::SetLT:
390 case Instruction::SetGT:
391 NewI = BinaryOperator::create((Instruction::BinaryOps)I.getOpcode(),
392 ConvertValue(I.getOperand(0)),
393 ConvertValue(I.getOperand(1)));
396 case Instruction::Shr:
397 case Instruction::Shl:
398 NewI = new ShiftInst(cast<ShiftInst>(I).getOpcode(),
399 ConvertValue(I.getOperand(0)),
400 ConvertValue(I.getOperand(1)));
404 // Memory Instructions
405 case Instruction::Alloca:
407 new AllocaInst(ConvertType(I.getType()),
408 I.getNumOperands() ? ConvertValue(I.getOperand(0)) :0);
410 case Instruction::Malloc:
412 new MallocInst(ConvertType(I.getType()),
413 I.getNumOperands() ? ConvertValue(I.getOperand(0)) :0);
416 case Instruction::Free:
417 NewI = new FreeInst(ConvertValue(I.getOperand(0)));
420 case Instruction::Load:
421 case Instruction::Store:
422 case Instruction::GetElementPtr: {
423 const MemAccessInst &MAI = cast<MemAccessInst>(I);
424 vector<Value*> Indices(MAI.idx_begin(), MAI.idx_end());
425 const Value *Ptr = MAI.getPointerOperand();
426 Value *NewPtr = ConvertValue(Ptr);
427 if (!Indices.empty()) {
428 const Type *PTy = cast<PointerType>(Ptr->getType())->getElementType();
429 AdjustIndices(cast<CompositeType>(PTy), Indices);
432 if (isa<LoadInst>(I)) {
433 NewI = new LoadInst(NewPtr, Indices);
434 } else if (isa<StoreInst>(I)) {
435 NewI = new StoreInst(ConvertValue(I.getOperand(0)), NewPtr, Indices);
436 } else if (isa<GetElementPtrInst>(I)) {
437 NewI = new GetElementPtrInst(NewPtr, Indices);
439 assert(0 && "Unknown memory access inst!!!");
444 // Miscellaneous Instructions
445 case Instruction::PHINode: {
446 const PHINode &OldPN = cast<PHINode>(I);
447 PHINode *PN = new PHINode(ConvertType(OldPN.getType()));
448 for (unsigned i = 0; i < OldPN.getNumIncomingValues(); ++i)
449 PN->addIncoming(ConvertValue(OldPN.getIncomingValue(i)),
450 cast<BasicBlock>(ConvertValue(OldPN.getIncomingBlock(i))));
454 case Instruction::Cast:
455 NewI = new CastInst(ConvertValue(I.getOperand(0)),
456 ConvertType(I.getType()));
458 case Instruction::Call: {
459 Value *Meth = ConvertValue(I.getOperand(0));
460 vector<Value*> Operands;
461 for (unsigned i = 1; i < I.getNumOperands(); ++i)
462 Operands.push_back(ConvertValue(I.getOperand(i)));
463 NewI = new CallInst(Meth, Operands);
468 assert(0 && "UNKNOWN INSTRUCTION ENCOUNTERED!\n");
472 NewI->setName(I.getName());
473 NewBB->getInstList().push_back(NewI);
475 // Check to see if we had to make a placeholder for this value...
476 map<const Value*,Value*>::iterator LVMI = LocalValueMap.find(&I);
477 if (LVMI != LocalValueMap.end()) {
478 // Yup, make sure it's a placeholder...
479 Instruction *I = cast<Instruction>(LVMI->second);
480 assert(I->getOpcode() == Instruction::UserOp1 && "Not a placeholder!");
482 // Replace all uses of the place holder with the real deal...
483 I->replaceAllUsesWith(NewI);
484 delete I; // And free the placeholder memory
487 // Keep track of the fact the the local implementation of this instruction
489 LocalValueMap[&I] = NewI;
493 LocalValueMap.clear();
497 bool MutateStructTypes::run(Module &M) {
500 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
501 transformFunction(I);
503 removeDeadGlobals(M);