1 //===- CodeExtractor.cpp - Pull code region into a new function -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the interface to tear out a code region, such as an
11 // individual loop or a parallel section, into a new function, replacing it with
12 // a call to the new function.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/Transforms/Utils/CodeExtractor.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/Optional.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/Analysis/BlockFrequencyInfo.h"
25 #include "llvm/Analysis/BlockFrequencyInfoImpl.h"
26 #include "llvm/Analysis/BranchProbabilityInfo.h"
27 #include "llvm/Analysis/LoopInfo.h"
28 #include "llvm/IR/Argument.h"
29 #include "llvm/IR/Attributes.h"
30 #include "llvm/IR/BasicBlock.h"
31 #include "llvm/IR/CFG.h"
32 #include "llvm/IR/Constant.h"
33 #include "llvm/IR/Constants.h"
34 #include "llvm/IR/DataLayout.h"
35 #include "llvm/IR/DerivedTypes.h"
36 #include "llvm/IR/Dominators.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/GlobalValue.h"
39 #include "llvm/IR/InstrTypes.h"
40 #include "llvm/IR/Instruction.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/IntrinsicInst.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/IR/LLVMContext.h"
45 #include "llvm/IR/MDBuilder.h"
46 #include "llvm/IR/Module.h"
47 #include "llvm/IR/Type.h"
48 #include "llvm/IR/User.h"
49 #include "llvm/IR/Value.h"
50 #include "llvm/IR/Verifier.h"
51 #include "llvm/Pass.h"
52 #include "llvm/Support/BlockFrequency.h"
53 #include "llvm/Support/BranchProbability.h"
54 #include "llvm/Support/Casting.h"
55 #include "llvm/Support/CommandLine.h"
56 #include "llvm/Support/Debug.h"
57 #include "llvm/Support/ErrorHandling.h"
58 #include "llvm/Support/raw_ostream.h"
59 #include "llvm/Transforms/Utils/BasicBlockUtils.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 
70 #define DEBUG_TYPE "code-extractor"
71 
72 // Provide a command-line option to aggregate function arguments into a struct
73 // for functions produced by the code extractor. This is useful when converting
74 // extracted functions to pthread-based code, as only one argument (void*) can
75 // be passed in to pthread_create().
76 static cl::opt<bool>
77 AggregateArgsOpt("aggregate-extracted-args", cl::Hidden,
78                  cl::desc("Aggregate arguments to code-extracted functions"));
79 
80 /// \brief Test whether a block is valid for extraction.
81 bool CodeExtractor::isBlockValidForExtraction(const BasicBlock &BB,
82                                               bool AllowVarArgs) {
83   // Landing pads must be in the function where they were inserted for cleanup.
84   if (BB.isEHPad())
85     return false;
86   // taking the address of a basic block moved to another function is illegal
87   if (BB.hasAddressTaken())
88     return false;
89 
90   // don't hoist code that uses another basicblock address, as it's likely to
91   // lead to unexpected behavior, like cross-function jumps
92   SmallPtrSet<User const *, 16> Visited;
93   SmallVector<User const *, 16> ToVisit;
94 
95   for (Instruction const &Inst : BB)
96     ToVisit.push_back(&Inst);
97 
98   while (!ToVisit.empty()) {
99     User const *Curr = ToVisit.pop_back_val();
100     if (!Visited.insert(Curr).second)
101       continue;
102     if (isa<BlockAddress const>(Curr))
103       return false; // even a reference to self is likely to be not compatible
104 
105     if (isa<Instruction>(Curr) && cast<Instruction>(Curr)->getParent() != &BB)
106       continue;
107 
108     for (auto const &U : Curr->operands()) {
109       if (auto *UU = dyn_cast<User>(U))
110         ToVisit.push_back(UU);
111     }
112   }
113 
114   // Don't hoist code containing allocas or invokes. If explicitly requested,
115   // allow vastart.
116   for (BasicBlock::const_iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
117     if (isa<AllocaInst>(I) || isa<InvokeInst>(I))
118       return false;
119     if (const CallInst *CI = dyn_cast<CallInst>(I))
120       if (const Function *F = CI->getCalledFunction())
121         if (F->getIntrinsicID() == Intrinsic::vastart) {
122           if (AllowVarArgs)
123             continue;
124           else
125             return false;
126         }
127   }
128 
129   return true;
130 }
131 
132 /// \brief Build a set of blocks to extract if the input blocks are viable.
133 static SetVector<BasicBlock *>
134 buildExtractionBlockSet(ArrayRef<BasicBlock *> BBs, DominatorTree *DT,
135                         bool AllowVarArgs) {
136   assert(!BBs.empty() && "The set of blocks to extract must be non-empty");
137   SetVector<BasicBlock *> Result;
138 
139   // Loop over the blocks, adding them to our set-vector, and aborting with an
140   // empty set if we encounter invalid blocks.
141   for (BasicBlock *BB : BBs) {
142     // If this block is dead, don't process it.
143     if (DT && !DT->isReachableFromEntry(BB))
144       continue;
145 
146     if (!Result.insert(BB))
147       llvm_unreachable("Repeated basic blocks in extraction input");
148     if (!CodeExtractor::isBlockValidForExtraction(*BB, AllowVarArgs)) {
149       Result.clear();
150       return Result;
151     }
152   }
153 
154 #ifndef NDEBUG
155   for (SetVector<BasicBlock *>::iterator I = std::next(Result.begin()),
156                                          E = Result.end();
157        I != E; ++I)
158     for (pred_iterator PI = pred_begin(*I), PE = pred_end(*I);
159          PI != PE; ++PI)
160       assert(Result.count(*PI) &&
161              "No blocks in this region may have entries from outside the region"
162              " except for the first block!");
163 #endif
164 
165   return Result;
166 }
167 
168 CodeExtractor::CodeExtractor(ArrayRef<BasicBlock *> BBs, DominatorTree *DT,
169                              bool AggregateArgs, BlockFrequencyInfo *BFI,
170                              BranchProbabilityInfo *BPI, bool AllowVarArgs)
171     : DT(DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI),
172       BPI(BPI), AllowVarArgs(AllowVarArgs),
173       Blocks(buildExtractionBlockSet(BBs, DT, AllowVarArgs)) {}
174 
175 CodeExtractor::CodeExtractor(DominatorTree &DT, Loop &L, bool AggregateArgs,
176                              BlockFrequencyInfo *BFI,
177                              BranchProbabilityInfo *BPI)
178     : DT(&DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI),
179       BPI(BPI), Blocks(buildExtractionBlockSet(L.getBlocks(), &DT,
180                                                /* AllowVarArgs */ false)) {}
181 
182 /// definedInRegion - Return true if the specified value is defined in the
183 /// extracted region.
184 static bool definedInRegion(const SetVector<BasicBlock *> &Blocks, Value *V) {
185   if (Instruction *I = dyn_cast<Instruction>(V))
186     if (Blocks.count(I->getParent()))
187       return true;
188   return false;
189 }
190 
191 /// definedInCaller - Return true if the specified value is defined in the
192 /// function being code extracted, but not in the region being extracted.
193 /// These values must be passed in as live-ins to the function.
194 static bool definedInCaller(const SetVector<BasicBlock *> &Blocks, Value *V) {
195   if (isa<Argument>(V)) return true;
196   if (Instruction *I = dyn_cast<Instruction>(V))
197     if (!Blocks.count(I->getParent()))
198       return true;
199   return false;
200 }
201 
202 static BasicBlock *getCommonExitBlock(const SetVector<BasicBlock *> &Blocks) {
203   BasicBlock *CommonExitBlock = nullptr;
204   auto hasNonCommonExitSucc = [&](BasicBlock *Block) {
205     for (auto *Succ : successors(Block)) {
206       // Internal edges, ok.
207       if (Blocks.count(Succ))
208         continue;
209       if (!CommonExitBlock) {
210         CommonExitBlock = Succ;
211         continue;
212       }
213       if (CommonExitBlock == Succ)
214         continue;
215 
216       return true;
217     }
218     return false;
219   };
220 
221   if (any_of(Blocks, hasNonCommonExitSucc))
222     return nullptr;
223 
224   return CommonExitBlock;
225 }
226 
227 bool CodeExtractor::isLegalToShrinkwrapLifetimeMarkers(
228     Instruction *Addr) const {
229   AllocaInst *AI = cast<AllocaInst>(Addr->stripInBoundsConstantOffsets());
230   Function *Func = (*Blocks.begin())->getParent();
231   for (BasicBlock &BB : *Func) {
232     if (Blocks.count(&BB))
233       continue;
234     for (Instruction &II : BB) {
235       if (isa<DbgInfoIntrinsic>(II))
236         continue;
237 
238       unsigned Opcode = II.getOpcode();
239       Value *MemAddr = nullptr;
240       switch (Opcode) {
241       case Instruction::Store:
242       case Instruction::Load: {
243         if (Opcode == Instruction::Store) {
244           StoreInst *SI = cast<StoreInst>(&II);
245           MemAddr = SI->getPointerOperand();
246         } else {
247           LoadInst *LI = cast<LoadInst>(&II);
248           MemAddr = LI->getPointerOperand();
249         }
250         // Global variable can not be aliased with locals.
251         if (dyn_cast<Constant>(MemAddr))
252           break;
253         Value *Base = MemAddr->stripInBoundsConstantOffsets();
254         if (!dyn_cast<AllocaInst>(Base) || Base == AI)
255           return false;
256         break;
257       }
258       default: {
259         IntrinsicInst *IntrInst = dyn_cast<IntrinsicInst>(&II);
260         if (IntrInst) {
261           if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_start ||
262               IntrInst->getIntrinsicID() == Intrinsic::lifetime_end)
263             break;
264           return false;
265         }
266         // Treat all the other cases conservatively if it has side effects.
267         if (II.mayHaveSideEffects())
268           return false;
269       }
270       }
271     }
272   }
273 
274   return true;
275 }
276 
277 BasicBlock *
278 CodeExtractor::findOrCreateBlockForHoisting(BasicBlock *CommonExitBlock) {
279   BasicBlock *SinglePredFromOutlineRegion = nullptr;
280   assert(!Blocks.count(CommonExitBlock) &&
281          "Expect a block outside the region!");
282   for (auto *Pred : predecessors(CommonExitBlock)) {
283     if (!Blocks.count(Pred))
284       continue;
285     if (!SinglePredFromOutlineRegion) {
286       SinglePredFromOutlineRegion = Pred;
287     } else if (SinglePredFromOutlineRegion != Pred) {
288       SinglePredFromOutlineRegion = nullptr;
289       break;
290     }
291   }
292 
293   if (SinglePredFromOutlineRegion)
294     return SinglePredFromOutlineRegion;
295 
296 #ifndef NDEBUG
297   auto getFirstPHI = [](BasicBlock *BB) {
298     BasicBlock::iterator I = BB->begin();
299     PHINode *FirstPhi = nullptr;
300     while (I != BB->end()) {
301       PHINode *Phi = dyn_cast<PHINode>(I);
302       if (!Phi)
303         break;
304       if (!FirstPhi) {
305         FirstPhi = Phi;
306         break;
307       }
308     }
309     return FirstPhi;
310   };
311   // If there are any phi nodes, the single pred either exists or has already
312   // be created before code extraction.
313   assert(!getFirstPHI(CommonExitBlock) && "Phi not expected");
314 #endif
315 
316   BasicBlock *NewExitBlock = CommonExitBlock->splitBasicBlock(
317       CommonExitBlock->getFirstNonPHI()->getIterator());
318 
319   for (auto PI = pred_begin(CommonExitBlock), PE = pred_end(CommonExitBlock);
320        PI != PE;) {
321     BasicBlock *Pred = *PI++;
322     if (Blocks.count(Pred))
323       continue;
324     Pred->getTerminator()->replaceUsesOfWith(CommonExitBlock, NewExitBlock);
325   }
326   // Now add the old exit block to the outline region.
327   Blocks.insert(CommonExitBlock);
328   return CommonExitBlock;
329 }
330 
331 void CodeExtractor::findAllocas(ValueSet &SinkCands, ValueSet &HoistCands,
332                                 BasicBlock *&ExitBlock) const {
333   Function *Func = (*Blocks.begin())->getParent();
334   ExitBlock = getCommonExitBlock(Blocks);
335 
336   for (BasicBlock &BB : *Func) {
337     if (Blocks.count(&BB))
338       continue;
339     for (Instruction &II : BB) {
340       auto *AI = dyn_cast<AllocaInst>(&II);
341       if (!AI)
342         continue;
343 
344       // Find the pair of life time markers for address 'Addr' that are either
345       // defined inside the outline region or can legally be shrinkwrapped into
346       // the outline region. If there are not other untracked uses of the
347       // address, return the pair of markers if found; otherwise return a pair
348       // of nullptr.
349       auto GetLifeTimeMarkers =
350           [&](Instruction *Addr, bool &SinkLifeStart,
351               bool &HoistLifeEnd) -> std::pair<Instruction *, Instruction *> {
352         Instruction *LifeStart = nullptr, *LifeEnd = nullptr;
353 
354         for (User *U : Addr->users()) {
355           IntrinsicInst *IntrInst = dyn_cast<IntrinsicInst>(U);
356           if (IntrInst) {
357             if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_start) {
358               // Do not handle the case where AI has multiple start markers.
359               if (LifeStart)
360                 return std::make_pair<Instruction *>(nullptr, nullptr);
361               LifeStart = IntrInst;
362             }
363             if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_end) {
364               if (LifeEnd)
365                 return std::make_pair<Instruction *>(nullptr, nullptr);
366               LifeEnd = IntrInst;
367             }
368             continue;
369           }
370           // Find untracked uses of the address, bail.
371           if (!definedInRegion(Blocks, U))
372             return std::make_pair<Instruction *>(nullptr, nullptr);
373         }
374 
375         if (!LifeStart || !LifeEnd)
376           return std::make_pair<Instruction *>(nullptr, nullptr);
377 
378         SinkLifeStart = !definedInRegion(Blocks, LifeStart);
379         HoistLifeEnd = !definedInRegion(Blocks, LifeEnd);
380         // Do legality Check.
381         if ((SinkLifeStart || HoistLifeEnd) &&
382             !isLegalToShrinkwrapLifetimeMarkers(Addr))
383           return std::make_pair<Instruction *>(nullptr, nullptr);
384 
385         // Check to see if we have a place to do hoisting, if not, bail.
386         if (HoistLifeEnd && !ExitBlock)
387           return std::make_pair<Instruction *>(nullptr, nullptr);
388 
389         return std::make_pair(LifeStart, LifeEnd);
390       };
391 
392       bool SinkLifeStart = false, HoistLifeEnd = false;
393       auto Markers = GetLifeTimeMarkers(AI, SinkLifeStart, HoistLifeEnd);
394 
395       if (Markers.first) {
396         if (SinkLifeStart)
397           SinkCands.insert(Markers.first);
398         SinkCands.insert(AI);
399         if (HoistLifeEnd)
400           HoistCands.insert(Markers.second);
401         continue;
402       }
403 
404       // Follow the bitcast.
405       Instruction *MarkerAddr = nullptr;
406       for (User *U : AI->users()) {
407         if (U->stripInBoundsConstantOffsets() == AI) {
408           SinkLifeStart = false;
409           HoistLifeEnd = false;
410           Instruction *Bitcast = cast<Instruction>(U);
411           Markers = GetLifeTimeMarkers(Bitcast, SinkLifeStart, HoistLifeEnd);
412           if (Markers.first) {
413             MarkerAddr = Bitcast;
414             continue;
415           }
416         }
417 
418         // Found unknown use of AI.
419         if (!definedInRegion(Blocks, U)) {
420           MarkerAddr = nullptr;
421           break;
422         }
423       }
424 
425       if (MarkerAddr) {
426         if (SinkLifeStart)
427           SinkCands.insert(Markers.first);
428         if (!definedInRegion(Blocks, MarkerAddr))
429           SinkCands.insert(MarkerAddr);
430         SinkCands.insert(AI);
431         if (HoistLifeEnd)
432           HoistCands.insert(Markers.second);
433       }
434     }
435   }
436 }
437 
438 void CodeExtractor::findInputsOutputs(ValueSet &Inputs, ValueSet &Outputs,
439                                       const ValueSet &SinkCands) const {
440   for (BasicBlock *BB : Blocks) {
441     // If a used value is defined outside the region, it's an input.  If an
442     // instruction is used outside the region, it's an output.
443     for (Instruction &II : *BB) {
444       for (User::op_iterator OI = II.op_begin(), OE = II.op_end(); OI != OE;
445            ++OI) {
446         Value *V = *OI;
447         if (!SinkCands.count(V) && definedInCaller(Blocks, V))
448           Inputs.insert(V);
449       }
450 
451       for (User *U : II.users())
452         if (!definedInRegion(Blocks, U)) {
453           Outputs.insert(&II);
454           break;
455         }
456     }
457   }
458 }
459 
460 /// severSplitPHINodes - If a PHI node has multiple inputs from outside of the
461 /// region, we need to split the entry block of the region so that the PHI node
462 /// is easier to deal with.
463 void CodeExtractor::severSplitPHINodes(BasicBlock *&Header) {
464   unsigned NumPredsFromRegion = 0;
465   unsigned NumPredsOutsideRegion = 0;
466 
467   if (Header != &Header->getParent()->getEntryBlock()) {
468     PHINode *PN = dyn_cast<PHINode>(Header->begin());
469     if (!PN) return;  // No PHI nodes.
470 
471     // If the header node contains any PHI nodes, check to see if there is more
472     // than one entry from outside the region.  If so, we need to sever the
473     // header block into two.
474     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
475       if (Blocks.count(PN->getIncomingBlock(i)))
476         ++NumPredsFromRegion;
477       else
478         ++NumPredsOutsideRegion;
479 
480     // If there is one (or fewer) predecessor from outside the region, we don't
481     // need to do anything special.
482     if (NumPredsOutsideRegion <= 1) return;
483   }
484 
485   // Otherwise, we need to split the header block into two pieces: one
486   // containing PHI nodes merging values from outside of the region, and a
487   // second that contains all of the code for the block and merges back any
488   // incoming values from inside of the region.
489   BasicBlock *NewBB = SplitBlock(Header, Header->getFirstNonPHI(), DT);
490 
491   // We only want to code extract the second block now, and it becomes the new
492   // header of the region.
493   BasicBlock *OldPred = Header;
494   Blocks.remove(OldPred);
495   Blocks.insert(NewBB);
496   Header = NewBB;
497 
498   // Okay, now we need to adjust the PHI nodes and any branches from within the
499   // region to go to the new header block instead of the old header block.
500   if (NumPredsFromRegion) {
501     PHINode *PN = cast<PHINode>(OldPred->begin());
502     // Loop over all of the predecessors of OldPred that are in the region,
503     // changing them to branch to NewBB instead.
504     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
505       if (Blocks.count(PN->getIncomingBlock(i))) {
506         TerminatorInst *TI = PN->getIncomingBlock(i)->getTerminator();
507         TI->replaceUsesOfWith(OldPred, NewBB);
508       }
509 
510     // Okay, everything within the region is now branching to the right block, we
511     // just have to update the PHI nodes now, inserting PHI nodes into NewBB.
512     BasicBlock::iterator AfterPHIs;
513     for (AfterPHIs = OldPred->begin(); isa<PHINode>(AfterPHIs); ++AfterPHIs) {
514       PHINode *PN = cast<PHINode>(AfterPHIs);
515       // Create a new PHI node in the new region, which has an incoming value
516       // from OldPred of PN.
517       PHINode *NewPN = PHINode::Create(PN->getType(), 1 + NumPredsFromRegion,
518                                        PN->getName() + ".ce", &NewBB->front());
519       PN->replaceAllUsesWith(NewPN);
520       NewPN->addIncoming(PN, OldPred);
521 
522       // Loop over all of the incoming value in PN, moving them to NewPN if they
523       // are from the extracted region.
524       for (unsigned i = 0; i != PN->getNumIncomingValues(); ++i) {
525         if (Blocks.count(PN->getIncomingBlock(i))) {
526           NewPN->addIncoming(PN->getIncomingValue(i), PN->getIncomingBlock(i));
527           PN->removeIncomingValue(i);
528           --i;
529         }
530       }
531     }
532   }
533 }
534 
535 void CodeExtractor::splitReturnBlocks() {
536   for (BasicBlock *Block : Blocks)
537     if (ReturnInst *RI = dyn_cast<ReturnInst>(Block->getTerminator())) {
538       BasicBlock *New =
539           Block->splitBasicBlock(RI->getIterator(), Block->getName() + ".ret");
540       if (DT) {
541         // Old dominates New. New node dominates all other nodes dominated
542         // by Old.
543         DomTreeNode *OldNode = DT->getNode(Block);
544         SmallVector<DomTreeNode *, 8> Children(OldNode->begin(),
545                                                OldNode->end());
546 
547         DomTreeNode *NewNode = DT->addNewBlock(New, Block);
548 
549         for (DomTreeNode *I : Children)
550           DT->changeImmediateDominator(I, NewNode);
551       }
552     }
553 }
554 
555 /// constructFunction - make a function based on inputs and outputs, as follows:
556 /// f(in0, ..., inN, out0, ..., outN)
557 Function *CodeExtractor::constructFunction(const ValueSet &inputs,
558                                            const ValueSet &outputs,
559                                            BasicBlock *header,
560                                            BasicBlock *newRootNode,
561                                            BasicBlock *newHeader,
562                                            Function *oldFunction,
563                                            Module *M) {
564   DEBUG(dbgs() << "inputs: " << inputs.size() << "\n");
565   DEBUG(dbgs() << "outputs: " << outputs.size() << "\n");
566 
567   // This function returns unsigned, outputs will go back by reference.
568   switch (NumExitBlocks) {
569   case 0:
570   case 1: RetTy = Type::getVoidTy(header->getContext()); break;
571   case 2: RetTy = Type::getInt1Ty(header->getContext()); break;
572   default: RetTy = Type::getInt16Ty(header->getContext()); break;
573   }
574 
575   std::vector<Type *> paramTy;
576 
577   // Add the types of the input values to the function's argument list
578   for (Value *value : inputs) {
579     DEBUG(dbgs() << "value used in func: " << *value << "\n");
580     paramTy.push_back(value->getType());
581   }
582 
583   // Add the types of the output values to the function's argument list.
584   for (Value *output : outputs) {
585     DEBUG(dbgs() << "instr used in func: " << *output << "\n");
586     if (AggregateArgs)
587       paramTy.push_back(output->getType());
588     else
589       paramTy.push_back(PointerType::getUnqual(output->getType()));
590   }
591 
592   DEBUG({
593     dbgs() << "Function type: " << *RetTy << " f(";
594     for (Type *i : paramTy)
595       dbgs() << *i << ", ";
596     dbgs() << ")\n";
597   });
598 
599   StructType *StructTy;
600   if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
601     StructTy = StructType::get(M->getContext(), paramTy);
602     paramTy.clear();
603     paramTy.push_back(PointerType::getUnqual(StructTy));
604   }
605   FunctionType *funcType =
606                   FunctionType::get(RetTy, paramTy,
607                                     AllowVarArgs && oldFunction->isVarArg());
608 
609   // Create the new function
610   Function *newFunction = Function::Create(funcType,
611                                            GlobalValue::InternalLinkage,
612                                            oldFunction->getName() + "_" +
613                                            header->getName(), M);
614   // If the old function is no-throw, so is the new one.
615   if (oldFunction->doesNotThrow())
616     newFunction->setDoesNotThrow();
617 
618   // Inherit the uwtable attribute if we need to.
619   if (oldFunction->hasUWTable())
620     newFunction->setHasUWTable();
621 
622   // Inherit all of the target dependent attributes.
623   //  (e.g. If the extracted region contains a call to an x86.sse
624   //  instruction we need to make sure that the extracted region has the
625   //  "target-features" attribute allowing it to be lowered.
626   // FIXME: This should be changed to check to see if a specific
627   //           attribute can not be inherited.
628   AttrBuilder AB(oldFunction->getAttributes().getFnAttributes());
629   for (const auto &Attr : AB.td_attrs())
630     newFunction->addFnAttr(Attr.first, Attr.second);
631 
632   newFunction->getBasicBlockList().push_back(newRootNode);
633 
634   // Create an iterator to name all of the arguments we inserted.
635   Function::arg_iterator AI = newFunction->arg_begin();
636 
637   // Rewrite all users of the inputs in the extracted region to use the
638   // arguments (or appropriate addressing into struct) instead.
639   for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
640     Value *RewriteVal;
641     if (AggregateArgs) {
642       Value *Idx[2];
643       Idx[0] = Constant::getNullValue(Type::getInt32Ty(header->getContext()));
644       Idx[1] = ConstantInt::get(Type::getInt32Ty(header->getContext()), i);
645       TerminatorInst *TI = newFunction->begin()->getTerminator();
646       GetElementPtrInst *GEP = GetElementPtrInst::Create(
647           StructTy, &*AI, Idx, "gep_" + inputs[i]->getName(), TI);
648       RewriteVal = new LoadInst(GEP, "loadgep_" + inputs[i]->getName(), TI);
649     } else
650       RewriteVal = &*AI++;
651 
652     std::vector<User *> Users(inputs[i]->user_begin(), inputs[i]->user_end());
653     for (User *use : Users)
654       if (Instruction *inst = dyn_cast<Instruction>(use))
655         if (Blocks.count(inst->getParent()))
656           inst->replaceUsesOfWith(inputs[i], RewriteVal);
657   }
658 
659   // Set names for input and output arguments.
660   if (!AggregateArgs) {
661     AI = newFunction->arg_begin();
662     for (unsigned i = 0, e = inputs.size(); i != e; ++i, ++AI)
663       AI->setName(inputs[i]->getName());
664     for (unsigned i = 0, e = outputs.size(); i != e; ++i, ++AI)
665       AI->setName(outputs[i]->getName()+".out");
666   }
667 
668   // Rewrite branches to basic blocks outside of the loop to new dummy blocks
669   // within the new function. This must be done before we lose track of which
670   // blocks were originally in the code region.
671   std::vector<User *> Users(header->user_begin(), header->user_end());
672   for (unsigned i = 0, e = Users.size(); i != e; ++i)
673     // The BasicBlock which contains the branch is not in the region
674     // modify the branch target to a new block
675     if (TerminatorInst *TI = dyn_cast<TerminatorInst>(Users[i]))
676       if (!Blocks.count(TI->getParent()) &&
677           TI->getParent()->getParent() == oldFunction)
678         TI->replaceUsesOfWith(header, newHeader);
679 
680   return newFunction;
681 }
682 
683 /// emitCallAndSwitchStatement - This method sets up the caller side by adding
684 /// the call instruction, splitting any PHI nodes in the header block as
685 /// necessary.
686 void CodeExtractor::
687 emitCallAndSwitchStatement(Function *newFunction, BasicBlock *codeReplacer,
688                            ValueSet &inputs, ValueSet &outputs) {
689   // Emit a call to the new function, passing in: *pointer to struct (if
690   // aggregating parameters), or plan inputs and allocated memory for outputs
691   std::vector<Value *> params, StructValues, ReloadOutputs, Reloads;
692 
693   Module *M = newFunction->getParent();
694   LLVMContext &Context = M->getContext();
695   const DataLayout &DL = M->getDataLayout();
696 
697   // Add inputs as params, or to be filled into the struct
698   for (Value *input : inputs)
699     if (AggregateArgs)
700       StructValues.push_back(input);
701     else
702       params.push_back(input);
703 
704   // Create allocas for the outputs
705   for (Value *output : outputs) {
706     if (AggregateArgs) {
707       StructValues.push_back(output);
708     } else {
709       AllocaInst *alloca =
710         new AllocaInst(output->getType(), DL.getAllocaAddrSpace(),
711                        nullptr, output->getName() + ".loc",
712                        &codeReplacer->getParent()->front().front());
713       ReloadOutputs.push_back(alloca);
714       params.push_back(alloca);
715     }
716   }
717 
718   StructType *StructArgTy = nullptr;
719   AllocaInst *Struct = nullptr;
720   if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
721     std::vector<Type *> ArgTypes;
722     for (ValueSet::iterator v = StructValues.begin(),
723            ve = StructValues.end(); v != ve; ++v)
724       ArgTypes.push_back((*v)->getType());
725 
726     // Allocate a struct at the beginning of this function
727     StructArgTy = StructType::get(newFunction->getContext(), ArgTypes);
728     Struct = new AllocaInst(StructArgTy, DL.getAllocaAddrSpace(), nullptr,
729                             "structArg",
730                             &codeReplacer->getParent()->front().front());
731     params.push_back(Struct);
732 
733     for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
734       Value *Idx[2];
735       Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
736       Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), i);
737       GetElementPtrInst *GEP = GetElementPtrInst::Create(
738           StructArgTy, Struct, Idx, "gep_" + StructValues[i]->getName());
739       codeReplacer->getInstList().push_back(GEP);
740       StoreInst *SI = new StoreInst(StructValues[i], GEP);
741       codeReplacer->getInstList().push_back(SI);
742     }
743   }
744 
745   // Emit the call to the function
746   CallInst *call = CallInst::Create(newFunction, params,
747                                     NumExitBlocks > 1 ? "targetBlock" : "");
748   codeReplacer->getInstList().push_back(call);
749 
750   Function::arg_iterator OutputArgBegin = newFunction->arg_begin();
751   unsigned FirstOut = inputs.size();
752   if (!AggregateArgs)
753     std::advance(OutputArgBegin, inputs.size());
754 
755   // Reload the outputs passed in by reference.
756   Function::arg_iterator OAI = OutputArgBegin;
757   for (unsigned i = 0, e = outputs.size(); i != e; ++i) {
758     Value *Output = nullptr;
759     if (AggregateArgs) {
760       Value *Idx[2];
761       Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
762       Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i);
763       GetElementPtrInst *GEP = GetElementPtrInst::Create(
764           StructArgTy, Struct, Idx, "gep_reload_" + outputs[i]->getName());
765       codeReplacer->getInstList().push_back(GEP);
766       Output = GEP;
767     } else {
768       Output = ReloadOutputs[i];
769     }
770     LoadInst *load = new LoadInst(Output, outputs[i]->getName()+".reload");
771     Reloads.push_back(load);
772     codeReplacer->getInstList().push_back(load);
773     std::vector<User *> Users(outputs[i]->user_begin(), outputs[i]->user_end());
774     for (unsigned u = 0, e = Users.size(); u != e; ++u) {
775       Instruction *inst = cast<Instruction>(Users[u]);
776       if (!Blocks.count(inst->getParent()))
777         inst->replaceUsesOfWith(outputs[i], load);
778     }
779 
780     // Store to argument right after the definition of output value.
781     auto *OutI = dyn_cast<Instruction>(outputs[i]);
782     if (!OutI)
783       continue;
784     // Find proper insertion point.
785     Instruction *InsertPt = OutI->getNextNode();
786     // Let's assume that there is no other guy interleave non-PHI in PHIs.
787     if (isa<PHINode>(InsertPt))
788       InsertPt = InsertPt->getParent()->getFirstNonPHI();
789 
790     assert(OAI != newFunction->arg_end() &&
791            "Number of output arguments should match "
792            "the amount of defined values");
793     if (AggregateArgs) {
794       Value *Idx[2];
795       Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
796       Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i);
797       GetElementPtrInst *GEP = GetElementPtrInst::Create(
798           StructArgTy, &*OAI, Idx, "gep_" + outputs[i]->getName(), InsertPt);
799       new StoreInst(outputs[i], GEP, InsertPt);
800       // Since there should be only one struct argument aggregating
801       // all the output values, we shouldn't increment OAI, which always
802       // points to the struct argument, in this case.
803     } else {
804       new StoreInst(outputs[i], &*OAI, InsertPt);
805       ++OAI;
806     }
807   }
808 
809   // Now we can emit a switch statement using the call as a value.
810   SwitchInst *TheSwitch =
811       SwitchInst::Create(Constant::getNullValue(Type::getInt16Ty(Context)),
812                          codeReplacer, 0, codeReplacer);
813 
814   // Since there may be multiple exits from the original region, make the new
815   // function return an unsigned, switch on that number.  This loop iterates
816   // over all of the blocks in the extracted region, updating any terminator
817   // instructions in the to-be-extracted region that branch to blocks that are
818   // not in the region to be extracted.
819   std::map<BasicBlock *, BasicBlock *> ExitBlockMap;
820 
821   unsigned switchVal = 0;
822   for (BasicBlock *Block : Blocks) {
823     TerminatorInst *TI = Block->getTerminator();
824     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
825       if (!Blocks.count(TI->getSuccessor(i))) {
826         BasicBlock *OldTarget = TI->getSuccessor(i);
827         // add a new basic block which returns the appropriate value
828         BasicBlock *&NewTarget = ExitBlockMap[OldTarget];
829         if (!NewTarget) {
830           // If we don't already have an exit stub for this non-extracted
831           // destination, create one now!
832           NewTarget = BasicBlock::Create(Context,
833                                          OldTarget->getName() + ".exitStub",
834                                          newFunction);
835           unsigned SuccNum = switchVal++;
836 
837           Value *brVal = nullptr;
838           switch (NumExitBlocks) {
839           case 0:
840           case 1: break;  // No value needed.
841           case 2:         // Conditional branch, return a bool
842             brVal = ConstantInt::get(Type::getInt1Ty(Context), !SuccNum);
843             break;
844           default:
845             brVal = ConstantInt::get(Type::getInt16Ty(Context), SuccNum);
846             break;
847           }
848 
849           ReturnInst::Create(Context, brVal, NewTarget);
850 
851           // Update the switch instruction.
852           TheSwitch->addCase(ConstantInt::get(Type::getInt16Ty(Context),
853                                               SuccNum),
854                              OldTarget);
855         }
856 
857         // rewrite the original branch instruction with this new target
858         TI->setSuccessor(i, NewTarget);
859       }
860   }
861 
862   // Now that we've done the deed, simplify the switch instruction.
863   Type *OldFnRetTy = TheSwitch->getParent()->getParent()->getReturnType();
864   switch (NumExitBlocks) {
865   case 0:
866     // There are no successors (the block containing the switch itself), which
867     // means that previously this was the last part of the function, and hence
868     // this should be rewritten as a `ret'
869 
870     // Check if the function should return a value
871     if (OldFnRetTy->isVoidTy()) {
872       ReturnInst::Create(Context, nullptr, TheSwitch);  // Return void
873     } else if (OldFnRetTy == TheSwitch->getCondition()->getType()) {
874       // return what we have
875       ReturnInst::Create(Context, TheSwitch->getCondition(), TheSwitch);
876     } else {
877       // Otherwise we must have code extracted an unwind or something, just
878       // return whatever we want.
879       ReturnInst::Create(Context,
880                          Constant::getNullValue(OldFnRetTy), TheSwitch);
881     }
882 
883     TheSwitch->eraseFromParent();
884     break;
885   case 1:
886     // Only a single destination, change the switch into an unconditional
887     // branch.
888     BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch);
889     TheSwitch->eraseFromParent();
890     break;
891   case 2:
892     BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getSuccessor(2),
893                        call, TheSwitch);
894     TheSwitch->eraseFromParent();
895     break;
896   default:
897     // Otherwise, make the default destination of the switch instruction be one
898     // of the other successors.
899     TheSwitch->setCondition(call);
900     TheSwitch->setDefaultDest(TheSwitch->getSuccessor(NumExitBlocks));
901     // Remove redundant case
902     TheSwitch->removeCase(SwitchInst::CaseIt(TheSwitch, NumExitBlocks-1));
903     break;
904   }
905 }
906 
907 void CodeExtractor::moveCodeToFunction(Function *newFunction) {
908   Function *oldFunc = (*Blocks.begin())->getParent();
909   Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList();
910   Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList();
911 
912   for (BasicBlock *Block : Blocks) {
913     // Delete the basic block from the old function, and the list of blocks
914     oldBlocks.remove(Block);
915 
916     // Insert this basic block into the new function
917     newBlocks.push_back(Block);
918   }
919 }
920 
921 void CodeExtractor::calculateNewCallTerminatorWeights(
922     BasicBlock *CodeReplacer,
923     DenseMap<BasicBlock *, BlockFrequency> &ExitWeights,
924     BranchProbabilityInfo *BPI) {
925   using Distribution = BlockFrequencyInfoImplBase::Distribution;
926   using BlockNode = BlockFrequencyInfoImplBase::BlockNode;
927 
928   // Update the branch weights for the exit block.
929   TerminatorInst *TI = CodeReplacer->getTerminator();
930   SmallVector<unsigned, 8> BranchWeights(TI->getNumSuccessors(), 0);
931 
932   // Block Frequency distribution with dummy node.
933   Distribution BranchDist;
934 
935   // Add each of the frequencies of the successors.
936   for (unsigned i = 0, e = TI->getNumSuccessors(); i < e; ++i) {
937     BlockNode ExitNode(i);
938     uint64_t ExitFreq = ExitWeights[TI->getSuccessor(i)].getFrequency();
939     if (ExitFreq != 0)
940       BranchDist.addExit(ExitNode, ExitFreq);
941     else
942       BPI->setEdgeProbability(CodeReplacer, i, BranchProbability::getZero());
943   }
944 
945   // Check for no total weight.
946   if (BranchDist.Total == 0)
947     return;
948 
949   // Normalize the distribution so that they can fit in unsigned.
950   BranchDist.normalize();
951 
952   // Create normalized branch weights and set the metadata.
953   for (unsigned I = 0, E = BranchDist.Weights.size(); I < E; ++I) {
954     const auto &Weight = BranchDist.Weights[I];
955 
956     // Get the weight and update the current BFI.
957     BranchWeights[Weight.TargetNode.Index] = Weight.Amount;
958     BranchProbability BP(Weight.Amount, BranchDist.Total);
959     BPI->setEdgeProbability(CodeReplacer, Weight.TargetNode.Index, BP);
960   }
961   TI->setMetadata(
962       LLVMContext::MD_prof,
963       MDBuilder(TI->getContext()).createBranchWeights(BranchWeights));
964 }
965 
966 Function *CodeExtractor::extractCodeRegion() {
967   if (!isEligible())
968     return nullptr;
969 
970   // Assumption: this is a single-entry code region, and the header is the first
971   // block in the region.
972   BasicBlock *header = *Blocks.begin();
973   Function *oldFunction = header->getParent();
974 
975   // For functions with varargs, check that varargs handling is only done in the
976   // outlined function, i.e vastart and vaend are only used in outlined blocks.
977   if (AllowVarArgs && oldFunction->getFunctionType()->isVarArg()) {
978     auto containsVarArgIntrinsic = [](Instruction &I) {
979       if (const CallInst *CI = dyn_cast<CallInst>(&I))
980         if (const Function *F = CI->getCalledFunction())
981           return F->getIntrinsicID() == Intrinsic::vastart ||
982                  F->getIntrinsicID() == Intrinsic::vaend;
983       return false;
984     };
985 
986     for (auto &BB : *oldFunction) {
987       if (Blocks.count(&BB))
988         continue;
989       if (llvm::any_of(BB, containsVarArgIntrinsic))
990         return nullptr;
991     }
992   }
993   ValueSet inputs, outputs, SinkingCands, HoistingCands;
994   BasicBlock *CommonExit = nullptr;
995 
996   // Calculate the entry frequency of the new function before we change the root
997   //   block.
998   BlockFrequency EntryFreq;
999   if (BFI) {
1000     assert(BPI && "Both BPI and BFI are required to preserve profile info");
1001     for (BasicBlock *Pred : predecessors(header)) {
1002       if (Blocks.count(Pred))
1003         continue;
1004       EntryFreq +=
1005           BFI->getBlockFreq(Pred) * BPI->getEdgeProbability(Pred, header);
1006     }
1007   }
1008 
1009   // If we have to split PHI nodes or the entry block, do so now.
1010   severSplitPHINodes(header);
1011 
1012   // If we have any return instructions in the region, split those blocks so
1013   // that the return is not in the region.
1014   splitReturnBlocks();
1015 
1016   // This takes place of the original loop
1017   BasicBlock *codeReplacer = BasicBlock::Create(header->getContext(),
1018                                                 "codeRepl", oldFunction,
1019                                                 header);
1020 
1021   // The new function needs a root node because other nodes can branch to the
1022   // head of the region, but the entry node of a function cannot have preds.
1023   BasicBlock *newFuncRoot = BasicBlock::Create(header->getContext(),
1024                                                "newFuncRoot");
1025   newFuncRoot->getInstList().push_back(BranchInst::Create(header));
1026 
1027   findAllocas(SinkingCands, HoistingCands, CommonExit);
1028   assert(HoistingCands.empty() || CommonExit);
1029 
1030   // Find inputs to, outputs from the code region.
1031   findInputsOutputs(inputs, outputs, SinkingCands);
1032 
1033   // Now sink all instructions which only have non-phi uses inside the region
1034   for (auto *II : SinkingCands)
1035     cast<Instruction>(II)->moveBefore(*newFuncRoot,
1036                                       newFuncRoot->getFirstInsertionPt());
1037 
1038   if (!HoistingCands.empty()) {
1039     auto *HoistToBlock = findOrCreateBlockForHoisting(CommonExit);
1040     Instruction *TI = HoistToBlock->getTerminator();
1041     for (auto *II : HoistingCands)
1042       cast<Instruction>(II)->moveBefore(TI);
1043   }
1044 
1045   // Calculate the exit blocks for the extracted region and the total exit
1046   // weights for each of those blocks.
1047   DenseMap<BasicBlock *, BlockFrequency> ExitWeights;
1048   SmallPtrSet<BasicBlock *, 1> ExitBlocks;
1049   for (BasicBlock *Block : Blocks) {
1050     for (succ_iterator SI = succ_begin(Block), SE = succ_end(Block); SI != SE;
1051          ++SI) {
1052       if (!Blocks.count(*SI)) {
1053         // Update the branch weight for this successor.
1054         if (BFI) {
1055           BlockFrequency &BF = ExitWeights[*SI];
1056           BF += BFI->getBlockFreq(Block) * BPI->getEdgeProbability(Block, *SI);
1057         }
1058         ExitBlocks.insert(*SI);
1059       }
1060     }
1061   }
1062   NumExitBlocks = ExitBlocks.size();
1063 
1064   // Construct new function based on inputs/outputs & add allocas for all defs.
1065   Function *newFunction = constructFunction(inputs, outputs, header,
1066                                             newFuncRoot,
1067                                             codeReplacer, oldFunction,
1068                                             oldFunction->getParent());
1069 
1070   // Update the entry count of the function.
1071   if (BFI) {
1072     Optional<uint64_t> EntryCount =
1073         BFI->getProfileCountFromFreq(EntryFreq.getFrequency());
1074     if (EntryCount.hasValue())
1075       newFunction->setEntryCount(EntryCount.getValue());
1076     BFI->setBlockFreq(codeReplacer, EntryFreq.getFrequency());
1077   }
1078 
1079   emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs);
1080 
1081   moveCodeToFunction(newFunction);
1082 
1083   // Update the branch weights for the exit block.
1084   if (BFI && NumExitBlocks > 1)
1085     calculateNewCallTerminatorWeights(codeReplacer, ExitWeights, BPI);
1086 
1087   // Loop over all of the PHI nodes in the header block, and change any
1088   // references to the old incoming edge to be the new incoming edge.
1089   for (BasicBlock::iterator I = header->begin(); isa<PHINode>(I); ++I) {
1090     PHINode *PN = cast<PHINode>(I);
1091     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1092       if (!Blocks.count(PN->getIncomingBlock(i)))
1093         PN->setIncomingBlock(i, newFuncRoot);
1094   }
1095 
1096   // Look at all successors of the codeReplacer block.  If any of these blocks
1097   // had PHI nodes in them, we need to update the "from" block to be the code
1098   // replacer, not the original block in the extracted region.
1099   std::vector<BasicBlock *> Succs(succ_begin(codeReplacer),
1100                                   succ_end(codeReplacer));
1101   for (unsigned i = 0, e = Succs.size(); i != e; ++i)
1102     for (BasicBlock::iterator I = Succs[i]->begin(); isa<PHINode>(I); ++I) {
1103       PHINode *PN = cast<PHINode>(I);
1104       std::set<BasicBlock*> ProcessedPreds;
1105       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1106         if (Blocks.count(PN->getIncomingBlock(i))) {
1107           if (ProcessedPreds.insert(PN->getIncomingBlock(i)).second)
1108             PN->setIncomingBlock(i, codeReplacer);
1109           else {
1110             // There were multiple entries in the PHI for this block, now there
1111             // is only one, so remove the duplicated entries.
1112             PN->removeIncomingValue(i, false);
1113             --i; --e;
1114           }
1115         }
1116     }
1117 
1118   DEBUG(if (verifyFunction(*newFunction))
1119         report_fatal_error("verifyFunction failed!"));
1120   return newFunction;
1121 }
1122