blob: c642dd076506c27650d969db785e48831e641443 [file] [log] [blame]
Chris Lattnerafade922002-11-20 22:28:10 +00001//===- ExtractFunction.cpp - Extract a function from Program --------------===//
Misha Brukman3da94ae2005-04-22 00:00:37 +00002//
John Criswell7c0e0222003-10-20 17:47:21 +00003// 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.
Misha Brukman3da94ae2005-04-22 00:00:37 +00007//
John Criswell7c0e0222003-10-20 17:47:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerafade922002-11-20 22:28:10 +00009//
Chris Lattnerefdc0b52004-03-14 20:50:42 +000010// This file implements several methods that are used to extract functions,
11// loops, or portions of a module from the rest of the module.
Chris Lattnerafade922002-11-20 22:28:10 +000012//
13//===----------------------------------------------------------------------===//
14
15#include "BugDriver.h"
Chris Lattner5a7a9e52006-03-08 23:55:38 +000016#include "llvm/Constants.h"
17#include "llvm/DerivedTypes.h"
Chris Lattnerafade922002-11-20 22:28:10 +000018#include "llvm/Module.h"
19#include "llvm/PassManager.h"
Brian Gaeked1a85a72003-09-10 21:11:42 +000020#include "llvm/Pass.h"
Patrick Jenkinse47863e2006-07-28 01:19:28 +000021#include "llvm/SymbolTable.h"
Misha Brukmane49603d2003-08-07 21:19:30 +000022#include "llvm/Analysis/Verifier.h"
Chris Lattnerafade922002-11-20 22:28:10 +000023#include "llvm/Transforms/IPO.h"
Chris Lattner65207852003-01-23 02:48:33 +000024#include "llvm/Transforms/Scalar.h"
Chris Lattnerafade922002-11-20 22:28:10 +000025#include "llvm/Transforms/Utils/Cloning.h"
Chris Lattner5e783ab2004-05-11 21:54:13 +000026#include "llvm/Transforms/Utils/FunctionUtils.h"
Chris Lattner5da69c72003-10-23 15:42:55 +000027#include "llvm/Target/TargetData.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000028#include "llvm/Support/CommandLine.h"
29#include "llvm/Support/Debug.h"
30#include "llvm/Support/FileUtilities.h"
Chris Lattnerfb4b96e2004-04-02 16:28:32 +000031#include <set>
Chris Lattnere31a9cc2006-01-22 22:53:40 +000032#include <iostream>
Chris Lattnerc6b519d2003-11-23 04:51:05 +000033using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000034
35namespace llvm {
Chris Lattnerc6b519d2003-11-23 04:51:05 +000036 bool DisableSimplifyCFG = false;
Brian Gaeked0fde302003-11-11 22:41:34 +000037} // End llvm namespace
38
Chris Lattner6db70ef2003-04-25 22:08:12 +000039namespace {
40 cl::opt<bool>
Chris Lattner6db70ef2003-04-25 22:08:12 +000041 NoDCE ("disable-dce",
42 cl::desc("Do not use the -dce pass to reduce testcases"));
Chris Lattner47ae4a12003-08-05 15:51:05 +000043 cl::opt<bool, true>
44 NoSCFG("disable-simplifycfg", cl::location(DisableSimplifyCFG),
Chris Lattner6db70ef2003-04-25 22:08:12 +000045 cl::desc("Do not use the -simplifycfg pass to reduce testcases"));
46}
Chris Lattnerafade922002-11-20 22:28:10 +000047
Chris Lattner65207852003-01-23 02:48:33 +000048/// deleteInstructionFromProgram - This method clones the current Program and
49/// deletes the specified instruction from the cloned module. It then runs a
50/// series of cleanup passes (ADCE and SimplifyCFG) to eliminate any code which
51/// depends on the value. The modified module is then returned.
52///
Chris Lattner0cc88072004-02-18 21:50:26 +000053Module *BugDriver::deleteInstructionFromProgram(const Instruction *I,
Chris Lattner65207852003-01-23 02:48:33 +000054 unsigned Simplification) const {
55 Module *Result = CloneModule(Program);
56
Chris Lattner0cc88072004-02-18 21:50:26 +000057 const BasicBlock *PBB = I->getParent();
58 const Function *PF = PBB->getParent();
Chris Lattner65207852003-01-23 02:48:33 +000059
60 Module::iterator RFI = Result->begin(); // Get iterator to corresponding fn
Chris Lattner0cc88072004-02-18 21:50:26 +000061 std::advance(RFI, std::distance(PF->getParent()->begin(),
62 Module::const_iterator(PF)));
Chris Lattner65207852003-01-23 02:48:33 +000063
64 Function::iterator RBI = RFI->begin(); // Get iterator to corresponding BB
Chris Lattner0cc88072004-02-18 21:50:26 +000065 std::advance(RBI, std::distance(PF->begin(), Function::const_iterator(PBB)));
Chris Lattner65207852003-01-23 02:48:33 +000066
67 BasicBlock::iterator RI = RBI->begin(); // Get iterator to corresponding inst
Chris Lattner0cc88072004-02-18 21:50:26 +000068 std::advance(RI, std::distance(PBB->begin(), BasicBlock::const_iterator(I)));
69 Instruction *TheInst = RI; // Got the corresponding instruction!
Chris Lattner65207852003-01-23 02:48:33 +000070
71 // If this instruction produces a value, replace any users with null values
Chris Lattner0cc88072004-02-18 21:50:26 +000072 if (TheInst->getType() != Type::VoidTy)
73 TheInst->replaceAllUsesWith(Constant::getNullValue(TheInst->getType()));
Chris Lattner65207852003-01-23 02:48:33 +000074
75 // Remove the instruction from the program.
Chris Lattner0cc88072004-02-18 21:50:26 +000076 TheInst->getParent()->getInstList().erase(TheInst);
Chris Lattner65207852003-01-23 02:48:33 +000077
Chris Lattner5a7a9e52006-03-08 23:55:38 +000078
79 //writeProgramToFile("current.bc", Result);
80
Chris Lattner44be2572003-04-24 22:53:24 +000081 // Spiff up the output a little bit.
Chris Lattner65207852003-01-23 02:48:33 +000082 PassManager Passes;
Chris Lattner5da69c72003-10-23 15:42:55 +000083 // Make sure that the appropriate target data is always used...
Chris Lattner831b1212006-06-16 18:23:49 +000084 Passes.add(new TargetData(Result));
Chris Lattner5da69c72003-10-23 15:42:55 +000085
Chris Lattnerefdc0b52004-03-14 20:50:42 +000086 /// FIXME: If this used runPasses() like the methods below, we could get rid
87 /// of the -disable-* options!
Chris Lattner6db70ef2003-04-25 22:08:12 +000088 if (Simplification > 1 && !NoDCE)
Chris Lattner65207852003-01-23 02:48:33 +000089 Passes.add(createDeadCodeEliminationPass());
Chris Lattner47ae4a12003-08-05 15:51:05 +000090 if (Simplification && !DisableSimplifyCFG)
Chris Lattner65207852003-01-23 02:48:33 +000091 Passes.add(createCFGSimplificationPass()); // Delete dead control flow
Chris Lattner10f22cb2003-03-07 18:17:13 +000092
93 Passes.add(createVerifierPass());
Chris Lattner65207852003-01-23 02:48:33 +000094 Passes.run(*Result);
95 return Result;
96}
Chris Lattnerba386d92003-02-28 16:13:20 +000097
Chris Lattnerfcb6ec02003-11-05 21:45:35 +000098static const PassInfo *getPI(Pass *P) {
99 const PassInfo *PI = P->getPassInfo();
100 delete P;
101 return PI;
102}
103
Chris Lattnerba386d92003-02-28 16:13:20 +0000104/// performFinalCleanups - This method clones the current Program and performs
105/// a series of cleanups intended to get rid of extra cruft on the module
Chris Lattner9b5b1902005-02-23 06:12:11 +0000106/// before handing it to the user.
Chris Lattnerba386d92003-02-28 16:13:20 +0000107///
Chris Lattnerfcb6ec02003-11-05 21:45:35 +0000108Module *BugDriver::performFinalCleanups(Module *M, bool MayModifySemantics) {
Chris Lattner28b8ed92003-05-21 19:41:31 +0000109 // Make all functions external, so GlobalDCE doesn't delete them...
110 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
111 I->setLinkage(GlobalValue::ExternalLinkage);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000112
Chris Lattnerfcb6ec02003-11-05 21:45:35 +0000113 std::vector<const PassInfo*> CleanupPasses;
114 CleanupPasses.push_back(getPI(createFunctionResolvingPass()));
115 CleanupPasses.push_back(getPI(createGlobalDCEPass()));
116 CleanupPasses.push_back(getPI(createDeadTypeEliminationPass()));
Chris Lattnerfcb6ec02003-11-05 21:45:35 +0000117
Chris Lattnerc6b519d2003-11-23 04:51:05 +0000118 if (MayModifySemantics)
119 CleanupPasses.push_back(getPI(createDeadArgHackingPass()));
120 else
121 CleanupPasses.push_back(getPI(createDeadArgEliminationPass()));
Chris Lattnerfcb6ec02003-11-05 21:45:35 +0000122
Chris Lattnera75766a2004-03-14 21:17:22 +0000123 Module *New = runPassesOn(M, CleanupPasses);
124 if (New == 0) {
Chris Lattner7546c382004-03-14 20:02:07 +0000125 std::cerr << "Final cleanups failed. Sorry. :( Please report a bug!\n";
Chris Lattner9b5b1902005-02-23 06:12:11 +0000126 return M;
Chris Lattnerfcb6ec02003-11-05 21:45:35 +0000127 }
Chris Lattnera75766a2004-03-14 21:17:22 +0000128 delete M;
129 return New;
Chris Lattnerba386d92003-02-28 16:13:20 +0000130}
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000131
132
Chris Lattner7546c382004-03-14 20:02:07 +0000133/// ExtractLoop - Given a module, extract up to one loop from it into a new
134/// function. This returns null if there are no extractable loops in the
135/// program or if the loop extractor crashes.
136Module *BugDriver::ExtractLoop(Module *M) {
137 std::vector<const PassInfo*> LoopExtractPasses;
138 LoopExtractPasses.push_back(getPI(createSingleLoopExtractorPass()));
139
Chris Lattnera75766a2004-03-14 21:17:22 +0000140 Module *NewM = runPassesOn(M, LoopExtractPasses);
141 if (NewM == 0) {
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000142 Module *Old = swapProgramIn(M);
143 std::cout << "*** Loop extraction failed: ";
144 EmitProgressBytecode("loopextraction", true);
145 std::cout << "*** Sorry. :( Please report a bug!\n";
146 swapProgramIn(Old);
Chris Lattner7546c382004-03-14 20:02:07 +0000147 return 0;
Chris Lattner7546c382004-03-14 20:02:07 +0000148 }
Chris Lattnera75766a2004-03-14 21:17:22 +0000149
150 // Check to see if we created any new functions. If not, no loops were
Chris Lattnera269ec72004-11-18 19:40:13 +0000151 // extracted and we should return null. Limit the number of loops we extract
152 // to avoid taking forever.
153 static unsigned NumExtracted = 32;
Chris Lattner90c18c52004-11-16 06:31:38 +0000154 if (M->size() == NewM->size() || --NumExtracted == 0) {
Chris Lattnera75766a2004-03-14 21:17:22 +0000155 delete NewM;
156 return 0;
Chris Lattner90c18c52004-11-16 06:31:38 +0000157 } else {
158 assert(M->size() < NewM->size() && "Loop extract removed functions?");
159 Module::iterator MI = NewM->begin();
160 for (unsigned i = 0, e = M->size(); i != e; ++i)
161 ++MI;
Chris Lattnera75766a2004-03-14 21:17:22 +0000162 }
Misha Brukman3da94ae2005-04-22 00:00:37 +0000163
Chris Lattnera75766a2004-03-14 21:17:22 +0000164 return NewM;
Chris Lattner7546c382004-03-14 20:02:07 +0000165}
166
167
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000168// DeleteFunctionBody - "Remove" the function by deleting all of its basic
169// blocks, making it external.
170//
171void llvm::DeleteFunctionBody(Function *F) {
172 // delete the body of the function...
173 F->deleteBody();
174 assert(F->isExternal() && "This didn't make the function external!");
175}
176
Chris Lattner5a7a9e52006-03-08 23:55:38 +0000177/// GetTorInit - Given a list of entries for static ctors/dtors, return them
178/// as a constant array.
179static Constant *GetTorInit(std::vector<std::pair<Function*, int> > &TorList) {
180 assert(!TorList.empty() && "Don't create empty tor list!");
181 std::vector<Constant*> ArrayElts;
182 for (unsigned i = 0, e = TorList.size(); i != e; ++i) {
183 std::vector<Constant*> Elts;
Reid Spencerb83eb642006-10-20 07:07:24 +0000184 Elts.push_back(ConstantInt::get(Type::IntTy, TorList[i].second));
Chris Lattner5a7a9e52006-03-08 23:55:38 +0000185 Elts.push_back(TorList[i].first);
186 ArrayElts.push_back(ConstantStruct::get(Elts));
187 }
188 return ConstantArray::get(ArrayType::get(ArrayElts[0]->getType(),
189 ArrayElts.size()),
190 ArrayElts);
191}
192
193/// SplitStaticCtorDtor - A module was recently split into two parts, M1/M2, and
194/// M1 has all of the global variables. If M2 contains any functions that are
195/// static ctors/dtors, we need to add an llvm.global_[cd]tors global to M2, and
196/// prune appropriate entries out of M1s list.
197static void SplitStaticCtorDtor(const char *GlobalName, Module *M1, Module *M2){
198 GlobalVariable *GV = M1->getNamedGlobal(GlobalName);
199 if (!GV || GV->isExternal() || GV->hasInternalLinkage() ||
200 !GV->use_empty()) return;
201
202 std::vector<std::pair<Function*, int> > M1Tors, M2Tors;
203 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
204 if (!InitList) return;
205
206 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
207 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
208 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
209
210 if (CS->getOperand(1)->isNullValue())
211 break; // Found a null terminator, stop here.
212
Reid Spencerb83eb642006-10-20 07:07:24 +0000213 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
214 int Priority = CI ? CI->getSExtValue() : 0;
Chris Lattner5a7a9e52006-03-08 23:55:38 +0000215
216 Constant *FP = CS->getOperand(1);
217 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
218 if (CE->getOpcode() == Instruction::Cast)
219 FP = CE->getOperand(0);
220 if (Function *F = dyn_cast<Function>(FP)) {
221 if (!F->isExternal())
222 M1Tors.push_back(std::make_pair(F, Priority));
223 else {
224 // Map to M2's version of the function.
225 F = M2->getFunction(F->getName(), F->getFunctionType());
226 M2Tors.push_back(std::make_pair(F, Priority));
227 }
228 }
229 }
230 }
231
232 GV->eraseFromParent();
233 if (!M1Tors.empty()) {
234 Constant *M1Init = GetTorInit(M1Tors);
235 new GlobalVariable(M1Init->getType(), false, GlobalValue::AppendingLinkage,
236 M1Init, GlobalName, M1);
237 }
238
239 GV = M2->getNamedGlobal(GlobalName);
240 assert(GV && "Not a clone of M1?");
241 assert(GV->use_empty() && "llvm.ctors shouldn't have uses!");
242
243 GV->eraseFromParent();
244 if (!M2Tors.empty()) {
245 Constant *M2Init = GetTorInit(M2Tors);
246 new GlobalVariable(M2Init->getType(), false, GlobalValue::AppendingLinkage,
247 M2Init, GlobalName, M2);
248 }
249}
250
Chris Lattner1bb6f062006-08-29 23:38:20 +0000251/// RewriteUsesInNewModule - Given a constant 'OrigVal' and a module 'OrigMod',
252/// find all uses of the constant. If they are not in the specified module,
253/// replace them with uses of another constant 'NewVal'.
Patrick Jenkinse47863e2006-07-28 01:19:28 +0000254static void RewriteUsesInNewModule(Constant *OrigVal, Constant *NewVal,
Chris Lattner1bb6f062006-08-29 23:38:20 +0000255 Module *OrigMod) {
Patrick Jenkinse47863e2006-07-28 01:19:28 +0000256 assert(OrigVal->getType() == NewVal->getType() &&
257 "Can't replace something with a different type");
258 for (Value::use_iterator UI = OrigVal->use_begin(), E = OrigVal->use_end();
259 UI != E; ) {
260 Value::use_iterator TmpUI = UI++;
261 User *U = *TmpUI;
262 if (Instruction *Inst = dyn_cast<Instruction>(U)) {
Chris Lattner1bb6f062006-08-29 23:38:20 +0000263 if (Inst->getParent()->getParent()->getParent() != OrigMod)
Patrick Jenkinse47863e2006-07-28 01:19:28 +0000264 TmpUI.getUse() = NewVal;
Chris Lattner1bb6f062006-08-29 23:38:20 +0000265 } else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(U)) {
266 if (GV->getParent() != OrigMod)
267 TmpUI.getUse() = NewVal;
Patrick Jenkinse47863e2006-07-28 01:19:28 +0000268 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
269 // If nothing uses this, don't bother making a copy.
270 if (CE->use_empty()) continue;
271 Constant *NewCE = CE->getWithOperandReplaced(TmpUI.getOperandNo(),
272 NewVal);
Chris Lattner1bb6f062006-08-29 23:38:20 +0000273 RewriteUsesInNewModule(CE, NewCE, OrigMod);
Patrick Jenkinse47863e2006-07-28 01:19:28 +0000274 } else if (ConstantStruct *CS = dyn_cast<ConstantStruct>(U)) {
275 // If nothing uses this, don't bother making a copy.
276 if (CS->use_empty()) continue;
277 unsigned OpNo = TmpUI.getOperandNo();
278 std::vector<Constant*> Ops;
279 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
280 Ops.push_back(i == OpNo ? NewVal : CS->getOperand(i));
281 Constant *NewStruct = ConstantStruct::get(Ops);
Chris Lattner1bb6f062006-08-29 23:38:20 +0000282 RewriteUsesInNewModule(CS, NewStruct, OrigMod);
Patrick Jenkinse47863e2006-07-28 01:19:28 +0000283 } else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(U)) {
284 // If nothing uses this, don't bother making a copy.
285 if (CP->use_empty()) continue;
286 unsigned OpNo = TmpUI.getOperandNo();
287 std::vector<Constant*> Ops;
288 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
289 Ops.push_back(i == OpNo ? NewVal : CP->getOperand(i));
290 Constant *NewPacked = ConstantPacked::get(Ops);
Chris Lattner1bb6f062006-08-29 23:38:20 +0000291 RewriteUsesInNewModule(CP, NewPacked, OrigMod);
Patrick Jenkinse47863e2006-07-28 01:19:28 +0000292 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(U)) {
293 // If nothing uses this, don't bother making a copy.
294 if (CA->use_empty()) continue;
295 unsigned OpNo = TmpUI.getOperandNo();
296 std::vector<Constant*> Ops;
297 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
298 Ops.push_back(i == OpNo ? NewVal : CA->getOperand(i));
299 }
300 Constant *NewArray = ConstantArray::get(CA->getType(), Ops);
Chris Lattner1bb6f062006-08-29 23:38:20 +0000301 RewriteUsesInNewModule(CA, NewArray, OrigMod);
Patrick Jenkinse47863e2006-07-28 01:19:28 +0000302 } else {
303 assert(0 && "Unexpected user");
304 }
305 }
306}
307
308
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000309/// SplitFunctionsOutOfModule - Given a module and a list of functions in the
310/// module, split the functions OUT of the specified module, and place them in
311/// the new module.
312Module *llvm::SplitFunctionsOutOfModule(Module *M,
313 const std::vector<Function*> &F) {
314 // Make sure functions & globals are all external so that linkage
315 // between the two modules will work.
316 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
317 I->setLinkage(GlobalValue::ExternalLinkage);
Chris Lattner5a7a9e52006-03-08 23:55:38 +0000318 for (Module::global_iterator I = M->global_begin(), E = M->global_end();
319 I != E; ++I)
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000320 I->setLinkage(GlobalValue::ExternalLinkage);
321
Patrick Jenkinse47863e2006-07-28 01:19:28 +0000322 // First off, we need to create the new module...
323 Module *New = new Module(M->getModuleIdentifier());
324 New->setEndianness(M->getEndianness());
325 New->setPointerSize(M->getPointerSize());
326 New->setTargetTriple(M->getTargetTriple());
327 New->setModuleInlineAsm(M->getModuleInlineAsm());
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000328
Patrick Jenkinse47863e2006-07-28 01:19:28 +0000329 // Copy all of the dependent libraries over.
330 for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I)
331 New->addLibrary(*I);
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000332
Patrick Jenkinse47863e2006-07-28 01:19:28 +0000333 // build a set of the functions to search later...
Chris Lattnerfb4b96e2004-04-02 16:28:32 +0000334 std::set<std::pair<std::string, const PointerType*> > TestFunctions;
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000335 for (unsigned i = 0, e = F.size(); i != e; ++i) {
Patrick Jenkinse47863e2006-07-28 01:19:28 +0000336 TestFunctions.insert(std::make_pair(F[i]->getName(), F[i]->getType()));
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000337 }
338
Patrick Jenkinse47863e2006-07-28 01:19:28 +0000339 std::map<GlobalValue*, GlobalValue*> GlobalToPrototypeMap;
340 std::vector<GlobalValue*> OrigGlobals;
341
342 // Adding specified functions to new module...
343 for (Module::iterator I = M->begin(), E = M->end(); I != E;) {
344 OrigGlobals.push_back(I);
Chris Lattner1bb6f062006-08-29 23:38:20 +0000345 if (TestFunctions.count(std::make_pair(I->getName(), I->getType()))) {
Patrick Jenkinse47863e2006-07-28 01:19:28 +0000346 Module::iterator tempI = I;
347 I++;
Chris Lattner1bb6f062006-08-29 23:38:20 +0000348 Function *Func = new Function(tempI->getFunctionType(),
Patrick Jenkinse47863e2006-07-28 01:19:28 +0000349 GlobalValue::ExternalLinkage);
Chris Lattner1bb6f062006-08-29 23:38:20 +0000350 M->getFunctionList().insert(tempI, Func);
Patrick Jenkinse47863e2006-07-28 01:19:28 +0000351 New->getFunctionList().splice(New->end(),
352 M->getFunctionList(),
353 tempI);
Chris Lattner1bb6f062006-08-29 23:38:20 +0000354 Func->setName(tempI->getName());
355 Func->setCallingConv(tempI->getCallingConv());
356 GlobalToPrototypeMap[tempI] = Func;
Patrick Jenkinse47863e2006-07-28 01:19:28 +0000357 } else {
Chris Lattner1bb6f062006-08-29 23:38:20 +0000358 Function *Func = new Function(I->getFunctionType(),
Patrick Jenkinse47863e2006-07-28 01:19:28 +0000359 GlobalValue::ExternalLinkage,
360 I->getName(),
361 New);
Chris Lattner1bb6f062006-08-29 23:38:20 +0000362 Func->setCallingConv(I->getCallingConv());
363 GlobalToPrototypeMap[I] = Func;
Patrick Jenkinse47863e2006-07-28 01:19:28 +0000364 I++;
365 }
366 }
367
Chris Lattner1bb6f062006-08-29 23:38:20 +0000368 // Copy over global variable list.
369 for (Module::global_iterator I = M->global_begin(), E = M->global_end();
370 I != E; ++I) {
Patrick Jenkinse47863e2006-07-28 01:19:28 +0000371 OrigGlobals.push_back(I);
Chris Lattner1bb6f062006-08-29 23:38:20 +0000372 GlobalVariable *G = new GlobalVariable(I->getType()->getElementType(),
373 I->isConstant(),
374 GlobalValue::ExternalLinkage,
375 0, I->getName(), New);
376 GlobalToPrototypeMap[I] = G;
Patrick Jenkinse47863e2006-07-28 01:19:28 +0000377 }
Chris Lattner5a7a9e52006-03-08 23:55:38 +0000378
Patrick Jenkinse47863e2006-07-28 01:19:28 +0000379 // Copy all of the type symbol table entries over.
380 const SymbolTable &SymTab = M->getSymbolTable();
381 SymbolTable::type_const_iterator TypeI = SymTab.type_begin();
382 SymbolTable::type_const_iterator TypeE = SymTab.type_end();
383 for (; TypeI != TypeE; ++TypeI)
384 New->addTypeName(TypeI->first, TypeI->second);
385
386 // Loop over globals, rewriting uses in the module the prototype is in to use
387 // the prototype.
388 for (unsigned i = 0, e = OrigGlobals.size(); i != e; ++i) {
389 assert(OrigGlobals[i]->getName() ==
Chris Lattner1bb6f062006-08-29 23:38:20 +0000390 GlobalToPrototypeMap[OrigGlobals[i]]->getName() &&
391 "Something got renamed?");
Patrick Jenkinse47863e2006-07-28 01:19:28 +0000392 RewriteUsesInNewModule(OrigGlobals[i], GlobalToPrototypeMap[OrigGlobals[i]],
393 OrigGlobals[i]->getParent());
394 }
395
Chris Lattner5a7a9e52006-03-08 23:55:38 +0000396 // Make sure that there is a global ctor/dtor array in both halves of the
397 // module if they both have static ctor/dtor functions.
398 SplitStaticCtorDtor("llvm.global_ctors", M, New);
399 SplitStaticCtorDtor("llvm.global_dtors", M, New);
400
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000401 return New;
402}
Chris Lattner5e783ab2004-05-11 21:54:13 +0000403
404//===----------------------------------------------------------------------===//
405// Basic Block Extraction Code
406//===----------------------------------------------------------------------===//
407
408namespace {
409 std::vector<BasicBlock*> BlocksToNotExtract;
410
411 /// BlockExtractorPass - This pass is used by bugpoint to extract all blocks
412 /// from the module into their own functions except for those specified by the
413 /// BlocksToNotExtract list.
Chris Lattnerb12914b2004-09-20 04:48:05 +0000414 class BlockExtractorPass : public ModulePass {
415 bool runOnModule(Module &M);
Chris Lattner5e783ab2004-05-11 21:54:13 +0000416 };
Chris Lattner7f8897f2006-08-27 22:42:52 +0000417 RegisterPass<BlockExtractorPass>
Chris Lattner5e783ab2004-05-11 21:54:13 +0000418 XX("extract-bbs", "Extract Basic Blocks From Module (for bugpoint use)");
419}
420
Chris Lattnerb12914b2004-09-20 04:48:05 +0000421bool BlockExtractorPass::runOnModule(Module &M) {
Chris Lattner5e783ab2004-05-11 21:54:13 +0000422 std::set<BasicBlock*> TranslatedBlocksToNotExtract;
423 for (unsigned i = 0, e = BlocksToNotExtract.size(); i != e; ++i) {
424 BasicBlock *BB = BlocksToNotExtract[i];
425 Function *F = BB->getParent();
426
427 // Map the corresponding function in this module.
428 Function *MF = M.getFunction(F->getName(), F->getFunctionType());
429
430 // Figure out which index the basic block is in its function.
431 Function::iterator BBI = MF->begin();
432 std::advance(BBI, std::distance(F->begin(), Function::iterator(BB)));
433 TranslatedBlocksToNotExtract.insert(BBI);
434 }
435
436 // Now that we know which blocks to not extract, figure out which ones we WANT
437 // to extract.
438 std::vector<BasicBlock*> BlocksToExtract;
439 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
440 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
441 if (!TranslatedBlocksToNotExtract.count(BB))
442 BlocksToExtract.push_back(BB);
443
444 for (unsigned i = 0, e = BlocksToExtract.size(); i != e; ++i)
445 ExtractBasicBlock(BlocksToExtract[i]);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000446
Chris Lattner5e783ab2004-05-11 21:54:13 +0000447 return !BlocksToExtract.empty();
448}
449
450/// ExtractMappedBlocksFromModule - Extract all but the specified basic blocks
451/// into their own functions. The only detail is that M is actually a module
452/// cloned from the one the BBs are in, so some mapping needs to be performed.
453/// If this operation fails for some reason (ie the implementation is buggy),
454/// this function should return null, otherwise it returns a new Module.
455Module *BugDriver::ExtractMappedBlocksFromModule(const
456 std::vector<BasicBlock*> &BBs,
457 Module *M) {
458 // Set the global list so that pass will be able to access it.
459 BlocksToNotExtract = BBs;
460
461 std::vector<const PassInfo*> PI;
462 PI.push_back(getPI(new BlockExtractorPass()));
463 Module *Ret = runPassesOn(M, PI);
464 BlocksToNotExtract.clear();
Chris Lattner891150f2004-08-12 02:36:50 +0000465 if (Ret == 0) {
Chris Lattner5e783ab2004-05-11 21:54:13 +0000466 std::cout << "*** Basic Block extraction failed, please report a bug!\n";
Chris Lattner891150f2004-08-12 02:36:50 +0000467 M = swapProgramIn(M);
468 EmitProgressBytecode("basicblockextractfail", true);
Chris Lattnerb923b2e2006-05-12 17:28:36 +0000469 swapProgramIn(M);
Chris Lattner891150f2004-08-12 02:36:50 +0000470 }
Chris Lattner5e783ab2004-05-11 21:54:13 +0000471 return Ret;
472}