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