CodeExtractor.cpp 31 KB

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