CloneFunction.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788
  1. //===- CloneFunction.cpp - Clone a function into another 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 CloneFunctionInto interface, which is used as the
  11. // low-level function cloner. This is used by the CloneFunction and function
  12. // inliner to do the dirty work of copying the body of a function around.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "llvm/Transforms/Utils/Cloning.h"
  16. #include "llvm/ADT/SmallVector.h"
  17. #include "llvm/Analysis/ConstantFolding.h"
  18. #include "llvm/Analysis/InstructionSimplify.h"
  19. #include "llvm/Analysis/LoopInfo.h"
  20. #include "llvm/IR/CFG.h"
  21. #include "llvm/IR/Constants.h"
  22. #include "llvm/IR/DebugInfo.h"
  23. #include "llvm/IR/DerivedTypes.h"
  24. #include "llvm/IR/Function.h"
  25. #include "llvm/IR/GlobalVariable.h"
  26. #include "llvm/IR/Instructions.h"
  27. #include "llvm/IR/IntrinsicInst.h"
  28. #include "llvm/IR/LLVMContext.h"
  29. #include "llvm/IR/Metadata.h"
  30. #include "llvm/IR/Module.h"
  31. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  32. #include "llvm/Transforms/Utils/Local.h"
  33. #include "llvm/Transforms/Utils/ValueMapper.h"
  34. #include <map>
  35. using namespace llvm;
  36. /// See comments in Cloning.h.
  37. BasicBlock *llvm::CloneBasicBlock(const BasicBlock *BB,
  38. ValueToValueMapTy &VMap,
  39. const Twine &NameSuffix, Function *F,
  40. ClonedCodeInfo *CodeInfo) {
  41. BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "", F);
  42. if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
  43. bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
  44. // Loop over all instructions, and copy them over.
  45. for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
  46. II != IE; ++II) {
  47. Instruction *NewInst = II->clone();
  48. if (II->hasName())
  49. NewInst->setName(II->getName()+NameSuffix);
  50. NewBB->getInstList().push_back(NewInst);
  51. VMap[II] = NewInst; // Add instruction map to value.
  52. hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
  53. if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
  54. if (isa<ConstantInt>(AI->getArraySize()))
  55. hasStaticAllocas = true;
  56. else
  57. hasDynamicAllocas = true;
  58. }
  59. }
  60. if (CodeInfo) {
  61. CodeInfo->ContainsCalls |= hasCalls;
  62. CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
  63. CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
  64. BB != &BB->getParent()->getEntryBlock();
  65. }
  66. return NewBB;
  67. }
  68. // Clone OldFunc into NewFunc, transforming the old arguments into references to
  69. // VMap values.
  70. //
  71. void llvm::CloneFunctionInto(Function *NewFunc, const Function *OldFunc,
  72. ValueToValueMapTy &VMap,
  73. bool ModuleLevelChanges,
  74. SmallVectorImpl<ReturnInst*> &Returns,
  75. const char *NameSuffix, ClonedCodeInfo *CodeInfo,
  76. ValueMapTypeRemapper *TypeMapper,
  77. ValueMaterializer *Materializer) {
  78. assert(NameSuffix && "NameSuffix cannot be null!");
  79. #ifndef NDEBUG
  80. for (Function::const_arg_iterator I = OldFunc->arg_begin(),
  81. E = OldFunc->arg_end(); I != E; ++I)
  82. assert(VMap.count(I) && "No mapping from source argument specified!");
  83. #endif
  84. // Copy all attributes other than those stored in the AttributeSet. We need
  85. // to remap the parameter indices of the AttributeSet.
  86. AttributeSet NewAttrs = NewFunc->getAttributes();
  87. NewFunc->copyAttributesFrom(OldFunc);
  88. NewFunc->setAttributes(NewAttrs);
  89. AttributeSet OldAttrs = OldFunc->getAttributes();
  90. // Clone any argument attributes that are present in the VMap.
  91. for (const Argument &OldArg : OldFunc->args())
  92. if (Argument *NewArg = dyn_cast<Argument>(VMap[&OldArg])) {
  93. AttributeSet attrs =
  94. OldAttrs.getParamAttributes(OldArg.getArgNo() + 1);
  95. if (attrs.getNumSlots() > 0)
  96. NewArg->addAttr(attrs);
  97. }
  98. NewFunc->setAttributes(
  99. NewFunc->getAttributes()
  100. .addAttributes(NewFunc->getContext(), AttributeSet::ReturnIndex,
  101. OldAttrs.getRetAttributes())
  102. .addAttributes(NewFunc->getContext(), AttributeSet::FunctionIndex,
  103. OldAttrs.getFnAttributes()));
  104. // Loop over all of the basic blocks in the function, cloning them as
  105. // appropriate. Note that we save BE this way in order to handle cloning of
  106. // recursive functions into themselves.
  107. //
  108. for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
  109. BI != BE; ++BI) {
  110. const BasicBlock &BB = *BI;
  111. // Create a new basic block and copy instructions into it!
  112. BasicBlock *CBB = CloneBasicBlock(&BB, VMap, NameSuffix, NewFunc, CodeInfo);
  113. // Add basic block mapping.
  114. VMap[&BB] = CBB;
  115. // It is only legal to clone a function if a block address within that
  116. // function is never referenced outside of the function. Given that, we
  117. // want to map block addresses from the old function to block addresses in
  118. // the clone. (This is different from the generic ValueMapper
  119. // implementation, which generates an invalid blockaddress when
  120. // cloning a function.)
  121. if (BB.hasAddressTaken()) {
  122. Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc),
  123. const_cast<BasicBlock*>(&BB));
  124. VMap[OldBBAddr] = BlockAddress::get(NewFunc, CBB);
  125. }
  126. // Note return instructions for the caller.
  127. if (ReturnInst *RI = dyn_cast<ReturnInst>(CBB->getTerminator()))
  128. Returns.push_back(RI);
  129. }
  130. // Loop over all of the instructions in the function, fixing up operand
  131. // references as we go. This uses VMap to do all the hard work.
  132. for (Function::iterator BB = cast<BasicBlock>(VMap[OldFunc->begin()]),
  133. BE = NewFunc->end(); BB != BE; ++BB)
  134. // Loop over all instructions, fixing each one as we find it...
  135. for (BasicBlock::iterator II = BB->begin(); II != BB->end(); ++II)
  136. RemapInstruction(II, VMap,
  137. ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
  138. TypeMapper, Materializer);
  139. }
  140. // Find the MDNode which corresponds to the subprogram data that described F.
  141. static DISubprogram *FindSubprogram(const Function *F,
  142. DebugInfoFinder &Finder) {
  143. for (DISubprogram *Subprogram : Finder.subprograms()) {
  144. if (Subprogram->describes(F))
  145. return Subprogram;
  146. }
  147. return nullptr;
  148. }
  149. // Add an operand to an existing MDNode. The new operand will be added at the
  150. // back of the operand list.
  151. static void AddOperand(DICompileUnit *CU, DISubprogramArray SPs,
  152. Metadata *NewSP) {
  153. SmallVector<Metadata *, 16> NewSPs;
  154. NewSPs.reserve(SPs.size() + 1);
  155. for (auto *SP : SPs)
  156. NewSPs.push_back(SP);
  157. NewSPs.push_back(NewSP);
  158. CU->replaceSubprograms(MDTuple::get(CU->getContext(), NewSPs));
  159. }
  160. // Clone the module-level debug info associated with OldFunc. The cloned data
  161. // will point to NewFunc instead.
  162. static void CloneDebugInfoMetadata(Function *NewFunc, const Function *OldFunc,
  163. ValueToValueMapTy &VMap) {
  164. DebugInfoFinder Finder;
  165. Finder.processModule(*OldFunc->getParent());
  166. const DISubprogram *OldSubprogramMDNode = FindSubprogram(OldFunc, Finder);
  167. if (!OldSubprogramMDNode) return;
  168. // Ensure that OldFunc appears in the map.
  169. // (if it's already there it must point to NewFunc anyway)
  170. VMap[OldFunc] = NewFunc;
  171. auto *NewSubprogram =
  172. cast<DISubprogram>(MapMetadata(OldSubprogramMDNode, VMap));
  173. for (auto *CU : Finder.compile_units()) {
  174. auto Subprograms = CU->getSubprograms();
  175. // If the compile unit's function list contains the old function, it should
  176. // also contain the new one.
  177. for (auto *SP : Subprograms) {
  178. if (SP == OldSubprogramMDNode) {
  179. AddOperand(CU, Subprograms, NewSubprogram);
  180. break;
  181. }
  182. }
  183. }
  184. }
  185. /// Return a copy of the specified function, but without
  186. /// embedding the function into another module. Also, any references specified
  187. /// in the VMap are changed to refer to their mapped value instead of the
  188. /// original one. If any of the arguments to the function are in the VMap,
  189. /// the arguments are deleted from the resultant function. The VMap is
  190. /// updated to include mappings from all of the instructions and basicblocks in
  191. /// the function from their old to new values.
  192. ///
  193. Function *llvm::CloneFunction(const Function *F, ValueToValueMapTy &VMap,
  194. bool ModuleLevelChanges,
  195. ClonedCodeInfo *CodeInfo) {
  196. std::vector<Type*> ArgTypes;
  197. // The user might be deleting arguments to the function by specifying them in
  198. // the VMap. If so, we need to not add the arguments to the arg ty vector
  199. //
  200. for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
  201. I != E; ++I)
  202. if (VMap.count(I) == 0) // Haven't mapped the argument to anything yet?
  203. ArgTypes.push_back(I->getType());
  204. // Create a new function type...
  205. FunctionType *FTy = FunctionType::get(F->getFunctionType()->getReturnType(),
  206. ArgTypes, F->getFunctionType()->isVarArg());
  207. // Create the new function...
  208. Function *NewF = Function::Create(FTy, F->getLinkage(), F->getName());
  209. // Loop over the arguments, copying the names of the mapped arguments over...
  210. Function::arg_iterator DestI = NewF->arg_begin();
  211. for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
  212. I != E; ++I)
  213. if (VMap.count(I) == 0) { // Is this argument preserved?
  214. DestI->setName(I->getName()); // Copy the name over...
  215. VMap[I] = DestI++; // Add mapping to VMap
  216. }
  217. if (ModuleLevelChanges)
  218. CloneDebugInfoMetadata(NewF, F, VMap);
  219. SmallVector<ReturnInst*, 8> Returns; // Ignore returns cloned.
  220. CloneFunctionInto(NewF, F, VMap, ModuleLevelChanges, Returns, "", CodeInfo);
  221. return NewF;
  222. }
  223. namespace {
  224. /// This is a private class used to implement CloneAndPruneFunctionInto.
  225. struct PruningFunctionCloner {
  226. Function *NewFunc;
  227. const Function *OldFunc;
  228. ValueToValueMapTy &VMap;
  229. bool ModuleLevelChanges;
  230. const char *NameSuffix;
  231. ClonedCodeInfo *CodeInfo;
  232. CloningDirector *Director;
  233. ValueMapTypeRemapper *TypeMapper;
  234. ValueMaterializer *Materializer;
  235. public:
  236. PruningFunctionCloner(Function *newFunc, const Function *oldFunc,
  237. ValueToValueMapTy &valueMap, bool moduleLevelChanges,
  238. const char *nameSuffix, ClonedCodeInfo *codeInfo,
  239. CloningDirector *Director)
  240. : NewFunc(newFunc), OldFunc(oldFunc), VMap(valueMap),
  241. ModuleLevelChanges(moduleLevelChanges), NameSuffix(nameSuffix),
  242. CodeInfo(codeInfo), Director(Director) {
  243. // These are optional components. The Director may return null.
  244. if (Director) {
  245. TypeMapper = Director->getTypeRemapper();
  246. Materializer = Director->getValueMaterializer();
  247. } else {
  248. TypeMapper = nullptr;
  249. Materializer = nullptr;
  250. }
  251. }
  252. /// The specified block is found to be reachable, clone it and
  253. /// anything that it can reach.
  254. void CloneBlock(const BasicBlock *BB,
  255. BasicBlock::const_iterator StartingInst,
  256. std::vector<const BasicBlock*> &ToClone);
  257. };
  258. }
  259. /// The specified block is found to be reachable, clone it and
  260. /// anything that it can reach.
  261. void PruningFunctionCloner::CloneBlock(const BasicBlock *BB,
  262. BasicBlock::const_iterator StartingInst,
  263. std::vector<const BasicBlock*> &ToClone){
  264. WeakVH &BBEntry = VMap[BB];
  265. // Have we already cloned this block?
  266. if (BBEntry) return;
  267. // Nope, clone it now.
  268. BasicBlock *NewBB;
  269. BBEntry = NewBB = BasicBlock::Create(BB->getContext());
  270. if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
  271. // It is only legal to clone a function if a block address within that
  272. // function is never referenced outside of the function. Given that, we
  273. // want to map block addresses from the old function to block addresses in
  274. // the clone. (This is different from the generic ValueMapper
  275. // implementation, which generates an invalid blockaddress when
  276. // cloning a function.)
  277. //
  278. // Note that we don't need to fix the mapping for unreachable blocks;
  279. // the default mapping there is safe.
  280. if (BB->hasAddressTaken()) {
  281. Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc),
  282. const_cast<BasicBlock*>(BB));
  283. VMap[OldBBAddr] = BlockAddress::get(NewFunc, NewBB);
  284. }
  285. bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
  286. // Loop over all instructions, and copy them over, DCE'ing as we go. This
  287. // loop doesn't include the terminator.
  288. for (BasicBlock::const_iterator II = StartingInst, IE = --BB->end();
  289. II != IE; ++II) {
  290. // If the "Director" remaps the instruction, don't clone it.
  291. if (Director) {
  292. CloningDirector::CloningAction Action
  293. = Director->handleInstruction(VMap, II, NewBB);
  294. // If the cloning director says stop, we want to stop everything, not
  295. // just break out of the loop (which would cause the terminator to be
  296. // cloned). The cloning director is responsible for inserting a proper
  297. // terminator into the new basic block in this case.
  298. if (Action == CloningDirector::StopCloningBB)
  299. return;
  300. // If the cloning director says skip, continue to the next instruction.
  301. // In this case, the cloning director is responsible for mapping the
  302. // skipped instruction to some value that is defined in the new
  303. // basic block.
  304. if (Action == CloningDirector::SkipInstruction)
  305. continue;
  306. }
  307. Instruction *NewInst = II->clone();
  308. // Eagerly remap operands to the newly cloned instruction, except for PHI
  309. // nodes for which we defer processing until we update the CFG.
  310. if (!isa<PHINode>(NewInst)) {
  311. RemapInstruction(NewInst, VMap,
  312. ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
  313. TypeMapper, Materializer);
  314. // If we can simplify this instruction to some other value, simply add
  315. // a mapping to that value rather than inserting a new instruction into
  316. // the basic block.
  317. if (Value *V =
  318. SimplifyInstruction(NewInst, BB->getModule()->getDataLayout())) {
  319. // On the off-chance that this simplifies to an instruction in the old
  320. // function, map it back into the new function.
  321. if (Value *MappedV = VMap.lookup(V))
  322. V = MappedV;
  323. VMap[II] = V;
  324. delete NewInst;
  325. continue;
  326. }
  327. }
  328. if (II->hasName())
  329. NewInst->setName(II->getName()+NameSuffix);
  330. VMap[II] = NewInst; // Add instruction map to value.
  331. NewBB->getInstList().push_back(NewInst);
  332. hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
  333. if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
  334. if (isa<ConstantInt>(AI->getArraySize()))
  335. hasStaticAllocas = true;
  336. else
  337. hasDynamicAllocas = true;
  338. }
  339. }
  340. // Finally, clone over the terminator.
  341. const TerminatorInst *OldTI = BB->getTerminator();
  342. bool TerminatorDone = false;
  343. if (Director) {
  344. CloningDirector::CloningAction Action
  345. = Director->handleInstruction(VMap, OldTI, NewBB);
  346. // If the cloning director says stop, we want to stop everything, not
  347. // just break out of the loop (which would cause the terminator to be
  348. // cloned). The cloning director is responsible for inserting a proper
  349. // terminator into the new basic block in this case.
  350. if (Action == CloningDirector::StopCloningBB)
  351. return;
  352. if (Action == CloningDirector::CloneSuccessors) {
  353. // If the director says to skip with a terminate instruction, we still
  354. // need to clone this block's successors.
  355. const TerminatorInst *TI = NewBB->getTerminator();
  356. for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
  357. ToClone.push_back(TI->getSuccessor(i));
  358. return;
  359. }
  360. assert(Action != CloningDirector::SkipInstruction &&
  361. "SkipInstruction is not valid for terminators.");
  362. }
  363. if (const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) {
  364. if (BI->isConditional()) {
  365. // If the condition was a known constant in the callee...
  366. ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
  367. // Or is a known constant in the caller...
  368. if (!Cond) {
  369. Value *V = VMap[BI->getCondition()];
  370. Cond = dyn_cast_or_null<ConstantInt>(V);
  371. }
  372. // Constant fold to uncond branch!
  373. if (Cond) {
  374. BasicBlock *Dest = BI->getSuccessor(!Cond->getZExtValue());
  375. VMap[OldTI] = BranchInst::Create(Dest, NewBB);
  376. ToClone.push_back(Dest);
  377. TerminatorDone = true;
  378. }
  379. }
  380. } else if (const SwitchInst *SI = dyn_cast<SwitchInst>(OldTI)) {
  381. // If switching on a value known constant in the caller.
  382. ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition());
  383. if (!Cond) { // Or known constant after constant prop in the callee...
  384. Value *V = VMap[SI->getCondition()];
  385. Cond = dyn_cast_or_null<ConstantInt>(V);
  386. }
  387. if (Cond) { // Constant fold to uncond branch!
  388. SwitchInst::ConstCaseIt Case = SI->findCaseValue(Cond);
  389. BasicBlock *Dest = const_cast<BasicBlock*>(Case.getCaseSuccessor());
  390. VMap[OldTI] = BranchInst::Create(Dest, NewBB);
  391. ToClone.push_back(Dest);
  392. TerminatorDone = true;
  393. }
  394. }
  395. if (!TerminatorDone) {
  396. Instruction *NewInst = OldTI->clone();
  397. if (OldTI->hasName())
  398. NewInst->setName(OldTI->getName()+NameSuffix);
  399. NewBB->getInstList().push_back(NewInst);
  400. VMap[OldTI] = NewInst; // Add instruction map to value.
  401. // Recursively clone any reachable successor blocks.
  402. const TerminatorInst *TI = BB->getTerminator();
  403. for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
  404. ToClone.push_back(TI->getSuccessor(i));
  405. }
  406. if (CodeInfo) {
  407. CodeInfo->ContainsCalls |= hasCalls;
  408. CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
  409. CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
  410. BB != &BB->getParent()->front();
  411. }
  412. }
  413. /// This works like CloneAndPruneFunctionInto, except that it does not clone the
  414. /// entire function. Instead it starts at an instruction provided by the caller
  415. /// and copies (and prunes) only the code reachable from that instruction.
  416. void llvm::CloneAndPruneIntoFromInst(Function *NewFunc, const Function *OldFunc,
  417. const Instruction *StartingInst,
  418. ValueToValueMapTy &VMap,
  419. bool ModuleLevelChanges,
  420. SmallVectorImpl<ReturnInst *> &Returns,
  421. const char *NameSuffix,
  422. ClonedCodeInfo *CodeInfo,
  423. CloningDirector *Director) {
  424. assert(NameSuffix && "NameSuffix cannot be null!");
  425. ValueMapTypeRemapper *TypeMapper = nullptr;
  426. ValueMaterializer *Materializer = nullptr;
  427. if (Director) {
  428. TypeMapper = Director->getTypeRemapper();
  429. Materializer = Director->getValueMaterializer();
  430. }
  431. #ifndef NDEBUG
  432. // If the cloning starts at the begining of the function, verify that
  433. // the function arguments are mapped.
  434. if (!StartingInst)
  435. for (Function::const_arg_iterator II = OldFunc->arg_begin(),
  436. E = OldFunc->arg_end(); II != E; ++II)
  437. assert(VMap.count(II) && "No mapping from source argument specified!");
  438. #endif
  439. PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges,
  440. NameSuffix, CodeInfo, Director);
  441. const BasicBlock *StartingBB;
  442. if (StartingInst)
  443. StartingBB = StartingInst->getParent();
  444. else {
  445. StartingBB = &OldFunc->getEntryBlock();
  446. StartingInst = StartingBB->begin();
  447. }
  448. // Clone the entry block, and anything recursively reachable from it.
  449. std::vector<const BasicBlock*> CloneWorklist;
  450. PFC.CloneBlock(StartingBB, StartingInst, CloneWorklist);
  451. while (!CloneWorklist.empty()) {
  452. const BasicBlock *BB = CloneWorklist.back();
  453. CloneWorklist.pop_back();
  454. PFC.CloneBlock(BB, BB->begin(), CloneWorklist);
  455. }
  456. // Loop over all of the basic blocks in the old function. If the block was
  457. // reachable, we have cloned it and the old block is now in the value map:
  458. // insert it into the new function in the right order. If not, ignore it.
  459. //
  460. // Defer PHI resolution until rest of function is resolved.
  461. SmallVector<const PHINode*, 16> PHIToResolve;
  462. for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
  463. BI != BE; ++BI) {
  464. Value *V = VMap[BI];
  465. BasicBlock *NewBB = cast_or_null<BasicBlock>(V);
  466. if (!NewBB) continue; // Dead block.
  467. // Add the new block to the new function.
  468. NewFunc->getBasicBlockList().push_back(NewBB);
  469. // Handle PHI nodes specially, as we have to remove references to dead
  470. // blocks.
  471. for (BasicBlock::const_iterator I = BI->begin(), E = BI->end(); I != E; ++I) {
  472. // PHI nodes may have been remapped to non-PHI nodes by the caller or
  473. // during the cloning process.
  474. if (const PHINode *PN = dyn_cast<PHINode>(I)) {
  475. if (isa<PHINode>(VMap[PN]))
  476. PHIToResolve.push_back(PN);
  477. else
  478. break;
  479. } else {
  480. break;
  481. }
  482. }
  483. // Finally, remap the terminator instructions, as those can't be remapped
  484. // until all BBs are mapped.
  485. RemapInstruction(NewBB->getTerminator(), VMap,
  486. ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
  487. TypeMapper, Materializer);
  488. }
  489. // Defer PHI resolution until rest of function is resolved, PHI resolution
  490. // requires the CFG to be up-to-date.
  491. for (unsigned phino = 0, e = PHIToResolve.size(); phino != e; ) {
  492. const PHINode *OPN = PHIToResolve[phino];
  493. unsigned NumPreds = OPN->getNumIncomingValues();
  494. const BasicBlock *OldBB = OPN->getParent();
  495. BasicBlock *NewBB = cast<BasicBlock>(VMap[OldBB]);
  496. // Map operands for blocks that are live and remove operands for blocks
  497. // that are dead.
  498. for (; phino != PHIToResolve.size() &&
  499. PHIToResolve[phino]->getParent() == OldBB; ++phino) {
  500. OPN = PHIToResolve[phino];
  501. PHINode *PN = cast<PHINode>(VMap[OPN]);
  502. for (unsigned pred = 0, e = NumPreds; pred != e; ++pred) {
  503. Value *V = VMap[PN->getIncomingBlock(pred)];
  504. if (BasicBlock *MappedBlock = cast_or_null<BasicBlock>(V)) {
  505. Value *InVal = MapValue(PN->getIncomingValue(pred),
  506. VMap,
  507. ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
  508. assert(InVal && "Unknown input value?");
  509. PN->setIncomingValue(pred, InVal);
  510. PN->setIncomingBlock(pred, MappedBlock);
  511. } else {
  512. PN->removeIncomingValue(pred, false);
  513. --pred, --e; // Revisit the next entry.
  514. }
  515. }
  516. }
  517. // The loop above has removed PHI entries for those blocks that are dead
  518. // and has updated others. However, if a block is live (i.e. copied over)
  519. // but its terminator has been changed to not go to this block, then our
  520. // phi nodes will have invalid entries. Update the PHI nodes in this
  521. // case.
  522. PHINode *PN = cast<PHINode>(NewBB->begin());
  523. NumPreds = std::distance(pred_begin(NewBB), pred_end(NewBB));
  524. if (NumPreds != PN->getNumIncomingValues()) {
  525. assert(NumPreds < PN->getNumIncomingValues());
  526. // Count how many times each predecessor comes to this block.
  527. std::map<BasicBlock*, unsigned> PredCount;
  528. for (pred_iterator PI = pred_begin(NewBB), E = pred_end(NewBB);
  529. PI != E; ++PI)
  530. --PredCount[*PI];
  531. // Figure out how many entries to remove from each PHI.
  532. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
  533. ++PredCount[PN->getIncomingBlock(i)];
  534. // At this point, the excess predecessor entries are positive in the
  535. // map. Loop over all of the PHIs and remove excess predecessor
  536. // entries.
  537. BasicBlock::iterator I = NewBB->begin();
  538. for (; (PN = dyn_cast<PHINode>(I)); ++I) {
  539. for (std::map<BasicBlock*, unsigned>::iterator PCI =PredCount.begin(),
  540. E = PredCount.end(); PCI != E; ++PCI) {
  541. BasicBlock *Pred = PCI->first;
  542. for (unsigned NumToRemove = PCI->second; NumToRemove; --NumToRemove)
  543. PN->removeIncomingValue(Pred, false);
  544. }
  545. }
  546. }
  547. // If the loops above have made these phi nodes have 0 or 1 operand,
  548. // replace them with undef or the input value. We must do this for
  549. // correctness, because 0-operand phis are not valid.
  550. PN = cast<PHINode>(NewBB->begin());
  551. if (PN->getNumIncomingValues() == 0) {
  552. BasicBlock::iterator I = NewBB->begin();
  553. BasicBlock::const_iterator OldI = OldBB->begin();
  554. while ((PN = dyn_cast<PHINode>(I++))) {
  555. Value *NV = UndefValue::get(PN->getType());
  556. PN->replaceAllUsesWith(NV);
  557. assert(VMap[OldI] == PN && "VMap mismatch");
  558. VMap[OldI] = NV;
  559. PN->eraseFromParent();
  560. ++OldI;
  561. }
  562. }
  563. }
  564. // Make a second pass over the PHINodes now that all of them have been
  565. // remapped into the new function, simplifying the PHINode and performing any
  566. // recursive simplifications exposed. This will transparently update the
  567. // WeakVH in the VMap. Notably, we rely on that so that if we coalesce
  568. // two PHINodes, the iteration over the old PHIs remains valid, and the
  569. // mapping will just map us to the new node (which may not even be a PHI
  570. // node).
  571. for (unsigned Idx = 0, Size = PHIToResolve.size(); Idx != Size; ++Idx)
  572. if (PHINode *PN = dyn_cast<PHINode>(VMap[PHIToResolve[Idx]]))
  573. recursivelySimplifyInstruction(PN);
  574. // Now that the inlined function body has been fully constructed, go through
  575. // and zap unconditional fall-through branches. This happens all the time when
  576. // specializing code: code specialization turns conditional branches into
  577. // uncond branches, and this code folds them.
  578. Function::iterator Begin = cast<BasicBlock>(VMap[StartingBB]);
  579. Function::iterator I = Begin;
  580. while (I != NewFunc->end()) {
  581. // Check if this block has become dead during inlining or other
  582. // simplifications. Note that the first block will appear dead, as it has
  583. // not yet been wired up properly.
  584. if (I != Begin && (pred_begin(I) == pred_end(I) ||
  585. I->getSinglePredecessor() == I)) {
  586. BasicBlock *DeadBB = I++;
  587. DeleteDeadBlock(DeadBB);
  588. continue;
  589. }
  590. // We need to simplify conditional branches and switches with a constant
  591. // operand. We try to prune these out when cloning, but if the
  592. // simplification required looking through PHI nodes, those are only
  593. // available after forming the full basic block. That may leave some here,
  594. // and we still want to prune the dead code as early as possible.
  595. ConstantFoldTerminator(I);
  596. BranchInst *BI = dyn_cast<BranchInst>(I->getTerminator());
  597. if (!BI || BI->isConditional()) { ++I; continue; }
  598. BasicBlock *Dest = BI->getSuccessor(0);
  599. if (!Dest->getSinglePredecessor()) {
  600. ++I; continue;
  601. }
  602. // We shouldn't be able to get single-entry PHI nodes here, as instsimplify
  603. // above should have zapped all of them..
  604. assert(!isa<PHINode>(Dest->begin()));
  605. // We know all single-entry PHI nodes in the inlined function have been
  606. // removed, so we just need to splice the blocks.
  607. BI->eraseFromParent();
  608. // Make all PHI nodes that referred to Dest now refer to I as their source.
  609. Dest->replaceAllUsesWith(I);
  610. // Move all the instructions in the succ to the pred.
  611. I->getInstList().splice(I->end(), Dest->getInstList());
  612. // Remove the dest block.
  613. Dest->eraseFromParent();
  614. // Do not increment I, iteratively merge all things this block branches to.
  615. }
  616. // Make a final pass over the basic blocks from the old function to gather
  617. // any return instructions which survived folding. We have to do this here
  618. // because we can iteratively remove and merge returns above.
  619. for (Function::iterator I = cast<BasicBlock>(VMap[StartingBB]),
  620. E = NewFunc->end();
  621. I != E; ++I)
  622. if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator()))
  623. Returns.push_back(RI);
  624. }
  625. /// This works exactly like CloneFunctionInto,
  626. /// except that it does some simple constant prop and DCE on the fly. The
  627. /// effect of this is to copy significantly less code in cases where (for
  628. /// example) a function call with constant arguments is inlined, and those
  629. /// constant arguments cause a significant amount of code in the callee to be
  630. /// dead. Since this doesn't produce an exact copy of the input, it can't be
  631. /// used for things like CloneFunction or CloneModule.
  632. void llvm::CloneAndPruneFunctionInto(Function *NewFunc, const Function *OldFunc,
  633. ValueToValueMapTy &VMap,
  634. bool ModuleLevelChanges,
  635. SmallVectorImpl<ReturnInst*> &Returns,
  636. const char *NameSuffix,
  637. ClonedCodeInfo *CodeInfo,
  638. Instruction *TheCall) {
  639. CloneAndPruneIntoFromInst(NewFunc, OldFunc, OldFunc->front().begin(), VMap,
  640. ModuleLevelChanges, Returns, NameSuffix, CodeInfo,
  641. nullptr);
  642. }
  643. /// \brief Remaps instructions in \p Blocks using the mapping in \p VMap.
  644. void llvm::remapInstructionsInBlocks(
  645. const SmallVectorImpl<BasicBlock *> &Blocks, ValueToValueMapTy &VMap) {
  646. // Rewrite the code to refer to itself.
  647. for (auto *BB : Blocks)
  648. for (auto &Inst : *BB)
  649. RemapInstruction(&Inst, VMap,
  650. RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
  651. }
  652. /// \brief Clones a loop \p OrigLoop. Returns the loop and the blocks in \p
  653. /// Blocks.
  654. ///
  655. /// Updates LoopInfo and DominatorTree assuming the loop is dominated by block
  656. /// \p LoopDomBB. Insert the new blocks before block specified in \p Before.
  657. Loop *llvm::cloneLoopWithPreheader(BasicBlock *Before, BasicBlock *LoopDomBB,
  658. Loop *OrigLoop, ValueToValueMapTy &VMap,
  659. const Twine &NameSuffix, LoopInfo *LI,
  660. DominatorTree *DT,
  661. SmallVectorImpl<BasicBlock *> &Blocks) {
  662. Function *F = OrigLoop->getHeader()->getParent();
  663. Loop *ParentLoop = OrigLoop->getParentLoop();
  664. Loop *NewLoop = new Loop();
  665. if (ParentLoop)
  666. ParentLoop->addChildLoop(NewLoop);
  667. else
  668. LI->addTopLevelLoop(NewLoop);
  669. BasicBlock *OrigPH = OrigLoop->getLoopPreheader();
  670. assert(OrigPH && "No preheader");
  671. BasicBlock *NewPH = CloneBasicBlock(OrigPH, VMap, NameSuffix, F);
  672. // To rename the loop PHIs.
  673. VMap[OrigPH] = NewPH;
  674. Blocks.push_back(NewPH);
  675. // Update LoopInfo.
  676. if (ParentLoop)
  677. ParentLoop->addBasicBlockToLoop(NewPH, *LI);
  678. // Update DominatorTree.
  679. DT->addNewBlock(NewPH, LoopDomBB);
  680. for (BasicBlock *BB : OrigLoop->getBlocks()) {
  681. BasicBlock *NewBB = CloneBasicBlock(BB, VMap, NameSuffix, F);
  682. VMap[BB] = NewBB;
  683. // Update LoopInfo.
  684. NewLoop->addBasicBlockToLoop(NewBB, *LI);
  685. // Update DominatorTree.
  686. BasicBlock *IDomBB = DT->getNode(BB)->getIDom()->getBlock();
  687. DT->addNewBlock(NewBB, cast<BasicBlock>(VMap[IDomBB]));
  688. Blocks.push_back(NewBB);
  689. }
  690. // Move them physically from the end of the block list.
  691. F->getBasicBlockList().splice(Before, F->getBasicBlockList(), NewPH);
  692. F->getBasicBlockList().splice(Before, F->getBasicBlockList(),
  693. NewLoop->getHeader(), F->end());
  694. return NewLoop;
  695. }