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