LLVM 24.0.0git
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/STLExtras.h"
19#include "llvm/ADT/SetVector.h"
26#include "llvm/IR/Argument.h"
27#include "llvm/IR/Attributes.h"
28#include "llvm/IR/CFG.h"
29#include "llvm/IR/Constant.h"
30#include "llvm/IR/Constants.h"
31#include "llvm/IR/DIBuilder.h"
32#include "llvm/IR/DataLayout.h"
33#include "llvm/IR/DebugInfo.h"
36#include "llvm/IR/Dominators.h"
37#include "llvm/IR/Function.h"
38#include "llvm/IR/GlobalValue.h"
40#include "llvm/IR/InstrTypes.h"
41#include "llvm/IR/Instruction.h"
44#include "llvm/IR/Intrinsics.h"
45#include "llvm/IR/LLVMContext.h"
46#include "llvm/IR/MDBuilder.h"
47#include "llvm/IR/Module.h"
49#include "llvm/IR/Type.h"
50#include "llvm/IR/User.h"
51#include "llvm/IR/Value.h"
52#include "llvm/IR/Verifier.h"
57#include "llvm/Support/Debug.h"
61#include <cassert>
62#include <cstdint>
63#include <iterator>
64#include <map>
65#include <vector>
66
67using namespace llvm;
68using namespace llvm::PatternMatch;
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().
76static cl::opt<bool>
77AggregateArgsOpt("aggregate-extracted-args", cl::Hidden,
78 cl::desc("Aggregate arguments to code-extracted functions"));
79
80/// Test whether a block is valid for extraction.
82 const SetVector<BasicBlock *> &Result,
83 bool AllowVarArgs, bool AllowAlloca) {
84 // taking the address of a basic block moved to another function is illegal
85 if (BB.hasAddressTaken())
86 return false;
87
88 // don't hoist code that uses another basicblock address, as it's likely to
89 // lead to unexpected behavior, like cross-function jumps
92
93 while (!ToVisit.empty()) {
94 User const *Curr = ToVisit.pop_back_val();
95 if (!Visited.insert(Curr).second)
96 continue;
98 return false; // even a reference to self is likely to be not compatible
99
100 if (isa<Instruction>(Curr) && cast<Instruction>(Curr)->getParent() != &BB)
101 continue;
102
103 for (auto const &U : Curr->operands()) {
104 if (auto *UU = dyn_cast<User>(U))
105 ToVisit.push_back(UU);
106 }
107 }
108
109 // If explicitly requested, allow vastart and alloca. For invoke instructions
110 // verify that extraction is valid.
111 for (BasicBlock::const_iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
112 if (isa<AllocaInst>(I)) {
113 if (!AllowAlloca)
114 return false;
115 continue;
116 }
117
118 if (const auto *II = dyn_cast<InvokeInst>(I)) {
119 // Unwind destination (either a landingpad, catchswitch, or cleanuppad)
120 // must be a part of the subgraph which is being extracted.
121 if (auto *UBB = II->getUnwindDest())
122 if (!Result.count(UBB))
123 return false;
124 continue;
125 }
126
127 // All catch handlers of a catchswitch instruction as well as the unwind
128 // destination must be in the subgraph.
129 if (const auto *CSI = dyn_cast<CatchSwitchInst>(I)) {
130 if (auto *UBB = CSI->getUnwindDest())
131 if (!Result.count(UBB))
132 return false;
133 for (const auto *HBB : CSI->handlers())
134 if (!Result.count(const_cast<BasicBlock*>(HBB)))
135 return false;
136 continue;
137 }
138
139 // Make sure that entire catch handler is within subgraph. It is sufficient
140 // to check that catch return's block is in the list.
141 if (const auto *CPI = dyn_cast<CatchPadInst>(I)) {
142 for (const auto *U : CPI->users())
143 if (const auto *CRI = dyn_cast<CatchReturnInst>(U))
144 if (!Result.count(const_cast<BasicBlock*>(CRI->getParent())))
145 return false;
146 continue;
147 }
148
149 // And do similar checks for cleanup handler - the entire handler must be
150 // in subgraph which is going to be extracted. For cleanup return should
151 // additionally check that the unwind destination is also in the subgraph.
152 if (const auto *CPI = dyn_cast<CleanupPadInst>(I)) {
153 for (const auto *U : CPI->users())
154 if (const auto *CRI = dyn_cast<CleanupReturnInst>(U))
155 if (!Result.count(const_cast<BasicBlock*>(CRI->getParent())))
156 return false;
157 continue;
158 }
159 if (const auto *CRI = dyn_cast<CleanupReturnInst>(I)) {
160 if (auto *UBB = CRI->getUnwindDest())
161 if (!Result.count(UBB))
162 return false;
163 continue;
164 }
165
166 // llvm.experimental.deoptimize must return the enclosing function's return
167 // type. Extraction changes the outlined function signature, which can make
168 // the deoptimize call invalid.
170 return false;
171
172 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
173 // musttail calls have several restrictions, generally enforcing matching
174 // calling conventions between the caller parent and musttail callee.
175 // We can't usually honor them, because the extracted function has a
176 // different signature altogether, taking inputs/outputs and returning
177 // a control-flow identifier rather than the actual return value.
178 if (CI->isMustTailCall())
179 return false;
180
181 if (const Function *F = CI->getCalledFunction()) {
182 auto IID = F->getIntrinsicID();
183 if (IID == Intrinsic::vastart) {
184 if (AllowVarArgs)
185 continue;
186 else
187 return false;
188 }
189
190 // Currently, we miscompile outlined copies of eh_typid_for. There are
191 // proposals for fixing this in llvm.org/PR39545.
192 if (IID == Intrinsic::eh_typeid_for)
193 return false;
194 }
195 }
196 }
197
198 return true;
199}
200
201/// Build a set of blocks to extract if the input blocks are viable.
204 bool AllowVarArgs, bool AllowAlloca) {
205 assert(!BBs.empty() && "The set of blocks to extract must be non-empty");
207
208 // Loop over the blocks, adding them to our set-vector, and aborting with an
209 // empty set if we encounter invalid blocks.
210 for (BasicBlock *BB : BBs) {
211 // If this block is dead, don't process it.
212 if (DT && !DT->isReachableFromEntry(BB))
213 continue;
214
215 if (!Result.insert(BB))
216 llvm_unreachable("Repeated basic blocks in extraction input");
217 }
218
219 LLVM_DEBUG(dbgs() << "Region front block: " << Result.front()->getName()
220 << '\n');
221
222 for (auto *BB : Result) {
223 if (!isBlockValidForExtraction(*BB, Result, AllowVarArgs, AllowAlloca))
224 return {};
225
226 // Make sure that the first block is not a landing pad.
227 if (BB == Result.front()) {
228 if (BB->isEHPad()) {
229 LLVM_DEBUG(dbgs() << "The first block cannot be an unwind block\n");
230 return {};
231 }
232 continue;
233 }
234
235 // All blocks other than the first must not have predecessors outside of
236 // the subgraph which is being extracted.
237 for (auto *PBB : predecessors(BB))
238 if (!Result.count(PBB)) {
239 LLVM_DEBUG(dbgs() << "No blocks in this region may have entries from "
240 "outside the region except for the first block!\n"
241 << "Problematic source BB: " << BB->getName() << "\n"
242 << "Problematic destination BB: " << PBB->getName()
243 << "\n");
244 return {};
245 }
246 }
247
248 return Result;
249}
250
251/// isAlignmentPreservedForAddrCast - Return true if the cast operation
252/// for specified target preserves original alignment
253static bool isAlignmentPreservedForAddrCast(const Triple &TargetTriple) {
254 switch (TargetTriple.getArch()) {
257 return true;
258 // TODO: Add other architectures for which we are certain that alignment
259 // is preserved during address space cast operations.
260 default:
261 return false;
262 }
263 return false;
264}
265
267 bool AggregateArgs, BlockFrequencyInfo *BFI,
269 bool AllowVarArgs, bool AllowAlloca,
270 BasicBlock *AllocationBlock,
271 ArrayRef<BasicBlock *> DeallocationBlocks,
272 std::string Suffix, bool ArgsInZeroAddressSpace,
273 bool VoidReturnWithSingleOutput)
274 : DT(DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI),
275 BPI(BPI), AC(AC), AllocationBlock(AllocationBlock),
276 DeallocationBlocks(DeallocationBlocks), AllowVarArgs(AllowVarArgs),
277 Blocks(buildExtractionBlockSet(BBs, DT, AllowVarArgs, AllowAlloca)),
278 Suffix(Suffix), ArgsInZeroAddressSpace(ArgsInZeroAddressSpace),
279 VoidReturnWithSingleOutput(VoidReturnWithSingleOutput) {}
280
281/// definedInRegion - Return true if the specified value is defined in the
282/// extracted region.
283static bool definedInRegion(const SetVector<BasicBlock *> &Blocks, Value *V) {
285 if (Blocks.count(I->getParent()))
286 return true;
287 return false;
288}
289
290/// definedInCaller - Return true if the specified value is defined in the
291/// function being code extracted, but not in the region being extracted.
292/// These values must be passed in as live-ins to the function.
293static bool definedInCaller(const SetVector<BasicBlock *> &Blocks, Value *V) {
294 if (isa<Argument>(V)) return true;
296 if (!Blocks.count(I->getParent()))
297 return true;
298 return false;
299}
300
302 BasicBlock *CommonExitBlock = nullptr;
303 auto hasNonCommonExitSucc = [&](BasicBlock *Block) {
304 for (auto *Succ : successors(Block)) {
305 // Internal edges, ok.
306 if (Blocks.count(Succ))
307 continue;
308 if (!CommonExitBlock) {
309 CommonExitBlock = Succ;
310 continue;
311 }
312 if (CommonExitBlock != Succ)
313 return true;
314 }
315 return false;
316 };
317
318 if (any_of(Blocks, hasNonCommonExitSucc))
319 return nullptr;
320
321 return CommonExitBlock;
322}
323
325 for (BasicBlock &BB : F) {
326 for (Instruction &II : BB)
327 if (auto *AI = dyn_cast<AllocaInst>(&II))
328 Allocas.push_back(AI);
329
330 findSideEffectInfoForBlock(BB);
331 }
332}
333
334void CodeExtractorAnalysisCache::findSideEffectInfoForBlock(BasicBlock &BB) {
335 for (Instruction &II : BB) {
336 unsigned Opcode = II.getOpcode();
337 Value *MemAddr = nullptr;
338 switch (Opcode) {
339 case Instruction::Store:
340 case Instruction::Load: {
341 if (Opcode == Instruction::Store) {
343 MemAddr = SI->getPointerOperand();
344 } else {
345 LoadInst *LI = cast<LoadInst>(&II);
346 MemAddr = LI->getPointerOperand();
347 }
348 // Global variable can not be aliased with locals.
349 if (isa<Constant>(MemAddr))
350 break;
352 if (!isa<AllocaInst>(Base)) {
353 SideEffectingBlocks.insert(&BB);
354 return;
355 }
356 BaseMemAddrs[&BB].insert(Base);
357 break;
358 }
359 default: {
360 IntrinsicInst *IntrInst = dyn_cast<IntrinsicInst>(&II);
361 if (IntrInst) {
362 if (IntrInst->isLifetimeStartOrEnd() || isa<PseudoProbeInst>(IntrInst))
363 break;
364 SideEffectingBlocks.insert(&BB);
365 return;
366 }
367 // Treat all the other cases conservatively if it has side effects.
368 if (II.mayHaveSideEffects()) {
369 SideEffectingBlocks.insert(&BB);
370 return;
371 }
372 }
373 }
374 }
375}
376
378 BasicBlock &BB, AllocaInst *Addr) const {
379 if (SideEffectingBlocks.count(&BB))
380 return true;
381 auto It = BaseMemAddrs.find(&BB);
382 if (It != BaseMemAddrs.end())
383 return It->second.count(Addr);
384 return false;
385}
386
388 const CodeExtractorAnalysisCache &CEAC, Instruction *Addr) const {
390 Function *Func = (*Blocks.begin())->getParent();
391 for (BasicBlock &BB : *Func) {
392 if (Blocks.count(&BB))
393 continue;
394 if (CEAC.doesBlockContainClobberOfAddr(BB, AI))
395 return false;
396 }
397 return true;
398}
399
402 BasicBlock *SinglePredFromOutlineRegion = nullptr;
403 assert(!Blocks.count(CommonExitBlock) &&
404 "Expect a block outside the region!");
405 for (auto *Pred : predecessors(CommonExitBlock)) {
406 if (!Blocks.count(Pred))
407 continue;
408 if (!SinglePredFromOutlineRegion) {
409 SinglePredFromOutlineRegion = Pred;
410 } else if (SinglePredFromOutlineRegion != Pred) {
411 SinglePredFromOutlineRegion = nullptr;
412 break;
413 }
414 }
415
416 if (SinglePredFromOutlineRegion)
417 return SinglePredFromOutlineRegion;
418
419#ifndef NDEBUG
420 auto getFirstPHI = [](BasicBlock *BB) {
421 BasicBlock::iterator I = BB->begin();
422 PHINode *FirstPhi = nullptr;
423 while (I != BB->end()) {
425 if (!Phi)
426 break;
427 if (!FirstPhi) {
428 FirstPhi = Phi;
429 break;
430 }
431 }
432 return FirstPhi;
433 };
434 // If there are any phi nodes, the single pred either exists or has already
435 // be created before code extraction.
436 assert(!getFirstPHI(CommonExitBlock) && "Phi not expected");
437#endif
438
439 BasicBlock *NewExitBlock =
440 CommonExitBlock->splitBasicBlock(CommonExitBlock->getFirstNonPHIIt());
441
442 for (BasicBlock *Pred :
443 llvm::make_early_inc_range(predecessors(CommonExitBlock))) {
444 if (Blocks.count(Pred))
445 continue;
446 Pred->getTerminator()->replaceUsesOfWith(CommonExitBlock, NewExitBlock);
447 }
448 // Now add the old exit block to the outline region.
449 Blocks.insert(CommonExitBlock);
450 return CommonExitBlock;
451}
452
454 DebugLoc, Type *VarType,
455 const Twine &Name,
456 AddrSpaceCastInst **CastedAlloc) {
457 // An alloca needs no debug location, so the one passed in goes unused here.
458 BasicBlock *BB = AllocaIP.getNodeParent();
459 const DataLayout &DL = BB->getDataLayout();
460 Instruction *Alloca =
461 new AllocaInst(VarType, DL.getAllocaAddrSpace(), nullptr, Name, AllocaIP);
462
463 if (CastedAlloc && ArgsInZeroAddressSpace && DL.getAllocaAddrSpace() != 0) {
464 *CastedAlloc = new AddrSpaceCastInst(
465 Alloca, PointerType::get(BB->getContext(), 0), Name + ".ascast");
466 (*CastedAlloc)->insertAfter(Alloca->getIterator());
467 }
468 return Alloca;
469}
470
472 Value *, Type *) {
473 // Default alloca instructions created by allocateVar are released implicitly.
474 return nullptr;
475}
476
477// Find the pair of life time markers for address 'Addr' that are either
478// defined inside the outline region or can legally be shrinkwrapped into the
479// outline region. If there are not other untracked uses of the address, return
480// the pair of markers if found; otherwise return a pair of nullptr.
481CodeExtractor::LifetimeMarkerInfo
482CodeExtractor::getLifetimeMarkers(const CodeExtractorAnalysisCache &CEAC,
483 Instruction *Addr,
484 BasicBlock *ExitBlock) const {
485 LifetimeMarkerInfo Info;
486
487 for (User *U : Addr->users()) {
489 if (IntrInst) {
490 // We don't model addresses with multiple start/end markers, but the
491 // markers do not need to be in the region.
492 if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_start) {
493 if (Info.LifeStart)
494 return {};
495 Info.LifeStart = IntrInst;
496 continue;
497 }
498 if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_end) {
499 if (Info.LifeEnd)
500 return {};
501 Info.LifeEnd = IntrInst;
502 continue;
503 }
504 }
505 // Find untracked uses of the address, bail.
506 if (!definedInRegion(Blocks, U))
507 return {};
508 }
509
510 if (!Info.LifeStart || !Info.LifeEnd)
511 return {};
512
513 Info.SinkLifeStart = !definedInRegion(Blocks, Info.LifeStart);
514 Info.HoistLifeEnd = !definedInRegion(Blocks, Info.LifeEnd);
515 // Do legality check.
516 if ((Info.SinkLifeStart || Info.HoistLifeEnd) &&
518 return {};
519
520 // Check to see if we have a place to do hoisting, if not, bail.
521 if (Info.HoistLifeEnd && !ExitBlock)
522 return {};
523
524 return Info;
525}
526
528 ValueSet &SinkCands, ValueSet &HoistCands,
529 BasicBlock *&ExitBlock) const {
530 Function *Func = (*Blocks.begin())->getParent();
531 ExitBlock = getCommonExitBlock(Blocks);
532
533 auto moveOrIgnoreLifetimeMarkers =
534 [&](const LifetimeMarkerInfo &LMI) -> bool {
535 if (!LMI.LifeStart)
536 return false;
537 if (LMI.SinkLifeStart) {
538 LLVM_DEBUG(dbgs() << "Sinking lifetime.start: " << *LMI.LifeStart
539 << "\n");
540 SinkCands.insert(LMI.LifeStart);
541 }
542 if (LMI.HoistLifeEnd) {
543 LLVM_DEBUG(dbgs() << "Hoisting lifetime.end: " << *LMI.LifeEnd << "\n");
544 HoistCands.insert(LMI.LifeEnd);
545 }
546 return true;
547 };
548
549 // Look up allocas in the original function in CodeExtractorAnalysisCache, as
550 // this is much faster than walking all the instructions.
551 for (AllocaInst *AI : CEAC.getAllocas()) {
552 BasicBlock *BB = AI->getParent();
553 if (Blocks.count(BB))
554 continue;
555
556 // As a prior call to extractCodeRegion() may have shrinkwrapped the alloca,
557 // check whether it is actually still in the original function.
558 Function *AIFunc = BB->getParent();
559 if (AIFunc != Func)
560 continue;
561
562 LifetimeMarkerInfo MarkerInfo = getLifetimeMarkers(CEAC, AI, ExitBlock);
563 bool Moved = moveOrIgnoreLifetimeMarkers(MarkerInfo);
564 if (Moved) {
565 LLVM_DEBUG(dbgs() << "Sinking alloca: " << *AI << "\n");
566 SinkCands.insert(AI);
567 continue;
568 }
569 }
570}
571
573 if (Blocks.empty())
574 return false;
575 BasicBlock *Header = *Blocks.begin();
576 Function *F = Header->getParent();
577
578 // For functions with varargs, check that varargs handling is only done in the
579 // outlined function, i.e vastart and vaend are only used in outlined blocks.
580 if (AllowVarArgs && F->getFunctionType()->isVarArg()) {
581 auto containsVarArgIntrinsic = [](const Instruction &I) {
582 if (const CallInst *CI = dyn_cast<CallInst>(&I))
583 if (const Function *Callee = CI->getCalledFunction())
584 return Callee->getIntrinsicID() == Intrinsic::vastart ||
585 Callee->getIntrinsicID() == Intrinsic::vaend;
586 return false;
587 };
588
589 for (auto &BB : *F) {
590 if (Blocks.count(&BB))
591 continue;
592 if (llvm::any_of(BB, containsVarArgIntrinsic))
593 return false;
594 }
595 }
596 // stacksave as input implies stackrestore in the outlined function.
597 // This can confuse prolog epilog insertion phase.
598 // stacksave's uses must not cross outlined function.
599 for (BasicBlock *BB : Blocks) {
600 for (Instruction &I : *BB) {
602 if (!II)
603 continue;
604 bool IsSave = II->getIntrinsicID() == Intrinsic::stacksave;
605 bool IsRestore = II->getIntrinsicID() == Intrinsic::stackrestore;
606 if (IsSave && any_of(II->users(), [&Blks = this->Blocks](User *U) {
607 return !definedInRegion(Blks, U);
608 }))
609 return false;
610 if (IsRestore && !definedInRegion(Blocks, II->getArgOperand(0)))
611 return false;
612 }
613 }
614 return true;
615}
616
617void CodeExtractor::findInputsOutputs(ValueSet &Inputs, ValueSet &Outputs,
618 const ValueSet &SinkCands,
619 bool CollectGlobalInputs) {
620 for (BasicBlock *BB : Blocks) {
621 // If a used value is defined outside the region, it's an input. If an
622 // instruction is used outside the region, it's an output.
623 for (Instruction &II : *BB) {
624 for (auto &OI : II.operands()) {
625 Value *V = OI;
626 if (!SinkCands.count(V) &&
627 (definedInCaller(Blocks, V) ||
628 (CollectGlobalInputs && llvm::isa<llvm::GlobalVariable>(V))))
629 Inputs.insert(V);
630 }
631
632 for (User *U : II.users())
633 if (!definedInRegion(Blocks, U)) {
634 Outputs.insert(&II);
635 break;
636 }
637 }
638 }
639
640 // Reset stale state from any prior call in HotColdSplitting; the CFG may
641 // have changed since.
642 FuncRetVal = nullptr;
643 if (!VoidReturnWithSingleOutput && !AggregateArgs && Outputs.size() == 1 &&
644 getCommonExitBlock(Blocks)) {
645 FuncRetVal = Outputs[0];
646 Outputs.clear();
647 }
648}
649
650/// severSplitPHINodesOfEntry - If a PHI node has multiple inputs from outside
651/// of the region, we need to split the entry block of the region so that the
652/// PHI node is easier to deal with.
653void CodeExtractor::severSplitPHINodesOfEntry(BasicBlock *&Header) {
654 unsigned NumPredsFromRegion = 0;
655 unsigned NumPredsOutsideRegion = 0;
656
657 if (Header != &Header->getParent()->getEntryBlock()) {
658 PHINode *PN = dyn_cast<PHINode>(Header->begin());
659 if (!PN) return; // No PHI nodes.
660
661 // If the header node contains any PHI nodes, check to see if there is more
662 // than one entry from outside the region. If so, we need to sever the
663 // header block into two.
664 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
665 if (Blocks.count(PN->getIncomingBlock(i)))
666 ++NumPredsFromRegion;
667 else
668 ++NumPredsOutsideRegion;
669
670 // If there is one (or fewer) predecessor from outside the region, we don't
671 // need to do anything special.
672 if (NumPredsOutsideRegion <= 1) return;
673 }
674
675 // Otherwise, we need to split the header block into two pieces: one
676 // containing PHI nodes merging values from outside of the region, and a
677 // second that contains all of the code for the block and merges back any
678 // incoming values from inside of the region.
679 BasicBlock *NewBB = SplitBlock(Header, Header->getFirstNonPHIIt(), DT);
680
681 // We only want to code extract the second block now, and it becomes the new
682 // header of the region.
683 BasicBlock *OldPred = Header;
684 Blocks.remove(OldPred);
685 Blocks.insert(NewBB);
686 Header = NewBB;
687
688 // Okay, now we need to adjust the PHI nodes and any branches from within the
689 // region to go to the new header block instead of the old header block.
690 if (NumPredsFromRegion) {
691 PHINode *PN = cast<PHINode>(OldPred->begin());
692 // Loop over all of the predecessors of OldPred that are in the region,
693 // changing them to branch to NewBB instead.
694 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
695 if (Blocks.count(PN->getIncomingBlock(i))) {
697 TI->replaceUsesOfWith(OldPred, NewBB);
698 }
699
700 // Okay, everything within the region is now branching to the right block, we
701 // just have to update the PHI nodes now, inserting PHI nodes into NewBB.
702 BasicBlock::iterator AfterPHIs;
703 for (AfterPHIs = OldPred->begin(); isa<PHINode>(AfterPHIs); ++AfterPHIs) {
704 PHINode *PN = cast<PHINode>(AfterPHIs);
705 // Create a new PHI node in the new region, which has an incoming value
706 // from OldPred of PN.
707 PHINode *NewPN = PHINode::Create(PN->getType(), 1 + NumPredsFromRegion,
708 PN->getName() + ".ce");
709 NewPN->insertBefore(NewBB->begin());
710 PN->replaceAllUsesWith(NewPN);
711 NewPN->addIncoming(PN, OldPred);
712
713 // Loop over all of the incoming value in PN, moving them to NewPN if they
714 // are from the extracted region.
715 PN->removeIncomingValueIf([&](unsigned i) {
716 if (Blocks.count(PN->getIncomingBlock(i))) {
717 NewPN->addIncoming(PN->getIncomingValue(i), PN->getIncomingBlock(i));
718 return true;
719 }
720 return false;
721 });
722 }
723 }
724}
725
726/// severSplitPHINodesOfExits - if PHI nodes in exit blocks have inputs from
727/// outlined region, we split these PHIs on two: one with inputs from region
728/// and other with remaining incoming blocks; then first PHIs are placed in
729/// outlined region.
730void CodeExtractor::severSplitPHINodesOfExits() {
731 for (BasicBlock *ExitBB : ExtractedFuncRetVals) {
732 BasicBlock *NewBB = nullptr;
733
734 for (PHINode &PN : ExitBB->phis()) {
735 // Find all incoming values from the outlining region.
736 SmallVector<unsigned, 2> IncomingVals;
737 for (unsigned i = 0; i < PN.getNumIncomingValues(); ++i)
738 if (Blocks.count(PN.getIncomingBlock(i)))
739 IncomingVals.push_back(i);
740
741 // Do not process PHI if there is one (or fewer) predecessor from region.
742 // If PHI has exactly one predecessor from region, only this one incoming
743 // will be replaced on codeRepl block, so it should be safe to skip PHI.
744 if (IncomingVals.size() <= 1)
745 continue;
746
747 // Create block for new PHIs and add it to the list of outlined if it
748 // wasn't done before.
749 if (!NewBB) {
750 NewBB = BasicBlock::Create(ExitBB->getContext(),
751 ExitBB->getName() + ".split",
752 ExitBB->getParent(), ExitBB);
754 for (BasicBlock *PredBB : Preds)
755 if (Blocks.count(PredBB))
756 PredBB->getTerminator()->replaceUsesOfWith(ExitBB, NewBB);
757 UncondBrInst::Create(ExitBB, NewBB);
758 Blocks.insert(NewBB);
759 }
760
761 // Split this PHI.
762 PHINode *NewPN = PHINode::Create(PN.getType(), IncomingVals.size(),
763 PN.getName() + ".ce");
764 NewPN->insertBefore(NewBB->getFirstNonPHIIt());
765 for (unsigned i : IncomingVals)
766 NewPN->addIncoming(PN.getIncomingValue(i), PN.getIncomingBlock(i));
767 for (unsigned i : reverse(IncomingVals))
768 PN.removeIncomingValue(i, false);
769 PN.addIncoming(NewPN, NewBB);
770 }
771 }
772}
773
774void CodeExtractor::splitReturnBlocks() {
775 for (BasicBlock *Block : Blocks)
776 if (ReturnInst *RI = dyn_cast<ReturnInst>(Block->getTerminator())) {
777 BasicBlock *New =
778 Block->splitBasicBlock(RI->getIterator(), Block->getName() + ".ret");
779 if (DT) {
780 // Old dominates New. New node dominates all other nodes dominated
781 // by Old.
782 DomTreeNode *OldNode = DT->getNode(Block);
784 OldNode->end());
785
786 DomTreeNode *NewNode = DT->addNewBlock(New, Block);
787
788 for (DomTreeNode *I : Children)
789 DT->changeImmediateDominator(I, NewNode);
790 }
791 }
792}
793
794Function *CodeExtractor::constructFunctionDeclaration(
795 const ValueSet &inputs, const ValueSet &outputs, BlockFrequency EntryFreq,
796 const Twine &Name, ValueSet &StructValues, StructType *&StructTy) {
797 LLVM_DEBUG(dbgs() << "inputs: " << inputs.size() << "\n");
798 LLVM_DEBUG(dbgs() << "outputs: " << outputs.size() << "\n");
799
800 Function *oldFunction = Blocks.front()->getParent();
801 Module *M = Blocks.front()->getModule();
802
803 // Assemble the function's parameter lists.
804 std::vector<Type *> ParamTy;
805 std::vector<Type *> AggParamTy;
806 const DataLayout &DL = M->getDataLayout();
807
808 // Add the types of the input values to the function's argument list
809 for (Value *value : inputs) {
810 LLVM_DEBUG(dbgs() << "value used in func: " << *value << "\n");
811 if (AggregateArgs && !ExcludeArgsFromAggregate.contains(value)) {
812 AggParamTy.push_back(value->getType());
813 StructValues.insert(value);
814 } else
815 ParamTy.push_back(value->getType());
816 }
817
818 // Add the types of the output values to the function's argument list.
819 for (Value *output : outputs) {
820 LLVM_DEBUG(dbgs() << "instr used in func: " << *output << "\n");
821 if (AggregateArgs && !ExcludeArgsFromAggregate.contains(output)) {
822 AggParamTy.push_back(output->getType());
823 StructValues.insert(output);
824 } else
825 ParamTy.push_back(
826 PointerType::get(output->getContext(), DL.getAllocaAddrSpace()));
827 }
828
829 assert(
830 (ParamTy.size() + AggParamTy.size()) ==
831 (inputs.size() + outputs.size()) &&
832 "Number of scalar and aggregate params does not match inputs, outputs");
833 assert((StructValues.empty() || AggregateArgs) &&
834 "Expeced StructValues only with AggregateArgs set");
835
836 // Concatenate scalar and aggregate params in ParamTy.
837 if (!AggParamTy.empty()) {
838 StructTy = StructType::get(M->getContext(), AggParamTy);
839 ParamTy.push_back(PointerType::get(
840 M->getContext(), ArgsInZeroAddressSpace ? 0 : DL.getAllocaAddrSpace()));
841 }
842
843 Type *RetTy = FuncRetVal ? FuncRetVal->getType() : getSwitchType();
844 LLVM_DEBUG({
845 dbgs() << "Function type: " << *RetTy << " f(";
846 for (Type *i : ParamTy)
847 dbgs() << *i << ", ";
848 dbgs() << ")\n";
849 });
850
851 FunctionType *funcType = FunctionType::get(
852 RetTy, ParamTy, AllowVarArgs && oldFunction->isVarArg());
853
854 // Create the new function
855 Function *newFunction =
857 oldFunction->getAddressSpace(), Name, M);
858
859 // Propagate personality info to the new function if there is one.
860 if (oldFunction->hasPersonalityFn())
861 newFunction->setPersonalityFn(oldFunction->getPersonalityFn());
862
863 // Inherit all of the target dependent attributes and white-listed
864 // target independent attributes.
865 // (e.g. If the extracted region contains a call to an x86.sse
866 // instruction we need to make sure that the extracted region has the
867 // "target-features" attribute allowing it to be lowered.
868 // FIXME: This should be changed to check to see if a specific
869 // attribute can not be inherited.
870 for (const auto &Attr : oldFunction->getAttributes().getFnAttrs()) {
871 if (Attr.isStringAttribute()) {
872 if (Attr.getKindAsString() == "thunk")
873 continue;
874 } else
875 switch (Attr.getKindAsEnum()) {
876 // Those attributes cannot be propagated safely. Explicitly list them
877 // here so we get a warning if new attributes are added.
878 case Attribute::AllocSize:
879 case Attribute::Builtin:
880 case Attribute::Convergent:
881 case Attribute::JumpTable:
882 case Attribute::Naked:
883 case Attribute::NoBuiltin:
884 case Attribute::NoMerge:
885 case Attribute::NoReturn:
886 case Attribute::NoSync:
887 case Attribute::ReturnsTwice:
888 case Attribute::Speculatable:
889 case Attribute::StackAlignment:
890 case Attribute::WillReturn:
891 case Attribute::AllocKind:
892 case Attribute::PresplitCoroutine:
893 case Attribute::Memory:
894 case Attribute::NoFPClass:
895 case Attribute::CoroDestroyOnlyWhenComplete:
896 case Attribute::CoroElideSafe:
897 case Attribute::NoDivergenceSource:
898 case Attribute::NoCreateUndefOrPoison:
899 continue;
900 // Those attributes should be safe to propagate to the extracted function.
901 case Attribute::AlwaysInline:
902 case Attribute::Cold:
903 case Attribute::DisableSanitizerInstrumentation:
904 case Attribute::Flatten:
905 case Attribute::FnRetThunkExtern:
906 case Attribute::Hot:
907 case Attribute::HybridPatchable:
908 case Attribute::NoRecurse:
909 case Attribute::InlineHint:
910 case Attribute::LikelyModuleLocal:
911 case Attribute::MinSize:
912 case Attribute::NoCallback:
913 case Attribute::NoDuplicate:
914 case Attribute::NoFree:
915 case Attribute::NoImplicitFloat:
916 case Attribute::NoInline:
917 case Attribute::NoIPA:
918 case Attribute::NoOutline:
919 case Attribute::NonLazyBind:
920 case Attribute::NoRedZone:
921 case Attribute::NoUnwind:
922 case Attribute::NoSanitizeBounds:
923 case Attribute::NoSanitizeCoverage:
924 case Attribute::NullPointerIsValid:
925 case Attribute::OptimizeForDebugging:
926 case Attribute::OptForFuzzing:
927 case Attribute::OptimizeNone:
928 case Attribute::OptimizeForSize:
929 case Attribute::SafeStack:
930 case Attribute::ShadowCallStack:
931 case Attribute::SanitizeAddress:
932 case Attribute::SanitizeMemory:
933 case Attribute::SanitizeNumericalStability:
934 case Attribute::SanitizeThread:
935 case Attribute::SanitizeConcurrency:
936 case Attribute::SanitizeType:
937 case Attribute::SanitizeHWAddress:
938 case Attribute::SanitizeMemTag:
939 case Attribute::SanitizeRealtime:
940 case Attribute::SanitizeRealtimeBlocking:
941 case Attribute::SanitizeAllocToken:
942 case Attribute::SpeculativeLoadHardening:
943 case Attribute::StackProtect:
944 case Attribute::StackProtectReq:
945 case Attribute::StackProtectStrong:
946 case Attribute::StrictFP:
947 case Attribute::UWTable:
948 case Attribute::VScaleRange:
949 case Attribute::NoCfCheck:
950 case Attribute::MustProgress:
951 case Attribute::NoProfile:
952 case Attribute::SkipProfile:
953 case Attribute::DenormalFPEnv:
954 break;
955 // These attributes cannot be applied to functions.
956 case Attribute::Alignment:
957 case Attribute::AllocatedPointer:
958 case Attribute::AllocAlign:
959 case Attribute::ByVal:
960 case Attribute::Captures:
961 case Attribute::Dereferenceable:
962 case Attribute::DereferenceableOrNull:
963 case Attribute::ElementType:
964 case Attribute::InAlloca:
965 case Attribute::InReg:
966 case Attribute::Nest:
967 case Attribute::NoAlias:
968 case Attribute::NoUndef:
969 case Attribute::NonNull:
970 case Attribute::Preallocated:
971 case Attribute::ReadNone:
972 case Attribute::ReadOnly:
973 case Attribute::Returned:
974 case Attribute::SExt:
975 case Attribute::StructRet:
976 case Attribute::SwiftError:
977 case Attribute::SwiftSelf:
978 case Attribute::SwiftAsync:
979 case Attribute::ZExt:
980 case Attribute::ImmArg:
981 case Attribute::ByRef:
982 case Attribute::WriteOnly:
983 case Attribute::Writable:
984 case Attribute::DeadOnUnwind:
985 case Attribute::Range:
986 case Attribute::Initializes:
987 case Attribute::NoExt:
988 case Attribute::NoFreeObj:
989 // These are not really attributes.
990 case Attribute::None:
994 case Attribute::DeadOnReturn:
995 llvm_unreachable("Not a function attribute");
996 }
997
998 newFunction->addFnAttr(Attr);
999 }
1000
1001 // Create scalar and aggregate iterators to name all of the arguments we
1002 // inserted.
1003 Function::arg_iterator ScalarAI = newFunction->arg_begin();
1004
1005 // Set names and attributes for input and output arguments.
1006 ScalarAI = newFunction->arg_begin();
1007 for (Value *input : inputs) {
1008 if (StructValues.contains(input))
1009 continue;
1010
1011 ScalarAI->setName(input->getName());
1012 if (input->isSwiftError())
1013 newFunction->addParamAttr(ScalarAI - newFunction->arg_begin(),
1014 Attribute::SwiftError);
1015 ++ScalarAI;
1016 }
1017 for (Value *output : outputs) {
1018 if (StructValues.contains(output))
1019 continue;
1020
1021 ScalarAI->setName(output->getName() + ".out");
1022 ++ScalarAI;
1023 }
1024
1025 // Update the entry count of the function.
1026 if (BFI) {
1027 auto Count = BFI->getProfileCountFromFreq(EntryFreq);
1028 if (Count.has_value())
1029 newFunction->setEntryCount(*Count);
1030 }
1031
1032 return newFunction;
1033}
1034
1035/// If the original function has debug info, we have to add a debug location
1036/// to the new branch instruction from the artificial entry block.
1037/// We use the debug location of the first instruction in the extracted
1038/// blocks, as there is no other equivalent line in the source code.
1039static void applyFirstDebugLoc(Function *oldFunction,
1041 Instruction *BranchI) {
1042 if (oldFunction->getSubprogram()) {
1043 any_of(Blocks, [&BranchI](const BasicBlock *BB) {
1044 return any_of(*BB, [&BranchI](const Instruction &I) {
1045 if (!I.getDebugLoc())
1046 return false;
1047 BranchI->setDebugLoc(I.getDebugLoc());
1048 return true;
1049 });
1050 });
1051 }
1052}
1053
1054/// Erase lifetime.start markers which reference inputs to the extraction
1055/// region, and insert the referenced memory into \p LifetimesStart.
1056///
1057/// The extraction region is defined by a set of blocks (\p Blocks), and a set
1058/// of allocas which will be moved from the caller function into the extracted
1059/// function (\p SunkAllocas).
1061 const SetVector<Value *> &SunkAllocas,
1062 SetVector<Value *> &LifetimesStart) {
1063 for (BasicBlock *BB : Blocks) {
1066 if (!II)
1067 continue;
1068
1069 // Get the memory operand of the lifetime marker. If the underlying
1070 // object is a sunk alloca, or is otherwise defined in the extraction
1071 // region, the lifetime marker must not be erased.
1072 Value *Mem = II->getOperand(0);
1073 if (SunkAllocas.count(Mem) || definedInRegion(Blocks, Mem))
1074 continue;
1075
1076 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
1077 LifetimesStart.insert(Mem);
1078 II->eraseFromParent();
1079 }
1080 }
1081}
1082
1083/// Insert lifetime start/end markers surrounding the call to the new function
1084/// for objects defined in the caller.
1086 Module *M, ArrayRef<Value *> LifetimesStart, ArrayRef<Value *> LifetimesEnd,
1087 CallInst *TheCall) {
1088 Instruction *Term = TheCall->getParent()->getTerminator();
1089
1090 // Emit lifetime markers for the pointers given in \p Objects. Insert the
1091 // markers before the call if \p InsertBefore, and after the call otherwise.
1092 auto insertMarkers = [&](Intrinsic::ID MarkerFunc, ArrayRef<Value *> Objects,
1093 bool InsertBefore) {
1094 for (Value *Mem : Objects) {
1096 TheCall->getFunction()) &&
1097 "Input memory not defined in original function");
1098
1099 Function *Func =
1100 Intrinsic::getOrInsertDeclaration(M, MarkerFunc, Mem->getType());
1101 auto Marker = CallInst::Create(Func, Mem);
1102 if (InsertBefore)
1103 Marker->insertBefore(TheCall->getIterator());
1104 else
1105 Marker->insertBefore(Term->getIterator());
1106 }
1107 };
1108
1109 if (!LifetimesStart.empty()) {
1110 insertMarkers(Intrinsic::lifetime_start, LifetimesStart,
1111 /*InsertBefore=*/true);
1112 }
1113
1114 if (!LifetimesEnd.empty()) {
1115 insertMarkers(Intrinsic::lifetime_end, LifetimesEnd,
1116 /*InsertBefore=*/false);
1117 }
1118}
1119
1120void CodeExtractor::moveCodeToFunction(Function *newFunction) {
1121 auto newFuncIt = newFunction->begin();
1122 for (BasicBlock *Block : Blocks) {
1123 // Delete the basic block from the old function, and the list of blocks
1124 Block->removeFromParent();
1125
1126 // Insert this basic block into the new function
1127 // Insert the original blocks after the entry block created
1128 // for the new function. The entry block may be followed
1129 // by a set of exit blocks at this point, but these exit
1130 // blocks better be placed at the end of the new function.
1131 newFuncIt = newFunction->insert(std::next(newFuncIt), Block);
1132 }
1133}
1134
1135void CodeExtractor::calculateNewCallTerminatorWeights(
1136 BasicBlock *CodeReplacer,
1137 const DenseMap<BasicBlock *, BlockFrequency> &ExitWeights,
1138 BranchProbabilityInfo *BPI) {
1139 using Distribution = BlockFrequencyInfoImplBase::Distribution;
1140 using BlockNode = BlockFrequencyInfoImplBase::BlockNode;
1141
1142 // Update the branch weights for the exit block.
1143 Instruction *TI = CodeReplacer->getTerminator();
1144 SmallVector<unsigned, 8> BranchWeights(TI->getNumSuccessors(), 0);
1145
1146 // Block Frequency distribution with dummy node.
1147 Distribution BranchDist;
1148
1149 SmallVector<BranchProbability, 4> EdgeProbabilities(
1151
1152 // Add each of the frequencies of the successors.
1153 for (unsigned i = 0, e = TI->getNumSuccessors(); i < e; ++i) {
1154 BlockNode ExitNode(i);
1155 uint64_t ExitFreq = ExitWeights.lookup(TI->getSuccessor(i)).getFrequency();
1156 if (ExitFreq != 0)
1157 BranchDist.addExit(ExitNode, ExitFreq);
1158 else
1159 EdgeProbabilities[i] = BranchProbability::getZero();
1160 }
1161
1162 // Check for no total weight.
1163 if (BranchDist.Total == 0) {
1164 BPI->setEdgeProbability(CodeReplacer, EdgeProbabilities);
1165 return;
1166 }
1167
1168 // Normalize the distribution so that they can fit in unsigned.
1169 BranchDist.normalize();
1170
1171 // Create normalized branch weights and set the metadata.
1172 for (unsigned I = 0, E = BranchDist.Weights.size(); I < E; ++I) {
1173 const auto &Weight = BranchDist.Weights[I];
1174
1175 // Get the weight and update the current BFI.
1176 BranchWeights[Weight.TargetNode.Index] = Weight.Amount;
1177 BranchProbability BP(Weight.Amount, BranchDist.Total);
1178 EdgeProbabilities[Weight.TargetNode.Index] = BP;
1179 }
1180 BPI->setEdgeProbability(CodeReplacer, EdgeProbabilities);
1181 TI->setMetadata(
1182 LLVMContext::MD_prof,
1183 MDBuilder(TI->getContext()).createBranchWeights(BranchWeights));
1184}
1185
1186/// Erase debug info intrinsics which refer to values in \p F but aren't in
1187/// \p F.
1189 for (Instruction &I : instructions(F)) {
1190 SmallVector<DbgVariableRecord *, 4> DbgVariableRecords;
1191 findDbgUsers(&I, DbgVariableRecords);
1192 for (DbgVariableRecord *DVR : DbgVariableRecords)
1193 if (DVR->getFunction() != &F)
1194 DVR->eraseFromParent();
1195 }
1196}
1197
1198/// Fix up the debug info in the old and new functions. Following changes are
1199/// done.
1200/// 1. If a debug record points to a value that has been replaced, update the
1201/// record to use the new value.
1202/// 2. If an Input value that has been replaced was used as a location of a
1203/// debug record in the Parent function, then materealize a similar record in
1204/// the new function.
1205/// 3. Point line locations and debug intrinsics to the new subprogram scope
1206/// 4. Remove intrinsics which point to values outside of the new function.
1207static void fixupDebugInfoPostExtraction(Function &OldFunc, Function &NewFunc,
1208 CallInst &TheCall,
1209 const SetVector<Value *> &Inputs,
1210 ArrayRef<Value *> NewValues) {
1211 DISubprogram *OldSP = OldFunc.getSubprogram();
1212 LLVMContext &Ctx = OldFunc.getContext();
1213
1214 if (!OldSP) {
1215 // Erase any debug info the new function contains.
1216 stripDebugInfo(NewFunc);
1217 // Make sure the old function doesn't contain any non-local metadata refs.
1219 return;
1220 }
1221
1222 // Create a subprogram for the new function. Leave out a description of the
1223 // function arguments, as the parameters don't correspond to anything at the
1224 // source level.
1225 assert(OldSP->getUnit() && "Missing compile unit for subprogram");
1226 DIBuilder DIB(*OldFunc.getParent(), /*AllowUnresolved=*/false,
1227 OldSP->getUnit());
1228 auto SPType = DIB.createSubroutineType(DIB.getOrCreateTypeArray({}));
1229 DISubprogram::DISPFlags SPFlags = DISubprogram::SPFlagDefinition |
1230 DISubprogram::SPFlagOptimized |
1231 DISubprogram::SPFlagLocalToUnit;
1232 auto NewSP = DIB.createFunction(
1233 OldSP->getUnit(), NewFunc.getName(), NewFunc.getName(), OldSP->getFile(),
1234 /*LineNo=*/0, SPType, /*ScopeLine=*/0, DINode::FlagZero, SPFlags);
1235 NewFunc.setSubprogram(NewSP);
1236
1237 auto UpdateOrInsertDebugRecord = [&](auto *DR, Value *OldLoc, Value *NewLoc,
1238 DIExpression *Expr, bool Declare) {
1239 if (DR->getParent()->getParent() == &NewFunc) {
1240 DR->replaceVariableLocationOp(OldLoc, NewLoc);
1241 return;
1242 }
1243 if (Declare) {
1244 DIB.insertDeclare(NewLoc, DR->getVariable(), Expr, DR->getDebugLoc(),
1245 &NewFunc.getEntryBlock());
1246 return;
1247 }
1248 DIB.insertDbgValue(NewLoc, DR->getVariable(), Expr, DR->getDebugLoc(),
1249 NewFunc.getEntryBlock().getTerminator()->getIterator());
1250 };
1251 for (auto [Input, NewVal] : zip_equal(Inputs, NewValues)) {
1253 findDbgUsers(Input, DPUsers);
1254
1255 // Iterate the debug users of the Input values. If they are in the extracted
1256 // function then update their location with the new value. If they are in
1257 // the parent function then create a similar debug record.
1258 for (auto *DVR : DPUsers) {
1259 DIExpression *Expr = DVR->getNumVariableLocationOps() == 1
1260 ? DVR->getExpression()
1261 : DIB.createExpression();
1262 UpdateOrInsertDebugRecord(DVR, Input, NewVal, Expr, DVR->isDbgDeclare());
1263 }
1264 }
1265
1266 auto IsInvalidLocation = [&NewFunc](Value *Location) {
1267 // Location is invalid if it isn't a constant, an instruction or an
1268 // argument, or is an instruction/argument but isn't in the new function.
1269 if (!Location || (!isa<Constant>(Location) && !isa<Argument>(Location) &&
1270 !isa<Instruction>(Location)))
1271 return true;
1272
1273 if (Argument *Arg = dyn_cast<Argument>(Location))
1274 return Arg->getParent() != &NewFunc;
1275 if (Instruction *LocationInst = dyn_cast<Instruction>(Location))
1276 return LocationInst->getFunction() != &NewFunc;
1277 return false;
1278 };
1279
1280 // Debug intrinsics in the new function need to be updated in one of two
1281 // ways:
1282 // 1) They need to be deleted, because they describe a value in the old
1283 // function.
1284 // 2) They need to point to fresh metadata, e.g. because they currently
1285 // point to a variable in the wrong scope.
1286 SmallDenseMap<DINode *, DINode *> RemappedMetadata;
1289
1290 auto GetUpdatedDIVariable = [&](DILocalVariable *OldVar) {
1291 DINode *&NewVar = RemappedMetadata[OldVar];
1292 if (!NewVar) {
1294 *OldVar->getScope(), *NewSP, Ctx, Cache);
1295 NewVar = DIB.createAutoVariable(
1296 NewScope, OldVar->getName(), OldVar->getFile(), OldVar->getLine(),
1297 OldVar->getType(), /*AlwaysPreserve=*/false, DINode::FlagZero,
1298 OldVar->getAlignInBits());
1299 }
1300 return cast<DILocalVariable>(NewVar);
1301 };
1302
1303 auto UpdateDbgLabel = [&](auto *LabelRecord) {
1304 // Point the label record to a fresh label within the new function if
1305 // the record was not inlined from some other function.
1306 if (LabelRecord->getDebugLoc().getInlinedAt())
1307 return;
1308 DILabel *OldLabel = LabelRecord->getLabel();
1309 DINode *&NewLabel = RemappedMetadata[OldLabel];
1310 if (!NewLabel) {
1312 *OldLabel->getScope(), *NewSP, Ctx, Cache);
1313 NewLabel =
1314 DILabel::get(Ctx, NewScope, OldLabel->getName(), OldLabel->getFile(),
1315 OldLabel->getLine(), OldLabel->getColumn(),
1316 OldLabel->isArtificial(), OldLabel->getCoroSuspendIdx());
1317 }
1318 LabelRecord->setLabel(cast<DILabel>(NewLabel));
1319 };
1320
1321 auto UpdateDbgRecordsOnInst = [&](Instruction &I) -> void {
1322 for (DbgRecord &DR : I.getDbgRecordRange()) {
1323 if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) {
1324 UpdateDbgLabel(DLR);
1325 continue;
1326 }
1327
1329 // If any of the used locations are invalid, delete the record.
1330 if (any_of(DVR.location_ops(), IsInvalidLocation)) {
1331 DVRsToDelete.push_back(&DVR);
1332 continue;
1333 }
1334
1335 // DbgAssign intrinsics have an extra Value argument:
1336 if (DVR.isDbgAssign() && IsInvalidLocation(DVR.getAddress())) {
1337 DVRsToDelete.push_back(&DVR);
1338 continue;
1339 }
1340
1341 // If the variable was in the scope of the old function, i.e. it was not
1342 // inlined, point the intrinsic to a fresh variable within the new
1343 // function.
1344 if (!DVR.getDebugLoc().getInlinedAt())
1345 DVR.setVariable(GetUpdatedDIVariable(DVR.getVariable()));
1346 }
1347 };
1348
1349 for (Instruction &I : instructions(NewFunc))
1350 UpdateDbgRecordsOnInst(I);
1351
1352 for (auto *DVR : DVRsToDelete)
1353 DVR->getMarker()->MarkedInstr->dropOneDbgRecord(DVR);
1354 DIB.finalizeSubprogram(NewSP);
1355
1356 // Fix up the scope information attached to the line locations and the
1357 // debug assignment metadata in the new function.
1359 for (Instruction &I : instructions(NewFunc)) {
1360 if (const DebugLoc &DL = I.getDebugLoc())
1361 I.setDebugLoc(
1362 DebugLoc::replaceInlinedAtSubprogram(DL, *NewSP, Ctx, Cache));
1363 for (DbgRecord &DR : I.getDbgRecordRange())
1364 DR.setDebugLoc(DebugLoc::replaceInlinedAtSubprogram(DR.getDebugLoc(),
1365 *NewSP, Ctx, Cache));
1366
1367 // Loop info metadata may contain line locations. Fix them up.
1368 auto updateLoopInfoLoc = [&Ctx, &Cache, NewSP](Metadata *MD) -> Metadata * {
1369 if (auto *Loc = dyn_cast_or_null<DILocation>(MD))
1370 return DebugLoc::replaceInlinedAtSubprogram(Loc, *NewSP, Ctx, Cache);
1371 return MD;
1372 };
1373 updateLoopMetadataDebugLocations(I, updateLoopInfoLoc);
1374 at::remapAssignID(AssignmentIDMap, I);
1375 }
1376 if (!TheCall.getDebugLoc())
1377 TheCall.setDebugLoc(DILocation::get(Ctx, 0, 0, OldSP));
1378
1380}
1381
1382Function *
1384 ValueSet Inputs, Outputs;
1385 return extractCodeRegion(CEAC, Inputs, Outputs);
1386}
1387
1388Function *
1390 ValueSet &inputs, ValueSet &outputs) {
1391 if (!isEligible())
1392 return nullptr;
1393
1394 // Assumption: this is a single-entry code region, and the header is the first
1395 // block in the region.
1396 BasicBlock *header = *Blocks.begin();
1397 Function *oldFunction = header->getParent();
1398
1399 normalizeCFGForExtraction(header);
1400
1401 // Remove @llvm.assume calls that will be moved to the new function from the
1402 // old function's assumption cache.
1403 for (BasicBlock *Block : Blocks) {
1405 if (auto *AI = dyn_cast<AssumeInst>(&I)) {
1406 if (AC)
1407 AC->unregisterAssumption(AI);
1408 AI->eraseFromParent();
1409 }
1410 }
1411 }
1412
1413 ValueSet SinkingCands, HoistingCands;
1414 BasicBlock *CommonExit = nullptr;
1415 findAllocas(CEAC, SinkingCands, HoistingCands, CommonExit);
1416 assert(HoistingCands.empty() || CommonExit);
1417
1418 // Find inputs to, outputs from the code region.
1419 findInputsOutputs(inputs, outputs, SinkingCands);
1420
1421 // Collect objects which are inputs to the extraction region and also
1422 // referenced by lifetime start markers within it. The effects of these
1423 // markers must be replicated in the calling function to prevent the stack
1424 // coloring pass from merging slots which store input objects.
1425 ValueSet LifetimesStart;
1426 eraseLifetimeMarkersOnInputs(Blocks, SinkingCands, LifetimesStart);
1427
1428 if (!HoistingCands.empty()) {
1429 auto *HoistToBlock = findOrCreateBlockForHoisting(CommonExit);
1430 Instruction *TI = HoistToBlock->getTerminator();
1431 for (auto *II : HoistingCands)
1433 computeExtractedFuncRetVals();
1434 }
1435
1436 // CFG/ExitBlocks must not change hereafter
1437
1438 // Calculate the entry frequency of the new function before we change the root
1439 // block.
1440 BlockFrequency EntryFreq;
1442 if (BFI) {
1443 assert(BPI && "Both BPI and BFI are required to preserve profile info");
1444 for (BasicBlock *Pred : predecessors(header)) {
1445 if (Blocks.count(Pred))
1446 continue;
1447 EntryFreq +=
1448 BFI->getBlockFreq(Pred) * BPI->getEdgeProbability(Pred, header);
1449 }
1450
1451 for (BasicBlock *Succ : ExtractedFuncRetVals) {
1452 for (BasicBlock *Block : predecessors(Succ)) {
1453 if (!Blocks.count(Block))
1454 continue;
1455
1456 // Update the branch weight for this successor.
1457 BlockFrequency &BF = ExitWeights[Succ];
1458 BF += BFI->getBlockFreq(Block) * BPI->getEdgeProbability(Block, Succ);
1459 }
1460 }
1461 }
1462
1463 // Determine position for the replacement code. Do so before header is moved
1464 // to the new function.
1465 BasicBlock *ReplIP = header;
1466 while (ReplIP && Blocks.count(ReplIP))
1467 ReplIP = ReplIP->getNextNode();
1468
1469 // Construct new function based on inputs/outputs & add allocas for all defs.
1470 std::string SuffixToUse =
1471 Suffix.empty()
1472 ? (header->getName().empty() ? "extracted" : header->getName().str())
1473 : Suffix;
1474
1475 ValueSet StructValues;
1476 StructType *StructTy = nullptr;
1477 Function *newFunction = constructFunctionDeclaration(
1478 inputs, outputs, EntryFreq, oldFunction->getName() + "." + SuffixToUse,
1479 StructValues, StructTy);
1480 SmallVector<Value *> NewValues;
1481
1482 emitFunctionBody(inputs, outputs, StructValues, newFunction, StructTy, header,
1483 SinkingCands, NewValues);
1484
1485 std::vector<Value *> Reloads;
1486 CallInst *TheCall = emitReplacerCall(
1487 inputs, outputs, StructValues, newFunction, StructTy, oldFunction, ReplIP,
1488 EntryFreq, LifetimesStart.getArrayRef(), Reloads);
1489
1490 insertReplacerCall(oldFunction, header, TheCall, outputs, Reloads,
1491 ExitWeights);
1492
1493 fixupDebugInfoPostExtraction(*oldFunction, *newFunction, *TheCall, inputs,
1494 NewValues);
1495
1496 LLVM_DEBUG(llvm::dbgs() << "After extractCodeRegion - newFunction:\n");
1497 LLVM_DEBUG(newFunction->dump());
1498 LLVM_DEBUG(llvm::dbgs() << "After extractCodeRegion - oldFunction:\n");
1499 LLVM_DEBUG(oldFunction->dump());
1500 LLVM_DEBUG(if (AC && verifyAssumptionCache(*oldFunction, *newFunction, AC))
1501 report_fatal_error("Stale Asumption cache for old Function!"));
1502 return newFunction;
1503}
1504
1505void CodeExtractor::normalizeCFGForExtraction(BasicBlock *&header) {
1506 // If we have any return instructions in the region, split those blocks so
1507 // that the return is not in the region.
1508 splitReturnBlocks();
1509
1510 // If we have to split PHI nodes of the entry or exit blocks, do so now.
1511 severSplitPHINodesOfEntry(header);
1512
1513 // If a PHI in an exit block has multiple incoming values from the outlined
1514 // region, create a new PHI for those values within the region such that only
1515 // PHI itself becomes an output value, not each of its incoming values
1516 // individually.
1517 computeExtractedFuncRetVals();
1518 severSplitPHINodesOfExits();
1519}
1520
1521void CodeExtractor::computeExtractedFuncRetVals() {
1522 ExtractedFuncRetVals.clear();
1523
1525 for (BasicBlock *Block : Blocks) {
1526 for (BasicBlock *Succ : successors(Block)) {
1527 if (Blocks.count(Succ))
1528 continue;
1529
1530 bool IsNew = ExitBlocks.insert(Succ).second;
1531 if (IsNew)
1532 ExtractedFuncRetVals.push_back(Succ);
1533 }
1534 }
1535}
1536
1537Type *CodeExtractor::getSwitchType() {
1538 LLVMContext &Context = Blocks.front()->getContext();
1539
1540 assert(ExtractedFuncRetVals.size() < 0xffff &&
1541 "too many exit blocks for switch");
1542 switch (ExtractedFuncRetVals.size()) {
1543 case 0:
1544 case 1:
1545 return Type::getVoidTy(Context);
1546 case 2:
1547 // Conditional branch, return a bool
1548 return Type::getInt1Ty(Context);
1549 default:
1550 return Type::getInt16Ty(Context);
1551 }
1552}
1553
1554void CodeExtractor::emitFunctionBody(
1555 const ValueSet &inputs, const ValueSet &outputs,
1556 const ValueSet &StructValues, Function *newFunction,
1557 StructType *StructArgTy, BasicBlock *header, const ValueSet &SinkingCands,
1558 SmallVectorImpl<Value *> &NewValues) {
1559 Function *oldFunction = header->getParent();
1560 LLVMContext &Context = oldFunction->getContext();
1561
1562 // The new function needs a root node because other nodes can branch to the
1563 // head of the region, but the entry node of a function cannot have preds.
1564 BasicBlock *newFuncRoot =
1565 BasicBlock::Create(Context, "newFuncRoot", newFunction);
1566
1567 // Now sink all instructions which only have non-phi uses inside the region.
1568 // Group the allocas at the start of the block, so that any bitcast uses of
1569 // the allocas are well-defined.
1570 for (auto *II : SinkingCands) {
1571 if (!isa<AllocaInst>(II)) {
1572 cast<Instruction>(II)->moveBefore(*newFuncRoot,
1573 newFuncRoot->getFirstInsertionPt());
1574 }
1575 }
1576 for (auto *II : SinkingCands) {
1577 if (auto *AI = dyn_cast<AllocaInst>(II)) {
1578 AI->moveBefore(*newFuncRoot, newFuncRoot->getFirstInsertionPt());
1579 }
1580 }
1581
1582 Function::arg_iterator ScalarAI = newFunction->arg_begin();
1583 Argument *AggArg = StructValues.empty()
1584 ? nullptr
1585 : newFunction->getArg(newFunction->arg_size() - 1);
1586
1587 // Rewrite all users of the inputs in the extracted region to use the
1588 // arguments (or appropriate addressing into struct) instead.
1589 for (unsigned i = 0, e = inputs.size(), aggIdx = 0; i != e; ++i) {
1590 Value *RewriteVal;
1591 if (StructValues.contains(inputs[i])) {
1592 Value *Idx[2];
1594 Idx[1] = ConstantInt::get(Type::getInt32Ty(header->getContext()), aggIdx);
1595 GetElementPtrInst *GEP = GetElementPtrInst::Create(
1596 StructArgTy, AggArg, Idx, "gep_" + inputs[i]->getName(), newFuncRoot);
1597 LoadInst *LoadGEP =
1598 new LoadInst(StructArgTy->getElementType(aggIdx), GEP,
1599 "loadgep_" + inputs[i]->getName(), newFuncRoot);
1600 // If we load pointer, we can add optional !align metadata
1601 // The existence of the !align metadata on the instruction tells
1602 // the optimizer that the value loaded is known to be aligned to
1603 // a boundary specified by the integer value in the metadata node.
1604 // Example:
1605 // %res = load ptr, ptr %input, align 8, !align !align_md_node
1606 // ^ ^
1607 // | |
1608 // alignment of %input address |
1609 // |
1610 // alignment of %res object
1611 if (StructArgTy->getElementType(aggIdx)->isPointerTy()) {
1612 unsigned AlignmentValue;
1613 const Triple &TargetTriple =
1614 newFunction->getParent()->getTargetTriple();
1615 const DataLayout &DL = header->getDataLayout();
1616 // Pointers without casting can provide more information about
1617 // alignment. Use pointers without casts if given target preserves
1618 // alignment information for cast the operation.
1619 if (isAlignmentPreservedForAddrCast(TargetTriple))
1620 AlignmentValue =
1621 inputs[i]->stripPointerCasts()->getPointerAlignment(DL).value();
1622 else
1623 AlignmentValue = inputs[i]->getPointerAlignment(DL).value();
1624 MDBuilder MDB(header->getContext());
1625 LoadGEP->setMetadata(
1626 LLVMContext::MD_align,
1628 header->getContext(),
1629 MDB.createConstant(ConstantInt::get(
1630 Type::getInt64Ty(header->getContext()), AlignmentValue))));
1631 }
1632 RewriteVal = LoadGEP;
1633 ++aggIdx;
1634 } else
1635 RewriteVal = &*ScalarAI++;
1636
1637 NewValues.push_back(RewriteVal);
1638 }
1639
1640 moveCodeToFunction(newFunction);
1641
1642 for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
1643 Value *RewriteVal = NewValues[i];
1644
1645 std::vector<User *> Users(inputs[i]->user_begin(), inputs[i]->user_end());
1646 for (User *use : Users)
1647 if (Instruction *inst = dyn_cast<Instruction>(use))
1648 if (Blocks.count(inst->getParent()))
1649 inst->replaceUsesOfWith(inputs[i], RewriteVal);
1650 }
1651
1652 // Since there may be multiple exits from the original region, make the new
1653 // function return an unsigned, switch on that number. This loop iterates
1654 // over all of the blocks in the extracted region, updating any terminator
1655 // instructions in the to-be-extracted region that branch to blocks that are
1656 // not in the region to be extracted.
1657 std::map<BasicBlock *, BasicBlock *> ExitBlockMap;
1658
1659 // Iterate over the previously collected targets, and create new blocks inside
1660 // the function to branch to.
1661 for (auto P : enumerate(ExtractedFuncRetVals)) {
1662 BasicBlock *OldTarget = P.value();
1663 size_t SuccNum = P.index();
1664
1665 BasicBlock *NewTarget = BasicBlock::Create(
1666 Context, OldTarget->getName() + ".exitStub", newFunction);
1667 ExitBlockMap[OldTarget] = NewTarget;
1668
1669 Value *brVal = nullptr;
1670 Type *RetTy = FuncRetVal ? FuncRetVal->getType() : getSwitchType();
1671 assert(ExtractedFuncRetVals.size() < 0xffff &&
1672 "too many exit blocks for switch");
1673 switch (ExtractedFuncRetVals.size()) {
1674 case 0:
1675 // No value needed.
1676 break;
1677 case 1:
1678 if (FuncRetVal)
1679 brVal = FuncRetVal;
1680 break;
1681 case 2: // Conditional branch, return a bool
1682 brVal = ConstantInt::get(RetTy, !SuccNum);
1683 break;
1684 default:
1685 brVal = ConstantInt::get(RetTy, SuccNum);
1686 break;
1687 }
1688
1689 ReturnInst::Create(Context, brVal, NewTarget);
1690 }
1691
1692 for (BasicBlock *Block : Blocks) {
1693 Instruction *TI = Block->getTerminator();
1694 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1695 if (Blocks.count(TI->getSuccessor(i)))
1696 continue;
1697 BasicBlock *OldTarget = TI->getSuccessor(i);
1698 // add a new basic block which returns the appropriate value
1699 BasicBlock *NewTarget = ExitBlockMap[OldTarget];
1700 assert(NewTarget && "Unknown target block!");
1701
1702 // rewrite the original branch instruction with this new target
1703 TI->setSuccessor(i, NewTarget);
1704 }
1705 }
1706
1707 // Loop over all of the PHI nodes in the header and exit blocks, and change
1708 // any references to the old incoming edge to be the new incoming edge.
1709 for (BasicBlock::iterator I = header->begin(); isa<PHINode>(I); ++I) {
1710 PHINode *PN = cast<PHINode>(I);
1711 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1712 if (!Blocks.count(PN->getIncomingBlock(i)))
1713 PN->setIncomingBlock(i, newFuncRoot);
1714 }
1715
1716 // Connect newFunction entry block to new header.
1717 UncondBrInst *BranchI = UncondBrInst::Create(header, newFuncRoot);
1718 applyFirstDebugLoc(oldFunction, Blocks.getArrayRef(), BranchI);
1719
1720 // Store the arguments right after the definition of output value.
1721 // This should be proceeded after creating exit stubs to be ensure that invoke
1722 // result restore will be placed in the outlined function.
1723 ScalarAI = newFunction->arg_begin();
1724 unsigned AggIdx = 0;
1725
1726 for (Value *Input : inputs) {
1727 if (StructValues.contains(Input))
1728 ++AggIdx;
1729 else
1730 ++ScalarAI;
1731 }
1732
1733 for (Value *Output : outputs) {
1734 // Find proper insertion point.
1735 // In case Output is an invoke, we insert the store at the beginning in the
1736 // 'normal destination' BB. Otherwise we insert the store right after
1737 // Output.
1738 BasicBlock::iterator InsertPt;
1739 if (auto *InvokeI = dyn_cast<InvokeInst>(Output))
1740 InsertPt = InvokeI->getNormalDest()->getFirstInsertionPt();
1741 else if (auto *Phi = dyn_cast<PHINode>(Output))
1742 InsertPt = Phi->getParent()->getFirstInsertionPt();
1743 else if (auto *OutI = dyn_cast<Instruction>(Output))
1744 InsertPt = std::next(OutI->getIterator());
1745 else {
1746 // Globals don't need to be updated, just advance to the next argument.
1747 if (StructValues.contains(Output))
1748 ++AggIdx;
1749 else
1750 ++ScalarAI;
1751 continue;
1752 }
1753
1754 assert((InsertPt->getFunction() == newFunction ||
1755 Blocks.count(InsertPt->getParent())) &&
1756 "InsertPt should be in new function");
1757
1758 if (StructValues.contains(Output)) {
1759 assert(AggArg && "Number of aggregate output arguments should match "
1760 "the number of defined values");
1761 Value *Idx[2];
1763 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), AggIdx);
1764 GetElementPtrInst *GEP = GetElementPtrInst::Create(
1765 StructArgTy, AggArg, Idx, "gep_" + Output->getName(), InsertPt);
1766 new StoreInst(Output, GEP, InsertPt);
1767 ++AggIdx;
1768 } else {
1769 assert(ScalarAI != newFunction->arg_end() &&
1770 "Number of scalar output arguments should match "
1771 "the number of defined values");
1772 new StoreInst(Output, &*ScalarAI, InsertPt);
1773 ++ScalarAI;
1774 }
1775 }
1776
1777 if (ExtractedFuncRetVals.empty()) {
1778 // Mark the new function `noreturn` if applicable. Terminators which resume
1779 // exception propagation are treated as returning instructions. This is to
1780 // avoid inserting traps after calls to outlined functions which unwind.
1781 if (none_of(Blocks, [](const BasicBlock *BB) {
1782 const Instruction *Term = BB->getTerminator();
1783 return isa<ReturnInst>(Term) || isa<ResumeInst>(Term);
1784 }))
1785 newFunction->setDoesNotReturn();
1786 }
1787}
1788
1789CallInst *CodeExtractor::emitReplacerCall(
1790 const ValueSet &inputs, const ValueSet &outputs,
1791 const ValueSet &StructValues, Function *newFunction,
1792 StructType *StructArgTy, Function *oldFunction, BasicBlock *ReplIP,
1793 BlockFrequency EntryFreq, ArrayRef<Value *> LifetimesStart,
1794 std::vector<Value *> &Reloads) {
1795 LLVMContext &Context = oldFunction->getContext();
1796 Module *M = oldFunction->getParent();
1797
1798 // This takes place of the original loop
1799 BasicBlock *codeReplacer =
1800 BasicBlock::Create(Context, "codeRepl", oldFunction, ReplIP);
1801 if (AllocationBlock)
1802 assert(AllocationBlock->getParent() == oldFunction &&
1803 "AllocationBlock is not in the same function");
1804 BasicBlock *AllocaBlock =
1805 AllocationBlock ? AllocationBlock : &oldFunction->getEntryBlock();
1806
1807 // If the original function has debug info, the terminator of the entry block
1808 // of the extracted function contains the first debug location of the
1809 // extracted function, set in extractCodeRegion.
1810 DebugLoc DL;
1811 if (oldFunction->getSubprogram())
1812 DL = newFunction->getEntryBlock().getTerminator()->getDebugLoc();
1813
1814 // Update the entry count of the function.
1815 if (BFI)
1816 BFI->setBlockFreq(codeReplacer, EntryFreq);
1817
1818 std::vector<Value *> params;
1819
1820 // Add inputs as params, or to be filled into the struct
1821 for (Value *input : inputs) {
1822 if (StructValues.contains(input))
1823 continue;
1824
1825 params.push_back(input);
1826 }
1827
1828 // Create allocas for the outputs
1829 std::vector<Value *> ReloadOutputs;
1830 for (Value *output : outputs) {
1831 if (StructValues.contains(output))
1832 continue;
1833
1834 Value *OutAlloc =
1835 allocateVar(AllocaBlock->getFirstInsertionPt(), DL, output->getType(),
1836 output->getName() + ".loc");
1837 params.push_back(OutAlloc);
1838 ReloadOutputs.push_back(OutAlloc);
1839 }
1840
1841 Instruction *Struct = nullptr;
1842 if (!StructValues.empty()) {
1843 AddrSpaceCastInst *StructSpaceCast = nullptr;
1844 Struct = allocateVar(AllocaBlock->getFirstInsertionPt(), DL, StructArgTy,
1845 "structArg", &StructSpaceCast);
1846 if (StructSpaceCast)
1847 params.push_back(StructSpaceCast);
1848 else
1849 params.push_back(Struct);
1850
1851 unsigned AggIdx = 0;
1852 for (Value *input : inputs) {
1853 if (!StructValues.contains(input))
1854 continue;
1855
1856 Value *Idx[2];
1858 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), AggIdx);
1859 GetElementPtrInst *GEP = GetElementPtrInst::Create(
1860 StructArgTy, Struct, Idx, "gep_" + input->getName());
1861 GEP->insertInto(codeReplacer, codeReplacer->end());
1862 new StoreInst(input, GEP, codeReplacer);
1863
1864 ++AggIdx;
1865 }
1866 }
1867
1868 // Emit the call to the function
1869 CallInst *call = CallInst::Create(
1870 newFunction, params, ExtractedFuncRetVals.size() > 1 ? "targetBlock" : "",
1871 codeReplacer);
1872
1873 // Set swifterror parameter attributes.
1874 unsigned ParamIdx = 0;
1875 unsigned AggIdx = 0;
1876 for (auto input : inputs) {
1877 if (StructValues.contains(input)) {
1878 ++AggIdx;
1879 } else {
1880 if (input->isSwiftError())
1881 call->addParamAttr(ParamIdx, Attribute::SwiftError);
1882 ++ParamIdx;
1883 }
1884 }
1885
1886 // Add debug location to the new call, if the original function has debug
1887 // info.
1888 if (DL)
1889 call->setDebugLoc(DL);
1890
1891 // Reload the outputs passed in by reference, use the struct if output is in
1892 // the aggregate or reload from the scalar argument.
1893 for (unsigned i = 0, e = outputs.size(), scalarIdx = 0; i != e; ++i) {
1894 Value *Output = nullptr;
1895 if (StructValues.contains(outputs[i])) {
1896 Value *Idx[2];
1898 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), AggIdx);
1899 GetElementPtrInst *GEP = GetElementPtrInst::Create(
1900 StructArgTy, Struct, Idx, "gep_reload_" + outputs[i]->getName());
1901 GEP->insertInto(codeReplacer, codeReplacer->end());
1902 Output = GEP;
1903 ++AggIdx;
1904 } else {
1905 Output = ReloadOutputs[scalarIdx];
1906 ++scalarIdx;
1907 }
1908 LoadInst *load =
1909 new LoadInst(outputs[i]->getType(), Output,
1910 outputs[i]->getName() + ".reload", codeReplacer);
1911 Reloads.push_back(load);
1912 }
1913
1914 // Now we can emit a switch statement using the call as a value.
1915 SwitchInst *TheSwitch =
1917 codeReplacer, 0, codeReplacer);
1918 for (auto P : enumerate(ExtractedFuncRetVals)) {
1919 BasicBlock *OldTarget = P.value();
1920 size_t SuccNum = P.index();
1921
1922 TheSwitch->addCase(ConstantInt::get(Type::getInt16Ty(Context), SuccNum),
1923 OldTarget);
1924 }
1925
1926 // Now that we've done the deed, simplify the switch instruction.
1927 Type *OldFnRetTy = TheSwitch->getParent()->getParent()->getReturnType();
1928 switch (ExtractedFuncRetVals.size()) {
1929 case 0:
1930 // There are no successors (the block containing the switch itself), which
1931 // means that previously this was the last part of the function, and hence
1932 // this should be rewritten as a `ret` or `unreachable`.
1933 if (newFunction->doesNotReturn()) {
1934 // If fn is no return, end with an unreachable terminator.
1935 (void)new UnreachableInst(Context, TheSwitch->getIterator());
1936 } else if (OldFnRetTy->isVoidTy()) {
1937 // We have no return value.
1938 ReturnInst::Create(Context, nullptr,
1939 TheSwitch->getIterator()); // Return void
1940 } else if (OldFnRetTy == TheSwitch->getCondition()->getType()) {
1941 // return what we have
1943 TheSwitch->getIterator());
1944 } else {
1945 // Otherwise we must have code extracted an unwind or something, just
1946 // return whatever we want.
1948 TheSwitch->getIterator());
1949 }
1950
1951 TheSwitch->eraseFromParent();
1952 break;
1953 case 1:
1954 // Only a single destination, change the switch into an unconditional
1955 // branch.
1956 UncondBrInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getIterator());
1957 TheSwitch->eraseFromParent();
1958 break;
1959 case 2:
1960 // Only two destinations, convert to a condition branch.
1961 // Remark: This also swaps the target branches:
1962 // 0 -> false -> getSuccessor(2); 1 -> true -> getSuccessor(1)
1963 CondBrInst::Create(call, TheSwitch->getSuccessor(1),
1964 TheSwitch->getSuccessor(2), TheSwitch->getIterator());
1965 TheSwitch->eraseFromParent();
1966 break;
1967 default:
1968 // Otherwise, make the default destination of the switch instruction be one
1969 // of the other successors.
1970 TheSwitch->setCondition(call);
1971 TheSwitch->setDefaultDest(
1972 TheSwitch->getSuccessor(ExtractedFuncRetVals.size()));
1973 // Remove redundant case
1974 TheSwitch->removeCase(
1975 SwitchInst::CaseIt(TheSwitch, ExtractedFuncRetVals.size() - 1));
1976 break;
1977 }
1978
1979 // Insert lifetime markers around the reloads of any output values. The
1980 // allocas output values are stored in are only in-use in the codeRepl block.
1981 insertLifetimeMarkersSurroundingCall(M, ReloadOutputs, ReloadOutputs, call);
1982
1983 // Replicate the effects of any lifetime start/end markers which referenced
1984 // input objects in the extraction region by placing markers around the call.
1985 insertLifetimeMarkersSurroundingCall(oldFunction->getParent(), LifetimesStart,
1986 {}, call);
1987
1988 // Deallocate intermediate variables if they need explicit deallocation.
1989 auto deallocVars = [&](BasicBlock::iterator DeallocIP) {
1990 int Index = 0;
1991 for (Value *Output : outputs) {
1992 if (!StructValues.contains(Output))
1993 deallocateVar(DeallocIP, DL, ReloadOutputs[Index++], Output->getType());
1994 }
1995
1996 if (Struct)
1997 deallocateVar(DeallocIP, DL, Struct, StructArgTy);
1998 };
1999
2000 if (DeallocationBlocks.empty()) {
2001 deallocVars(codeReplacer->end());
2002 } else {
2003 for (BasicBlock *DeallocationBlock : DeallocationBlocks)
2004 deallocVars(DeallocationBlock->getFirstInsertionPt());
2005 }
2006
2007 return call;
2008}
2009
2010void CodeExtractor::insertReplacerCall(
2011 Function *oldFunction, BasicBlock *header, CallInst *ReplacerCall,
2012 const ValueSet &outputs, ArrayRef<Value *> Reloads,
2013 const DenseMap<BasicBlock *, BlockFrequency> &ExitWeights) {
2014
2015 // Rewrite branches to basic blocks outside of the loop to new dummy blocks
2016 // within the new function. This must be done before we lose track of which
2017 // blocks were originally in the code region.
2018 BasicBlock *codeReplacer = ReplacerCall->getParent();
2019 std::vector<User *> Users(header->user_begin(), header->user_end());
2020 for (auto &U : Users)
2021 // The BasicBlock which contains the branch is not in the region
2022 // modify the branch target to a new block
2023 if (Instruction *I = dyn_cast<Instruction>(U))
2024 if (I->isTerminator() && I->getFunction() == oldFunction &&
2025 !Blocks.count(I->getParent()))
2026 I->replaceUsesOfWith(header, codeReplacer);
2027
2028 // When moving the code region it is sufficient to replace all uses to the
2029 // extracted function values. Since the original definition's block
2030 // dominated its use, it will also be dominated by codeReplacer's switch
2031 // which joined multiple exit blocks.
2032 for (BasicBlock *ExitBB : ExtractedFuncRetVals)
2033 for (PHINode &PN : ExitBB->phis()) {
2034 Value *IncomingCodeReplacerVal = nullptr;
2035 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
2036 // Ignore incoming values from outside of the extracted region.
2037 if (!Blocks.count(PN.getIncomingBlock(i)))
2038 continue;
2039
2040 // Ensure that there is only one incoming value from codeReplacer.
2041 if (!IncomingCodeReplacerVal) {
2042 PN.setIncomingBlock(i, codeReplacer);
2043 IncomingCodeReplacerVal = PN.getIncomingValue(i);
2044 } else
2045 assert(IncomingCodeReplacerVal == PN.getIncomingValue(i) &&
2046 "PHI has two incompatbile incoming values from codeRepl");
2047 }
2048 }
2049
2050 for (unsigned i = 0, e = outputs.size(); i != e; ++i) {
2051 Value *load = Reloads[i];
2052 std::vector<User *> Users(outputs[i]->user_begin(), outputs[i]->user_end());
2053 for (User *U : Users) {
2054 Instruction *inst = cast<Instruction>(U);
2055 if (inst->getParent()->getParent() == oldFunction)
2056 inst->replaceUsesOfWith(outputs[i], load);
2057 }
2058 }
2059
2060 if (FuncRetVal)
2061 FuncRetVal->replaceUsesWithIf(ReplacerCall, [&](Use &U) {
2062 return cast<Instruction>(U.getUser())->getFunction() == oldFunction;
2063 });
2064
2065 // Update the branch weights for the exit block.
2066 if (BFI && ExtractedFuncRetVals.size() > 1)
2067 calculateNewCallTerminatorWeights(codeReplacer, ExitWeights, BPI);
2068}
2069
2071 const Function &NewFunc,
2072 AssumptionCache *AC) {
2073 for (auto AssumeVH : AC->assumptions()) {
2074 auto *I = dyn_cast_or_null<CallInst>(AssumeVH);
2075 if (!I)
2076 continue;
2077
2078 // There shouldn't be any llvm.assume intrinsics in the new function.
2079 if (I->getFunction() != &OldFunc)
2080 return true;
2081
2082 // There shouldn't be any stale affected values in the assumption cache
2083 // that were previously in the old function, but that have now been moved
2084 // to the new function.
2085 for (auto AffectedValVH : AC->assumptionsFor(I->getOperand(0))) {
2086 auto *AffectedCI = dyn_cast_or_null<CallInst>(AffectedValVH);
2087 if (!AffectedCI)
2088 continue;
2089 if (AffectedCI->getFunction() != &OldFunc)
2090 return true;
2091 auto *AssumedInst = cast<Instruction>(AffectedCI->getOperand(0));
2092 if (AssumedInst->getFunction() != &OldFunc)
2093 return true;
2094 }
2095 }
2096 return false;
2097}
2098
2100 ExcludeArgsFromAggregate.insert(Arg);
2101}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
AMDGPU Mark last scratch load
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
This file contains the simple types necessary to represent the attributes associated with functions a...
static const Function * getParent(const Value *V)
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static void eraseDebugIntrinsicsWithNonLocalRefs(Function &F)
Erase debug info intrinsics which refer to values in F but aren't in F.
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.
static void applyFirstDebugLoc(Function *oldFunction, ArrayRef< BasicBlock * > Blocks, Instruction *BranchI)
If the original function has debug info, we have to add a debug location to the new branch instructio...
static bool definedInRegion(const SetVector< BasicBlock * > &Blocks, Value *V)
definedInRegion - Return true if the specified value is defined in the extracted region.
static bool definedInCaller(const SetVector< BasicBlock * > &Blocks, Value *V)
definedInCaller - Return true if the specified value is defined in the function being code extracted,...
static bool isBlockValidForExtraction(const BasicBlock &BB, const SetVector< BasicBlock * > &Result, bool AllowVarArgs, bool AllowAlloca)
Test whether a block is valid for extraction.
static BasicBlock * getCommonExitBlock(const SetVector< BasicBlock * > &Blocks)
static void eraseLifetimeMarkersOnInputs(const SetVector< BasicBlock * > &Blocks, const SetVector< Value * > &SunkAllocas, SetVector< Value * > &LifetimesStart)
Erase lifetime.start markers which reference inputs to the extraction region, and insert the referenc...
static bool isAlignmentPreservedForAddrCast(const Triple &TargetTriple)
isAlignmentPreservedForAddrCast - Return true if the cast operation for specified target preserves or...
static cl::opt< bool > AggregateArgsOpt("aggregate-extracted-args", cl::Hidden, cl::desc("Aggregate arguments to code-extracted functions"))
static void insertLifetimeMarkersSurroundingCall(Module *M, ArrayRef< Value * > LifetimesStart, ArrayRef< Value * > LifetimesEnd, CallInst *TheCall)
Insert lifetime start/end markers surrounding the call to the new function for objects defined in the...
static void fixupDebugInfoPostExtraction(Function &OldFunc, Function &NewFunc, CallInst &TheCall, const SetVector< Value * > &Inputs, ArrayRef< Value * > NewValues)
Fix up the debug info in the old and new functions.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
Hexagon Common GEP
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
iv Induction Variable Users
Definition IVUsers.cpp:48
Move duplicate certain instructions close to their use
Definition Localizer.cpp:78
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
uint64_t IntrinsicInst * II
#define P(N)
static StringRef getName(Value *V)
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
static Function * getFunction(FunctionType *Ty, const Twine &Name, Module *M)
The Input class is used to parse a yaml document into in-memory structs and vectors.
This class represents a conversion between pointers from one address space to another.
an instruction to allocate memory on the stack
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
A cache of @llvm.assume calls within a function.
@ TombstoneKey
Use as Tombstone key for DenseMap of AttrKind.
Definition Attributes.h:132
@ None
No attributes have been set.
Definition Attributes.h:127
@ EmptyKey
Use as Empty key for DenseMap of AttrKind.
Definition Attributes.h:131
@ EndAttrKinds
Sentinel value useful for loops.
Definition Attributes.h:130
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:453
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:440
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
LLVM_ABI BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
bool empty() const
Definition BasicBlock.h:462
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
Definition BasicBlock.h:666
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
InstListType::const_iterator const_iterator
Definition BasicBlock.h:171
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
LLVM_ABI const CallInst * getTerminatingDeoptimizeCall() const
Returns the call instruction calling @llvm.experimental.deoptimize prior to the terminating return in...
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Analysis providing branch probability information.
static constexpr BranchProbability getUnknown()
static constexpr BranchProbability getZero()
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
Adds the attribute to the indicated argument.
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
A cache for the CodeExtractor analysis.
ArrayRef< AllocaInst * > getAllocas() const
Get the allocas in the function at the time the analysis was created.
LLVM_ABI CodeExtractorAnalysisCache(Function &F)
LLVM_ABI bool doesBlockContainClobberOfAddr(BasicBlock &BB, AllocaInst *Addr) const
Check whether BB contains an instruction thought to load from, store to, or otherwise clobber the all...
BasicBlock * findOrCreateBlockForHoisting(BasicBlock *CommonExitBlock)
Find or create a block within the outline region for placing hoisted code.
void findInputsOutputs(ValueSet &Inputs, ValueSet &Outputs, const ValueSet &Allocas, bool CollectGlobalInputs=false)
Compute the set of input values and output values for the code.
void findAllocas(const CodeExtractorAnalysisCache &CEAC, ValueSet &SinkCands, ValueSet &HoistCands, BasicBlock *&ExitBlock) const
Find the set of allocas whose life ranges are contained within the outlined region.
CodeExtractor(ArrayRef< BasicBlock * > BBs, DominatorTree *DT=nullptr, bool AggregateArgs=false, BlockFrequencyInfo *BFI=nullptr, BranchProbabilityInfo *BPI=nullptr, AssumptionCache *AC=nullptr, bool AllowVarArgs=false, bool AllowAlloca=false, BasicBlock *AllocationBlock=nullptr, ArrayRef< BasicBlock * > DeallocationBlocks={}, std::string Suffix="", bool ArgsInZeroAddressSpace=false, bool VoidReturnWithSingleOutput=true)
Create a code extractor for a sequence of blocks.
Function * extractCodeRegion(const CodeExtractorAnalysisCache &CEAC)
Perform the extraction, returning the new function.
static bool verifyAssumptionCache(const Function &OldFunc, const Function &NewFunc, AssumptionCache *AC)
Verify that assumption cache isn't stale after a region is extracted.
virtual Instruction * allocateVar(IRBuilder<>::InsertPoint AllocaIP, DebugLoc DL, Type *VarType, const Twine &Name=Twine(""), AddrSpaceCastInst **CastedAlloc=nullptr)
Allocate an intermediate variable at the specified point.
bool isEligible() const
Test whether this code extractor is eligible.
void excludeArgFromAggregate(Value *Arg)
Exclude a value from aggregate argument passing when extracting a code region, passing it instead as ...
bool isLegalToShrinkwrapLifetimeMarkers(const CodeExtractorAnalysisCache &CEAC, Instruction *AllocaAddr) const
Check if life time marker nodes can be hoisted/sunk into the outline region.
virtual Instruction * deallocateVar(IRBuilder<>::InsertPoint DeallocIP, DebugLoc DL, Value *Var, Type *VarType)
Deallocate a previously-allocated intermediate variable at the specified point.
static CondBrInst * Create(Value *Cond, BasicBlock *IfTrue, BasicBlock *IfFalse, InsertPosition InsertBefore=nullptr)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
LLVM_ABI void finalizeSubprogram(DISubprogram *SP)
Finalize a specific subprogram - no new variables may be added to this subprogram afterwards.
Definition DIBuilder.cpp:53
LLVM_ABI DISubroutineType * createSubroutineType(DITypeArray ParameterTypes, DINode::DIFlags Flags=DINode::FlagZero, unsigned CC=0)
Create subroutine type.
LLVM_ABI DbgRecord * insertDbgValue(llvm::Value *Val, DILocalVariable *VarInfo, DIExpression *Expr, const DILocation *DL, InsertPosition InsertPt)
Insert a new dbg_value record.
LLVM_ABI DISubprogram * createFunction(DIScope *Scope, StringRef Name, StringRef LinkageName, DIFile *File, unsigned LineNo, DISubroutineType *Ty, unsigned ScopeLine, DINode::DIFlags Flags=DINode::FlagZero, DISubprogram::DISPFlags SPFlags=DISubprogram::SPFlagZero, DITemplateParameterArray TParams=nullptr, DISubprogram *Decl=nullptr, DITypeArray ThrownTypes=nullptr, DINodeArray Annotations=nullptr, StringRef TargetFuncName="", bool UseKeyInstructions=false)
Create a new descriptor for the specified subprogram.
LLVM_ABI DITypeArray getOrCreateTypeArray(ArrayRef< Metadata * > Elements)
Get a DITypeArray, create one if required.
LLVM_ABI DbgRecord * insertDeclare(Value *Storage, DILocalVariable *VarInfo, DIExpression *Expr, const DILocation *DL, BasicBlock *InsertAtEnd)
Insert a new dbg_declare record.
LLVM_ABI DIExpression * createExpression(ArrayRef< uint64_t > Addr={})
Create a new descriptor for the specified variable which has a complex address expression for its add...
LLVM_ABI DILocalVariable * createAutoVariable(DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNo, DIType *Ty, bool AlwaysPreserve=false, DINode::DIFlags Flags=DINode::FlagZero, uint32_t AlignInBits=0)
Create a new descriptor for an auto variable.
DWARF expression.
DIFile * getFile() const
StringRef getName() const
unsigned getLine() const
bool isArtificial() const
unsigned getColumn() const
DILocalScope * getScope() const
Get the local scope for this label.
std::optional< unsigned > getCoroSuspendIdx() const
A scope for locals.
static LLVM_ABI DILocalScope * cloneScopeForSubprogram(DILocalScope &RootScope, DISubprogram &NewSP, LLVMContext &Ctx, DenseMap< const MDNode *, MDNode * > &Cache)
Traverses the scope chain rooted at RootScope until it hits a Subprogram, recreating the chain with "...
Tagged DWARF-like metadata node.
LLVM_ABI StringRef getName() const
DIFile * getFile() const
Subprogram description. Uses SubclassData1.
DISPFlags
Debug info subprogram flags.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Records a position in IR for a source label (DILabel).
Base class for non-instruction debug metadata records that have positions within IR.
DebugLoc getDebugLoc() const
Record of a variable value-assignment, aka a non instruction representation of the dbg....
LLVM_ABI Value * getAddress() const
void setVariable(DILocalVariable *NewVar)
DILocalVariable * getVariable() const
LLVM_ABI iterator_range< location_op_iterator > location_ops() const
Get the locations corresponding to the variable referenced by the debug info intrinsic.
A debug info location.
Definition DebugLoc.h:126
static LLVM_ABI DebugLoc replaceInlinedAtSubprogram(const DebugLoc &DL, DISubprogram &NewSP, LLVMContext &Ctx, DenseMap< const MDNode *, MDNode * > &Cache)
Rebuild the entire inline-at chain by replacing the subprogram at the end of the chain with NewSP.
Definition DebugLoc.cpp:94
LLVM_ABI DILocation * getInlinedAt() const
Definition DebugLoc.cpp:58
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
iterator begin() const
iterator end() const
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
void addFnAttr(Attribute::AttrKind Kind)
Add function attributes to this function.
Definition Function.cpp:641
void setSubprogram(DISubprogram *SP)
Set the attached subprogram.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:169
const BasicBlock & getEntryBlock() const
Definition Function.h:794
Argument * arg_iterator
Definition Function.h:73
DISubprogram * getSubprogram() const
Get the attached subprogram.
void setDoesNotReturn()
Definition Function.h:569
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition Function.h:890
Constant * getPersonalityFn() const
Get the personality function associated with this function.
void setPersonalityFn(Constant *Fn)
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition Function.h:329
arg_iterator arg_end()
Definition Function.h:862
const Function & getFunction() const
Definition Function.h:167
iterator begin()
Definition Function.h:838
arg_iterator arg_begin()
Definition Function.h:853
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:352
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
adds the attribute to the list of attributes for the given arg.
Definition Function.cpp:669
Function::iterator insert(Function::iterator Position, BasicBlock *BB)
Insert BB in the basic block list at Position.
Definition Function.h:740
void setEntryCount(uint64_t Count, const DenseSet< GlobalValue::GUID > *Imports=nullptr)
Set the entry count for this function.
bool doesNotReturn() const
Determine if the function cannot return.
Definition Function.h:566
size_t arg_size() const
Definition Function.h:886
Argument * getArg(unsigned i) const
Definition Function.h:871
bool isVarArg() const
isVarArg - Return true if this function takes a variable number of arguments.
Definition Function.h:230
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
unsigned getAddressSpace() const
Module * getParent()
Get the module that this global value is contained inside of...
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
BasicBlock::iterator InsertPoint
InsertPoint - A saved insertion point.
Definition IRBuilder.h:253
LLVM_ABI bool isLifetimeStartOrEnd() const LLVM_READONLY
Return true if the instruction is a llvm.lifetime.start or llvm.lifetime.end marker.
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI void moveBefore(InstListType::iterator InsertPos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI BasicBlock * getSuccessor(unsigned Idx) const LLVM_READONLY
Return the specified successor. This instruction must be a terminator.
iterator_range< user_iterator > users()
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI void setSuccessor(unsigned Idx, BasicBlock *BB)
Update the specified successor to point at the provided block.
A wrapper class for inspecting calls to intrinsic functions.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
An instruction for reading from memory.
Value * getPointerOperand()
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1579
LLVM_ABI StringRef getName() const
Return the name of the corresponding LLVM basic block, or an empty string.
Root of the metadata hierarchy.
Definition Metadata.h:64
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
const Triple & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition Module.h:328
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
LLVM_ABI void removeIncomingValueIf(function_ref< bool(unsigned)> Predicate, bool DeletePHIIfEmpty=true)
Remove all incoming values for which the predicate returns true.
void setIncomingBlock(unsigned i, BasicBlock *BB)
LLVM_ABI Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
Remove an incoming value.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
Definition Type.cpp:887
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, InsertPosition InsertBefore=nullptr)
A vector that has set insertion semantics.
Definition SetVector.h:57
ArrayRef< value_type > getArrayRef() const
Definition SetVector.h:91
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
size_type count(const_arg_type key) const
Count the number of elements of a given key in the SetVector.
Definition SetVector.h:268
void clear()
Completely clear the SetVector.
Definition SetVector.h:273
bool empty() const
Determine if the SetVector is empty or not.
Definition SetVector.h:100
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:222
Class to represent struct types.
static LLVM_ABI 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:467
Type * getElementType(unsigned N) const
BasicBlock * getSuccessor(unsigned idx) const
static SwitchInst * Create(Value *Value, BasicBlock *Default, unsigned NumCases, InsertPosition InsertBefore=nullptr)
void setCondition(Value *V)
LLVM_ABI void addCase(ConstantInt *OnVal, BasicBlock *Dest)
Add an entry to the switch instruction.
CaseIteratorImpl< CaseHandle > CaseIt
void setDefaultDest(BasicBlock *DefaultCase)
Value * getCondition() const
LLVM_ABI CaseIt removeCase(CaseIt I)
This method removes the specified case and its successor from the switch instruction.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
ArchType getArch() const
Get the parsed architecture type of this triple.
Definition Triple.h:515
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:300
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:299
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:272
static LLVM_ABI IntegerType * getInt16Ty(LLVMContext &C)
Definition Type.cpp:298
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:296
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
op_range operands()
Definition User.h:267
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Definition User.cpp:25
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
user_iterator user_begin()
Definition Value.h:404
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:390
LLVM_ABI const Value * stripInBoundsConstantOffsets() const
Strip off pointer casts and all-constant inbounds GEPs.
Definition Value.cpp:720
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:549
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
user_iterator user_end()
Definition Value.h:412
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:315
LLVM_ABI void dump() const
Support for debugging, callable in GDB: V->dump()
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
LLVM_ABI void remapAssignID(DenseMap< DIAssignID *, DIAssignID * > &Map, Instruction &I)
Replace DIAssignID uses and attachments with IDs from Map.
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
detail::zippy< detail::zip_first, T, U, Args... > zip_equal(T &&t, U &&u, Args &&...args)
zip iterator that assumes that all iteratees have the same length.
Definition STLExtras.h:856
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2570
LLVM_ABI bool stripDebugInfo(Function &F)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
DomTreeNodeBase< BasicBlock > DomTreeNode
Definition Dominators.h:65
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
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:1762
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
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:1769
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto predecessors(const MachineBasicBlock *BB)
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
LLVM_ABI void updateLoopMetadataDebugLocations(Instruction &I, function_ref< Metadata *(Metadata *)> Updater)
Update the debug locations contained within the MD_loop metadata attached to the instruction I,...
LLVM_ABI void findDbgUsers(Value *V, SmallVectorImpl< DbgVariableRecord * > &DbgVariableRecords)
Finds the debug info records describing a value.