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