1 //===- CloneFunction.cpp - Clone a function into another function ---------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the CloneFunctionInto interface, which is used as the
10 // low-level function cloner.  This is used by the CloneFunction and function
11 // inliner to do the dirty work of copying the body of a function around.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/ADT/SetVector.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/Analysis/ConstantFolding.h"
18 #include "llvm/Analysis/DomTreeUpdater.h"
19 #include "llvm/Analysis/InstructionSimplify.h"
20 #include "llvm/Analysis/LoopInfo.h"
21 #include "llvm/IR/CFG.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DebugInfo.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/Function.h"
26 #include "llvm/IR/GlobalVariable.h"
27 #include "llvm/IR/Instructions.h"
28 #include "llvm/IR/IntrinsicInst.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/Metadata.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
33 #include "llvm/Transforms/Utils/Cloning.h"
34 #include "llvm/Transforms/Utils/Local.h"
35 #include "llvm/Transforms/Utils/ValueMapper.h"
36 #include <map>
37 using namespace llvm;
38 
39 /// See comments in Cloning.h.
40 BasicBlock *llvm::CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap,
41                                   const Twine &NameSuffix, Function *F,
42                                   ClonedCodeInfo *CodeInfo,
43                                   DebugInfoFinder *DIFinder) {
44   DenseMap<const MDNode *, MDNode *> Cache;
45   BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "", F);
46   if (BB->hasName())
47     NewBB->setName(BB->getName() + NameSuffix);
48 
49   bool hasCalls = false, hasDynamicAllocas = false;
50   Module *TheModule = F ? F->getParent() : nullptr;
51 
52   // Loop over all instructions, and copy them over.
53   for (const Instruction &I : *BB) {
54     if (DIFinder && TheModule)
55       DIFinder->processInstruction(*TheModule, I);
56 
57     Instruction *NewInst = I.clone();
58     if (I.hasName())
59       NewInst->setName(I.getName() + NameSuffix);
60     NewBB->getInstList().push_back(NewInst);
61     VMap[&I] = NewInst; // Add instruction map to value.
62 
63     hasCalls |= (isa<CallInst>(I) && !isa<DbgInfoIntrinsic>(I));
64     if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
65       if (!AI->isStaticAlloca()) {
66         hasDynamicAllocas = true;
67       }
68     }
69   }
70 
71   if (CodeInfo) {
72     CodeInfo->ContainsCalls          |= hasCalls;
73     CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
74   }
75   return NewBB;
76 }
77 
78 // Clone OldFunc into NewFunc, transforming the old arguments into references to
79 // VMap values.
80 //
81 void llvm::CloneFunctionInto(Function *NewFunc, const Function *OldFunc,
82                              ValueToValueMapTy &VMap,
83                              bool ModuleLevelChanges,
84                              SmallVectorImpl<ReturnInst*> &Returns,
85                              const char *NameSuffix, ClonedCodeInfo *CodeInfo,
86                              ValueMapTypeRemapper *TypeMapper,
87                              ValueMaterializer *Materializer) {
88   assert(NameSuffix && "NameSuffix cannot be null!");
89 
90 #ifndef NDEBUG
91   for (const Argument &I : OldFunc->args())
92     assert(VMap.count(&I) && "No mapping from source argument specified!");
93 #endif
94 
95   // Copy all attributes other than those stored in the AttributeList.  We need
96   // to remap the parameter indices of the AttributeList.
97   AttributeList NewAttrs = NewFunc->getAttributes();
98   NewFunc->copyAttributesFrom(OldFunc);
99   NewFunc->setAttributes(NewAttrs);
100 
101   // Fix up the personality function that got copied over.
102   if (OldFunc->hasPersonalityFn())
103     NewFunc->setPersonalityFn(
104         MapValue(OldFunc->getPersonalityFn(), VMap,
105                  ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
106                  TypeMapper, Materializer));
107 
108   SmallVector<AttributeSet, 4> NewArgAttrs(NewFunc->arg_size());
109   AttributeList OldAttrs = OldFunc->getAttributes();
110 
111   // Clone any argument attributes that are present in the VMap.
112   for (const Argument &OldArg : OldFunc->args()) {
113     if (Argument *NewArg = dyn_cast<Argument>(VMap[&OldArg])) {
114       NewArgAttrs[NewArg->getArgNo()] =
115           OldAttrs.getParamAttributes(OldArg.getArgNo());
116     }
117   }
118 
119   NewFunc->setAttributes(
120       AttributeList::get(NewFunc->getContext(), OldAttrs.getFnAttributes(),
121                          OldAttrs.getRetAttributes(), NewArgAttrs));
122 
123   bool MustCloneSP =
124       OldFunc->getParent() && OldFunc->getParent() == NewFunc->getParent();
125   DISubprogram *SP = OldFunc->getSubprogram();
126   if (SP) {
127     assert(!MustCloneSP || ModuleLevelChanges);
128     // Add mappings for some DebugInfo nodes that we don't want duplicated
129     // even if they're distinct.
130     auto &MD = VMap.MD();
131     MD[SP->getUnit()].reset(SP->getUnit());
132     MD[SP->getType()].reset(SP->getType());
133     MD[SP->getFile()].reset(SP->getFile());
134     // If we're not cloning into the same module, no need to clone the
135     // subprogram
136     if (!MustCloneSP)
137       MD[SP].reset(SP);
138   }
139 
140   SmallVector<std::pair<unsigned, MDNode *>, 1> MDs;
141   OldFunc->getAllMetadata(MDs);
142   for (auto MD : MDs) {
143     NewFunc->addMetadata(
144         MD.first,
145         *MapMetadata(MD.second, VMap,
146                      ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
147                      TypeMapper, Materializer));
148   }
149 
150   // Everything else beyond this point deals with function instructions,
151   // so if we are dealing with a function declaration, we're done.
152   if (OldFunc->isDeclaration())
153     return;
154 
155   // When we remap instructions, we want to avoid duplicating inlined
156   // DISubprograms, so record all subprograms we find as we duplicate
157   // instructions and then freeze them in the MD map.
158   // We also record information about dbg.value and dbg.declare to avoid
159   // duplicating the types.
160   DebugInfoFinder DIFinder;
161 
162   // Loop over all of the basic blocks in the function, cloning them as
163   // appropriate.  Note that we save BE this way in order to handle cloning of
164   // recursive functions into themselves.
165   //
166   for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
167        BI != BE; ++BI) {
168     const BasicBlock &BB = *BI;
169 
170     // Create a new basic block and copy instructions into it!
171     BasicBlock *CBB = CloneBasicBlock(&BB, VMap, NameSuffix, NewFunc, CodeInfo,
172                                       ModuleLevelChanges ? &DIFinder : nullptr);
173 
174     // Add basic block mapping.
175     VMap[&BB] = CBB;
176 
177     // It is only legal to clone a function if a block address within that
178     // function is never referenced outside of the function.  Given that, we
179     // want to map block addresses from the old function to block addresses in
180     // the clone. (This is different from the generic ValueMapper
181     // implementation, which generates an invalid blockaddress when
182     // cloning a function.)
183     if (BB.hasAddressTaken()) {
184       Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc),
185                                               const_cast<BasicBlock*>(&BB));
186       VMap[OldBBAddr] = BlockAddress::get(NewFunc, CBB);
187     }
188 
189     // Note return instructions for the caller.
190     if (ReturnInst *RI = dyn_cast<ReturnInst>(CBB->getTerminator()))
191       Returns.push_back(RI);
192   }
193 
194   for (DISubprogram *ISP : DIFinder.subprograms())
195     if (ISP != SP)
196       VMap.MD()[ISP].reset(ISP);
197 
198   for (DICompileUnit *CU : DIFinder.compile_units())
199     VMap.MD()[CU].reset(CU);
200 
201   for (DIType *Type : DIFinder.types())
202     VMap.MD()[Type].reset(Type);
203 
204   // Loop over all of the instructions in the function, fixing up operand
205   // references as we go.  This uses VMap to do all the hard work.
206   for (Function::iterator BB =
207            cast<BasicBlock>(VMap[&OldFunc->front()])->getIterator(),
208                           BE = NewFunc->end();
209        BB != BE; ++BB)
210     // Loop over all instructions, fixing each one as we find it...
211     for (Instruction &II : *BB)
212       RemapInstruction(&II, VMap,
213                        ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
214                        TypeMapper, Materializer);
215 
216   // Register all DICompileUnits of the old parent module in the new parent module
217   auto* OldModule = OldFunc->getParent();
218   auto* NewModule = NewFunc->getParent();
219   if (OldModule && NewModule && OldModule != NewModule && DIFinder.compile_unit_count()) {
220     auto* NMD = NewModule->getOrInsertNamedMetadata("llvm.dbg.cu");
221     // Avoid multiple insertions of the same DICompileUnit to NMD.
222     SmallPtrSet<const void*, 8> Visited;
223     for (auto* Operand : NMD->operands())
224       Visited.insert(Operand);
225     for (auto* Unit : DIFinder.compile_units())
226       // VMap.MD()[Unit] == Unit
227       if (Visited.insert(Unit).second)
228         NMD->addOperand(Unit);
229   }
230 }
231 
232 /// Return a copy of the specified function and add it to that function's
233 /// module.  Also, any references specified in the VMap are changed to refer to
234 /// their mapped value instead of the original one.  If any of the arguments to
235 /// the function are in the VMap, the arguments are deleted from the resultant
236 /// function.  The VMap is updated to include mappings from all of the
237 /// instructions and basicblocks in the function from their old to new values.
238 ///
239 Function *llvm::CloneFunction(Function *F, ValueToValueMapTy &VMap,
240                               ClonedCodeInfo *CodeInfo) {
241   std::vector<Type*> ArgTypes;
242 
243   // The user might be deleting arguments to the function by specifying them in
244   // the VMap.  If so, we need to not add the arguments to the arg ty vector
245   //
246   for (const Argument &I : F->args())
247     if (VMap.count(&I) == 0) // Haven't mapped the argument to anything yet?
248       ArgTypes.push_back(I.getType());
249 
250   // Create a new function type...
251   FunctionType *FTy = FunctionType::get(F->getFunctionType()->getReturnType(),
252                                     ArgTypes, F->getFunctionType()->isVarArg());
253 
254   // Create the new function...
255   Function *NewF = Function::Create(FTy, F->getLinkage(), F->getAddressSpace(),
256                                     F->getName(), F->getParent());
257 
258   // Loop over the arguments, copying the names of the mapped arguments over...
259   Function::arg_iterator DestI = NewF->arg_begin();
260   for (const Argument & I : F->args())
261     if (VMap.count(&I) == 0) {     // Is this argument preserved?
262       DestI->setName(I.getName()); // Copy the name over...
263       VMap[&I] = &*DestI++;        // Add mapping to VMap
264     }
265 
266   SmallVector<ReturnInst*, 8> Returns;  // Ignore returns cloned.
267   CloneFunctionInto(NewF, F, VMap, F->getSubprogram() != nullptr, Returns, "",
268                     CodeInfo);
269 
270   return NewF;
271 }
272 
273 
274 
275 namespace {
276   /// This is a private class used to implement CloneAndPruneFunctionInto.
277   struct PruningFunctionCloner {
278     Function *NewFunc;
279     const Function *OldFunc;
280     ValueToValueMapTy &VMap;
281     bool ModuleLevelChanges;
282     const char *NameSuffix;
283     ClonedCodeInfo *CodeInfo;
284 
285   public:
286     PruningFunctionCloner(Function *newFunc, const Function *oldFunc,
287                           ValueToValueMapTy &valueMap, bool moduleLevelChanges,
288                           const char *nameSuffix, ClonedCodeInfo *codeInfo)
289         : NewFunc(newFunc), OldFunc(oldFunc), VMap(valueMap),
290           ModuleLevelChanges(moduleLevelChanges), NameSuffix(nameSuffix),
291           CodeInfo(codeInfo) {}
292 
293     /// The specified block is found to be reachable, clone it and
294     /// anything that it can reach.
295     void CloneBlock(const BasicBlock *BB,
296                     BasicBlock::const_iterator StartingInst,
297                     std::vector<const BasicBlock*> &ToClone);
298   };
299 }
300 
301 /// The specified block is found to be reachable, clone it and
302 /// anything that it can reach.
303 void PruningFunctionCloner::CloneBlock(const BasicBlock *BB,
304                                        BasicBlock::const_iterator StartingInst,
305                                        std::vector<const BasicBlock*> &ToClone){
306   WeakTrackingVH &BBEntry = VMap[BB];
307 
308   // Have we already cloned this block?
309   if (BBEntry) return;
310 
311   // Nope, clone it now.
312   BasicBlock *NewBB;
313   BBEntry = NewBB = BasicBlock::Create(BB->getContext());
314   if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
315 
316   // It is only legal to clone a function if a block address within that
317   // function is never referenced outside of the function.  Given that, we
318   // want to map block addresses from the old function to block addresses in
319   // the clone. (This is different from the generic ValueMapper
320   // implementation, which generates an invalid blockaddress when
321   // cloning a function.)
322   //
323   // Note that we don't need to fix the mapping for unreachable blocks;
324   // the default mapping there is safe.
325   if (BB->hasAddressTaken()) {
326     Constant *OldBBAddr = BlockAddress::get(const_cast<Function*>(OldFunc),
327                                             const_cast<BasicBlock*>(BB));
328     VMap[OldBBAddr] = BlockAddress::get(NewFunc, NewBB);
329   }
330 
331   bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
332 
333   // Loop over all instructions, and copy them over, DCE'ing as we go.  This
334   // loop doesn't include the terminator.
335   for (BasicBlock::const_iterator II = StartingInst, IE = --BB->end();
336        II != IE; ++II) {
337 
338     Instruction *NewInst = II->clone();
339 
340     // Eagerly remap operands to the newly cloned instruction, except for PHI
341     // nodes for which we defer processing until we update the CFG.
342     if (!isa<PHINode>(NewInst)) {
343       RemapInstruction(NewInst, VMap,
344                        ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
345 
346       // If we can simplify this instruction to some other value, simply add
347       // a mapping to that value rather than inserting a new instruction into
348       // the basic block.
349       if (Value *V =
350               SimplifyInstruction(NewInst, BB->getModule()->getDataLayout())) {
351         // On the off-chance that this simplifies to an instruction in the old
352         // function, map it back into the new function.
353         if (NewFunc != OldFunc)
354           if (Value *MappedV = VMap.lookup(V))
355             V = MappedV;
356 
357         if (!NewInst->mayHaveSideEffects()) {
358           VMap[&*II] = V;
359           NewInst->deleteValue();
360           continue;
361         }
362       }
363     }
364 
365     if (II->hasName())
366       NewInst->setName(II->getName()+NameSuffix);
367     VMap[&*II] = NewInst; // Add instruction map to value.
368     NewBB->getInstList().push_back(NewInst);
369     hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
370 
371     if (CodeInfo)
372       if (auto *CB = dyn_cast<CallBase>(&*II))
373         if (CB->hasOperandBundles())
374           CodeInfo->OperandBundleCallSites.push_back(NewInst);
375 
376     if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
377       if (isa<ConstantInt>(AI->getArraySize()))
378         hasStaticAllocas = true;
379       else
380         hasDynamicAllocas = true;
381     }
382   }
383 
384   // Finally, clone over the terminator.
385   const Instruction *OldTI = BB->getTerminator();
386   bool TerminatorDone = false;
387   if (const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) {
388     if (BI->isConditional()) {
389       // If the condition was a known constant in the callee...
390       ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
391       // Or is a known constant in the caller...
392       if (!Cond) {
393         Value *V = VMap.lookup(BI->getCondition());
394         Cond = dyn_cast_or_null<ConstantInt>(V);
395       }
396 
397       // Constant fold to uncond branch!
398       if (Cond) {
399         BasicBlock *Dest = BI->getSuccessor(!Cond->getZExtValue());
400         VMap[OldTI] = BranchInst::Create(Dest, NewBB);
401         ToClone.push_back(Dest);
402         TerminatorDone = true;
403       }
404     }
405   } else if (const SwitchInst *SI = dyn_cast<SwitchInst>(OldTI)) {
406     // If switching on a value known constant in the caller.
407     ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition());
408     if (!Cond) { // Or known constant after constant prop in the callee...
409       Value *V = VMap.lookup(SI->getCondition());
410       Cond = dyn_cast_or_null<ConstantInt>(V);
411     }
412     if (Cond) {     // Constant fold to uncond branch!
413       SwitchInst::ConstCaseHandle Case = *SI->findCaseValue(Cond);
414       BasicBlock *Dest = const_cast<BasicBlock*>(Case.getCaseSuccessor());
415       VMap[OldTI] = BranchInst::Create(Dest, NewBB);
416       ToClone.push_back(Dest);
417       TerminatorDone = true;
418     }
419   }
420 
421   if (!TerminatorDone) {
422     Instruction *NewInst = OldTI->clone();
423     if (OldTI->hasName())
424       NewInst->setName(OldTI->getName()+NameSuffix);
425     NewBB->getInstList().push_back(NewInst);
426     VMap[OldTI] = NewInst;             // Add instruction map to value.
427 
428     if (CodeInfo)
429       if (auto *CB = dyn_cast<CallBase>(OldTI))
430         if (CB->hasOperandBundles())
431           CodeInfo->OperandBundleCallSites.push_back(NewInst);
432 
433     // Recursively clone any reachable successor blocks.
434     const Instruction *TI = BB->getTerminator();
435     for (const BasicBlock *Succ : successors(TI))
436       ToClone.push_back(Succ);
437   }
438 
439   if (CodeInfo) {
440     CodeInfo->ContainsCalls          |= hasCalls;
441     CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
442     CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
443       BB != &BB->getParent()->front();
444   }
445 }
446 
447 /// This works like CloneAndPruneFunctionInto, except that it does not clone the
448 /// entire function. Instead it starts at an instruction provided by the caller
449 /// and copies (and prunes) only the code reachable from that instruction.
450 void llvm::CloneAndPruneIntoFromInst(Function *NewFunc, const Function *OldFunc,
451                                      const Instruction *StartingInst,
452                                      ValueToValueMapTy &VMap,
453                                      bool ModuleLevelChanges,
454                                      SmallVectorImpl<ReturnInst *> &Returns,
455                                      const char *NameSuffix,
456                                      ClonedCodeInfo *CodeInfo) {
457   assert(NameSuffix && "NameSuffix cannot be null!");
458 
459   ValueMapTypeRemapper *TypeMapper = nullptr;
460   ValueMaterializer *Materializer = nullptr;
461 
462 #ifndef NDEBUG
463   // If the cloning starts at the beginning of the function, verify that
464   // the function arguments are mapped.
465   if (!StartingInst)
466     for (const Argument &II : OldFunc->args())
467       assert(VMap.count(&II) && "No mapping from source argument specified!");
468 #endif
469 
470   PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges,
471                             NameSuffix, CodeInfo);
472   const BasicBlock *StartingBB;
473   if (StartingInst)
474     StartingBB = StartingInst->getParent();
475   else {
476     StartingBB = &OldFunc->getEntryBlock();
477     StartingInst = &StartingBB->front();
478   }
479 
480   // Clone the entry block, and anything recursively reachable from it.
481   std::vector<const BasicBlock*> CloneWorklist;
482   PFC.CloneBlock(StartingBB, StartingInst->getIterator(), CloneWorklist);
483   while (!CloneWorklist.empty()) {
484     const BasicBlock *BB = CloneWorklist.back();
485     CloneWorklist.pop_back();
486     PFC.CloneBlock(BB, BB->begin(), CloneWorklist);
487   }
488 
489   // Loop over all of the basic blocks in the old function.  If the block was
490   // reachable, we have cloned it and the old block is now in the value map:
491   // insert it into the new function in the right order.  If not, ignore it.
492   //
493   // Defer PHI resolution until rest of function is resolved.
494   SmallVector<const PHINode*, 16> PHIToResolve;
495   for (const BasicBlock &BI : *OldFunc) {
496     Value *V = VMap.lookup(&BI);
497     BasicBlock *NewBB = cast_or_null<BasicBlock>(V);
498     if (!NewBB) continue;  // Dead block.
499 
500     // Add the new block to the new function.
501     NewFunc->getBasicBlockList().push_back(NewBB);
502 
503     // Handle PHI nodes specially, as we have to remove references to dead
504     // blocks.
505     for (const PHINode &PN : BI.phis()) {
506       // PHI nodes may have been remapped to non-PHI nodes by the caller or
507       // during the cloning process.
508       if (isa<PHINode>(VMap[&PN]))
509         PHIToResolve.push_back(&PN);
510       else
511         break;
512     }
513 
514     // Finally, remap the terminator instructions, as those can't be remapped
515     // until all BBs are mapped.
516     RemapInstruction(NewBB->getTerminator(), VMap,
517                      ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
518                      TypeMapper, Materializer);
519   }
520 
521   // Defer PHI resolution until rest of function is resolved, PHI resolution
522   // requires the CFG to be up-to-date.
523   for (unsigned phino = 0, e = PHIToResolve.size(); phino != e; ) {
524     const PHINode *OPN = PHIToResolve[phino];
525     unsigned NumPreds = OPN->getNumIncomingValues();
526     const BasicBlock *OldBB = OPN->getParent();
527     BasicBlock *NewBB = cast<BasicBlock>(VMap[OldBB]);
528 
529     // Map operands for blocks that are live and remove operands for blocks
530     // that are dead.
531     for (; phino != PHIToResolve.size() &&
532          PHIToResolve[phino]->getParent() == OldBB; ++phino) {
533       OPN = PHIToResolve[phino];
534       PHINode *PN = cast<PHINode>(VMap[OPN]);
535       for (unsigned pred = 0, e = NumPreds; pred != e; ++pred) {
536         Value *V = VMap.lookup(PN->getIncomingBlock(pred));
537         if (BasicBlock *MappedBlock = cast_or_null<BasicBlock>(V)) {
538           Value *InVal = MapValue(PN->getIncomingValue(pred),
539                                   VMap,
540                         ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
541           assert(InVal && "Unknown input value?");
542           PN->setIncomingValue(pred, InVal);
543           PN->setIncomingBlock(pred, MappedBlock);
544         } else {
545           PN->removeIncomingValue(pred, false);
546           --pred;  // Revisit the next entry.
547           --e;
548         }
549       }
550     }
551 
552     // The loop above has removed PHI entries for those blocks that are dead
553     // and has updated others.  However, if a block is live (i.e. copied over)
554     // but its terminator has been changed to not go to this block, then our
555     // phi nodes will have invalid entries.  Update the PHI nodes in this
556     // case.
557     PHINode *PN = cast<PHINode>(NewBB->begin());
558     NumPreds = pred_size(NewBB);
559     if (NumPreds != PN->getNumIncomingValues()) {
560       assert(NumPreds < PN->getNumIncomingValues());
561       // Count how many times each predecessor comes to this block.
562       std::map<BasicBlock*, unsigned> PredCount;
563       for (pred_iterator PI = pred_begin(NewBB), E = pred_end(NewBB);
564            PI != E; ++PI)
565         --PredCount[*PI];
566 
567       // Figure out how many entries to remove from each PHI.
568       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
569         ++PredCount[PN->getIncomingBlock(i)];
570 
571       // At this point, the excess predecessor entries are positive in the
572       // map.  Loop over all of the PHIs and remove excess predecessor
573       // entries.
574       BasicBlock::iterator I = NewBB->begin();
575       for (; (PN = dyn_cast<PHINode>(I)); ++I) {
576         for (const auto &PCI : PredCount) {
577           BasicBlock *Pred = PCI.first;
578           for (unsigned NumToRemove = PCI.second; NumToRemove; --NumToRemove)
579             PN->removeIncomingValue(Pred, false);
580         }
581       }
582     }
583 
584     // If the loops above have made these phi nodes have 0 or 1 operand,
585     // replace them with undef or the input value.  We must do this for
586     // correctness, because 0-operand phis are not valid.
587     PN = cast<PHINode>(NewBB->begin());
588     if (PN->getNumIncomingValues() == 0) {
589       BasicBlock::iterator I = NewBB->begin();
590       BasicBlock::const_iterator OldI = OldBB->begin();
591       while ((PN = dyn_cast<PHINode>(I++))) {
592         Value *NV = UndefValue::get(PN->getType());
593         PN->replaceAllUsesWith(NV);
594         assert(VMap[&*OldI] == PN && "VMap mismatch");
595         VMap[&*OldI] = NV;
596         PN->eraseFromParent();
597         ++OldI;
598       }
599     }
600   }
601 
602   // Make a second pass over the PHINodes now that all of them have been
603   // remapped into the new function, simplifying the PHINode and performing any
604   // recursive simplifications exposed. This will transparently update the
605   // WeakTrackingVH in the VMap. Notably, we rely on that so that if we coalesce
606   // two PHINodes, the iteration over the old PHIs remains valid, and the
607   // mapping will just map us to the new node (which may not even be a PHI
608   // node).
609   const DataLayout &DL = NewFunc->getParent()->getDataLayout();
610   SmallSetVector<const Value *, 8> Worklist;
611   for (unsigned Idx = 0, Size = PHIToResolve.size(); Idx != Size; ++Idx)
612     if (isa<PHINode>(VMap[PHIToResolve[Idx]]))
613       Worklist.insert(PHIToResolve[Idx]);
614 
615   // Note that we must test the size on each iteration, the worklist can grow.
616   for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
617     const Value *OrigV = Worklist[Idx];
618     auto *I = dyn_cast_or_null<Instruction>(VMap.lookup(OrigV));
619     if (!I)
620       continue;
621 
622     // Skip over non-intrinsic callsites, we don't want to remove any nodes from
623     // the CGSCC.
624     CallBase *CB = dyn_cast<CallBase>(I);
625     if (CB && CB->getCalledFunction() &&
626         !CB->getCalledFunction()->isIntrinsic())
627       continue;
628 
629     // See if this instruction simplifies.
630     Value *SimpleV = SimplifyInstruction(I, DL);
631     if (!SimpleV)
632       continue;
633 
634     // Stash away all the uses of the old instruction so we can check them for
635     // recursive simplifications after a RAUW. This is cheaper than checking all
636     // uses of To on the recursive step in most cases.
637     for (const User *U : OrigV->users())
638       Worklist.insert(cast<Instruction>(U));
639 
640     // Replace the instruction with its simplified value.
641     I->replaceAllUsesWith(SimpleV);
642 
643     // If the original instruction had no side effects, remove it.
644     if (isInstructionTriviallyDead(I))
645       I->eraseFromParent();
646     else
647       VMap[OrigV] = I;
648   }
649 
650   // Now that the inlined function body has been fully constructed, go through
651   // and zap unconditional fall-through branches. This happens all the time when
652   // specializing code: code specialization turns conditional branches into
653   // uncond branches, and this code folds them.
654   Function::iterator Begin = cast<BasicBlock>(VMap[StartingBB])->getIterator();
655   Function::iterator I = Begin;
656   while (I != NewFunc->end()) {
657     // We need to simplify conditional branches and switches with a constant
658     // operand. We try to prune these out when cloning, but if the
659     // simplification required looking through PHI nodes, those are only
660     // available after forming the full basic block. That may leave some here,
661     // and we still want to prune the dead code as early as possible.
662     //
663     // Do the folding before we check if the block is dead since we want code
664     // like
665     //  bb:
666     //    br i1 undef, label %bb, label %bb
667     // to be simplified to
668     //  bb:
669     //    br label %bb
670     // before we call I->getSinglePredecessor().
671     ConstantFoldTerminator(&*I);
672 
673     // Check if this block has become dead during inlining or other
674     // simplifications. Note that the first block will appear dead, as it has
675     // not yet been wired up properly.
676     if (I != Begin && (pred_begin(&*I) == pred_end(&*I) ||
677                        I->getSinglePredecessor() == &*I)) {
678       BasicBlock *DeadBB = &*I++;
679       DeleteDeadBlock(DeadBB);
680       continue;
681     }
682 
683     BranchInst *BI = dyn_cast<BranchInst>(I->getTerminator());
684     if (!BI || BI->isConditional()) { ++I; continue; }
685 
686     BasicBlock *Dest = BI->getSuccessor(0);
687     if (!Dest->getSinglePredecessor()) {
688       ++I; continue;
689     }
690 
691     // We shouldn't be able to get single-entry PHI nodes here, as instsimplify
692     // above should have zapped all of them..
693     assert(!isa<PHINode>(Dest->begin()));
694 
695     // We know all single-entry PHI nodes in the inlined function have been
696     // removed, so we just need to splice the blocks.
697     BI->eraseFromParent();
698 
699     // Make all PHI nodes that referred to Dest now refer to I as their source.
700     Dest->replaceAllUsesWith(&*I);
701 
702     // Move all the instructions in the succ to the pred.
703     I->getInstList().splice(I->end(), Dest->getInstList());
704 
705     // Remove the dest block.
706     Dest->eraseFromParent();
707 
708     // Do not increment I, iteratively merge all things this block branches to.
709   }
710 
711   // Make a final pass over the basic blocks from the old function to gather
712   // any return instructions which survived folding. We have to do this here
713   // because we can iteratively remove and merge returns above.
714   for (Function::iterator I = cast<BasicBlock>(VMap[StartingBB])->getIterator(),
715                           E = NewFunc->end();
716        I != E; ++I)
717     if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator()))
718       Returns.push_back(RI);
719 }
720 
721 
722 /// This works exactly like CloneFunctionInto,
723 /// except that it does some simple constant prop and DCE on the fly.  The
724 /// effect of this is to copy significantly less code in cases where (for
725 /// example) a function call with constant arguments is inlined, and those
726 /// constant arguments cause a significant amount of code in the callee to be
727 /// dead.  Since this doesn't produce an exact copy of the input, it can't be
728 /// used for things like CloneFunction or CloneModule.
729 void llvm::CloneAndPruneFunctionInto(Function *NewFunc, const Function *OldFunc,
730                                      ValueToValueMapTy &VMap,
731                                      bool ModuleLevelChanges,
732                                      SmallVectorImpl<ReturnInst*> &Returns,
733                                      const char *NameSuffix,
734                                      ClonedCodeInfo *CodeInfo,
735                                      Instruction *TheCall) {
736   CloneAndPruneIntoFromInst(NewFunc, OldFunc, &OldFunc->front().front(), VMap,
737                             ModuleLevelChanges, Returns, NameSuffix, CodeInfo);
738 }
739 
740 /// Remaps instructions in \p Blocks using the mapping in \p VMap.
741 void llvm::remapInstructionsInBlocks(
742     const SmallVectorImpl<BasicBlock *> &Blocks, ValueToValueMapTy &VMap) {
743   // Rewrite the code to refer to itself.
744   for (auto *BB : Blocks)
745     for (auto &Inst : *BB)
746       RemapInstruction(&Inst, VMap,
747                        RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
748 }
749 
750 /// Clones a loop \p OrigLoop.  Returns the loop and the blocks in \p
751 /// Blocks.
752 ///
753 /// Updates LoopInfo and DominatorTree assuming the loop is dominated by block
754 /// \p LoopDomBB.  Insert the new blocks before block specified in \p Before.
755 Loop *llvm::cloneLoopWithPreheader(BasicBlock *Before, BasicBlock *LoopDomBB,
756                                    Loop *OrigLoop, ValueToValueMapTy &VMap,
757                                    const Twine &NameSuffix, LoopInfo *LI,
758                                    DominatorTree *DT,
759                                    SmallVectorImpl<BasicBlock *> &Blocks) {
760   Function *F = OrigLoop->getHeader()->getParent();
761   Loop *ParentLoop = OrigLoop->getParentLoop();
762   DenseMap<Loop *, Loop *> LMap;
763 
764   Loop *NewLoop = LI->AllocateLoop();
765   LMap[OrigLoop] = NewLoop;
766   if (ParentLoop)
767     ParentLoop->addChildLoop(NewLoop);
768   else
769     LI->addTopLevelLoop(NewLoop);
770 
771   BasicBlock *OrigPH = OrigLoop->getLoopPreheader();
772   assert(OrigPH && "No preheader");
773   BasicBlock *NewPH = CloneBasicBlock(OrigPH, VMap, NameSuffix, F);
774   // To rename the loop PHIs.
775   VMap[OrigPH] = NewPH;
776   Blocks.push_back(NewPH);
777 
778   // Update LoopInfo.
779   if (ParentLoop)
780     ParentLoop->addBasicBlockToLoop(NewPH, *LI);
781 
782   // Update DominatorTree.
783   DT->addNewBlock(NewPH, LoopDomBB);
784 
785   for (Loop *CurLoop : OrigLoop->getLoopsInPreorder()) {
786     Loop *&NewLoop = LMap[CurLoop];
787     if (!NewLoop) {
788       NewLoop = LI->AllocateLoop();
789 
790       // Establish the parent/child relationship.
791       Loop *OrigParent = CurLoop->getParentLoop();
792       assert(OrigParent && "Could not find the original parent loop");
793       Loop *NewParentLoop = LMap[OrigParent];
794       assert(NewParentLoop && "Could not find the new parent loop");
795 
796       NewParentLoop->addChildLoop(NewLoop);
797     }
798   }
799 
800   for (BasicBlock *BB : OrigLoop->getBlocks()) {
801     Loop *CurLoop = LI->getLoopFor(BB);
802     Loop *&NewLoop = LMap[CurLoop];
803     assert(NewLoop && "Expecting new loop to be allocated");
804 
805     BasicBlock *NewBB = CloneBasicBlock(BB, VMap, NameSuffix, F);
806     VMap[BB] = NewBB;
807 
808     // Update LoopInfo.
809     NewLoop->addBasicBlockToLoop(NewBB, *LI);
810 
811     // Add DominatorTree node. After seeing all blocks, update to correct
812     // IDom.
813     DT->addNewBlock(NewBB, NewPH);
814 
815     Blocks.push_back(NewBB);
816   }
817 
818   for (BasicBlock *BB : OrigLoop->getBlocks()) {
819     // Update loop headers.
820     Loop *CurLoop = LI->getLoopFor(BB);
821     if (BB == CurLoop->getHeader())
822       LMap[CurLoop]->moveToHeader(cast<BasicBlock>(VMap[BB]));
823 
824     // Update DominatorTree.
825     BasicBlock *IDomBB = DT->getNode(BB)->getIDom()->getBlock();
826     DT->changeImmediateDominator(cast<BasicBlock>(VMap[BB]),
827                                  cast<BasicBlock>(VMap[IDomBB]));
828   }
829 
830   // Move them physically from the end of the block list.
831   F->getBasicBlockList().splice(Before->getIterator(), F->getBasicBlockList(),
832                                 NewPH);
833   F->getBasicBlockList().splice(Before->getIterator(), F->getBasicBlockList(),
834                                 NewLoop->getHeader()->getIterator(), F->end());
835 
836   return NewLoop;
837 }
838 
839 /// Duplicate non-Phi instructions from the beginning of block up to
840 /// StopAt instruction into a split block between BB and its predecessor.
841 BasicBlock *llvm::DuplicateInstructionsInSplitBetween(
842     BasicBlock *BB, BasicBlock *PredBB, Instruction *StopAt,
843     ValueToValueMapTy &ValueMapping, DomTreeUpdater &DTU) {
844 
845   assert(count(successors(PredBB), BB) == 1 &&
846          "There must be a single edge between PredBB and BB!");
847   // We are going to have to map operands from the original BB block to the new
848   // copy of the block 'NewBB'.  If there are PHI nodes in BB, evaluate them to
849   // account for entry from PredBB.
850   BasicBlock::iterator BI = BB->begin();
851   for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
852     ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
853 
854   BasicBlock *NewBB = SplitEdge(PredBB, BB);
855   NewBB->setName(PredBB->getName() + ".split");
856   Instruction *NewTerm = NewBB->getTerminator();
857 
858   // FIXME: SplitEdge does not yet take a DTU, so we include the split edge
859   //        in the update set here.
860   DTU.applyUpdates({{DominatorTree::Delete, PredBB, BB},
861                     {DominatorTree::Insert, PredBB, NewBB},
862                     {DominatorTree::Insert, NewBB, BB}});
863 
864   // Clone the non-phi instructions of BB into NewBB, keeping track of the
865   // mapping and using it to remap operands in the cloned instructions.
866   // Stop once we see the terminator too. This covers the case where BB's
867   // terminator gets replaced and StopAt == BB's terminator.
868   for (; StopAt != &*BI && BB->getTerminator() != &*BI; ++BI) {
869     Instruction *New = BI->clone();
870     New->setName(BI->getName());
871     New->insertBefore(NewTerm);
872     ValueMapping[&*BI] = New;
873 
874     // Remap operands to patch up intra-block references.
875     for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
876       if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
877         auto I = ValueMapping.find(Inst);
878         if (I != ValueMapping.end())
879           New->setOperand(i, I->second);
880       }
881   }
882 
883   return NewBB;
884 }
885