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