CodeExtractor.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756
  1. //===- CodeExtractor.cpp - Pull code region into a new function -----------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the interface to tear out a code region, such as an
  11. // individual loop or a parallel section, into a new function, replacing it with
  12. // a call to the new function.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "llvm/Transforms/Utils/FunctionUtils.h"
  16. #include "llvm/Constants.h"
  17. #include "llvm/DerivedTypes.h"
  18. #include "llvm/Instructions.h"
  19. #include "llvm/Intrinsics.h"
  20. #include "llvm/LLVMContext.h"
  21. #include "llvm/Module.h"
  22. #include "llvm/Pass.h"
  23. #include "llvm/Analysis/Dominators.h"
  24. #include "llvm/Analysis/LoopInfo.h"
  25. #include "llvm/Analysis/Verifier.h"
  26. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  27. #include "llvm/Support/CommandLine.h"
  28. #include "llvm/Support/Compiler.h"
  29. #include "llvm/Support/Debug.h"
  30. #include "llvm/Support/ErrorHandling.h"
  31. #include "llvm/ADT/StringExtras.h"
  32. #include <algorithm>
  33. #include <set>
  34. using namespace llvm;
  35. // Provide a command-line option to aggregate function arguments into a struct
  36. // for functions produced by the code extractor. This is useful when converting
  37. // extracted functions to pthread-based code, as only one argument (void*) can
  38. // be passed in to pthread_create().
  39. static cl::opt<bool>
  40. AggregateArgsOpt("aggregate-extracted-args", cl::Hidden,
  41. cl::desc("Aggregate arguments to code-extracted functions"));
  42. namespace {
  43. class VISIBILITY_HIDDEN CodeExtractor {
  44. typedef std::vector<Value*> Values;
  45. std::set<BasicBlock*> BlocksToExtract;
  46. DominatorTree* DT;
  47. bool AggregateArgs;
  48. unsigned NumExitBlocks;
  49. const Type *RetTy;
  50. public:
  51. CodeExtractor(DominatorTree* dt = 0, bool AggArgs = false)
  52. : DT(dt), AggregateArgs(AggArgs||AggregateArgsOpt), NumExitBlocks(~0U) {}
  53. Function *ExtractCodeRegion(const std::vector<BasicBlock*> &code);
  54. bool isEligible(const std::vector<BasicBlock*> &code);
  55. private:
  56. /// definedInRegion - Return true if the specified value is defined in the
  57. /// extracted region.
  58. bool definedInRegion(Value *V) const {
  59. if (Instruction *I = dyn_cast<Instruction>(V))
  60. if (BlocksToExtract.count(I->getParent()))
  61. return true;
  62. return false;
  63. }
  64. /// definedInCaller - Return true if the specified value is defined in the
  65. /// function being code extracted, but not in the region being extracted.
  66. /// These values must be passed in as live-ins to the function.
  67. bool definedInCaller(Value *V) const {
  68. if (isa<Argument>(V)) return true;
  69. if (Instruction *I = dyn_cast<Instruction>(V))
  70. if (!BlocksToExtract.count(I->getParent()))
  71. return true;
  72. return false;
  73. }
  74. void severSplitPHINodes(BasicBlock *&Header);
  75. void splitReturnBlocks();
  76. void findInputsOutputs(Values &inputs, Values &outputs);
  77. Function *constructFunction(const Values &inputs,
  78. const Values &outputs,
  79. BasicBlock *header,
  80. BasicBlock *newRootNode, BasicBlock *newHeader,
  81. Function *oldFunction, Module *M);
  82. void moveCodeToFunction(Function *newFunction);
  83. void emitCallAndSwitchStatement(Function *newFunction,
  84. BasicBlock *newHeader,
  85. Values &inputs,
  86. Values &outputs);
  87. };
  88. }
  89. /// severSplitPHINodes - If a PHI node has multiple inputs from outside of the
  90. /// region, we need to split the entry block of the region so that the PHI node
  91. /// is easier to deal with.
  92. void CodeExtractor::severSplitPHINodes(BasicBlock *&Header) {
  93. bool HasPredsFromRegion = false;
  94. unsigned NumPredsOutsideRegion = 0;
  95. if (Header != &Header->getParent()->getEntryBlock()) {
  96. PHINode *PN = dyn_cast<PHINode>(Header->begin());
  97. if (!PN) return; // No PHI nodes.
  98. // If the header node contains any PHI nodes, check to see if there is more
  99. // than one entry from outside the region. If so, we need to sever the
  100. // header block into two.
  101. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
  102. if (BlocksToExtract.count(PN->getIncomingBlock(i)))
  103. HasPredsFromRegion = true;
  104. else
  105. ++NumPredsOutsideRegion;
  106. // If there is one (or fewer) predecessor from outside the region, we don't
  107. // need to do anything special.
  108. if (NumPredsOutsideRegion <= 1) return;
  109. }
  110. // Otherwise, we need to split the header block into two pieces: one
  111. // containing PHI nodes merging values from outside of the region, and a
  112. // second that contains all of the code for the block and merges back any
  113. // incoming values from inside of the region.
  114. BasicBlock::iterator AfterPHIs = Header->getFirstNonPHI();
  115. BasicBlock *NewBB = Header->splitBasicBlock(AfterPHIs,
  116. Header->getName()+".ce");
  117. // We only want to code extract the second block now, and it becomes the new
  118. // header of the region.
  119. BasicBlock *OldPred = Header;
  120. BlocksToExtract.erase(OldPred);
  121. BlocksToExtract.insert(NewBB);
  122. Header = NewBB;
  123. // Okay, update dominator sets. The blocks that dominate the new one are the
  124. // blocks that dominate TIBB plus the new block itself.
  125. if (DT)
  126. DT->splitBlock(NewBB);
  127. // Okay, now we need to adjust the PHI nodes and any branches from within the
  128. // region to go to the new header block instead of the old header block.
  129. if (HasPredsFromRegion) {
  130. PHINode *PN = cast<PHINode>(OldPred->begin());
  131. // Loop over all of the predecessors of OldPred that are in the region,
  132. // changing them to branch to NewBB instead.
  133. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
  134. if (BlocksToExtract.count(PN->getIncomingBlock(i))) {
  135. TerminatorInst *TI = PN->getIncomingBlock(i)->getTerminator();
  136. TI->replaceUsesOfWith(OldPred, NewBB);
  137. }
  138. // Okay, everthing within the region is now branching to the right block, we
  139. // just have to update the PHI nodes now, inserting PHI nodes into NewBB.
  140. for (AfterPHIs = OldPred->begin(); isa<PHINode>(AfterPHIs); ++AfterPHIs) {
  141. PHINode *PN = cast<PHINode>(AfterPHIs);
  142. // Create a new PHI node in the new region, which has an incoming value
  143. // from OldPred of PN.
  144. PHINode *NewPN = PHINode::Create(PN->getType(), PN->getName()+".ce",
  145. NewBB->begin());
  146. NewPN->addIncoming(PN, OldPred);
  147. // Loop over all of the incoming value in PN, moving them to NewPN if they
  148. // are from the extracted region.
  149. for (unsigned i = 0; i != PN->getNumIncomingValues(); ++i) {
  150. if (BlocksToExtract.count(PN->getIncomingBlock(i))) {
  151. NewPN->addIncoming(PN->getIncomingValue(i), PN->getIncomingBlock(i));
  152. PN->removeIncomingValue(i);
  153. --i;
  154. }
  155. }
  156. }
  157. }
  158. }
  159. void CodeExtractor::splitReturnBlocks() {
  160. for (std::set<BasicBlock*>::iterator I = BlocksToExtract.begin(),
  161. E = BlocksToExtract.end(); I != E; ++I)
  162. if (ReturnInst *RI = dyn_cast<ReturnInst>((*I)->getTerminator()))
  163. (*I)->splitBasicBlock(RI, (*I)->getName()+".ret");
  164. }
  165. // findInputsOutputs - Find inputs to, outputs from the code region.
  166. //
  167. void CodeExtractor::findInputsOutputs(Values &inputs, Values &outputs) {
  168. std::set<BasicBlock*> ExitBlocks;
  169. for (std::set<BasicBlock*>::const_iterator ci = BlocksToExtract.begin(),
  170. ce = BlocksToExtract.end(); ci != ce; ++ci) {
  171. BasicBlock *BB = *ci;
  172. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
  173. // If a used value is defined outside the region, it's an input. If an
  174. // instruction is used outside the region, it's an output.
  175. for (User::op_iterator O = I->op_begin(), E = I->op_end(); O != E; ++O)
  176. if (definedInCaller(*O))
  177. inputs.push_back(*O);
  178. // Consider uses of this instruction (outputs).
  179. for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
  180. UI != E; ++UI)
  181. if (!definedInRegion(*UI)) {
  182. outputs.push_back(I);
  183. break;
  184. }
  185. } // for: insts
  186. // Keep track of the exit blocks from the region.
  187. TerminatorInst *TI = BB->getTerminator();
  188. for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
  189. if (!BlocksToExtract.count(TI->getSuccessor(i)))
  190. ExitBlocks.insert(TI->getSuccessor(i));
  191. } // for: basic blocks
  192. NumExitBlocks = ExitBlocks.size();
  193. // Eliminate duplicates.
  194. std::sort(inputs.begin(), inputs.end());
  195. inputs.erase(std::unique(inputs.begin(), inputs.end()), inputs.end());
  196. std::sort(outputs.begin(), outputs.end());
  197. outputs.erase(std::unique(outputs.begin(), outputs.end()), outputs.end());
  198. }
  199. /// constructFunction - make a function based on inputs and outputs, as follows:
  200. /// f(in0, ..., inN, out0, ..., outN)
  201. ///
  202. Function *CodeExtractor::constructFunction(const Values &inputs,
  203. const Values &outputs,
  204. BasicBlock *header,
  205. BasicBlock *newRootNode,
  206. BasicBlock *newHeader,
  207. Function *oldFunction,
  208. Module *M) {
  209. DOUT << "inputs: " << inputs.size() << "\n";
  210. DOUT << "outputs: " << outputs.size() << "\n";
  211. LLVMContext &Context = header->getContext();
  212. // This function returns unsigned, outputs will go back by reference.
  213. switch (NumExitBlocks) {
  214. case 0:
  215. case 1: RetTy = Type::VoidTy; break;
  216. case 2: RetTy = Type::Int1Ty; break;
  217. default: RetTy = Type::Int16Ty; break;
  218. }
  219. std::vector<const Type*> paramTy;
  220. // Add the types of the input values to the function's argument list
  221. for (Values::const_iterator i = inputs.begin(),
  222. e = inputs.end(); i != e; ++i) {
  223. const Value *value = *i;
  224. DOUT << "value used in func: " << *value << "\n";
  225. paramTy.push_back(value->getType());
  226. }
  227. // Add the types of the output values to the function's argument list.
  228. for (Values::const_iterator I = outputs.begin(), E = outputs.end();
  229. I != E; ++I) {
  230. DOUT << "instr used in func: " << **I << "\n";
  231. if (AggregateArgs)
  232. paramTy.push_back((*I)->getType());
  233. else
  234. paramTy.push_back(
  235. header->getContext().getPointerTypeUnqual((*I)->getType()));
  236. }
  237. DOUT << "Function type: " << *RetTy << " f(";
  238. for (std::vector<const Type*>::iterator i = paramTy.begin(),
  239. e = paramTy.end(); i != e; ++i)
  240. DOUT << **i << ", ";
  241. DOUT << ")\n";
  242. if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
  243. PointerType *StructPtr =
  244. Context.getPointerTypeUnqual(Context.getStructType(paramTy));
  245. paramTy.clear();
  246. paramTy.push_back(StructPtr);
  247. }
  248. const FunctionType *funcType =
  249. Context.getFunctionType(RetTy, paramTy, false);
  250. // Create the new function
  251. Function *newFunction = Function::Create(funcType,
  252. GlobalValue::InternalLinkage,
  253. oldFunction->getName() + "_" +
  254. header->getName(), M);
  255. // If the old function is no-throw, so is the new one.
  256. if (oldFunction->doesNotThrow())
  257. newFunction->setDoesNotThrow(true);
  258. newFunction->getBasicBlockList().push_back(newRootNode);
  259. // Create an iterator to name all of the arguments we inserted.
  260. Function::arg_iterator AI = newFunction->arg_begin();
  261. // Rewrite all users of the inputs in the extracted region to use the
  262. // arguments (or appropriate addressing into struct) instead.
  263. for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
  264. Value *RewriteVal;
  265. if (AggregateArgs) {
  266. Value *Idx[2];
  267. Idx[0] = Context.getNullValue(Type::Int32Ty);
  268. Idx[1] = Context.getConstantInt(Type::Int32Ty, i);
  269. TerminatorInst *TI = newFunction->begin()->getTerminator();
  270. GetElementPtrInst *GEP =
  271. GetElementPtrInst::Create(AI, Idx, Idx+2,
  272. "gep_" + inputs[i]->getName(), TI);
  273. RewriteVal = new LoadInst(GEP, "loadgep_" + inputs[i]->getName(), TI);
  274. } else
  275. RewriteVal = AI++;
  276. std::vector<User*> Users(inputs[i]->use_begin(), inputs[i]->use_end());
  277. for (std::vector<User*>::iterator use = Users.begin(), useE = Users.end();
  278. use != useE; ++use)
  279. if (Instruction* inst = dyn_cast<Instruction>(*use))
  280. if (BlocksToExtract.count(inst->getParent()))
  281. inst->replaceUsesOfWith(inputs[i], RewriteVal);
  282. }
  283. // Set names for input and output arguments.
  284. if (!AggregateArgs) {
  285. AI = newFunction->arg_begin();
  286. for (unsigned i = 0, e = inputs.size(); i != e; ++i, ++AI)
  287. AI->setName(inputs[i]->getName());
  288. for (unsigned i = 0, e = outputs.size(); i != e; ++i, ++AI)
  289. AI->setName(outputs[i]->getName()+".out");
  290. }
  291. // Rewrite branches to basic blocks outside of the loop to new dummy blocks
  292. // within the new function. This must be done before we lose track of which
  293. // blocks were originally in the code region.
  294. std::vector<User*> Users(header->use_begin(), header->use_end());
  295. for (unsigned i = 0, e = Users.size(); i != e; ++i)
  296. // The BasicBlock which contains the branch is not in the region
  297. // modify the branch target to a new block
  298. if (TerminatorInst *TI = dyn_cast<TerminatorInst>(Users[i]))
  299. if (!BlocksToExtract.count(TI->getParent()) &&
  300. TI->getParent()->getParent() == oldFunction)
  301. TI->replaceUsesOfWith(header, newHeader);
  302. return newFunction;
  303. }
  304. /// emitCallAndSwitchStatement - This method sets up the caller side by adding
  305. /// the call instruction, splitting any PHI nodes in the header block as
  306. /// necessary.
  307. void CodeExtractor::
  308. emitCallAndSwitchStatement(Function *newFunction, BasicBlock *codeReplacer,
  309. Values &inputs, Values &outputs) {
  310. LLVMContext &Context = codeReplacer->getContext();
  311. // Emit a call to the new function, passing in: *pointer to struct (if
  312. // aggregating parameters), or plan inputs and allocated memory for outputs
  313. std::vector<Value*> params, StructValues, ReloadOutputs;
  314. // Add inputs as params, or to be filled into the struct
  315. for (Values::iterator i = inputs.begin(), e = inputs.end(); i != e; ++i)
  316. if (AggregateArgs)
  317. StructValues.push_back(*i);
  318. else
  319. params.push_back(*i);
  320. // Create allocas for the outputs
  321. for (Values::iterator i = outputs.begin(), e = outputs.end(); i != e; ++i) {
  322. if (AggregateArgs) {
  323. StructValues.push_back(*i);
  324. } else {
  325. AllocaInst *alloca =
  326. new AllocaInst((*i)->getType(), 0, (*i)->getName()+".loc",
  327. codeReplacer->getParent()->begin()->begin());
  328. ReloadOutputs.push_back(alloca);
  329. params.push_back(alloca);
  330. }
  331. }
  332. AllocaInst *Struct = 0;
  333. if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
  334. std::vector<const Type*> ArgTypes;
  335. for (Values::iterator v = StructValues.begin(),
  336. ve = StructValues.end(); v != ve; ++v)
  337. ArgTypes.push_back((*v)->getType());
  338. // Allocate a struct at the beginning of this function
  339. Type *StructArgTy = Context.getStructType(ArgTypes);
  340. Struct =
  341. new AllocaInst(StructArgTy, 0, "structArg",
  342. codeReplacer->getParent()->begin()->begin());
  343. params.push_back(Struct);
  344. for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
  345. Value *Idx[2];
  346. Idx[0] = Context.getNullValue(Type::Int32Ty);
  347. Idx[1] = Context.getConstantInt(Type::Int32Ty, i);
  348. GetElementPtrInst *GEP =
  349. GetElementPtrInst::Create(Struct, Idx, Idx + 2,
  350. "gep_" + StructValues[i]->getName());
  351. codeReplacer->getInstList().push_back(GEP);
  352. StoreInst *SI = new StoreInst(StructValues[i], GEP);
  353. codeReplacer->getInstList().push_back(SI);
  354. }
  355. }
  356. // Emit the call to the function
  357. CallInst *call = CallInst::Create(newFunction, params.begin(), params.end(),
  358. NumExitBlocks > 1 ? "targetBlock" : "");
  359. codeReplacer->getInstList().push_back(call);
  360. Function::arg_iterator OutputArgBegin = newFunction->arg_begin();
  361. unsigned FirstOut = inputs.size();
  362. if (!AggregateArgs)
  363. std::advance(OutputArgBegin, inputs.size());
  364. // Reload the outputs passed in by reference
  365. for (unsigned i = 0, e = outputs.size(); i != e; ++i) {
  366. Value *Output = 0;
  367. if (AggregateArgs) {
  368. Value *Idx[2];
  369. Idx[0] = Context.getNullValue(Type::Int32Ty);
  370. Idx[1] = Context.getConstantInt(Type::Int32Ty, FirstOut + i);
  371. GetElementPtrInst *GEP
  372. = GetElementPtrInst::Create(Struct, Idx, Idx + 2,
  373. "gep_reload_" + outputs[i]->getName());
  374. codeReplacer->getInstList().push_back(GEP);
  375. Output = GEP;
  376. } else {
  377. Output = ReloadOutputs[i];
  378. }
  379. LoadInst *load = new LoadInst(Output, outputs[i]->getName()+".reload");
  380. codeReplacer->getInstList().push_back(load);
  381. std::vector<User*> Users(outputs[i]->use_begin(), outputs[i]->use_end());
  382. for (unsigned u = 0, e = Users.size(); u != e; ++u) {
  383. Instruction *inst = cast<Instruction>(Users[u]);
  384. if (!BlocksToExtract.count(inst->getParent()))
  385. inst->replaceUsesOfWith(outputs[i], load);
  386. }
  387. }
  388. // Now we can emit a switch statement using the call as a value.
  389. SwitchInst *TheSwitch =
  390. SwitchInst::Create(Context.getNullValue(Type::Int16Ty),
  391. codeReplacer, 0, codeReplacer);
  392. // Since there may be multiple exits from the original region, make the new
  393. // function return an unsigned, switch on that number. This loop iterates
  394. // over all of the blocks in the extracted region, updating any terminator
  395. // instructions in the to-be-extracted region that branch to blocks that are
  396. // not in the region to be extracted.
  397. std::map<BasicBlock*, BasicBlock*> ExitBlockMap;
  398. unsigned switchVal = 0;
  399. for (std::set<BasicBlock*>::const_iterator i = BlocksToExtract.begin(),
  400. e = BlocksToExtract.end(); i != e; ++i) {
  401. TerminatorInst *TI = (*i)->getTerminator();
  402. for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
  403. if (!BlocksToExtract.count(TI->getSuccessor(i))) {
  404. BasicBlock *OldTarget = TI->getSuccessor(i);
  405. // add a new basic block which returns the appropriate value
  406. BasicBlock *&NewTarget = ExitBlockMap[OldTarget];
  407. if (!NewTarget) {
  408. // If we don't already have an exit stub for this non-extracted
  409. // destination, create one now!
  410. NewTarget = BasicBlock::Create(OldTarget->getName() + ".exitStub",
  411. newFunction);
  412. unsigned SuccNum = switchVal++;
  413. Value *brVal = 0;
  414. switch (NumExitBlocks) {
  415. case 0:
  416. case 1: break; // No value needed.
  417. case 2: // Conditional branch, return a bool
  418. brVal = Context.getConstantInt(Type::Int1Ty, !SuccNum);
  419. break;
  420. default:
  421. brVal = Context.getConstantInt(Type::Int16Ty, SuccNum);
  422. break;
  423. }
  424. ReturnInst *NTRet = ReturnInst::Create(brVal, NewTarget);
  425. // Update the switch instruction.
  426. TheSwitch->addCase(Context.getConstantInt(Type::Int16Ty, SuccNum),
  427. OldTarget);
  428. // Restore values just before we exit
  429. Function::arg_iterator OAI = OutputArgBegin;
  430. for (unsigned out = 0, e = outputs.size(); out != e; ++out) {
  431. // For an invoke, the normal destination is the only one that is
  432. // dominated by the result of the invocation
  433. BasicBlock *DefBlock = cast<Instruction>(outputs[out])->getParent();
  434. bool DominatesDef = true;
  435. if (InvokeInst *Invoke = dyn_cast<InvokeInst>(outputs[out])) {
  436. DefBlock = Invoke->getNormalDest();
  437. // Make sure we are looking at the original successor block, not
  438. // at a newly inserted exit block, which won't be in the dominator
  439. // info.
  440. for (std::map<BasicBlock*, BasicBlock*>::iterator I =
  441. ExitBlockMap.begin(), E = ExitBlockMap.end(); I != E; ++I)
  442. if (DefBlock == I->second) {
  443. DefBlock = I->first;
  444. break;
  445. }
  446. // In the extract block case, if the block we are extracting ends
  447. // with an invoke instruction, make sure that we don't emit a
  448. // store of the invoke value for the unwind block.
  449. if (!DT && DefBlock != OldTarget)
  450. DominatesDef = false;
  451. }
  452. if (DT)
  453. DominatesDef = DT->dominates(DefBlock, OldTarget);
  454. if (DominatesDef) {
  455. if (AggregateArgs) {
  456. Value *Idx[2];
  457. Idx[0] = Context.getNullValue(Type::Int32Ty);
  458. Idx[1] = Context.getConstantInt(Type::Int32Ty,FirstOut+out);
  459. GetElementPtrInst *GEP =
  460. GetElementPtrInst::Create(OAI, Idx, Idx + 2,
  461. "gep_" + outputs[out]->getName(),
  462. NTRet);
  463. new StoreInst(outputs[out], GEP, NTRet);
  464. } else {
  465. new StoreInst(outputs[out], OAI, NTRet);
  466. }
  467. }
  468. // Advance output iterator even if we don't emit a store
  469. if (!AggregateArgs) ++OAI;
  470. }
  471. }
  472. // rewrite the original branch instruction with this new target
  473. TI->setSuccessor(i, NewTarget);
  474. }
  475. }
  476. // Now that we've done the deed, simplify the switch instruction.
  477. const Type *OldFnRetTy = TheSwitch->getParent()->getParent()->getReturnType();
  478. switch (NumExitBlocks) {
  479. case 0:
  480. // There are no successors (the block containing the switch itself), which
  481. // means that previously this was the last part of the function, and hence
  482. // this should be rewritten as a `ret'
  483. // Check if the function should return a value
  484. if (OldFnRetTy == Type::VoidTy) {
  485. ReturnInst::Create(0, TheSwitch); // Return void
  486. } else if (OldFnRetTy == TheSwitch->getCondition()->getType()) {
  487. // return what we have
  488. ReturnInst::Create(TheSwitch->getCondition(), TheSwitch);
  489. } else {
  490. // Otherwise we must have code extracted an unwind or something, just
  491. // return whatever we want.
  492. ReturnInst::Create(Context.getNullValue(OldFnRetTy), TheSwitch);
  493. }
  494. TheSwitch->eraseFromParent();
  495. break;
  496. case 1:
  497. // Only a single destination, change the switch into an unconditional
  498. // branch.
  499. BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch);
  500. TheSwitch->eraseFromParent();
  501. break;
  502. case 2:
  503. BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getSuccessor(2),
  504. call, TheSwitch);
  505. TheSwitch->eraseFromParent();
  506. break;
  507. default:
  508. // Otherwise, make the default destination of the switch instruction be one
  509. // of the other successors.
  510. TheSwitch->setOperand(0, call);
  511. TheSwitch->setSuccessor(0, TheSwitch->getSuccessor(NumExitBlocks));
  512. TheSwitch->removeCase(NumExitBlocks); // Remove redundant case
  513. break;
  514. }
  515. }
  516. void CodeExtractor::moveCodeToFunction(Function *newFunction) {
  517. Function *oldFunc = (*BlocksToExtract.begin())->getParent();
  518. Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList();
  519. Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList();
  520. for (std::set<BasicBlock*>::const_iterator i = BlocksToExtract.begin(),
  521. e = BlocksToExtract.end(); i != e; ++i) {
  522. // Delete the basic block from the old function, and the list of blocks
  523. oldBlocks.remove(*i);
  524. // Insert this basic block into the new function
  525. newBlocks.push_back(*i);
  526. }
  527. }
  528. /// ExtractRegion - Removes a loop from a function, replaces it with a call to
  529. /// new function. Returns pointer to the new function.
  530. ///
  531. /// algorithm:
  532. ///
  533. /// find inputs and outputs for the region
  534. ///
  535. /// for inputs: add to function as args, map input instr* to arg#
  536. /// for outputs: add allocas for scalars,
  537. /// add to func as args, map output instr* to arg#
  538. ///
  539. /// rewrite func to use argument #s instead of instr*
  540. ///
  541. /// for each scalar output in the function: at every exit, store intermediate
  542. /// computed result back into memory.
  543. ///
  544. Function *CodeExtractor::
  545. ExtractCodeRegion(const std::vector<BasicBlock*> &code) {
  546. if (!isEligible(code))
  547. return 0;
  548. // 1) Find inputs, outputs
  549. // 2) Construct new function
  550. // * Add allocas for defs, pass as args by reference
  551. // * Pass in uses as args
  552. // 3) Move code region, add call instr to func
  553. //
  554. BlocksToExtract.insert(code.begin(), code.end());
  555. Values inputs, outputs;
  556. // Assumption: this is a single-entry code region, and the header is the first
  557. // block in the region.
  558. BasicBlock *header = code[0];
  559. for (unsigned i = 1, e = code.size(); i != e; ++i)
  560. for (pred_iterator PI = pred_begin(code[i]), E = pred_end(code[i]);
  561. PI != E; ++PI)
  562. assert(BlocksToExtract.count(*PI) &&
  563. "No blocks in this region may have entries from outside the region"
  564. " except for the first block!");
  565. // If we have to split PHI nodes or the entry block, do so now.
  566. severSplitPHINodes(header);
  567. // If we have any return instructions in the region, split those blocks so
  568. // that the return is not in the region.
  569. splitReturnBlocks();
  570. Function *oldFunction = header->getParent();
  571. // This takes place of the original loop
  572. BasicBlock *codeReplacer = BasicBlock::Create("codeRepl", oldFunction,
  573. header);
  574. // The new function needs a root node because other nodes can branch to the
  575. // head of the region, but the entry node of a function cannot have preds.
  576. BasicBlock *newFuncRoot = BasicBlock::Create("newFuncRoot");
  577. newFuncRoot->getInstList().push_back(BranchInst::Create(header));
  578. // Find inputs to, outputs from the code region.
  579. findInputsOutputs(inputs, outputs);
  580. // Construct new function based on inputs/outputs & add allocas for all defs.
  581. Function *newFunction = constructFunction(inputs, outputs, header,
  582. newFuncRoot,
  583. codeReplacer, oldFunction,
  584. oldFunction->getParent());
  585. emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs);
  586. moveCodeToFunction(newFunction);
  587. // Loop over all of the PHI nodes in the header block, and change any
  588. // references to the old incoming edge to be the new incoming edge.
  589. for (BasicBlock::iterator I = header->begin(); isa<PHINode>(I); ++I) {
  590. PHINode *PN = cast<PHINode>(I);
  591. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
  592. if (!BlocksToExtract.count(PN->getIncomingBlock(i)))
  593. PN->setIncomingBlock(i, newFuncRoot);
  594. }
  595. // Look at all successors of the codeReplacer block. If any of these blocks
  596. // had PHI nodes in them, we need to update the "from" block to be the code
  597. // replacer, not the original block in the extracted region.
  598. std::vector<BasicBlock*> Succs(succ_begin(codeReplacer),
  599. succ_end(codeReplacer));
  600. for (unsigned i = 0, e = Succs.size(); i != e; ++i)
  601. for (BasicBlock::iterator I = Succs[i]->begin(); isa<PHINode>(I); ++I) {
  602. PHINode *PN = cast<PHINode>(I);
  603. std::set<BasicBlock*> ProcessedPreds;
  604. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
  605. if (BlocksToExtract.count(PN->getIncomingBlock(i))) {
  606. if (ProcessedPreds.insert(PN->getIncomingBlock(i)).second)
  607. PN->setIncomingBlock(i, codeReplacer);
  608. else {
  609. // There were multiple entries in the PHI for this block, now there
  610. // is only one, so remove the duplicated entries.
  611. PN->removeIncomingValue(i, false);
  612. --i; --e;
  613. }
  614. }
  615. }
  616. //cerr << "NEW FUNCTION: " << *newFunction;
  617. // verifyFunction(*newFunction);
  618. // cerr << "OLD FUNCTION: " << *oldFunction;
  619. // verifyFunction(*oldFunction);
  620. DEBUG(if (verifyFunction(*newFunction))
  621. llvm_report_error("verifyFunction failed!"));
  622. return newFunction;
  623. }
  624. bool CodeExtractor::isEligible(const std::vector<BasicBlock*> &code) {
  625. // Deny code region if it contains allocas or vastarts.
  626. for (std::vector<BasicBlock*>::const_iterator BB = code.begin(), e=code.end();
  627. BB != e; ++BB)
  628. for (BasicBlock::const_iterator I = (*BB)->begin(), Ie = (*BB)->end();
  629. I != Ie; ++I)
  630. if (isa<AllocaInst>(*I))
  631. return false;
  632. else if (const CallInst *CI = dyn_cast<CallInst>(I))
  633. if (const Function *F = CI->getCalledFunction())
  634. if (F->getIntrinsicID() == Intrinsic::vastart)
  635. return false;
  636. return true;
  637. }
  638. /// ExtractCodeRegion - slurp a sequence of basic blocks into a brand new
  639. /// function
  640. ///
  641. Function* llvm::ExtractCodeRegion(DominatorTree &DT,
  642. const std::vector<BasicBlock*> &code,
  643. bool AggregateArgs) {
  644. return CodeExtractor(&DT, AggregateArgs).ExtractCodeRegion(code);
  645. }
  646. /// ExtractBasicBlock - slurp a natural loop into a brand new function
  647. ///
  648. Function* llvm::ExtractLoop(DominatorTree &DT, Loop *L, bool AggregateArgs) {
  649. return CodeExtractor(&DT, AggregateArgs).ExtractCodeRegion(L->getBlocks());
  650. }
  651. /// ExtractBasicBlock - slurp a basic block into a brand new function
  652. ///
  653. Function* llvm::ExtractBasicBlock(BasicBlock *BB, bool AggregateArgs) {
  654. std::vector<BasicBlock*> Blocks;
  655. Blocks.push_back(BB);
  656. return CodeExtractor(0, AggregateArgs).ExtractCodeRegion(Blocks);
  657. }