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