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