1 //===- CodeExtractor.cpp - Pull code region into a new 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 interface to tear out a code region, such as an
10 // individual loop or a parallel section, into a new function, replacing it with
11 // a call to the new function.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Transforms/Utils/CodeExtractor.h"
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/Optional.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/Analysis/BlockFrequencyInfo.h"
24 #include "llvm/Analysis/BlockFrequencyInfoImpl.h"
25 #include "llvm/Analysis/BranchProbabilityInfo.h"
26 #include "llvm/Analysis/LoopInfo.h"
27 #include "llvm/IR/Argument.h"
28 #include "llvm/IR/Attributes.h"
29 #include "llvm/IR/BasicBlock.h"
30 #include "llvm/IR/CFG.h"
31 #include "llvm/IR/Constant.h"
32 #include "llvm/IR/Constants.h"
33 #include "llvm/IR/DataLayout.h"
34 #include "llvm/IR/DerivedTypes.h"
35 #include "llvm/IR/Dominators.h"
36 #include "llvm/IR/Function.h"
37 #include "llvm/IR/GlobalValue.h"
38 #include "llvm/IR/InstrTypes.h"
39 #include "llvm/IR/Instruction.h"
40 #include "llvm/IR/Instructions.h"
41 #include "llvm/IR/IntrinsicInst.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/IR/LLVMContext.h"
44 #include "llvm/IR/MDBuilder.h"
45 #include "llvm/IR/Module.h"
46 #include "llvm/IR/Type.h"
47 #include "llvm/IR/User.h"
48 #include "llvm/IR/Value.h"
49 #include "llvm/IR/Verifier.h"
50 #include "llvm/Pass.h"
51 #include "llvm/Support/BlockFrequency.h"
52 #include "llvm/Support/BranchProbability.h"
53 #include "llvm/Support/Casting.h"
54 #include "llvm/Support/CommandLine.h"
55 #include "llvm/Support/Debug.h"
56 #include "llvm/Support/ErrorHandling.h"
57 #include "llvm/Support/raw_ostream.h"
58 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
59 #include "llvm/Transforms/Utils/Local.h"
60 #include <cassert>
61 #include <cstdint>
62 #include <iterator>
63 #include <map>
64 #include <set>
65 #include <utility>
66 #include <vector>
67 
68 using namespace llvm;
69 using ProfileCount = Function::ProfileCount;
70 
71 #define DEBUG_TYPE "code-extractor"
72 
73 // Provide a command-line option to aggregate function arguments into a struct
74 // for functions produced by the code extractor. This is useful when converting
75 // extracted functions to pthread-based code, as only one argument (void*) can
76 // be passed in to pthread_create().
77 static cl::opt<bool>
78 AggregateArgsOpt("aggregate-extracted-args", cl::Hidden,
79                  cl::desc("Aggregate arguments to code-extracted functions"));
80 
81 /// Test whether a block is valid for extraction.
82 static bool isBlockValidForExtraction(const BasicBlock &BB,
83                                       const SetVector<BasicBlock *> &Result,
84                                       bool AllowVarArgs, bool AllowAlloca) {
85   // taking the address of a basic block moved to another function is illegal
86   if (BB.hasAddressTaken())
87     return false;
88 
89   // don't hoist code that uses another basicblock address, as it's likely to
90   // lead to unexpected behavior, like cross-function jumps
91   SmallPtrSet<User const *, 16> Visited;
92   SmallVector<User const *, 16> ToVisit;
93 
94   for (Instruction const &Inst : BB)
95     ToVisit.push_back(&Inst);
96 
97   while (!ToVisit.empty()) {
98     User const *Curr = ToVisit.pop_back_val();
99     if (!Visited.insert(Curr).second)
100       continue;
101     if (isa<BlockAddress const>(Curr))
102       return false; // even a reference to self is likely to be not compatible
103 
104     if (isa<Instruction>(Curr) && cast<Instruction>(Curr)->getParent() != &BB)
105       continue;
106 
107     for (auto const &U : Curr->operands()) {
108       if (auto *UU = dyn_cast<User>(U))
109         ToVisit.push_back(UU);
110     }
111   }
112 
113   // If explicitly requested, allow vastart and alloca. For invoke instructions
114   // verify that extraction is valid.
115   for (BasicBlock::const_iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
116     if (isa<AllocaInst>(I)) {
117        if (!AllowAlloca)
118          return false;
119        continue;
120     }
121 
122     if (const auto *II = dyn_cast<InvokeInst>(I)) {
123       // Unwind destination (either a landingpad, catchswitch, or cleanuppad)
124       // must be a part of the subgraph which is being extracted.
125       if (auto *UBB = II->getUnwindDest())
126         if (!Result.count(UBB))
127           return false;
128       continue;
129     }
130 
131     // All catch handlers of a catchswitch instruction as well as the unwind
132     // destination must be in the subgraph.
133     if (const auto *CSI = dyn_cast<CatchSwitchInst>(I)) {
134       if (auto *UBB = CSI->getUnwindDest())
135         if (!Result.count(UBB))
136           return false;
137       for (auto *HBB : CSI->handlers())
138         if (!Result.count(const_cast<BasicBlock*>(HBB)))
139           return false;
140       continue;
141     }
142 
143     // Make sure that entire catch handler is within subgraph. It is sufficient
144     // to check that catch return's block is in the list.
145     if (const auto *CPI = dyn_cast<CatchPadInst>(I)) {
146       for (const auto *U : CPI->users())
147         if (const auto *CRI = dyn_cast<CatchReturnInst>(U))
148           if (!Result.count(const_cast<BasicBlock*>(CRI->getParent())))
149             return false;
150       continue;
151     }
152 
153     // And do similar checks for cleanup handler - the entire handler must be
154     // in subgraph which is going to be extracted. For cleanup return should
155     // additionally check that the unwind destination is also in the subgraph.
156     if (const auto *CPI = dyn_cast<CleanupPadInst>(I)) {
157       for (const auto *U : CPI->users())
158         if (const auto *CRI = dyn_cast<CleanupReturnInst>(U))
159           if (!Result.count(const_cast<BasicBlock*>(CRI->getParent())))
160             return false;
161       continue;
162     }
163     if (const auto *CRI = dyn_cast<CleanupReturnInst>(I)) {
164       if (auto *UBB = CRI->getUnwindDest())
165         if (!Result.count(UBB))
166           return false;
167       continue;
168     }
169 
170     if (const CallInst *CI = dyn_cast<CallInst>(I)) {
171       if (const Function *F = CI->getCalledFunction()) {
172         auto IID = F->getIntrinsicID();
173         if (IID == Intrinsic::vastart) {
174           if (AllowVarArgs)
175             continue;
176           else
177             return false;
178         }
179 
180         // Currently, we miscompile outlined copies of eh_typid_for. There are
181         // proposals for fixing this in llvm.org/PR39545.
182         if (IID == Intrinsic::eh_typeid_for)
183           return false;
184       }
185     }
186   }
187 
188   return true;
189 }
190 
191 /// Build a set of blocks to extract if the input blocks are viable.
192 static SetVector<BasicBlock *>
193 buildExtractionBlockSet(ArrayRef<BasicBlock *> BBs, DominatorTree *DT,
194                         bool AllowVarArgs, bool AllowAlloca) {
195   assert(!BBs.empty() && "The set of blocks to extract must be non-empty");
196   SetVector<BasicBlock *> Result;
197 
198   // Loop over the blocks, adding them to our set-vector, and aborting with an
199   // empty set if we encounter invalid blocks.
200   for (BasicBlock *BB : BBs) {
201     // If this block is dead, don't process it.
202     if (DT && !DT->isReachableFromEntry(BB))
203       continue;
204 
205     if (!Result.insert(BB))
206       llvm_unreachable("Repeated basic blocks in extraction input");
207   }
208 
209   for (auto *BB : Result) {
210     if (!isBlockValidForExtraction(*BB, Result, AllowVarArgs, AllowAlloca))
211       return {};
212 
213     // Make sure that the first block is not a landing pad.
214     if (BB == Result.front()) {
215       if (BB->isEHPad()) {
216         LLVM_DEBUG(dbgs() << "The first block cannot be an unwind block\n");
217         return {};
218       }
219       continue;
220     }
221 
222     // All blocks other than the first must not have predecessors outside of
223     // the subgraph which is being extracted.
224     for (auto *PBB : predecessors(BB))
225       if (!Result.count(PBB)) {
226         LLVM_DEBUG(
227             dbgs() << "No blocks in this region may have entries from "
228                       "outside the region except for the first block!\n");
229         return {};
230       }
231   }
232 
233   return Result;
234 }
235 
236 CodeExtractor::CodeExtractor(ArrayRef<BasicBlock *> BBs, DominatorTree *DT,
237                              bool AggregateArgs, BlockFrequencyInfo *BFI,
238                              BranchProbabilityInfo *BPI, bool AllowVarArgs,
239                              bool AllowAlloca, std::string Suffix)
240     : DT(DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI),
241       BPI(BPI), AllowVarArgs(AllowVarArgs),
242       Blocks(buildExtractionBlockSet(BBs, DT, AllowVarArgs, AllowAlloca)),
243       Suffix(Suffix) {}
244 
245 CodeExtractor::CodeExtractor(DominatorTree &DT, Loop &L, bool AggregateArgs,
246                              BlockFrequencyInfo *BFI,
247                              BranchProbabilityInfo *BPI, std::string Suffix)
248     : DT(&DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI),
249       BPI(BPI), AllowVarArgs(false),
250       Blocks(buildExtractionBlockSet(L.getBlocks(), &DT,
251                                      /* AllowVarArgs */ false,
252                                      /* AllowAlloca */ false)),
253       Suffix(Suffix) {}
254 
255 /// definedInRegion - Return true if the specified value is defined in the
256 /// extracted region.
257 static bool definedInRegion(const SetVector<BasicBlock *> &Blocks, Value *V) {
258   if (Instruction *I = dyn_cast<Instruction>(V))
259     if (Blocks.count(I->getParent()))
260       return true;
261   return false;
262 }
263 
264 /// definedInCaller - Return true if the specified value is defined in the
265 /// function being code extracted, but not in the region being extracted.
266 /// These values must be passed in as live-ins to the function.
267 static bool definedInCaller(const SetVector<BasicBlock *> &Blocks, Value *V) {
268   if (isa<Argument>(V)) return true;
269   if (Instruction *I = dyn_cast<Instruction>(V))
270     if (!Blocks.count(I->getParent()))
271       return true;
272   return false;
273 }
274 
275 static BasicBlock *getCommonExitBlock(const SetVector<BasicBlock *> &Blocks) {
276   BasicBlock *CommonExitBlock = nullptr;
277   auto hasNonCommonExitSucc = [&](BasicBlock *Block) {
278     for (auto *Succ : successors(Block)) {
279       // Internal edges, ok.
280       if (Blocks.count(Succ))
281         continue;
282       if (!CommonExitBlock) {
283         CommonExitBlock = Succ;
284         continue;
285       }
286       if (CommonExitBlock == Succ)
287         continue;
288 
289       return true;
290     }
291     return false;
292   };
293 
294   if (any_of(Blocks, hasNonCommonExitSucc))
295     return nullptr;
296 
297   return CommonExitBlock;
298 }
299 
300 bool CodeExtractor::isLegalToShrinkwrapLifetimeMarkers(
301     Instruction *Addr) const {
302   AllocaInst *AI = cast<AllocaInst>(Addr->stripInBoundsConstantOffsets());
303   Function *Func = (*Blocks.begin())->getParent();
304   for (BasicBlock &BB : *Func) {
305     if (Blocks.count(&BB))
306       continue;
307     for (Instruction &II : BB) {
308       if (isa<DbgInfoIntrinsic>(II))
309         continue;
310 
311       unsigned Opcode = II.getOpcode();
312       Value *MemAddr = nullptr;
313       switch (Opcode) {
314       case Instruction::Store:
315       case Instruction::Load: {
316         if (Opcode == Instruction::Store) {
317           StoreInst *SI = cast<StoreInst>(&II);
318           MemAddr = SI->getPointerOperand();
319         } else {
320           LoadInst *LI = cast<LoadInst>(&II);
321           MemAddr = LI->getPointerOperand();
322         }
323         // Global variable can not be aliased with locals.
324         if (dyn_cast<Constant>(MemAddr))
325           break;
326         Value *Base = MemAddr->stripInBoundsConstantOffsets();
327         if (!dyn_cast<AllocaInst>(Base) || Base == AI)
328           return false;
329         break;
330       }
331       default: {
332         IntrinsicInst *IntrInst = dyn_cast<IntrinsicInst>(&II);
333         if (IntrInst) {
334           if (IntrInst->isLifetimeStartOrEnd())
335             break;
336           return false;
337         }
338         // Treat all the other cases conservatively if it has side effects.
339         if (II.mayHaveSideEffects())
340           return false;
341       }
342       }
343     }
344   }
345 
346   return true;
347 }
348 
349 BasicBlock *
350 CodeExtractor::findOrCreateBlockForHoisting(BasicBlock *CommonExitBlock) {
351   BasicBlock *SinglePredFromOutlineRegion = nullptr;
352   assert(!Blocks.count(CommonExitBlock) &&
353          "Expect a block outside the region!");
354   for (auto *Pred : predecessors(CommonExitBlock)) {
355     if (!Blocks.count(Pred))
356       continue;
357     if (!SinglePredFromOutlineRegion) {
358       SinglePredFromOutlineRegion = Pred;
359     } else if (SinglePredFromOutlineRegion != Pred) {
360       SinglePredFromOutlineRegion = nullptr;
361       break;
362     }
363   }
364 
365   if (SinglePredFromOutlineRegion)
366     return SinglePredFromOutlineRegion;
367 
368 #ifndef NDEBUG
369   auto getFirstPHI = [](BasicBlock *BB) {
370     BasicBlock::iterator I = BB->begin();
371     PHINode *FirstPhi = nullptr;
372     while (I != BB->end()) {
373       PHINode *Phi = dyn_cast<PHINode>(I);
374       if (!Phi)
375         break;
376       if (!FirstPhi) {
377         FirstPhi = Phi;
378         break;
379       }
380     }
381     return FirstPhi;
382   };
383   // If there are any phi nodes, the single pred either exists or has already
384   // be created before code extraction.
385   assert(!getFirstPHI(CommonExitBlock) && "Phi not expected");
386 #endif
387 
388   BasicBlock *NewExitBlock = CommonExitBlock->splitBasicBlock(
389       CommonExitBlock->getFirstNonPHI()->getIterator());
390 
391   for (auto PI = pred_begin(CommonExitBlock), PE = pred_end(CommonExitBlock);
392        PI != PE;) {
393     BasicBlock *Pred = *PI++;
394     if (Blocks.count(Pred))
395       continue;
396     Pred->getTerminator()->replaceUsesOfWith(CommonExitBlock, NewExitBlock);
397   }
398   // Now add the old exit block to the outline region.
399   Blocks.insert(CommonExitBlock);
400   return CommonExitBlock;
401 }
402 
403 void CodeExtractor::findAllocas(ValueSet &SinkCands, ValueSet &HoistCands,
404                                 BasicBlock *&ExitBlock) const {
405   Function *Func = (*Blocks.begin())->getParent();
406   ExitBlock = getCommonExitBlock(Blocks);
407 
408   for (BasicBlock &BB : *Func) {
409     if (Blocks.count(&BB))
410       continue;
411     for (Instruction &II : BB) {
412       auto *AI = dyn_cast<AllocaInst>(&II);
413       if (!AI)
414         continue;
415 
416       // Find the pair of life time markers for address 'Addr' that are either
417       // defined inside the outline region or can legally be shrinkwrapped into
418       // the outline region. If there are not other untracked uses of the
419       // address, return the pair of markers if found; otherwise return a pair
420       // of nullptr.
421       auto GetLifeTimeMarkers =
422           [&](Instruction *Addr, bool &SinkLifeStart,
423               bool &HoistLifeEnd) -> std::pair<Instruction *, Instruction *> {
424         Instruction *LifeStart = nullptr, *LifeEnd = nullptr;
425 
426         for (User *U : Addr->users()) {
427           IntrinsicInst *IntrInst = dyn_cast<IntrinsicInst>(U);
428           if (IntrInst) {
429             if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_start) {
430               // Do not handle the case where AI has multiple start markers.
431               if (LifeStart)
432                 return std::make_pair<Instruction *>(nullptr, nullptr);
433               LifeStart = IntrInst;
434             }
435             if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_end) {
436               if (LifeEnd)
437                 return std::make_pair<Instruction *>(nullptr, nullptr);
438               LifeEnd = IntrInst;
439             }
440             continue;
441           }
442           // Find untracked uses of the address, bail.
443           if (!definedInRegion(Blocks, U))
444             return std::make_pair<Instruction *>(nullptr, nullptr);
445         }
446 
447         if (!LifeStart || !LifeEnd)
448           return std::make_pair<Instruction *>(nullptr, nullptr);
449 
450         SinkLifeStart = !definedInRegion(Blocks, LifeStart);
451         HoistLifeEnd = !definedInRegion(Blocks, LifeEnd);
452         // Do legality Check.
453         if ((SinkLifeStart || HoistLifeEnd) &&
454             !isLegalToShrinkwrapLifetimeMarkers(Addr))
455           return std::make_pair<Instruction *>(nullptr, nullptr);
456 
457         // Check to see if we have a place to do hoisting, if not, bail.
458         if (HoistLifeEnd && !ExitBlock)
459           return std::make_pair<Instruction *>(nullptr, nullptr);
460 
461         return std::make_pair(LifeStart, LifeEnd);
462       };
463 
464       bool SinkLifeStart = false, HoistLifeEnd = false;
465       auto Markers = GetLifeTimeMarkers(AI, SinkLifeStart, HoistLifeEnd);
466 
467       if (Markers.first) {
468         if (SinkLifeStart)
469           SinkCands.insert(Markers.first);
470         SinkCands.insert(AI);
471         if (HoistLifeEnd)
472           HoistCands.insert(Markers.second);
473         continue;
474       }
475 
476       // Follow the bitcast.
477       Instruction *MarkerAddr = nullptr;
478       for (User *U : AI->users()) {
479         if (U->stripInBoundsConstantOffsets() == AI) {
480           SinkLifeStart = false;
481           HoistLifeEnd = false;
482           Instruction *Bitcast = cast<Instruction>(U);
483           Markers = GetLifeTimeMarkers(Bitcast, SinkLifeStart, HoistLifeEnd);
484           if (Markers.first) {
485             MarkerAddr = Bitcast;
486             continue;
487           }
488         }
489 
490         // Found unknown use of AI.
491         if (!definedInRegion(Blocks, U)) {
492           MarkerAddr = nullptr;
493           break;
494         }
495       }
496 
497       if (MarkerAddr) {
498         if (SinkLifeStart)
499           SinkCands.insert(Markers.first);
500         if (!definedInRegion(Blocks, MarkerAddr))
501           SinkCands.insert(MarkerAddr);
502         SinkCands.insert(AI);
503         if (HoistLifeEnd)
504           HoistCands.insert(Markers.second);
505       }
506     }
507   }
508 }
509 
510 void CodeExtractor::findInputsOutputs(ValueSet &Inputs, ValueSet &Outputs,
511                                       const ValueSet &SinkCands) const {
512   for (BasicBlock *BB : Blocks) {
513     // If a used value is defined outside the region, it's an input.  If an
514     // instruction is used outside the region, it's an output.
515     for (Instruction &II : *BB) {
516       for (User::op_iterator OI = II.op_begin(), OE = II.op_end(); OI != OE;
517            ++OI) {
518         Value *V = *OI;
519         if (!SinkCands.count(V) && definedInCaller(Blocks, V))
520           Inputs.insert(V);
521       }
522 
523       for (User *U : II.users())
524         if (!definedInRegion(Blocks, U)) {
525           Outputs.insert(&II);
526           break;
527         }
528     }
529   }
530 }
531 
532 /// severSplitPHINodesOfEntry - If a PHI node has multiple inputs from outside
533 /// of the region, we need to split the entry block of the region so that the
534 /// PHI node is easier to deal with.
535 void CodeExtractor::severSplitPHINodesOfEntry(BasicBlock *&Header) {
536   unsigned NumPredsFromRegion = 0;
537   unsigned NumPredsOutsideRegion = 0;
538 
539   if (Header != &Header->getParent()->getEntryBlock()) {
540     PHINode *PN = dyn_cast<PHINode>(Header->begin());
541     if (!PN) return;  // No PHI nodes.
542 
543     // If the header node contains any PHI nodes, check to see if there is more
544     // than one entry from outside the region.  If so, we need to sever the
545     // header block into two.
546     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
547       if (Blocks.count(PN->getIncomingBlock(i)))
548         ++NumPredsFromRegion;
549       else
550         ++NumPredsOutsideRegion;
551 
552     // If there is one (or fewer) predecessor from outside the region, we don't
553     // need to do anything special.
554     if (NumPredsOutsideRegion <= 1) return;
555   }
556 
557   // Otherwise, we need to split the header block into two pieces: one
558   // containing PHI nodes merging values from outside of the region, and a
559   // second that contains all of the code for the block and merges back any
560   // incoming values from inside of the region.
561   BasicBlock *NewBB = SplitBlock(Header, Header->getFirstNonPHI(), DT);
562 
563   // We only want to code extract the second block now, and it becomes the new
564   // header of the region.
565   BasicBlock *OldPred = Header;
566   Blocks.remove(OldPred);
567   Blocks.insert(NewBB);
568   Header = NewBB;
569 
570   // Okay, now we need to adjust the PHI nodes and any branches from within the
571   // region to go to the new header block instead of the old header block.
572   if (NumPredsFromRegion) {
573     PHINode *PN = cast<PHINode>(OldPred->begin());
574     // Loop over all of the predecessors of OldPred that are in the region,
575     // changing them to branch to NewBB instead.
576     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
577       if (Blocks.count(PN->getIncomingBlock(i))) {
578         Instruction *TI = PN->getIncomingBlock(i)->getTerminator();
579         TI->replaceUsesOfWith(OldPred, NewBB);
580       }
581 
582     // Okay, everything within the region is now branching to the right block, we
583     // just have to update the PHI nodes now, inserting PHI nodes into NewBB.
584     BasicBlock::iterator AfterPHIs;
585     for (AfterPHIs = OldPred->begin(); isa<PHINode>(AfterPHIs); ++AfterPHIs) {
586       PHINode *PN = cast<PHINode>(AfterPHIs);
587       // Create a new PHI node in the new region, which has an incoming value
588       // from OldPred of PN.
589       PHINode *NewPN = PHINode::Create(PN->getType(), 1 + NumPredsFromRegion,
590                                        PN->getName() + ".ce", &NewBB->front());
591       PN->replaceAllUsesWith(NewPN);
592       NewPN->addIncoming(PN, OldPred);
593 
594       // Loop over all of the incoming value in PN, moving them to NewPN if they
595       // are from the extracted region.
596       for (unsigned i = 0; i != PN->getNumIncomingValues(); ++i) {
597         if (Blocks.count(PN->getIncomingBlock(i))) {
598           NewPN->addIncoming(PN->getIncomingValue(i), PN->getIncomingBlock(i));
599           PN->removeIncomingValue(i);
600           --i;
601         }
602       }
603     }
604   }
605 }
606 
607 /// severSplitPHINodesOfExits - if PHI nodes in exit blocks have inputs from
608 /// outlined region, we split these PHIs on two: one with inputs from region
609 /// and other with remaining incoming blocks; then first PHIs are placed in
610 /// outlined region.
611 void CodeExtractor::severSplitPHINodesOfExits(
612     const SmallPtrSetImpl<BasicBlock *> &Exits) {
613   for (BasicBlock *ExitBB : Exits) {
614     BasicBlock *NewBB = nullptr;
615 
616     for (PHINode &PN : ExitBB->phis()) {
617       // Find all incoming values from the outlining region.
618       SmallVector<unsigned, 2> IncomingVals;
619       for (unsigned i = 0; i < PN.getNumIncomingValues(); ++i)
620         if (Blocks.count(PN.getIncomingBlock(i)))
621           IncomingVals.push_back(i);
622 
623       // Do not process PHI if there is one (or fewer) predecessor from region.
624       // If PHI has exactly one predecessor from region, only this one incoming
625       // will be replaced on codeRepl block, so it should be safe to skip PHI.
626       if (IncomingVals.size() <= 1)
627         continue;
628 
629       // Create block for new PHIs and add it to the list of outlined if it
630       // wasn't done before.
631       if (!NewBB) {
632         NewBB = BasicBlock::Create(ExitBB->getContext(),
633                                    ExitBB->getName() + ".split",
634                                    ExitBB->getParent(), ExitBB);
635         SmallVector<BasicBlock *, 4> Preds(pred_begin(ExitBB),
636                                            pred_end(ExitBB));
637         for (BasicBlock *PredBB : Preds)
638           if (Blocks.count(PredBB))
639             PredBB->getTerminator()->replaceUsesOfWith(ExitBB, NewBB);
640         BranchInst::Create(ExitBB, NewBB);
641         Blocks.insert(NewBB);
642       }
643 
644       // Split this PHI.
645       PHINode *NewPN =
646           PHINode::Create(PN.getType(), IncomingVals.size(),
647                           PN.getName() + ".ce", NewBB->getFirstNonPHI());
648       for (unsigned i : IncomingVals)
649         NewPN->addIncoming(PN.getIncomingValue(i), PN.getIncomingBlock(i));
650       for (unsigned i : reverse(IncomingVals))
651         PN.removeIncomingValue(i, false);
652       PN.addIncoming(NewPN, NewBB);
653     }
654   }
655 }
656 
657 void CodeExtractor::splitReturnBlocks() {
658   for (BasicBlock *Block : Blocks)
659     if (ReturnInst *RI = dyn_cast<ReturnInst>(Block->getTerminator())) {
660       BasicBlock *New =
661           Block->splitBasicBlock(RI->getIterator(), Block->getName() + ".ret");
662       if (DT) {
663         // Old dominates New. New node dominates all other nodes dominated
664         // by Old.
665         DomTreeNode *OldNode = DT->getNode(Block);
666         SmallVector<DomTreeNode *, 8> Children(OldNode->begin(),
667                                                OldNode->end());
668 
669         DomTreeNode *NewNode = DT->addNewBlock(New, Block);
670 
671         for (DomTreeNode *I : Children)
672           DT->changeImmediateDominator(I, NewNode);
673       }
674     }
675 }
676 
677 /// constructFunction - make a function based on inputs and outputs, as follows:
678 /// f(in0, ..., inN, out0, ..., outN)
679 Function *CodeExtractor::constructFunction(const ValueSet &inputs,
680                                            const ValueSet &outputs,
681                                            BasicBlock *header,
682                                            BasicBlock *newRootNode,
683                                            BasicBlock *newHeader,
684                                            Function *oldFunction,
685                                            Module *M) {
686   LLVM_DEBUG(dbgs() << "inputs: " << inputs.size() << "\n");
687   LLVM_DEBUG(dbgs() << "outputs: " << outputs.size() << "\n");
688 
689   // This function returns unsigned, outputs will go back by reference.
690   switch (NumExitBlocks) {
691   case 0:
692   case 1: RetTy = Type::getVoidTy(header->getContext()); break;
693   case 2: RetTy = Type::getInt1Ty(header->getContext()); break;
694   default: RetTy = Type::getInt16Ty(header->getContext()); break;
695   }
696 
697   std::vector<Type *> paramTy;
698 
699   // Add the types of the input values to the function's argument list
700   for (Value *value : inputs) {
701     LLVM_DEBUG(dbgs() << "value used in func: " << *value << "\n");
702     paramTy.push_back(value->getType());
703   }
704 
705   // Add the types of the output values to the function's argument list.
706   for (Value *output : outputs) {
707     LLVM_DEBUG(dbgs() << "instr used in func: " << *output << "\n");
708     if (AggregateArgs)
709       paramTy.push_back(output->getType());
710     else
711       paramTy.push_back(PointerType::getUnqual(output->getType()));
712   }
713 
714   LLVM_DEBUG({
715     dbgs() << "Function type: " << *RetTy << " f(";
716     for (Type *i : paramTy)
717       dbgs() << *i << ", ";
718     dbgs() << ")\n";
719   });
720 
721   StructType *StructTy;
722   if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
723     StructTy = StructType::get(M->getContext(), paramTy);
724     paramTy.clear();
725     paramTy.push_back(PointerType::getUnqual(StructTy));
726   }
727   FunctionType *funcType =
728                   FunctionType::get(RetTy, paramTy,
729                                     AllowVarArgs && oldFunction->isVarArg());
730 
731   std::string SuffixToUse =
732       Suffix.empty()
733           ? (header->getName().empty() ? "extracted" : header->getName().str())
734           : Suffix;
735   // Create the new function
736   Function *newFunction = Function::Create(
737       funcType, GlobalValue::InternalLinkage, oldFunction->getAddressSpace(),
738       oldFunction->getName() + "." + SuffixToUse, M);
739   // If the old function is no-throw, so is the new one.
740   if (oldFunction->doesNotThrow())
741     newFunction->setDoesNotThrow();
742 
743   // Inherit the uwtable attribute if we need to.
744   if (oldFunction->hasUWTable())
745     newFunction->setHasUWTable();
746 
747   // Inherit all of the target dependent attributes and white-listed
748   // target independent attributes.
749   //  (e.g. If the extracted region contains a call to an x86.sse
750   //  instruction we need to make sure that the extracted region has the
751   //  "target-features" attribute allowing it to be lowered.
752   // FIXME: This should be changed to check to see if a specific
753   //           attribute can not be inherited.
754   for (const auto &Attr : oldFunction->getAttributes().getFnAttributes()) {
755     if (Attr.isStringAttribute()) {
756       if (Attr.getKindAsString() == "thunk")
757         continue;
758     } else
759       switch (Attr.getKindAsEnum()) {
760       // Those attributes cannot be propagated safely. Explicitly list them
761       // here so we get a warning if new attributes are added. This list also
762       // includes non-function attributes.
763       case Attribute::Alignment:
764       case Attribute::AllocSize:
765       case Attribute::ArgMemOnly:
766       case Attribute::Builtin:
767       case Attribute::ByVal:
768       case Attribute::Convergent:
769       case Attribute::Dereferenceable:
770       case Attribute::DereferenceableOrNull:
771       case Attribute::InAlloca:
772       case Attribute::InReg:
773       case Attribute::InaccessibleMemOnly:
774       case Attribute::InaccessibleMemOrArgMemOnly:
775       case Attribute::JumpTable:
776       case Attribute::Naked:
777       case Attribute::Nest:
778       case Attribute::NoAlias:
779       case Attribute::NoBuiltin:
780       case Attribute::NoCapture:
781       case Attribute::NoReturn:
782       case Attribute::None:
783       case Attribute::NonNull:
784       case Attribute::ReadNone:
785       case Attribute::ReadOnly:
786       case Attribute::Returned:
787       case Attribute::ReturnsTwice:
788       case Attribute::SExt:
789       case Attribute::Speculatable:
790       case Attribute::StackAlignment:
791       case Attribute::StructRet:
792       case Attribute::SwiftError:
793       case Attribute::SwiftSelf:
794       case Attribute::WriteOnly:
795       case Attribute::ZExt:
796       case Attribute::EndAttrKinds:
797         continue;
798       // Those attributes should be safe to propagate to the extracted function.
799       case Attribute::AlwaysInline:
800       case Attribute::Cold:
801       case Attribute::NoRecurse:
802       case Attribute::InlineHint:
803       case Attribute::MinSize:
804       case Attribute::NoDuplicate:
805       case Attribute::NoImplicitFloat:
806       case Attribute::NoInline:
807       case Attribute::NonLazyBind:
808       case Attribute::NoRedZone:
809       case Attribute::NoUnwind:
810       case Attribute::OptForFuzzing:
811       case Attribute::OptimizeNone:
812       case Attribute::OptimizeForSize:
813       case Attribute::SafeStack:
814       case Attribute::ShadowCallStack:
815       case Attribute::SanitizeAddress:
816       case Attribute::SanitizeMemory:
817       case Attribute::SanitizeThread:
818       case Attribute::SanitizeHWAddress:
819       case Attribute::SpeculativeLoadHardening:
820       case Attribute::StackProtect:
821       case Attribute::StackProtectReq:
822       case Attribute::StackProtectStrong:
823       case Attribute::StrictFP:
824       case Attribute::UWTable:
825       case Attribute::NoCfCheck:
826         break;
827       }
828 
829     newFunction->addFnAttr(Attr);
830   }
831   newFunction->getBasicBlockList().push_back(newRootNode);
832 
833   // Create an iterator to name all of the arguments we inserted.
834   Function::arg_iterator AI = newFunction->arg_begin();
835 
836   // Rewrite all users of the inputs in the extracted region to use the
837   // arguments (or appropriate addressing into struct) instead.
838   for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
839     Value *RewriteVal;
840     if (AggregateArgs) {
841       Value *Idx[2];
842       Idx[0] = Constant::getNullValue(Type::getInt32Ty(header->getContext()));
843       Idx[1] = ConstantInt::get(Type::getInt32Ty(header->getContext()), i);
844       Instruction *TI = newFunction->begin()->getTerminator();
845       GetElementPtrInst *GEP = GetElementPtrInst::Create(
846           StructTy, &*AI, Idx, "gep_" + inputs[i]->getName(), TI);
847       RewriteVal = new LoadInst(GEP, "loadgep_" + inputs[i]->getName(), TI);
848     } else
849       RewriteVal = &*AI++;
850 
851     std::vector<User *> Users(inputs[i]->user_begin(), inputs[i]->user_end());
852     for (User *use : Users)
853       if (Instruction *inst = dyn_cast<Instruction>(use))
854         if (Blocks.count(inst->getParent()))
855           inst->replaceUsesOfWith(inputs[i], RewriteVal);
856   }
857 
858   // Set names for input and output arguments.
859   if (!AggregateArgs) {
860     AI = newFunction->arg_begin();
861     for (unsigned i = 0, e = inputs.size(); i != e; ++i, ++AI)
862       AI->setName(inputs[i]->getName());
863     for (unsigned i = 0, e = outputs.size(); i != e; ++i, ++AI)
864       AI->setName(outputs[i]->getName()+".out");
865   }
866 
867   // Rewrite branches to basic blocks outside of the loop to new dummy blocks
868   // within the new function. This must be done before we lose track of which
869   // blocks were originally in the code region.
870   std::vector<User *> Users(header->user_begin(), header->user_end());
871   for (unsigned i = 0, e = Users.size(); i != e; ++i)
872     // The BasicBlock which contains the branch is not in the region
873     // modify the branch target to a new block
874     if (Instruction *I = dyn_cast<Instruction>(Users[i]))
875       if (I->isTerminator() && !Blocks.count(I->getParent()) &&
876           I->getParent()->getParent() == oldFunction)
877         I->replaceUsesOfWith(header, newHeader);
878 
879   return newFunction;
880 }
881 
882 /// Scan the extraction region for lifetime markers which reference inputs.
883 /// Erase these markers. Return the inputs which were referenced.
884 ///
885 /// The extraction region is defined by a set of blocks (\p Blocks), and a set
886 /// of allocas which will be moved from the caller function into the extracted
887 /// function (\p SunkAllocas).
888 static SetVector<Value *>
889 eraseLifetimeMarkersOnInputs(const SetVector<BasicBlock *> &Blocks,
890                              const SetVector<Value *> &SunkAllocas) {
891   SetVector<Value *> InputObjectsWithLifetime;
892   for (BasicBlock *BB : Blocks) {
893     for (auto It = BB->begin(), End = BB->end(); It != End;) {
894       auto *II = dyn_cast<IntrinsicInst>(&*It);
895       ++It;
896       if (!II || !II->isLifetimeStartOrEnd())
897         continue;
898 
899       // Get the memory operand of the lifetime marker. If the underlying
900       // object is a sunk alloca, or is otherwise defined in the extraction
901       // region, the lifetime marker must not be erased.
902       Value *Mem = II->getOperand(1)->stripInBoundsOffsets();
903       if (SunkAllocas.count(Mem) || definedInRegion(Blocks, Mem))
904         continue;
905 
906       InputObjectsWithLifetime.insert(Mem);
907       II->eraseFromParent();
908     }
909   }
910   return InputObjectsWithLifetime;
911 }
912 
913 /// Insert lifetime start/end markers surrounding the call to the new function
914 /// for objects defined in the caller.
915 static void insertLifetimeMarkersSurroundingCall(Module *M,
916                                                  ArrayRef<Value *> Objects,
917                                                  CallInst *TheCall) {
918   if (Objects.empty())
919     return;
920 
921   LLVMContext &Ctx = M->getContext();
922   auto Int8PtrTy = Type::getInt8PtrTy(Ctx);
923   auto NegativeOne = ConstantInt::getSigned(Type::getInt64Ty(Ctx), -1);
924   auto StartFn = llvm::Intrinsic::getDeclaration(
925       M, llvm::Intrinsic::lifetime_start, Int8PtrTy);
926   auto EndFn = llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::lifetime_end,
927                                                Int8PtrTy);
928   Instruction *Term = TheCall->getParent()->getTerminator();
929   for (Value *Mem : Objects) {
930     assert((!isa<Instruction>(Mem) ||
931             cast<Instruction>(Mem)->getFunction() == TheCall->getFunction()) &&
932            "Input memory not defined in original function");
933     Value *MemAsI8Ptr = nullptr;
934     if (Mem->getType() == Int8PtrTy)
935       MemAsI8Ptr = Mem;
936     else
937       MemAsI8Ptr =
938           CastInst::CreatePointerCast(Mem, Int8PtrTy, "lt.cast", TheCall);
939 
940     auto StartMarker = CallInst::Create(StartFn, {NegativeOne, MemAsI8Ptr});
941     StartMarker->insertBefore(TheCall);
942     auto EndMarker = CallInst::Create(EndFn, {NegativeOne, MemAsI8Ptr});
943     EndMarker->insertBefore(Term);
944   }
945 }
946 
947 /// emitCallAndSwitchStatement - This method sets up the caller side by adding
948 /// the call instruction, splitting any PHI nodes in the header block as
949 /// necessary.
950 CallInst *CodeExtractor::emitCallAndSwitchStatement(Function *newFunction,
951                                                     BasicBlock *codeReplacer,
952                                                     ValueSet &inputs,
953                                                     ValueSet &outputs) {
954   // Emit a call to the new function, passing in: *pointer to struct (if
955   // aggregating parameters), or plan inputs and allocated memory for outputs
956   std::vector<Value *> params, StructValues, ReloadOutputs, Reloads;
957 
958   Module *M = newFunction->getParent();
959   LLVMContext &Context = M->getContext();
960   const DataLayout &DL = M->getDataLayout();
961   CallInst *call = nullptr;
962 
963   // Add inputs as params, or to be filled into the struct
964   for (Value *input : inputs)
965     if (AggregateArgs)
966       StructValues.push_back(input);
967     else
968       params.push_back(input);
969 
970   // Create allocas for the outputs
971   for (Value *output : outputs) {
972     if (AggregateArgs) {
973       StructValues.push_back(output);
974     } else {
975       AllocaInst *alloca =
976         new AllocaInst(output->getType(), DL.getAllocaAddrSpace(),
977                        nullptr, output->getName() + ".loc",
978                        &codeReplacer->getParent()->front().front());
979       ReloadOutputs.push_back(alloca);
980       params.push_back(alloca);
981     }
982   }
983 
984   StructType *StructArgTy = nullptr;
985   AllocaInst *Struct = nullptr;
986   if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
987     std::vector<Type *> ArgTypes;
988     for (ValueSet::iterator v = StructValues.begin(),
989            ve = StructValues.end(); v != ve; ++v)
990       ArgTypes.push_back((*v)->getType());
991 
992     // Allocate a struct at the beginning of this function
993     StructArgTy = StructType::get(newFunction->getContext(), ArgTypes);
994     Struct = new AllocaInst(StructArgTy, DL.getAllocaAddrSpace(), nullptr,
995                             "structArg",
996                             &codeReplacer->getParent()->front().front());
997     params.push_back(Struct);
998 
999     for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
1000       Value *Idx[2];
1001       Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
1002       Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), i);
1003       GetElementPtrInst *GEP = GetElementPtrInst::Create(
1004           StructArgTy, Struct, Idx, "gep_" + StructValues[i]->getName());
1005       codeReplacer->getInstList().push_back(GEP);
1006       StoreInst *SI = new StoreInst(StructValues[i], GEP);
1007       codeReplacer->getInstList().push_back(SI);
1008     }
1009   }
1010 
1011   // Emit the call to the function
1012   call = CallInst::Create(newFunction, params,
1013                           NumExitBlocks > 1 ? "targetBlock" : "");
1014   // Add debug location to the new call, if the original function has debug
1015   // info. In that case, the terminator of the entry block of the extracted
1016   // function contains the first debug location of the extracted function,
1017   // set in extractCodeRegion.
1018   if (codeReplacer->getParent()->getSubprogram()) {
1019     if (auto DL = newFunction->getEntryBlock().getTerminator()->getDebugLoc())
1020       call->setDebugLoc(DL);
1021   }
1022   codeReplacer->getInstList().push_back(call);
1023 
1024   Function::arg_iterator OutputArgBegin = newFunction->arg_begin();
1025   unsigned FirstOut = inputs.size();
1026   if (!AggregateArgs)
1027     std::advance(OutputArgBegin, inputs.size());
1028 
1029   // Reload the outputs passed in by reference.
1030   Function::arg_iterator OAI = OutputArgBegin;
1031   for (unsigned i = 0, e = outputs.size(); i != e; ++i) {
1032     Value *Output = nullptr;
1033     if (AggregateArgs) {
1034       Value *Idx[2];
1035       Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
1036       Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i);
1037       GetElementPtrInst *GEP = GetElementPtrInst::Create(
1038           StructArgTy, Struct, Idx, "gep_reload_" + outputs[i]->getName());
1039       codeReplacer->getInstList().push_back(GEP);
1040       Output = GEP;
1041     } else {
1042       Output = ReloadOutputs[i];
1043     }
1044     LoadInst *load = new LoadInst(Output, outputs[i]->getName()+".reload");
1045     Reloads.push_back(load);
1046     codeReplacer->getInstList().push_back(load);
1047     std::vector<User *> Users(outputs[i]->user_begin(), outputs[i]->user_end());
1048     for (unsigned u = 0, e = Users.size(); u != e; ++u) {
1049       Instruction *inst = cast<Instruction>(Users[u]);
1050       if (!Blocks.count(inst->getParent()))
1051         inst->replaceUsesOfWith(outputs[i], load);
1052     }
1053 
1054     // Store to argument right after the definition of output value.
1055     auto *OutI = dyn_cast<Instruction>(outputs[i]);
1056     if (!OutI)
1057       continue;
1058 
1059     // Find proper insertion point.
1060     BasicBlock::iterator InsertPt;
1061     // In case OutI is an invoke, we insert the store at the beginning in the
1062     // 'normal destination' BB. Otherwise we insert the store right after OutI.
1063     if (auto *InvokeI = dyn_cast<InvokeInst>(OutI))
1064       InsertPt = InvokeI->getNormalDest()->getFirstInsertionPt();
1065     else if (auto *Phi = dyn_cast<PHINode>(OutI))
1066       InsertPt = Phi->getParent()->getFirstInsertionPt();
1067     else
1068       InsertPt = std::next(OutI->getIterator());
1069 
1070     assert(OAI != newFunction->arg_end() &&
1071            "Number of output arguments should match "
1072            "the amount of defined values");
1073     if (AggregateArgs) {
1074       Value *Idx[2];
1075       Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
1076       Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i);
1077       GetElementPtrInst *GEP = GetElementPtrInst::Create(
1078           StructArgTy, &*OAI, Idx, "gep_" + outputs[i]->getName(), &*InsertPt);
1079       new StoreInst(outputs[i], GEP, &*InsertPt);
1080       // Since there should be only one struct argument aggregating
1081       // all the output values, we shouldn't increment OAI, which always
1082       // points to the struct argument, in this case.
1083     } else {
1084       new StoreInst(outputs[i], &*OAI, &*InsertPt);
1085       ++OAI;
1086     }
1087   }
1088 
1089   // Now we can emit a switch statement using the call as a value.
1090   SwitchInst *TheSwitch =
1091       SwitchInst::Create(Constant::getNullValue(Type::getInt16Ty(Context)),
1092                          codeReplacer, 0, codeReplacer);
1093 
1094   // Since there may be multiple exits from the original region, make the new
1095   // function return an unsigned, switch on that number.  This loop iterates
1096   // over all of the blocks in the extracted region, updating any terminator
1097   // instructions in the to-be-extracted region that branch to blocks that are
1098   // not in the region to be extracted.
1099   std::map<BasicBlock *, BasicBlock *> ExitBlockMap;
1100 
1101   unsigned switchVal = 0;
1102   for (BasicBlock *Block : Blocks) {
1103     Instruction *TI = Block->getTerminator();
1104     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
1105       if (!Blocks.count(TI->getSuccessor(i))) {
1106         BasicBlock *OldTarget = TI->getSuccessor(i);
1107         // add a new basic block which returns the appropriate value
1108         BasicBlock *&NewTarget = ExitBlockMap[OldTarget];
1109         if (!NewTarget) {
1110           // If we don't already have an exit stub for this non-extracted
1111           // destination, create one now!
1112           NewTarget = BasicBlock::Create(Context,
1113                                          OldTarget->getName() + ".exitStub",
1114                                          newFunction);
1115           unsigned SuccNum = switchVal++;
1116 
1117           Value *brVal = nullptr;
1118           switch (NumExitBlocks) {
1119           case 0:
1120           case 1: break;  // No value needed.
1121           case 2:         // Conditional branch, return a bool
1122             brVal = ConstantInt::get(Type::getInt1Ty(Context), !SuccNum);
1123             break;
1124           default:
1125             brVal = ConstantInt::get(Type::getInt16Ty(Context), SuccNum);
1126             break;
1127           }
1128 
1129           ReturnInst::Create(Context, brVal, NewTarget);
1130 
1131           // Update the switch instruction.
1132           TheSwitch->addCase(ConstantInt::get(Type::getInt16Ty(Context),
1133                                               SuccNum),
1134                              OldTarget);
1135         }
1136 
1137         // rewrite the original branch instruction with this new target
1138         TI->setSuccessor(i, NewTarget);
1139       }
1140   }
1141 
1142   // Now that we've done the deed, simplify the switch instruction.
1143   Type *OldFnRetTy = TheSwitch->getParent()->getParent()->getReturnType();
1144   switch (NumExitBlocks) {
1145   case 0:
1146     // There are no successors (the block containing the switch itself), which
1147     // means that previously this was the last part of the function, and hence
1148     // this should be rewritten as a `ret'
1149 
1150     // Check if the function should return a value
1151     if (OldFnRetTy->isVoidTy()) {
1152       ReturnInst::Create(Context, nullptr, TheSwitch);  // Return void
1153     } else if (OldFnRetTy == TheSwitch->getCondition()->getType()) {
1154       // return what we have
1155       ReturnInst::Create(Context, TheSwitch->getCondition(), TheSwitch);
1156     } else {
1157       // Otherwise we must have code extracted an unwind or something, just
1158       // return whatever we want.
1159       ReturnInst::Create(Context,
1160                          Constant::getNullValue(OldFnRetTy), TheSwitch);
1161     }
1162 
1163     TheSwitch->eraseFromParent();
1164     break;
1165   case 1:
1166     // Only a single destination, change the switch into an unconditional
1167     // branch.
1168     BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch);
1169     TheSwitch->eraseFromParent();
1170     break;
1171   case 2:
1172     BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getSuccessor(2),
1173                        call, TheSwitch);
1174     TheSwitch->eraseFromParent();
1175     break;
1176   default:
1177     // Otherwise, make the default destination of the switch instruction be one
1178     // of the other successors.
1179     TheSwitch->setCondition(call);
1180     TheSwitch->setDefaultDest(TheSwitch->getSuccessor(NumExitBlocks));
1181     // Remove redundant case
1182     TheSwitch->removeCase(SwitchInst::CaseIt(TheSwitch, NumExitBlocks-1));
1183     break;
1184   }
1185 
1186   // Insert lifetime markers around the reloads of any output values. The
1187   // allocas output values are stored in are only in-use in the codeRepl block.
1188   insertLifetimeMarkersSurroundingCall(M, ReloadOutputs, call);
1189 
1190   return call;
1191 }
1192 
1193 void CodeExtractor::moveCodeToFunction(Function *newFunction) {
1194   Function *oldFunc = (*Blocks.begin())->getParent();
1195   Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList();
1196   Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList();
1197 
1198   for (BasicBlock *Block : Blocks) {
1199     // Delete the basic block from the old function, and the list of blocks
1200     oldBlocks.remove(Block);
1201 
1202     // Insert this basic block into the new function
1203     newBlocks.push_back(Block);
1204   }
1205 }
1206 
1207 void CodeExtractor::calculateNewCallTerminatorWeights(
1208     BasicBlock *CodeReplacer,
1209     DenseMap<BasicBlock *, BlockFrequency> &ExitWeights,
1210     BranchProbabilityInfo *BPI) {
1211   using Distribution = BlockFrequencyInfoImplBase::Distribution;
1212   using BlockNode = BlockFrequencyInfoImplBase::BlockNode;
1213 
1214   // Update the branch weights for the exit block.
1215   Instruction *TI = CodeReplacer->getTerminator();
1216   SmallVector<unsigned, 8> BranchWeights(TI->getNumSuccessors(), 0);
1217 
1218   // Block Frequency distribution with dummy node.
1219   Distribution BranchDist;
1220 
1221   // Add each of the frequencies of the successors.
1222   for (unsigned i = 0, e = TI->getNumSuccessors(); i < e; ++i) {
1223     BlockNode ExitNode(i);
1224     uint64_t ExitFreq = ExitWeights[TI->getSuccessor(i)].getFrequency();
1225     if (ExitFreq != 0)
1226       BranchDist.addExit(ExitNode, ExitFreq);
1227     else
1228       BPI->setEdgeProbability(CodeReplacer, i, BranchProbability::getZero());
1229   }
1230 
1231   // Check for no total weight.
1232   if (BranchDist.Total == 0)
1233     return;
1234 
1235   // Normalize the distribution so that they can fit in unsigned.
1236   BranchDist.normalize();
1237 
1238   // Create normalized branch weights and set the metadata.
1239   for (unsigned I = 0, E = BranchDist.Weights.size(); I < E; ++I) {
1240     const auto &Weight = BranchDist.Weights[I];
1241 
1242     // Get the weight and update the current BFI.
1243     BranchWeights[Weight.TargetNode.Index] = Weight.Amount;
1244     BranchProbability BP(Weight.Amount, BranchDist.Total);
1245     BPI->setEdgeProbability(CodeReplacer, Weight.TargetNode.Index, BP);
1246   }
1247   TI->setMetadata(
1248       LLVMContext::MD_prof,
1249       MDBuilder(TI->getContext()).createBranchWeights(BranchWeights));
1250 }
1251 
1252 Function *CodeExtractor::extractCodeRegion() {
1253   if (!isEligible())
1254     return nullptr;
1255 
1256   // Assumption: this is a single-entry code region, and the header is the first
1257   // block in the region.
1258   BasicBlock *header = *Blocks.begin();
1259   Function *oldFunction = header->getParent();
1260 
1261   // For functions with varargs, check that varargs handling is only done in the
1262   // outlined function, i.e vastart and vaend are only used in outlined blocks.
1263   if (AllowVarArgs && oldFunction->getFunctionType()->isVarArg()) {
1264     auto containsVarArgIntrinsic = [](Instruction &I) {
1265       if (const CallInst *CI = dyn_cast<CallInst>(&I))
1266         if (const Function *F = CI->getCalledFunction())
1267           return F->getIntrinsicID() == Intrinsic::vastart ||
1268                  F->getIntrinsicID() == Intrinsic::vaend;
1269       return false;
1270     };
1271 
1272     for (auto &BB : *oldFunction) {
1273       if (Blocks.count(&BB))
1274         continue;
1275       if (llvm::any_of(BB, containsVarArgIntrinsic))
1276         return nullptr;
1277     }
1278   }
1279   ValueSet inputs, outputs, SinkingCands, HoistingCands;
1280   BasicBlock *CommonExit = nullptr;
1281 
1282   // Calculate the entry frequency of the new function before we change the root
1283   //   block.
1284   BlockFrequency EntryFreq;
1285   if (BFI) {
1286     assert(BPI && "Both BPI and BFI are required to preserve profile info");
1287     for (BasicBlock *Pred : predecessors(header)) {
1288       if (Blocks.count(Pred))
1289         continue;
1290       EntryFreq +=
1291           BFI->getBlockFreq(Pred) * BPI->getEdgeProbability(Pred, header);
1292     }
1293   }
1294 
1295   // If we have any return instructions in the region, split those blocks so
1296   // that the return is not in the region.
1297   splitReturnBlocks();
1298 
1299   // Calculate the exit blocks for the extracted region and the total exit
1300   // weights for each of those blocks.
1301   DenseMap<BasicBlock *, BlockFrequency> ExitWeights;
1302   SmallPtrSet<BasicBlock *, 1> ExitBlocks;
1303   for (BasicBlock *Block : Blocks) {
1304     for (succ_iterator SI = succ_begin(Block), SE = succ_end(Block); SI != SE;
1305          ++SI) {
1306       if (!Blocks.count(*SI)) {
1307         // Update the branch weight for this successor.
1308         if (BFI) {
1309           BlockFrequency &BF = ExitWeights[*SI];
1310           BF += BFI->getBlockFreq(Block) * BPI->getEdgeProbability(Block, *SI);
1311         }
1312         ExitBlocks.insert(*SI);
1313       }
1314     }
1315   }
1316   NumExitBlocks = ExitBlocks.size();
1317 
1318   // If we have to split PHI nodes of the entry or exit blocks, do so now.
1319   severSplitPHINodesOfEntry(header);
1320   severSplitPHINodesOfExits(ExitBlocks);
1321 
1322   // This takes place of the original loop
1323   BasicBlock *codeReplacer = BasicBlock::Create(header->getContext(),
1324                                                 "codeRepl", oldFunction,
1325                                                 header);
1326 
1327   // The new function needs a root node because other nodes can branch to the
1328   // head of the region, but the entry node of a function cannot have preds.
1329   BasicBlock *newFuncRoot = BasicBlock::Create(header->getContext(),
1330                                                "newFuncRoot");
1331   auto *BranchI = BranchInst::Create(header);
1332   // If the original function has debug info, we have to add a debug location
1333   // to the new branch instruction from the artificial entry block.
1334   // We use the debug location of the first instruction in the extracted
1335   // blocks, as there is no other equivalent line in the source code.
1336   if (oldFunction->getSubprogram()) {
1337     any_of(Blocks, [&BranchI](const BasicBlock *BB) {
1338       return any_of(*BB, [&BranchI](const Instruction &I) {
1339         if (!I.getDebugLoc())
1340           return false;
1341         BranchI->setDebugLoc(I.getDebugLoc());
1342         return true;
1343       });
1344     });
1345   }
1346   newFuncRoot->getInstList().push_back(BranchI);
1347 
1348   findAllocas(SinkingCands, HoistingCands, CommonExit);
1349   assert(HoistingCands.empty() || CommonExit);
1350 
1351   // Find inputs to, outputs from the code region.
1352   findInputsOutputs(inputs, outputs, SinkingCands);
1353 
1354   // Now sink all instructions which only have non-phi uses inside the region
1355   for (auto *II : SinkingCands)
1356     cast<Instruction>(II)->moveBefore(*newFuncRoot,
1357                                       newFuncRoot->getFirstInsertionPt());
1358 
1359   if (!HoistingCands.empty()) {
1360     auto *HoistToBlock = findOrCreateBlockForHoisting(CommonExit);
1361     Instruction *TI = HoistToBlock->getTerminator();
1362     for (auto *II : HoistingCands)
1363       cast<Instruction>(II)->moveBefore(TI);
1364   }
1365 
1366   // Collect objects which are inputs to the extraction region and also
1367   // referenced by lifetime start/end markers within it. The effects of these
1368   // markers must be replicated in the calling function to prevent the stack
1369   // coloring pass from merging slots which store input objects.
1370   ValueSet InputObjectsWithLifetime =
1371       eraseLifetimeMarkersOnInputs(Blocks, SinkingCands);
1372 
1373   // Construct new function based on inputs/outputs & add allocas for all defs.
1374   Function *newFunction =
1375       constructFunction(inputs, outputs, header, newFuncRoot, codeReplacer,
1376                         oldFunction, oldFunction->getParent());
1377 
1378   // Update the entry count of the function.
1379   if (BFI) {
1380     auto Count = BFI->getProfileCountFromFreq(EntryFreq.getFrequency());
1381     if (Count.hasValue())
1382       newFunction->setEntryCount(
1383           ProfileCount(Count.getValue(), Function::PCT_Real)); // FIXME
1384     BFI->setBlockFreq(codeReplacer, EntryFreq.getFrequency());
1385   }
1386 
1387   CallInst *TheCall =
1388       emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs);
1389 
1390   moveCodeToFunction(newFunction);
1391 
1392   // Replicate the effects of any lifetime start/end markers which referenced
1393   // input objects in the extraction region by placing markers around the call.
1394   insertLifetimeMarkersSurroundingCall(oldFunction->getParent(),
1395                                        InputObjectsWithLifetime.getArrayRef(),
1396                                        TheCall);
1397 
1398   // Propagate personality info to the new function if there is one.
1399   if (oldFunction->hasPersonalityFn())
1400     newFunction->setPersonalityFn(oldFunction->getPersonalityFn());
1401 
1402   // Update the branch weights for the exit block.
1403   if (BFI && NumExitBlocks > 1)
1404     calculateNewCallTerminatorWeights(codeReplacer, ExitWeights, BPI);
1405 
1406   // Loop over all of the PHI nodes in the header and exit blocks, and change
1407   // any references to the old incoming edge to be the new incoming edge.
1408   for (BasicBlock::iterator I = header->begin(); isa<PHINode>(I); ++I) {
1409     PHINode *PN = cast<PHINode>(I);
1410     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1411       if (!Blocks.count(PN->getIncomingBlock(i)))
1412         PN->setIncomingBlock(i, newFuncRoot);
1413   }
1414 
1415   for (BasicBlock *ExitBB : ExitBlocks)
1416     for (PHINode &PN : ExitBB->phis()) {
1417       Value *IncomingCodeReplacerVal = nullptr;
1418       for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1419         // Ignore incoming values from outside of the extracted region.
1420         if (!Blocks.count(PN.getIncomingBlock(i)))
1421           continue;
1422 
1423         // Ensure that there is only one incoming value from codeReplacer.
1424         if (!IncomingCodeReplacerVal) {
1425           PN.setIncomingBlock(i, codeReplacer);
1426           IncomingCodeReplacerVal = PN.getIncomingValue(i);
1427         } else
1428           assert(IncomingCodeReplacerVal == PN.getIncomingValue(i) &&
1429                  "PHI has two incompatbile incoming values from codeRepl");
1430       }
1431     }
1432 
1433   // Erase debug info intrinsics. Variable updates within the new function are
1434   // invisible to debuggers. This could be improved by defining a DISubprogram
1435   // for the new function.
1436   for (BasicBlock &BB : *newFunction) {
1437     auto BlockIt = BB.begin();
1438     // Remove debug info intrinsics from the new function.
1439     while (BlockIt != BB.end()) {
1440       Instruction *Inst = &*BlockIt;
1441       ++BlockIt;
1442       if (isa<DbgInfoIntrinsic>(Inst))
1443         Inst->eraseFromParent();
1444     }
1445     // Remove debug info intrinsics which refer to values in the new function
1446     // from the old function.
1447     SmallVector<DbgVariableIntrinsic *, 4> DbgUsers;
1448     for (Instruction &I : BB)
1449       findDbgUsers(DbgUsers, &I);
1450     for (DbgVariableIntrinsic *DVI : DbgUsers)
1451       DVI->eraseFromParent();
1452   }
1453 
1454   // Mark the new function `noreturn` if applicable. Terminators which resume
1455   // exception propagation are treated as returning instructions. This is to
1456   // avoid inserting traps after calls to outlined functions which unwind.
1457   bool doesNotReturn = none_of(*newFunction, [](const BasicBlock &BB) {
1458     const Instruction *Term = BB.getTerminator();
1459     return isa<ReturnInst>(Term) || isa<ResumeInst>(Term);
1460   });
1461   if (doesNotReturn)
1462     newFunction->setDoesNotReturn();
1463 
1464   LLVM_DEBUG(if (verifyFunction(*newFunction, &errs())) {
1465     newFunction->dump();
1466     report_fatal_error("verification of newFunction failed!");
1467   });
1468   LLVM_DEBUG(if (verifyFunction(*oldFunction))
1469              report_fatal_error("verification of oldFunction failed!"));
1470   return newFunction;
1471 }
1472