1 //===- ExtractFunction.cpp - Extract a function from Program --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements several methods that are used to extract functions,
11 // loops, or portions of a module from the rest of the module.
13 //===----------------------------------------------------------------------===//
15 #include "BugDriver.h"
16 #include "llvm/Analysis/Verifier.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/DataLayout.h"
19 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/IR/LLVMContext.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/Pass.h"
23 #include "llvm/PassManager.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/FileUtilities.h"
27 #include "llvm/Support/Path.h"
28 #include "llvm/Support/Signals.h"
29 #include "llvm/Support/ToolOutputFile.h"
30 #include "llvm/Transforms/IPO.h"
31 #include "llvm/Transforms/Scalar.h"
32 #include "llvm/Transforms/Utils/Cloning.h"
33 #include "llvm/Transforms/Utils/CodeExtractor.h"
38 bool DisableSimplifyCFG = false;
39 extern cl::opt<std::string> OutputPrefix;
40 } // End llvm namespace
45 cl::desc("Do not use the -dce pass to reduce testcases"));
47 NoSCFG("disable-simplifycfg", cl::location(DisableSimplifyCFG),
48 cl::desc("Do not use the -simplifycfg pass to reduce testcases"));
50 Function* globalInitUsesExternalBA(GlobalVariable* GV) {
51 if (!GV->hasInitializer())
54 Constant *I = GV->getInitializer();
56 // walk the values used by the initializer
57 // (and recurse into things like ConstantExpr)
58 std::vector<Constant*> Todo;
59 std::set<Constant*> Done;
62 while (!Todo.empty()) {
63 Constant* V = Todo.back();
67 if (BlockAddress *BA = dyn_cast<BlockAddress>(V)) {
68 Function *F = BA->getFunction();
69 if (F->isDeclaration())
73 for (User::op_iterator i = V->op_begin(), e = V->op_end(); i != e; ++i) {
74 Constant *C = dyn_cast<Constant>(*i);
75 if (C && !isa<GlobalValue>(C) && !Done.count(C))
81 } // end anonymous namespace
83 /// deleteInstructionFromProgram - This method clones the current Program and
84 /// deletes the specified instruction from the cloned module. It then runs a
85 /// series of cleanup passes (ADCE and SimplifyCFG) to eliminate any code which
86 /// depends on the value. The modified module is then returned.
88 Module *BugDriver::deleteInstructionFromProgram(const Instruction *I,
89 unsigned Simplification) {
91 Module *Clone = CloneModule(Program);
93 const BasicBlock *PBB = I->getParent();
94 const Function *PF = PBB->getParent();
96 Module::iterator RFI = Clone->begin(); // Get iterator to corresponding fn
97 std::advance(RFI, std::distance(PF->getParent()->begin(),
98 Module::const_iterator(PF)));
100 Function::iterator RBI = RFI->begin(); // Get iterator to corresponding BB
101 std::advance(RBI, std::distance(PF->begin(), Function::const_iterator(PBB)));
103 BasicBlock::iterator RI = RBI->begin(); // Get iterator to corresponding inst
104 std::advance(RI, std::distance(PBB->begin(), BasicBlock::const_iterator(I)));
105 Instruction *TheInst = RI; // Got the corresponding instruction!
107 // If this instruction produces a value, replace any users with null values
108 if (!TheInst->getType()->isVoidTy())
109 TheInst->replaceAllUsesWith(Constant::getNullValue(TheInst->getType()));
111 // Remove the instruction from the program.
112 TheInst->getParent()->getInstList().erase(TheInst);
114 // Spiff up the output a little bit.
115 std::vector<std::string> Passes;
117 /// Can we get rid of the -disable-* options?
118 if (Simplification > 1 && !NoDCE)
119 Passes.push_back("dce");
120 if (Simplification && !DisableSimplifyCFG)
121 Passes.push_back("simplifycfg"); // Delete dead control flow
123 Passes.push_back("verify");
124 Module *New = runPassesOn(Clone, Passes);
127 errs() << "Instruction removal failed. Sorry. :( Please report a bug!\n";
133 /// performFinalCleanups - This method clones the current Program and performs
134 /// a series of cleanups intended to get rid of extra cruft on the module
135 /// before handing it to the user.
137 Module *BugDriver::performFinalCleanups(Module *M, bool MayModifySemantics) {
138 // Make all functions external, so GlobalDCE doesn't delete them...
139 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
140 I->setLinkage(GlobalValue::ExternalLinkage);
142 std::vector<std::string> CleanupPasses;
143 CleanupPasses.push_back("globaldce");
145 if (MayModifySemantics)
146 CleanupPasses.push_back("deadarghaX0r");
148 CleanupPasses.push_back("deadargelim");
150 Module *New = runPassesOn(M, CleanupPasses);
152 errs() << "Final cleanups failed. Sorry. :( Please report a bug!\n";
160 /// ExtractLoop - Given a module, extract up to one loop from it into a new
161 /// function. This returns null if there are no extractable loops in the
162 /// program or if the loop extractor crashes.
163 Module *BugDriver::ExtractLoop(Module *M) {
164 std::vector<std::string> LoopExtractPasses;
165 LoopExtractPasses.push_back("loop-extract-single");
167 Module *NewM = runPassesOn(M, LoopExtractPasses);
169 outs() << "*** Loop extraction failed: ";
170 EmitProgressBitcode(M, "loopextraction", true);
171 outs() << "*** Sorry. :( Please report a bug!\n";
175 // Check to see if we created any new functions. If not, no loops were
176 // extracted and we should return null. Limit the number of loops we extract
177 // to avoid taking forever.
178 static unsigned NumExtracted = 32;
179 if (M->size() == NewM->size() || --NumExtracted == 0) {
183 assert(M->size() < NewM->size() && "Loop extract removed functions?");
184 Module::iterator MI = NewM->begin();
185 for (unsigned i = 0, e = M->size(); i != e; ++i)
193 // DeleteFunctionBody - "Remove" the function by deleting all of its basic
194 // blocks, making it external.
196 void llvm::DeleteFunctionBody(Function *F) {
197 // delete the body of the function...
199 assert(F->isDeclaration() && "This didn't make the function external!");
202 /// GetTorInit - Given a list of entries for static ctors/dtors, return them
203 /// as a constant array.
204 static Constant *GetTorInit(std::vector<std::pair<Function*, int> > &TorList) {
205 assert(!TorList.empty() && "Don't create empty tor list!");
206 std::vector<Constant*> ArrayElts;
207 Type *Int32Ty = Type::getInt32Ty(TorList[0].first->getContext());
210 StructType::get(Int32Ty, TorList[0].first->getType(), NULL);
211 for (unsigned i = 0, e = TorList.size(); i != e; ++i) {
213 ConstantInt::get(Int32Ty, TorList[i].second),
216 ArrayElts.push_back(ConstantStruct::get(STy, Elts));
218 return ConstantArray::get(ArrayType::get(ArrayElts[0]->getType(),
223 /// SplitStaticCtorDtor - A module was recently split into two parts, M1/M2, and
224 /// M1 has all of the global variables. If M2 contains any functions that are
225 /// static ctors/dtors, we need to add an llvm.global_[cd]tors global to M2, and
226 /// prune appropriate entries out of M1s list.
227 static void SplitStaticCtorDtor(const char *GlobalName, Module *M1, Module *M2,
228 ValueToValueMapTy &VMap) {
229 GlobalVariable *GV = M1->getNamedGlobal(GlobalName);
230 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage() ||
231 !GV->use_empty()) return;
233 std::vector<std::pair<Function*, int> > M1Tors, M2Tors;
234 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
235 if (!InitList) return;
237 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
238 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
239 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
241 if (CS->getOperand(1)->isNullValue())
242 break; // Found a null terminator, stop here.
244 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
245 int Priority = CI ? CI->getSExtValue() : 0;
247 Constant *FP = CS->getOperand(1);
248 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
250 FP = CE->getOperand(0);
251 if (Function *F = dyn_cast<Function>(FP)) {
252 if (!F->isDeclaration())
253 M1Tors.push_back(std::make_pair(F, Priority));
255 // Map to M2's version of the function.
256 F = cast<Function>(VMap[F]);
257 M2Tors.push_back(std::make_pair(F, Priority));
263 GV->eraseFromParent();
264 if (!M1Tors.empty()) {
265 Constant *M1Init = GetTorInit(M1Tors);
266 new GlobalVariable(*M1, M1Init->getType(), false,
267 GlobalValue::AppendingLinkage,
271 GV = M2->getNamedGlobal(GlobalName);
272 assert(GV && "Not a clone of M1?");
273 assert(GV->use_empty() && "llvm.ctors shouldn't have uses!");
275 GV->eraseFromParent();
276 if (!M2Tors.empty()) {
277 Constant *M2Init = GetTorInit(M2Tors);
278 new GlobalVariable(*M2, M2Init->getType(), false,
279 GlobalValue::AppendingLinkage,
285 /// SplitFunctionsOutOfModule - Given a module and a list of functions in the
286 /// module, split the functions OUT of the specified module, and place them in
289 llvm::SplitFunctionsOutOfModule(Module *M,
290 const std::vector<Function*> &F,
291 ValueToValueMapTy &VMap) {
292 // Make sure functions & globals are all external so that linkage
293 // between the two modules will work.
294 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
295 I->setLinkage(GlobalValue::ExternalLinkage);
296 for (Module::global_iterator I = M->global_begin(), E = M->global_end();
298 if (I->hasName() && I->getName()[0] == '\01')
299 I->setName(I->getName().substr(1));
300 I->setLinkage(GlobalValue::ExternalLinkage);
303 ValueToValueMapTy NewVMap;
304 Module *New = CloneModule(M, NewVMap);
306 // Remove the Test functions from the Safe module
307 std::set<Function *> TestFunctions;
308 for (unsigned i = 0, e = F.size(); i != e; ++i) {
309 Function *TNOF = cast<Function>(VMap[F[i]]);
310 DEBUG(errs() << "Removing function ");
311 DEBUG(TNOF->printAsOperand(errs(), false));
312 DEBUG(errs() << "\n");
313 TestFunctions.insert(cast<Function>(NewVMap[TNOF]));
314 DeleteFunctionBody(TNOF); // Function is now external in this module!
318 // Remove the Safe functions from the Test module
319 for (Module::iterator I = New->begin(), E = New->end(); I != E; ++I)
320 if (!TestFunctions.count(I))
321 DeleteFunctionBody(I);
324 // Try to split the global initializers evenly
325 for (Module::global_iterator I = M->global_begin(), E = M->global_end();
327 GlobalVariable *GV = cast<GlobalVariable>(NewVMap[I]);
328 if (Function *TestFn = globalInitUsesExternalBA(I)) {
329 if (Function *SafeFn = globalInitUsesExternalBA(GV)) {
330 errs() << "*** Error: when reducing functions, encountered "
332 GV->printAsOperand(errs(), false);
333 errs() << "' with an initializer that references blockaddresses "
334 "from safe function '" << SafeFn->getName()
335 << "' and from test function '" << TestFn->getName() << "'.\n";
338 I->setInitializer(0); // Delete the initializer to make it external
340 // If we keep it in the safe module, then delete it in the test module
341 GV->setInitializer(0);
345 // Make sure that there is a global ctor/dtor array in both halves of the
346 // module if they both have static ctor/dtor functions.
347 SplitStaticCtorDtor("llvm.global_ctors", M, New, NewVMap);
348 SplitStaticCtorDtor("llvm.global_dtors", M, New, NewVMap);
353 //===----------------------------------------------------------------------===//
354 // Basic Block Extraction Code
355 //===----------------------------------------------------------------------===//
357 /// ExtractMappedBlocksFromModule - Extract all but the specified basic blocks
358 /// into their own functions. The only detail is that M is actually a module
359 /// cloned from the one the BBs are in, so some mapping needs to be performed.
360 /// If this operation fails for some reason (ie the implementation is buggy),
361 /// this function should return null, otherwise it returns a new Module.
362 Module *BugDriver::ExtractMappedBlocksFromModule(const
363 std::vector<BasicBlock*> &BBs,
365 SmallString<128> Filename;
367 error_code EC = sys::fs::createUniqueFile(
368 OutputPrefix + "-extractblocks%%%%%%%", FD, Filename);
370 outs() << "*** Basic Block extraction failed!\n";
371 errs() << "Error creating temporary file: " << EC.message() << "\n";
372 EmitProgressBitcode(M, "basicblockextractfail", true);
375 sys::RemoveFileOnSignal(Filename);
377 tool_output_file BlocksToNotExtractFile(Filename.c_str(), FD);
378 for (std::vector<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
381 // If the BB doesn't have a name, give it one so we have something to key
383 if (!BB->hasName()) BB->setName("tmpbb");
384 BlocksToNotExtractFile.os() << BB->getParent()->getName() << " "
385 << BB->getName() << "\n";
387 BlocksToNotExtractFile.os().close();
388 if (BlocksToNotExtractFile.os().has_error()) {
389 errs() << "Error writing list of blocks to not extract\n";
390 EmitProgressBitcode(M, "basicblockextractfail", true);
391 BlocksToNotExtractFile.os().clear_error();
394 BlocksToNotExtractFile.keep();
396 std::string uniqueFN = "--extract-blocks-file=";
397 uniqueFN += Filename.str();
398 const char *ExtraArg = uniqueFN.c_str();
400 std::vector<std::string> PI;
401 PI.push_back("extract-blocks");
402 Module *Ret = runPassesOn(M, PI, false, 1, &ExtraArg);
404 sys::fs::remove(Filename.c_str());
407 outs() << "*** Basic Block extraction failed, please report a bug!\n";
408 EmitProgressBitcode(M, "basicblockextractfail", true);