1 //===- MutateStructTypes.cpp - Change struct defns ------------------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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.
16 // This is an interprocedural pass that requires the entire program to do a
19 //===----------------------------------------------------------------------===//
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"
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 std::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 *FT = cast<FunctionType>(Ty);
60 const Type *RetTy = ConvertType(FT->getReturnType());
61 std::vector<const Type*> ArgTypes;
63 for (FunctionType::ParamTypes::const_iterator I = FT->getParamTypes().begin(),
64 E = FT->getParamTypes().end(); I != E; ++I)
65 ArgTypes.push_back(ConvertType(*I));
67 DestTy = FunctionType::get(RetTy, ArgTypes, FT->isVarArg());
70 case Type::StructTyID: {
71 const StructType *ST = cast<StructType>(Ty);
72 const StructType::ElementTypes &El = ST->getElementTypes();
73 std::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 indices specified 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,
109 std::vector<Value*> &Idx,
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 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);
130 // Recursively process subtypes...
131 if (i+1 < Idx.size())
132 AdjustIndices(cast<CompositeType>(OldTy->getTypeAtIndex(Idx[i])), Idx, i+1);
136 // ConvertValue - Convert from the old value in the old type system to the new
139 Value *MutateStructTypes::ConvertValue(const Value *V) {
140 // Ignore null values and simple constants..
141 if (V == 0) return 0;
143 if (const Constant *CPV = dyn_cast<Constant>(V)) {
144 if (V->getType()->isPrimitiveType())
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!");
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
162 std::map<const Value*, Value*>::iterator I = LocalValueMap.find(V);
163 if (I != LocalValueMap.end()) return I->second;
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.
169 return LocalValueMap[V] = new BasicBlock(BB->getName());
172 DEBUG(std::cerr << "NPH: " << V << "\n");
174 // Otherwise make a constant to represent it
175 return LocalValueMap[V] = new ValuePlaceHolder(ConvertType(V->getType()));
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.
185 void MutateStructTypes::setTransforms(const TransformsType &XForm) {
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()));
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;
201 assert(OldTy->getElementTypes().size() == InVec.size() &&
202 "Action not specified for every element of structure type!");
204 std::vector<const Type *> NewType;
206 // Convert the elements of the type over, including the new position mapping
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);
215 TI = find(InVec.begin(), InVec.end(), ++Idx);
218 // Create a new type that corresponds to the destination type
219 PATypeHolder NSTy = StructType::get(NewType);
221 // Refine the old opaque type to the new type to properly handle recursive
224 const Type *OldTypeStub = TypeMap.find(OldTy)->second.get();
225 ((DerivedType*)OldTypeStub)->refineAbstractTypeTo(NSTy);
227 // Add the transformation to the Transforms map.
228 Transforms.insert(std::make_pair(OldTy,
229 std::make_pair(cast<StructType>(NSTy.get()), InVec)));
231 DEBUG(std::cerr << "Mutate " << OldTy << "\nTo " << NSTy << "\n");
235 void MutateStructTypes::clearTransforms() {
239 assert(LocalValueMap.empty() &&
240 "Local Value Map should always be empty between transformations!");
243 // processGlobals - This loops over global constants defined in the
244 // module, converting them to their new type.
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.
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()));
256 // Create a new function to put stuff into...
257 Function *NewMeth = new Function(NewMTy, I->getLinkage(), I->getName());
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 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)));
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();
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);
300 for(Module::iterator I = M.begin(); I != M.end();) {
301 if (GlobalMap.find(I) != GlobalMap.end())
302 I = M.getFunctionList().erase(I);
310 // transformFunction - This transforms the instructions of the function to use
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
319 Function *NewMeth = cast<Function>(GMI->second);
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
329 // Loop over all of the basic blocks copying instructions over...
330 for (Function::const_iterator BB = M->begin(), BBE = M->end(); BB != BBE;
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
336 // Copy over all of the instructions in the basic block...
337 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
340 const Instruction &I = *II; // Get the current instruction...
341 Instruction *NewI = 0;
343 switch (I.getOpcode()) {
344 // Terminator Instructions
345 case Instruction::Ret:
346 NewI = new ReturnInst(
347 ConvertValue(cast<ReturnInst>(I).getReturnValue()));
349 case Instruction::Br: {
350 const BranchInst &BI = cast<BranchInst>(I);
351 if (BI.isConditional()) {
353 new BranchInst(cast<BasicBlock>(ConvertValue(BI.getSuccessor(0))),
354 cast<BasicBlock>(ConvertValue(BI.getSuccessor(1))),
355 ConvertValue(BI.getCondition()));
358 new BranchInst(cast<BasicBlock>(ConvertValue(BI.getSuccessor(0))));
362 case Instruction::Switch:
363 case Instruction::Invoke:
364 case Instruction::Unwind:
365 assert(0 && "Insn not implemented!");
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:
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)));
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)));
398 // Memory Instructions
399 case Instruction::Alloca:
402 ConvertType(cast<PointerType>(I.getType())->getElementType()),
403 I.getNumOperands() ? ConvertValue(I.getOperand(0)) :0);
405 case Instruction::Malloc:
408 ConvertType(cast<PointerType>(I.getType())->getElementType()),
409 I.getNumOperands() ? ConvertValue(I.getOperand(0)) :0);
412 case Instruction::Free:
413 NewI = new FreeInst(ConvertValue(I.getOperand(0)));
416 case Instruction::Load:
417 NewI = new LoadInst(ConvertValue(I.getOperand(0)));
419 case Instruction::Store:
420 NewI = new StoreInst(ConvertValue(I.getOperand(0)),
421 ConvertValue(I.getOperand(1)));
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()) {
428 cast<PointerType>(GEP.getOperand(0)->getType())->getElementType();
429 AdjustIndices(cast<CompositeType>(PTy), Indices);
432 NewI = new GetElementPtrInst(ConvertValue(GEP.getOperand(0)), Indices);
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))));
446 case Instruction::Cast:
447 NewI = new CastInst(ConvertValue(I.getOperand(0)),
448 ConvertType(I.getType()));
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);
460 assert(0 && "UNKNOWN INSTRUCTION ENCOUNTERED!\n");
464 NewI->setName(I.getName());
465 NewBB->getInstList().push_back(NewI);
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!");
474 // Replace all uses of the place holder with the real deal...
475 I->replaceAllUsesWith(NewI);
476 delete I; // And free the placeholder memory
479 // Keep track of the fact the the local implementation of this instruction
481 LocalValueMap[&I] = NewI;
485 LocalValueMap.clear();
489 bool MutateStructTypes::run(Module &M) {
492 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
493 transformFunction(I);
495 removeDeadGlobals(M);