LLVM 24.0.0git
InlineFunction.cpp
Go to the documentation of this file.
1//===- InlineFunction.cpp - Code to perform function inlining -------------===//
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 inlining of a function into a call site, resolving
10// parameters and the return value as appropriate.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/ADT/DenseMap.h"
15#include "llvm/ADT/STLExtras.h"
16#include "llvm/ADT/SetVector.h"
35#include "llvm/IR/Argument.h"
37#include "llvm/IR/Attributes.h"
38#include "llvm/IR/BasicBlock.h"
39#include "llvm/IR/CFG.h"
40#include "llvm/IR/Constant.h"
42#include "llvm/IR/Constants.h"
43#include "llvm/IR/DataLayout.h"
44#include "llvm/IR/DebugInfo.h"
46#include "llvm/IR/DebugLoc.h"
48#include "llvm/IR/Dominators.h"
50#include "llvm/IR/Function.h"
52#include "llvm/IR/IRBuilder.h"
53#include "llvm/IR/InlineAsm.h"
54#include "llvm/IR/InstrTypes.h"
55#include "llvm/IR/Instruction.h"
58#include "llvm/IR/Intrinsics.h"
59#include "llvm/IR/LLVMContext.h"
60#include "llvm/IR/MDBuilder.h"
61#include "llvm/IR/Metadata.h"
62#include "llvm/IR/Module.h"
65#include "llvm/IR/Type.h"
66#include "llvm/IR/User.h"
67#include "llvm/IR/Value.h"
75#include <algorithm>
76#include <cassert>
77#include <cstdint>
78#include <deque>
79#include <iterator>
80#include <optional>
81#include <string>
82#include <utility>
83#include <vector>
84
85#define DEBUG_TYPE "inline-function"
86
87using namespace llvm;
88using namespace llvm::memprof;
89
90static cl::opt<bool>
91EnableNoAliasConversion("enable-noalias-to-md-conversion", cl::init(true),
93 cl::desc("Convert noalias attributes to metadata during inlining."));
94
95static cl::opt<bool>
96 UseNoAliasIntrinsic("use-noalias-intrinsic-during-inlining", cl::Hidden,
97 cl::init(true),
98 cl::desc("Use the llvm.experimental.noalias.scope.decl "
99 "intrinsic during inlining."));
100
101// Disabled by default, because the added alignment assumptions may increase
102// compile-time and block optimizations. This option is not suitable for use
103// with frontends that emit comprehensive parameter alignment annotations.
104static cl::opt<bool>
105PreserveAlignmentAssumptions("preserve-alignment-assumptions-during-inlining",
106 cl::init(false), cl::Hidden,
107 cl::desc("Convert align attributes to assumptions during inlining."));
108
110 "max-inst-checked-for-throw-during-inlining", cl::Hidden,
111 cl::desc("the maximum number of instructions analyzed for may throw during "
112 "attribute inference in inlined body"),
113 cl::init(4));
114
115namespace {
116
117 /// A class for recording information about inlining a landing pad.
118 class LandingPadInliningInfo {
119 /// Destination of the invoke's unwind.
120 BasicBlock *OuterResumeDest;
121
122 /// Destination for the callee's resume.
123 BasicBlock *InnerResumeDest = nullptr;
124
125 /// LandingPadInst associated with the invoke.
126 LandingPadInst *CallerLPad = nullptr;
127
128 /// PHI for EH values from landingpad insts.
129 PHINode *InnerEHValuesPHI = nullptr;
130
131 SmallVector<Value*, 8> UnwindDestPHIValues;
132
133 public:
134 LandingPadInliningInfo(InvokeInst *II)
135 : OuterResumeDest(II->getUnwindDest()) {
136 // If there are PHI nodes in the unwind destination block, we need to keep
137 // track of which values came into them from the invoke before removing
138 // the edge from this block.
139 BasicBlock *InvokeBB = II->getParent();
140 BasicBlock::iterator I = OuterResumeDest->begin();
141 for (; isa<PHINode>(I); ++I) {
142 // Save the value to use for this edge.
144 UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB));
145 }
146
147 CallerLPad = cast<LandingPadInst>(I);
148 }
149
150 /// The outer unwind destination is the target of
151 /// unwind edges introduced for calls within the inlined function.
152 BasicBlock *getOuterResumeDest() const {
153 return OuterResumeDest;
154 }
155
156 BasicBlock *getInnerResumeDest();
157
158 LandingPadInst *getLandingPadInst() const { return CallerLPad; }
159
160 /// Forward the 'resume' instruction to the caller's landing pad block.
161 /// When the landing pad block has only one predecessor, this is
162 /// a simple branch. When there is more than one predecessor, we need to
163 /// split the landing pad block after the landingpad instruction and jump
164 /// to there.
165 void forwardResume(ResumeInst *RI);
166
167 /// Add incoming-PHI values to the unwind destination block for the given
168 /// basic block, using the values for the original invoke's source block.
169 void addIncomingPHIValuesFor(BasicBlock *BB) const {
170 addIncomingPHIValuesForInto(BB, OuterResumeDest);
171 }
172
173 void addIncomingPHIValuesForInto(BasicBlock *src, BasicBlock *dest) const {
174 BasicBlock::iterator I = dest->begin();
175 for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
176 PHINode *phi = cast<PHINode>(I);
177 phi->addIncoming(UnwindDestPHIValues[i], src);
178 }
179 }
180 };
181} // end anonymous namespace
182
185 while (It != BB.end()) {
186 if (auto *IntrinsicCall = dyn_cast<ConvergenceControlInst>(It)) {
187 if (IntrinsicCall->isEntry()) {
188 return IntrinsicCall;
189 }
190 }
191 It = std::next(It);
192 }
193 return nullptr;
194}
195
196/// Get or create a target for the branch from ResumeInsts.
197BasicBlock *LandingPadInliningInfo::getInnerResumeDest() {
198 if (InnerResumeDest) return InnerResumeDest;
199
200 // Split the landing pad.
201 BasicBlock::iterator SplitPoint = ++CallerLPad->getIterator();
202 InnerResumeDest =
203 OuterResumeDest->splitBasicBlock(SplitPoint,
204 OuterResumeDest->getName() + ".body");
205
206 // The number of incoming edges we expect to the inner landing pad.
207 const unsigned PHICapacity = 2;
208
209 // Create corresponding new PHIs for all the PHIs in the outer landing pad.
210 BasicBlock::iterator InsertPoint = InnerResumeDest->begin();
211 BasicBlock::iterator I = OuterResumeDest->begin();
212 for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
213 PHINode *OuterPHI = cast<PHINode>(I);
214 PHINode *InnerPHI = PHINode::Create(OuterPHI->getType(), PHICapacity,
215 OuterPHI->getName() + ".lpad-body");
216 InnerPHI->insertBefore(InsertPoint);
217 OuterPHI->replaceAllUsesWith(InnerPHI);
218 InnerPHI->addIncoming(OuterPHI, OuterResumeDest);
219 }
220
221 // Create a PHI for the exception values.
222 InnerEHValuesPHI =
223 PHINode::Create(CallerLPad->getType(), PHICapacity, "eh.lpad-body");
224 InnerEHValuesPHI->insertBefore(InsertPoint);
225 CallerLPad->replaceAllUsesWith(InnerEHValuesPHI);
226 InnerEHValuesPHI->addIncoming(CallerLPad, OuterResumeDest);
227
228 // All done.
229 return InnerResumeDest;
230}
231
232/// Forward the 'resume' instruction to the caller's landing pad block.
233/// When the landing pad block has only one predecessor, this is a simple
234/// branch. When there is more than one predecessor, we need to split the
235/// landing pad block after the landingpad instruction and jump to there.
236void LandingPadInliningInfo::forwardResume(ResumeInst *RI) {
237 BasicBlock *Dest = getInnerResumeDest();
238 BasicBlock *Src = RI->getParent();
239
240 auto *BI = UncondBrInst::Create(Dest, Src);
241 BI->setDebugLoc(RI->getDebugLoc());
242
243 // Update the PHIs in the destination. They were inserted in an order which
244 // makes this work.
245 addIncomingPHIValuesForInto(Src, Dest);
246
247 InnerEHValuesPHI->addIncoming(RI->getOperand(0), Src);
248 RI->eraseFromParent();
249}
250
251/// Helper for getUnwindDestToken/getUnwindDestTokenHelper.
252static Value *getParentPad(Value *EHPad) {
253 if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
254 return FPI->getParentPad();
255 return cast<CatchSwitchInst>(EHPad)->getParentPad();
256}
257
259
260/// Helper for getUnwindDestToken that does the descendant-ward part of
261/// the search.
263 UnwindDestMemoTy &MemoMap) {
264 SmallVector<Instruction *, 8> Worklist(1, EHPad);
265
266 while (!Worklist.empty()) {
267 Instruction *CurrentPad = Worklist.pop_back_val();
268 // We only put pads on the worklist that aren't in the MemoMap. When
269 // we find an unwind dest for a pad we may update its ancestors, but
270 // the queue only ever contains uncles/great-uncles/etc. of CurrentPad,
271 // so they should never get updated while queued on the worklist.
272 assert(!MemoMap.count(CurrentPad));
273 Value *UnwindDestToken = nullptr;
274 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(CurrentPad)) {
275 if (CatchSwitch->hasUnwindDest()) {
276 UnwindDestToken = &*CatchSwitch->getUnwindDest()->getFirstNonPHIIt();
277 } else {
278 // Catchswitch doesn't have a 'nounwind' variant, and one might be
279 // annotated as "unwinds to caller" when really it's nounwind (see
280 // e.g. SimplifyCFGOpt::SimplifyUnreachable), so we can't infer the
281 // parent's unwind dest from this. We can check its catchpads'
282 // descendants, since they might include a cleanuppad with an
283 // "unwinds to caller" cleanupret, which can be trusted.
284 for (auto HI = CatchSwitch->handler_begin(),
285 HE = CatchSwitch->handler_end();
286 HI != HE && !UnwindDestToken; ++HI) {
287 BasicBlock *HandlerBlock = *HI;
288 auto *CatchPad =
289 cast<CatchPadInst>(&*HandlerBlock->getFirstNonPHIIt());
290 for (User *Child : CatchPad->users()) {
291 // Intentionally ignore invokes here -- since the catchswitch is
292 // marked "unwind to caller", it would be a verifier error if it
293 // contained an invoke which unwinds out of it, so any invoke we'd
294 // encounter must unwind to some child of the catch.
295 if (!isa<CleanupPadInst>(Child) && !isa<CatchSwitchInst>(Child))
296 continue;
297
298 Instruction *ChildPad = cast<Instruction>(Child);
299 auto Memo = MemoMap.find(ChildPad);
300 if (Memo == MemoMap.end()) {
301 // Haven't figured out this child pad yet; queue it.
302 Worklist.push_back(ChildPad);
303 continue;
304 }
305 // We've already checked this child, but might have found that
306 // it offers no proof either way.
307 Value *ChildUnwindDestToken = Memo->second;
308 if (!ChildUnwindDestToken)
309 continue;
310 // We already know the child's unwind dest, which can either
311 // be ConstantTokenNone to indicate unwind to caller, or can
312 // be another child of the catchpad. Only the former indicates
313 // the unwind dest of the catchswitch.
314 if (isa<ConstantTokenNone>(ChildUnwindDestToken)) {
315 UnwindDestToken = ChildUnwindDestToken;
316 break;
317 }
318 assert(getParentPad(ChildUnwindDestToken) == CatchPad);
319 }
320 }
321 }
322 } else {
323 auto *CleanupPad = cast<CleanupPadInst>(CurrentPad);
324 for (User *U : CleanupPad->users()) {
325 if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(U)) {
326 if (BasicBlock *RetUnwindDest = CleanupRet->getUnwindDest())
327 UnwindDestToken = &*RetUnwindDest->getFirstNonPHIIt();
328 else
329 UnwindDestToken = ConstantTokenNone::get(CleanupPad->getContext());
330 break;
331 }
332 Value *ChildUnwindDestToken;
333 if (auto *Invoke = dyn_cast<InvokeInst>(U)) {
334 ChildUnwindDestToken = &*Invoke->getUnwindDest()->getFirstNonPHIIt();
335 } else if (isa<CleanupPadInst>(U) || isa<CatchSwitchInst>(U)) {
336 Instruction *ChildPad = cast<Instruction>(U);
337 auto Memo = MemoMap.find(ChildPad);
338 if (Memo == MemoMap.end()) {
339 // Haven't resolved this child yet; queue it and keep searching.
340 Worklist.push_back(ChildPad);
341 continue;
342 }
343 // We've checked this child, but still need to ignore it if it
344 // had no proof either way.
345 ChildUnwindDestToken = Memo->second;
346 if (!ChildUnwindDestToken)
347 continue;
348 } else {
349 // Not a relevant user of the cleanuppad
350 continue;
351 }
352 // In a well-formed program, the child/invoke must either unwind to
353 // an(other) child of the cleanup, or exit the cleanup. In the
354 // first case, continue searching.
355 if (isa<Instruction>(ChildUnwindDestToken) &&
356 getParentPad(ChildUnwindDestToken) == CleanupPad)
357 continue;
358 UnwindDestToken = ChildUnwindDestToken;
359 break;
360 }
361 }
362 // If we haven't found an unwind dest for CurrentPad, we may have queued its
363 // children, so move on to the next in the worklist.
364 if (!UnwindDestToken)
365 continue;
366
367 // Now we know that CurrentPad unwinds to UnwindDestToken. It also exits
368 // any ancestors of CurrentPad up to but not including UnwindDestToken's
369 // parent pad. Record this in the memo map, and check to see if the
370 // original EHPad being queried is one of the ones exited.
371 Value *UnwindParent;
372 if (auto *UnwindPad = dyn_cast<Instruction>(UnwindDestToken))
373 UnwindParent = getParentPad(UnwindPad);
374 else
375 UnwindParent = nullptr;
376 bool ExitedOriginalPad = false;
377 for (Instruction *ExitedPad = CurrentPad;
378 ExitedPad && ExitedPad != UnwindParent;
379 ExitedPad = dyn_cast<Instruction>(getParentPad(ExitedPad))) {
380 // Skip over catchpads since they just follow their catchswitches.
381 if (isa<CatchPadInst>(ExitedPad))
382 continue;
383 MemoMap[ExitedPad] = UnwindDestToken;
384 ExitedOriginalPad |= (ExitedPad == EHPad);
385 }
386
387 if (ExitedOriginalPad)
388 return UnwindDestToken;
389
390 // Continue the search.
391 }
392
393 // No definitive information is contained within this funclet.
394 return nullptr;
395}
396
397/// Given an EH pad, find where it unwinds. If it unwinds to an EH pad,
398/// return that pad instruction. If it unwinds to caller, return
399/// ConstantTokenNone. If it does not have a definitive unwind destination,
400/// return nullptr.
401///
402/// This routine gets invoked for calls in funclets in inlinees when inlining
403/// an invoke. Since many funclets don't have calls inside them, it's queried
404/// on-demand rather than building a map of pads to unwind dests up front.
405/// Determining a funclet's unwind dest may require recursively searching its
406/// descendants, and also ancestors and cousins if the descendants don't provide
407/// an answer. Since most funclets will have their unwind dest immediately
408/// available as the unwind dest of a catchswitch or cleanupret, this routine
409/// searches top-down from the given pad and then up. To avoid worst-case
410/// quadratic run-time given that approach, it uses a memo map to avoid
411/// re-processing funclet trees. The callers that rewrite the IR as they go
412/// take advantage of this, for correctness, by checking/forcing rewritten
413/// pads' entries to match the original callee view.
415 UnwindDestMemoTy &MemoMap) {
416 // Catchpads unwind to the same place as their catchswitch;
417 // redirct any queries on catchpads so the code below can
418 // deal with just catchswitches and cleanuppads.
419 if (auto *CPI = dyn_cast<CatchPadInst>(EHPad))
420 EHPad = CPI->getCatchSwitch();
421
422 // Check if we've already determined the unwind dest for this pad.
423 auto Memo = MemoMap.find(EHPad);
424 if (Memo != MemoMap.end())
425 return Memo->second;
426
427 // Search EHPad and, if necessary, its descendants.
428 Value *UnwindDestToken = getUnwindDestTokenHelper(EHPad, MemoMap);
429 assert((UnwindDestToken == nullptr) != (MemoMap.count(EHPad) != 0));
430 if (UnwindDestToken)
431 return UnwindDestToken;
432
433 // No information is available for this EHPad from itself or any of its
434 // descendants. An unwind all the way out to a pad in the caller would
435 // need also to agree with the unwind dest of the parent funclet, so
436 // search up the chain to try to find a funclet with information. Put
437 // null entries in the memo map to avoid re-processing as we go up.
438 MemoMap[EHPad] = nullptr;
439#ifndef NDEBUG
441 TempMemos.insert(EHPad);
442#endif
443 Instruction *LastUselessPad = EHPad;
444 Value *AncestorToken;
445 for (AncestorToken = getParentPad(EHPad);
446 auto *AncestorPad = dyn_cast<Instruction>(AncestorToken);
447 AncestorToken = getParentPad(AncestorToken)) {
448 // Skip over catchpads since they just follow their catchswitches.
449 if (isa<CatchPadInst>(AncestorPad))
450 continue;
451 // If the MemoMap had an entry mapping AncestorPad to nullptr, since we
452 // haven't yet called getUnwindDestTokenHelper for AncestorPad in this
453 // call to getUnwindDestToken, that would mean that AncestorPad had no
454 // information in itself, its descendants, or its ancestors. If that
455 // were the case, then we should also have recorded the lack of information
456 // for the descendant that we're coming from. So assert that we don't
457 // find a null entry in the MemoMap for AncestorPad.
458 assert(!MemoMap.count(AncestorPad) || MemoMap[AncestorPad]);
459 auto AncestorMemo = MemoMap.find(AncestorPad);
460 if (AncestorMemo == MemoMap.end()) {
461 UnwindDestToken = getUnwindDestTokenHelper(AncestorPad, MemoMap);
462 } else {
463 UnwindDestToken = AncestorMemo->second;
464 }
465 if (UnwindDestToken)
466 break;
467 LastUselessPad = AncestorPad;
468 MemoMap[LastUselessPad] = nullptr;
469#ifndef NDEBUG
470 TempMemos.insert(LastUselessPad);
471#endif
472 }
473
474 // We know that getUnwindDestTokenHelper was called on LastUselessPad and
475 // returned nullptr (and likewise for EHPad and any of its ancestors up to
476 // LastUselessPad), so LastUselessPad has no information from below. Since
477 // getUnwindDestTokenHelper must investigate all downward paths through
478 // no-information nodes to prove that a node has no information like this,
479 // and since any time it finds information it records it in the MemoMap for
480 // not just the immediately-containing funclet but also any ancestors also
481 // exited, it must be the case that, walking downward from LastUselessPad,
482 // visiting just those nodes which have not been mapped to an unwind dest
483 // by getUnwindDestTokenHelper (the nullptr TempMemos notwithstanding, since
484 // they are just used to keep getUnwindDestTokenHelper from repeating work),
485 // any node visited must have been exhaustively searched with no information
486 // for it found.
487 SmallVector<Instruction *, 8> Worklist(1, LastUselessPad);
488 while (!Worklist.empty()) {
489 Instruction *UselessPad = Worklist.pop_back_val();
490 auto Memo = MemoMap.find(UselessPad);
491 if (Memo != MemoMap.end() && Memo->second) {
492 // Here the name 'UselessPad' is a bit of a misnomer, because we've found
493 // that it is a funclet that does have information about unwinding to
494 // a particular destination; its parent was a useless pad.
495 // Since its parent has no information, the unwind edge must not escape
496 // the parent, and must target a sibling of this pad. This local unwind
497 // gives us no information about EHPad. Leave it and the subtree rooted
498 // at it alone.
499 assert(getParentPad(Memo->second) == getParentPad(UselessPad));
500 continue;
501 }
502 // We know we don't have information for UselesPad. If it has an entry in
503 // the MemoMap (mapping it to nullptr), it must be one of the TempMemos
504 // added on this invocation of getUnwindDestToken; if a previous invocation
505 // recorded nullptr, it would have had to prove that the ancestors of
506 // UselessPad, which include LastUselessPad, had no information, and that
507 // in turn would have required proving that the descendants of
508 // LastUselesPad, which include EHPad, have no information about
509 // LastUselessPad, which would imply that EHPad was mapped to nullptr in
510 // the MemoMap on that invocation, which isn't the case if we got here.
511 assert(!MemoMap.count(UselessPad) || TempMemos.count(UselessPad));
512 // Assert as we enumerate users that 'UselessPad' doesn't have any unwind
513 // information that we'd be contradicting by making a map entry for it
514 // (which is something that getUnwindDestTokenHelper must have proved for
515 // us to get here). Just assert on is direct users here; the checks in
516 // this downward walk at its descendants will verify that they don't have
517 // any unwind edges that exit 'UselessPad' either (i.e. they either have no
518 // unwind edges or unwind to a sibling).
519 MemoMap[UselessPad] = UnwindDestToken;
520 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(UselessPad)) {
521 assert(CatchSwitch->getUnwindDest() == nullptr && "Expected useless pad");
522 for (BasicBlock *HandlerBlock : CatchSwitch->handlers()) {
523 auto *CatchPad = &*HandlerBlock->getFirstNonPHIIt();
524 for (User *U : CatchPad->users()) {
525 assert((!isa<InvokeInst>(U) ||
527 ->getUnwindDest()
528 ->getFirstNonPHIIt()) == CatchPad)) &&
529 "Expected useless pad");
531 Worklist.push_back(cast<Instruction>(U));
532 }
533 }
534 } else {
535 assert(isa<CleanupPadInst>(UselessPad));
536 for (User *U : UselessPad->users()) {
537 assert(!isa<CleanupReturnInst>(U) && "Expected useless pad");
538 assert(
539 (!isa<InvokeInst>(U) ||
541 &*cast<InvokeInst>(U)->getUnwindDest()->getFirstNonPHIIt()) ==
542 UselessPad)) &&
543 "Expected useless pad");
545 Worklist.push_back(cast<Instruction>(U));
546 }
547 }
548 }
549
550 return UnwindDestToken;
551}
552
553/// When we inline a basic block into an invoke,
554/// we have to turn all of the calls that can throw into invokes.
555/// This function analyze BB to see if there are any calls, and if so,
556/// it rewrites them to be invokes that jump to InvokeDest and fills in the PHI
557/// nodes in that block with the values specified in InvokeDestPHIValues.
559 BasicBlock *BB, BasicBlock *UnwindEdge,
560 SmallSetVector<const Value *, 4> &OriginallyIndirectCalls,
561 UnwindDestMemoTy *FuncletUnwindMap = nullptr) {
563 // We only need to check for function calls: inlined invoke
564 // instructions require no special handling.
566
567 if (!CI || CI->doesNotThrow())
568 continue;
569
570 // We do not need to (and in fact, cannot) convert possibly throwing calls
571 // to @llvm.experimental_deoptimize (resp. @llvm.experimental.guard) into
572 // invokes. The caller's "segment" of the deoptimization continuation
573 // attached to the newly inlined @llvm.experimental_deoptimize
574 // (resp. @llvm.experimental.guard) call should contain the exception
575 // handling logic, if any.
576 if (auto *F = CI->getCalledFunction())
577 if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize ||
578 F->getIntrinsicID() == Intrinsic::experimental_guard)
579 continue;
580
581 if (auto FuncletBundle = CI->getOperandBundle(LLVMContext::OB_funclet)) {
582 // This call is nested inside a funclet. If that funclet has an unwind
583 // destination within the inlinee, then unwinding out of this call would
584 // be UB. Rewriting this call to an invoke which targets the inlined
585 // invoke's unwind dest would give the call's parent funclet multiple
586 // unwind destinations, which is something that subsequent EH table
587 // generation can't handle and that the veirifer rejects. So when we
588 // see such a call, leave it as a call.
589 auto *FuncletPad = cast<Instruction>(FuncletBundle->Inputs[0]);
590 Value *UnwindDestToken =
591 getUnwindDestToken(FuncletPad, *FuncletUnwindMap);
592 if (UnwindDestToken && !isa<ConstantTokenNone>(UnwindDestToken))
593 continue;
594#ifndef NDEBUG
595 Instruction *MemoKey;
596 if (auto *CatchPad = dyn_cast<CatchPadInst>(FuncletPad))
597 MemoKey = CatchPad->getCatchSwitch();
598 else
599 MemoKey = FuncletPad;
600 assert(FuncletUnwindMap->count(MemoKey) &&
601 (*FuncletUnwindMap)[MemoKey] == UnwindDestToken &&
602 "must get memoized to avoid confusing later searches");
603#endif // NDEBUG
604 }
605
606 bool WasIndirect = OriginallyIndirectCalls.remove(CI);
607 changeToInvokeAndSplitBasicBlock(CI, UnwindEdge);
608 if (WasIndirect)
609 OriginallyIndirectCalls.insert(BB->getTerminator());
610 return BB;
611 }
612 return nullptr;
613}
614
615/// If we inlined an invoke site, we need to convert calls
616/// in the body of the inlined function into invokes.
617///
618/// II is the invoke instruction being inlined. FirstNewBlock is the first
619/// block of the inlined code (the last block is the end of the function),
620/// and InlineCodeInfo is information about the code that got inlined.
621static void HandleInlinedLandingPad(InvokeInst *II, BasicBlock *FirstNewBlock,
622 ClonedCodeInfo &InlinedCodeInfo) {
623 BasicBlock *InvokeDest = II->getUnwindDest();
624
625 Function *Caller = FirstNewBlock->getParent();
626
627 // The inlined code is currently at the end of the function, scan from the
628 // start of the inlined code to its end, checking for stuff we need to
629 // rewrite.
630 LandingPadInliningInfo Invoke(II);
631
632 // Get all of the inlined landing pad instructions. Keep them in block order
633 // so the clauses appended below get a deterministic use-list order.
635 for (Function::iterator I = FirstNewBlock->getIterator(), E = Caller->end();
636 I != E; ++I)
637 if (InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator()))
638 InlinedLPads.insert(II->getLandingPadInst());
639
640 // Append the clauses from the outer landing pad instruction into the inlined
641 // landing pad instructions.
642 LandingPadInst *OuterLPad = Invoke.getLandingPadInst();
643 for (LandingPadInst *InlinedLPad : InlinedLPads) {
644 unsigned OuterNum = OuterLPad->getNumClauses();
645 InlinedLPad->reserveClauses(OuterNum);
646 for (unsigned OuterIdx = 0; OuterIdx != OuterNum; ++OuterIdx)
647 InlinedLPad->addClause(OuterLPad->getClause(OuterIdx));
648 if (OuterLPad->isCleanup())
649 InlinedLPad->setCleanup(true);
650 }
651
652 for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end();
653 BB != E; ++BB) {
654 if (InlinedCodeInfo.ContainsCalls)
656 &*BB, Invoke.getOuterResumeDest(),
657 InlinedCodeInfo.OriginallyIndirectCalls))
658 // Update any PHI nodes in the exceptional block to indicate that there
659 // is now a new entry in them.
660 Invoke.addIncomingPHIValuesFor(NewBB);
661
662 // Forward any resumes that are remaining here.
663 if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator()))
664 Invoke.forwardResume(RI);
665 }
666
667 // Now that everything is happy, we have one final detail. The PHI nodes in
668 // the exception destination block still have entries due to the original
669 // invoke instruction. Eliminate these entries (which might even delete the
670 // PHI node) now.
671 InvokeDest->removePredecessor(II->getParent());
672}
673
674/// If we inlined an invoke site, we need to convert calls
675/// in the body of the inlined function into invokes.
676///
677/// II is the invoke instruction being inlined. FirstNewBlock is the first
678/// block of the inlined code (the last block is the end of the function),
679/// and InlineCodeInfo is information about the code that got inlined.
680static void HandleInlinedEHPad(InvokeInst *II, BasicBlock *FirstNewBlock,
681 ClonedCodeInfo &InlinedCodeInfo) {
682 BasicBlock *UnwindDest = II->getUnwindDest();
683 Function *Caller = FirstNewBlock->getParent();
684
685 assert(UnwindDest->getFirstNonPHIIt()->isEHPad() && "unexpected BasicBlock!");
686
687 // If there are PHI nodes in the unwind destination block, we need to keep
688 // track of which values came into them from the invoke before removing the
689 // edge from this block.
690 SmallVector<Value *, 8> UnwindDestPHIValues;
691 BasicBlock *InvokeBB = II->getParent();
692 for (PHINode &PHI : UnwindDest->phis()) {
693 // Save the value to use for this edge.
694 UnwindDestPHIValues.push_back(PHI.getIncomingValueForBlock(InvokeBB));
695 }
696
697 // Add incoming-PHI values to the unwind destination block for the given basic
698 // block, using the values for the original invoke's source block.
699 auto UpdatePHINodes = [&](BasicBlock *Src) {
700 BasicBlock::iterator I = UnwindDest->begin();
701 for (Value *V : UnwindDestPHIValues) {
703 PHI->addIncoming(V, Src);
704 ++I;
705 }
706 };
707
708 // This connects all the instructions which 'unwind to caller' to the invoke
709 // destination.
710 UnwindDestMemoTy FuncletUnwindMap;
711 for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end();
712 BB != E; ++BB) {
713 if (auto *CRI = dyn_cast<CleanupReturnInst>(BB->getTerminator())) {
714 if (CRI->unwindsToCaller()) {
715 auto *CleanupPad = CRI->getCleanupPad();
716 CleanupReturnInst::Create(CleanupPad, UnwindDest, CRI->getIterator());
717 CRI->eraseFromParent();
718 UpdatePHINodes(&*BB);
719 // Finding a cleanupret with an unwind destination would confuse
720 // subsequent calls to getUnwindDestToken, so map the cleanuppad
721 // to short-circuit any such calls and recognize this as an "unwind
722 // to caller" cleanup.
723 assert(!FuncletUnwindMap.count(CleanupPad) ||
724 isa<ConstantTokenNone>(FuncletUnwindMap[CleanupPad]));
725 FuncletUnwindMap[CleanupPad] =
726 ConstantTokenNone::get(Caller->getContext());
727 }
728 }
729
730 BasicBlock::iterator I = BB->getFirstNonPHIIt();
731 if (!I->isEHPad())
732 continue;
733
734 Instruction *Replacement = nullptr;
735 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I)) {
736 if (CatchSwitch->unwindsToCaller()) {
737 Value *UnwindDestToken;
738 if (auto *ParentPad =
739 dyn_cast<Instruction>(CatchSwitch->getParentPad())) {
740 // This catchswitch is nested inside another funclet. If that
741 // funclet has an unwind destination within the inlinee, then
742 // unwinding out of this catchswitch would be UB. Rewriting this
743 // catchswitch to unwind to the inlined invoke's unwind dest would
744 // give the parent funclet multiple unwind destinations, which is
745 // something that subsequent EH table generation can't handle and
746 // that the veirifer rejects. So when we see such a call, leave it
747 // as "unwind to caller".
748 UnwindDestToken = getUnwindDestToken(ParentPad, FuncletUnwindMap);
749 if (UnwindDestToken && !isa<ConstantTokenNone>(UnwindDestToken))
750 continue;
751 } else {
752 // This catchswitch has no parent to inherit constraints from, and
753 // none of its descendants can have an unwind edge that exits it and
754 // targets another funclet in the inlinee. It may or may not have a
755 // descendant that definitively has an unwind to caller. In either
756 // case, we'll have to assume that any unwinds out of it may need to
757 // be routed to the caller, so treat it as though it has a definitive
758 // unwind to caller.
759 UnwindDestToken = ConstantTokenNone::get(Caller->getContext());
760 }
761 auto *NewCatchSwitch = CatchSwitchInst::Create(
762 CatchSwitch->getParentPad(), UnwindDest,
763 CatchSwitch->getNumHandlers(), CatchSwitch->getName(),
764 CatchSwitch->getIterator());
765 for (BasicBlock *PadBB : CatchSwitch->handlers())
766 NewCatchSwitch->addHandler(PadBB);
767 // Propagate info for the old catchswitch over to the new one in
768 // the unwind map. This also serves to short-circuit any subsequent
769 // checks for the unwind dest of this catchswitch, which would get
770 // confused if they found the outer handler in the callee.
771 FuncletUnwindMap[NewCatchSwitch] = UnwindDestToken;
772 Replacement = NewCatchSwitch;
773 }
774 } else if (!isa<FuncletPadInst>(I)) {
775 llvm_unreachable("unexpected EHPad!");
776 }
777
778 if (Replacement) {
779 Replacement->takeName(&*I);
780 I->replaceAllUsesWith(Replacement);
781 I->eraseFromParent();
782 UpdatePHINodes(&*BB);
783 }
784 }
785
786 if (InlinedCodeInfo.ContainsCalls)
787 for (Function::iterator BB = FirstNewBlock->getIterator(),
788 E = Caller->end();
789 BB != E; ++BB)
791 &*BB, UnwindDest, InlinedCodeInfo.OriginallyIndirectCalls,
792 &FuncletUnwindMap))
793 // Update any PHI nodes in the exceptional block to indicate that there
794 // is now a new entry in them.
795 UpdatePHINodes(NewBB);
796
797 // Now that everything is happy, we have one final detail. The PHI nodes in
798 // the exception destination block still have entries due to the original
799 // invoke instruction. Eliminate these entries (which might even delete the
800 // PHI node) now.
801 UnwindDest->removePredecessor(InvokeBB);
802}
803
804static bool haveCommonPrefix(MDNode *MIBStackContext,
805 MDNode *CallsiteStackContext) {
806 assert(MIBStackContext->getNumOperands() > 0 &&
807 CallsiteStackContext->getNumOperands() > 0);
808 // Because of the context trimming performed during matching, the callsite
809 // context could have more stack ids than the MIB. We match up to the end of
810 // the shortest stack context.
811 for (auto MIBStackIter = MIBStackContext->op_begin(),
812 CallsiteStackIter = CallsiteStackContext->op_begin();
813 MIBStackIter != MIBStackContext->op_end() &&
814 CallsiteStackIter != CallsiteStackContext->op_end();
815 MIBStackIter++, CallsiteStackIter++) {
816 auto *Val1 = mdconst::dyn_extract<ConstantInt>(*MIBStackIter);
817 auto *Val2 = mdconst::dyn_extract<ConstantInt>(*CallsiteStackIter);
818 assert(Val1 && Val2);
819 if (Val1->getZExtValue() != Val2->getZExtValue())
820 return false;
821 }
822 return true;
823}
824
826 Call->setMetadata(LLVMContext::MD_memprof, nullptr);
827}
828
830 Call->setMetadata(LLVMContext::MD_callsite, nullptr);
831}
832
834 const std::vector<Metadata *> &MIBList,
836 assert(!MIBList.empty());
837 // Remove existing memprof, which will either be replaced or may not be needed
838 // if we are able to use a single allocation type function attribute.
841 for (Metadata *MIB : MIBList)
842 CallStack.addCallStack(cast<MDNode>(MIB));
843 bool MemprofMDAttached = CallStack.buildAndAttachMIBMetadata(CI);
844 assert(MemprofMDAttached == CI->hasMetadata(LLVMContext::MD_memprof));
845 if (!MemprofMDAttached)
846 // If we used a function attribute remove the callsite metadata as well.
848}
849
850// Update the metadata on the inlined copy ClonedCall of a call OrigCall in the
851// inlined callee body, based on the callsite metadata InlinedCallsiteMD from
852// the call that was inlined.
853static void propagateMemProfHelper(const CallBase *OrigCall,
854 CallBase *ClonedCall,
855 MDNode *InlinedCallsiteMD,
857 MDNode *OrigCallsiteMD = ClonedCall->getMetadata(LLVMContext::MD_callsite);
858 MDNode *ClonedCallsiteMD = nullptr;
859 // Check if the call originally had callsite metadata, and update it for the
860 // new call in the inlined body.
861 if (OrigCallsiteMD) {
862 // The cloned call's context is now the concatenation of the original call's
863 // callsite metadata and the callsite metadata on the call where it was
864 // inlined.
865 ClonedCallsiteMD = MDNode::concatenate(OrigCallsiteMD, InlinedCallsiteMD);
866 ClonedCall->setMetadata(LLVMContext::MD_callsite, ClonedCallsiteMD);
867 }
868
869 // Update any memprof metadata on the cloned call.
870 MDNode *OrigMemProfMD = ClonedCall->getMetadata(LLVMContext::MD_memprof);
871 if (!OrigMemProfMD)
872 return;
873 // We currently expect that allocations with memprof metadata also have
874 // callsite metadata for the allocation's part of the context.
875 assert(OrigCallsiteMD);
876
877 // New call's MIB list.
878 std::vector<Metadata *> NewMIBList;
879
880 // For each MIB metadata, check if its call stack context starts with the
881 // new clone's callsite metadata. If so, that MIB goes onto the cloned call in
882 // the inlined body. If not, it stays on the out-of-line original call.
883 for (auto &MIBOp : OrigMemProfMD->operands()) {
884 MDNode *MIB = dyn_cast<MDNode>(MIBOp);
885 // Stack is first operand of MIB.
886 MDNode *StackMD = getMIBStackNode(MIB);
887 assert(StackMD);
888 // See if the new cloned callsite context matches this profiled context.
889 if (haveCommonPrefix(StackMD, ClonedCallsiteMD))
890 // Add it to the cloned call's MIB list.
891 NewMIBList.push_back(MIB);
892 }
893 if (NewMIBList.empty()) {
894 removeMemProfMetadata(ClonedCall);
895 removeCallsiteMetadata(ClonedCall);
896 return;
897 }
898 if (NewMIBList.size() < OrigMemProfMD->getNumOperands())
899 updateMemprofMetadata(ClonedCall, NewMIBList, ORE);
900}
901
902// Update memprof related metadata (!memprof and !callsite) based on the
903// inlining of Callee into the callsite at CB. The updates include merging the
904// inlined callee's callsite metadata with that of the inlined call,
905// and moving the subset of any memprof contexts to the inlined callee
906// allocations if they match the new inlined call stack.
907static void
909 bool ContainsMemProfMetadata,
912 MDNode *CallsiteMD = CB.getMetadata(LLVMContext::MD_callsite);
913 // Only need to update if the inlined callsite had callsite metadata, or if
914 // there was any memprof metadata inlined.
915 if (!CallsiteMD && !ContainsMemProfMetadata)
916 return;
917
918 // Propagate metadata onto the cloned calls in the inlined callee.
919 for (const auto &Entry : VMap) {
920 // See if this is a call that has been inlined and remapped, and not
921 // simplified away in the process.
922 auto *OrigCall = dyn_cast_or_null<CallBase>(Entry.first);
923 auto *ClonedCall = dyn_cast_or_null<CallBase>(Entry.second);
924 if (!OrigCall || !ClonedCall)
925 continue;
926 // If the inlined callsite did not have any callsite metadata, then it isn't
927 // involved in any profiled call contexts, and we can remove any memprof
928 // metadata on the cloned call.
929 if (!CallsiteMD) {
930 removeMemProfMetadata(ClonedCall);
931 removeCallsiteMetadata(ClonedCall);
932 continue;
933 }
934 propagateMemProfHelper(OrigCall, ClonedCall, CallsiteMD, ORE);
935 }
936}
937
938/// Collect all calls that produce RetVal, following only pointer-preserving
939/// instructions (cast, phi, select).
942 SmallVector<Value *, 8> Worklist{RetVal};
944 while (!Worklist.empty()) {
945 Value *V = Worklist.pop_back_val();
946 if (!V->getType()->isPointerTy() || !Visited.insert(V).second)
947 continue;
948 if (auto *CB = dyn_cast<CallBase>(V))
949 Out.push_back(CB);
951 Worklist.push_back(cast<CastInst>(V)->getOperand(0));
952 else if (auto *PN = dyn_cast<PHINode>(V))
953 append_range(Worklist, PN->incoming_values());
954 else if (auto *SI = dyn_cast<SelectInst>(V)) {
955 Worklist.push_back(SI->getTrueValue());
956 Worklist.push_back(SI->getFalseValue());
957 }
958 }
959}
960
961/// When inlining a call that carries !alloc_token metadata, propagate that
962/// metadata onto calls exposed by inlining the wrapper body. Propagation is
963/// restricted to return-value producing calls, which avoids instrumenting
964/// unrelated calls in the wrapper body.
965static void
968 ClonedCodeInfo &InlinedFunctionInfo) {
969 MDNode *AllocTokenMD = CB.getMetadata(LLVMContext::MD_alloc_token);
970 if (!AllocTokenMD)
971 return;
972
974 for (BasicBlock &BB : *CalledFunc)
975 if (auto *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
976 if (Value *RV = RI->getReturnValue())
977 collectPointerReturningCalls(RV, AllocCalls);
978
979 for (CallBase *OrigCall : AllocCalls) {
980 auto *ClonedCall = dyn_cast_or_null<CallBase>(VMap.lookup(OrigCall));
981 if (!ClonedCall)
982 continue;
983 // Skip calls simplified during inlining; propagation may be incorrect.
984 if (InlinedFunctionInfo.isSimplified(OrigCall, ClonedCall))
985 continue;
986 // Fill missing only: never overwrite a more specific token the wrapper
987 // already set on an internal allocation. An unknown type (empty type name
988 // with function name) is not more specific.
989 if (MDNode *MD = ClonedCall->getMetadata(LLVMContext::MD_alloc_token)) {
990 if (MD->getNumOperands() != 3 ||
991 !cast<MDString>(MD->getOperand(0))->getString().empty())
992 continue;
993 }
994 ClonedCall->setMetadata(LLVMContext::MD_alloc_token, AllocTokenMD);
995 }
996}
997
998/// When inlining a call site that has !llvm.mem.parallel_loop_access,
999/// !llvm.access.group, !alias.scope or !noalias metadata, that metadata should
1000/// be propagated to all memory-accessing cloned instructions.
1002 Function::iterator FEnd) {
1003 MDNode *MemParallelLoopAccess =
1004 CB.getMetadata(LLVMContext::MD_mem_parallel_loop_access);
1005 MDNode *AccessGroup = CB.getMetadata(LLVMContext::MD_access_group);
1006 MDNode *AliasScope = CB.getMetadata(LLVMContext::MD_alias_scope);
1007 MDNode *NoAlias = CB.getMetadata(LLVMContext::MD_noalias);
1008 if (!MemParallelLoopAccess && !AccessGroup && !AliasScope && !NoAlias)
1009 return;
1010
1011 for (BasicBlock &BB : make_range(FStart, FEnd)) {
1012 for (Instruction &I : BB) {
1013 // This metadata is only relevant for instructions that access memory.
1014 if (!I.mayReadOrWriteMemory())
1015 continue;
1016
1017 if (MemParallelLoopAccess) {
1018 // TODO: This probably should not overwrite MemParalleLoopAccess.
1019 MemParallelLoopAccess = MDNode::concatenate(
1020 I.getMetadata(LLVMContext::MD_mem_parallel_loop_access),
1021 MemParallelLoopAccess);
1022 I.setMetadata(LLVMContext::MD_mem_parallel_loop_access,
1023 MemParallelLoopAccess);
1024 }
1025
1026 if (AccessGroup)
1027 I.setMetadata(LLVMContext::MD_access_group, uniteAccessGroups(
1028 I.getMetadata(LLVMContext::MD_access_group), AccessGroup));
1029
1030 if (AliasScope)
1031 I.setMetadata(LLVMContext::MD_alias_scope, MDNode::concatenate(
1032 I.getMetadata(LLVMContext::MD_alias_scope), AliasScope));
1033
1034 if (NoAlias)
1035 I.setMetadata(LLVMContext::MD_noalias, MDNode::concatenate(
1036 I.getMetadata(LLVMContext::MD_noalias), NoAlias));
1037 }
1038 }
1039}
1040
1041/// Track inlining chain via inlined.from metadata for dontcall diagnostics.
1042static void PropagateInlinedFromMetadata(CallBase &CB, StringRef CalledFuncName,
1043 StringRef CallerFuncName,
1044 Function::iterator FStart,
1045 Function::iterator FEnd) {
1046 LLVMContext &Ctx = CB.getContext();
1047 uint64_t InlineSiteLoc = 0;
1048 if (auto *MD = CB.getMetadata("srcloc"))
1049 if (auto *CI = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0)))
1050 InlineSiteLoc = CI->getZExtValue();
1051
1052 auto *I64Ty = Type::getInt64Ty(Ctx);
1053 auto MakeMDInt = [&](uint64_t V) {
1054 return ConstantAsMetadata::get(ConstantInt::get(I64Ty, V));
1055 };
1056
1057 for (BasicBlock &BB : make_range(FStart, FEnd)) {
1058 for (Instruction &I : BB) {
1059 auto *CI = dyn_cast<CallInst>(&I);
1060 if (!CI || !CI->getMetadata("srcloc"))
1061 continue;
1062 auto *Callee = CI->getCalledFunction();
1063 if (!Callee || (!Callee->hasFnAttribute("dontcall-error") &&
1064 !Callee->hasFnAttribute("dontcall-warn")))
1065 continue;
1066
1068 if (MDNode *Existing = CI->getMetadata("inlined.from"))
1069 append_range(Ops, Existing->operands());
1070 else {
1071 Ops.push_back(MDString::get(Ctx, CalledFuncName));
1072 Ops.push_back(MakeMDInt(0));
1073 }
1074 Ops.push_back(MDString::get(Ctx, CallerFuncName));
1075 Ops.push_back(MakeMDInt(InlineSiteLoc));
1076 CI->setMetadata("inlined.from", MDNode::get(Ctx, Ops));
1077 }
1078 }
1079}
1080
1081/// Bundle operands of the inlined function must be added to inlined call sites.
1083 Instruction *CallSiteEHPad) {
1084 for (Instruction &II : llvm::make_early_inc_range(*InlinedBB)) {
1086 if (!I)
1087 continue;
1088 // Skip call sites which already have a "funclet" bundle.
1089 if (I->getOperandBundle(LLVMContext::OB_funclet))
1090 continue;
1091 // Skip call sites which are nounwind intrinsics (as long as they don't
1092 // lower into regular function calls in the course of IR transformations).
1093 auto *CalledFn =
1094 dyn_cast<Function>(I->getCalledOperand()->stripPointerCasts());
1095 if (CalledFn && CalledFn->isIntrinsic() && I->doesNotThrow() &&
1096 !IntrinsicInst::mayLowerToFunctionCall(CalledFn->getIntrinsicID()))
1097 continue;
1098
1100 I->getOperandBundlesAsDefs(OpBundles);
1101 OpBundles.emplace_back("funclet", CallSiteEHPad);
1102
1103 Instruction *NewInst = CallBase::Create(I, OpBundles, I->getIterator());
1104 NewInst->takeName(I);
1105 I->replaceAllUsesWith(NewInst);
1106 I->eraseFromParent();
1107 }
1108}
1109
1110namespace {
1111/// Utility for cloning !noalias and !alias.scope metadata. When a code region
1112/// using scoped alias metadata is inlined, the aliasing relationships may not
1113/// hold between the two version. It is necessary to create a deep clone of the
1114/// metadata, putting the two versions in separate scope domains.
1115class ScopedAliasMetadataDeepCloner {
1116 using MetadataMap = DenseMap<const MDNode *, TrackingMDNodeRef>;
1117 SetVector<const MDNode *> MD;
1118 MetadataMap MDMap;
1119 void addRecursiveMetadataUses();
1120
1121public:
1122 ScopedAliasMetadataDeepCloner(const Function *F);
1123
1124 /// Create a new clone of the scoped alias metadata, which will be used by
1125 /// subsequent remap() calls.
1126 void clone();
1127
1128 /// Remap instructions in the given range from the original to the cloned
1129 /// metadata.
1130 void remap(Function::iterator FStart, Function::iterator FEnd);
1131};
1132} // namespace
1133
1134ScopedAliasMetadataDeepCloner::ScopedAliasMetadataDeepCloner(
1135 const Function *F) {
1136 for (const BasicBlock &BB : *F) {
1137 for (const Instruction &I : BB) {
1138 if (const MDNode *M = I.getMetadata(LLVMContext::MD_alias_scope))
1139 MD.insert(M);
1140 if (const MDNode *M = I.getMetadata(LLVMContext::MD_noalias))
1141 MD.insert(M);
1142
1143 // We also need to clone the metadata in noalias intrinsics.
1144 if (const auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I))
1145 MD.insert(Decl->getScopeList());
1146 }
1147 }
1148 addRecursiveMetadataUses();
1149}
1150
1151void ScopedAliasMetadataDeepCloner::addRecursiveMetadataUses() {
1152 SmallVector<const Metadata *, 16> Queue(MD.begin(), MD.end());
1153 while (!Queue.empty()) {
1154 const MDNode *M = cast<MDNode>(Queue.pop_back_val());
1155 for (const Metadata *Op : M->operands())
1156 if (const MDNode *OpMD = dyn_cast<MDNode>(Op))
1157 if (MD.insert(OpMD))
1158 Queue.push_back(OpMD);
1159 }
1160}
1161
1162void ScopedAliasMetadataDeepCloner::clone() {
1163 assert(MDMap.empty() && "clone() already called ?");
1164
1166 for (const MDNode *I : MD) {
1167 DummyNodes.push_back(MDTuple::getTemporary(I->getContext(), {}));
1168 MDMap[I].reset(DummyNodes.back().get());
1169 }
1170
1171 // Create new metadata nodes to replace the dummy nodes, replacing old
1172 // metadata references with either a dummy node or an already-created new
1173 // node.
1175 for (const MDNode *I : MD) {
1176 for (const Metadata *Op : I->operands()) {
1177 if (const MDNode *M = dyn_cast<MDNode>(Op))
1178 NewOps.push_back(MDMap[M]);
1179 else
1180 NewOps.push_back(const_cast<Metadata *>(Op));
1181 }
1182
1183 MDNode *NewM = MDNode::get(I->getContext(), NewOps);
1184 MDTuple *TempM = cast<MDTuple>(MDMap[I]);
1185 assert(TempM->isTemporary() && "Expected temporary node");
1186
1187 TempM->replaceAllUsesWith(NewM);
1188 NewOps.clear();
1189 }
1190}
1191
1192void ScopedAliasMetadataDeepCloner::remap(Function::iterator FStart,
1193 Function::iterator FEnd) {
1194 if (MDMap.empty())
1195 return; // Nothing to do.
1196
1197 for (BasicBlock &BB : make_range(FStart, FEnd)) {
1198 for (Instruction &I : BB) {
1199 // TODO: The null checks for the MDMap.lookup() results should no longer
1200 // be necessary.
1201 if (MDNode *M = I.getMetadata(LLVMContext::MD_alias_scope))
1202 if (MDNode *MNew = MDMap.lookup(M))
1203 I.setMetadata(LLVMContext::MD_alias_scope, MNew);
1204
1205 if (MDNode *M = I.getMetadata(LLVMContext::MD_noalias))
1206 if (MDNode *MNew = MDMap.lookup(M))
1207 I.setMetadata(LLVMContext::MD_noalias, MNew);
1208
1209 if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I))
1210 if (MDNode *MNew = MDMap.lookup(Decl->getScopeList()))
1211 Decl->setScopeList(MNew);
1212 }
1213 }
1214}
1215
1216/// If the inlined function has noalias arguments,
1217/// then add new alias scopes for each noalias argument, tag the mapped noalias
1218/// parameters with noalias metadata specifying the new scope, and tag all
1219/// non-derived loads, stores and memory intrinsics with the new alias scopes.
1221 const DataLayout &DL, AAResults *CalleeAAR,
1222 ClonedCodeInfo &InlinedFunctionInfo) {
1224 return;
1225
1226 const Function *CalledFunc = CB.getCalledFunction();
1228
1229 for (const Argument &Arg : CalledFunc->args())
1230 if (CB.paramHasAttr(Arg.getArgNo(), Attribute::NoAlias) && !Arg.use_empty())
1231 NoAliasArgs.push_back(&Arg);
1232
1233 if (NoAliasArgs.empty())
1234 return;
1235
1236 // To do a good job, if a noalias variable is captured, we need to know if
1237 // the capture point dominates the particular use we're considering.
1238 DominatorTree DT;
1239 DT.recalculate(const_cast<Function&>(*CalledFunc));
1240
1241 // noalias indicates that pointer values based on the argument do not alias
1242 // pointer values which are not based on it. So we add a new "scope" for each
1243 // noalias function argument. Accesses using pointers based on that argument
1244 // become part of that alias scope, accesses using pointers not based on that
1245 // argument are tagged as noalias with that scope.
1246
1248 MDBuilder MDB(CalledFunc->getContext());
1249
1250 // Create a new scope domain for this function. Its scopes are disjoint,
1251 // since accesses based on one noalias argument don't alias accesses based on
1252 // another one.
1253 MDNode *NewDomain = MDB.createAnonymousAliasScopeDomain(
1254 CalledFunc->getName(), /*DisjointScopes=*/true);
1255 for (unsigned i = 0, e = NoAliasArgs.size(); i != e; ++i) {
1256 const Argument *A = NoAliasArgs[i];
1257
1258 std::string Name = std::string(CalledFunc->getName());
1259 if (A->hasName()) {
1260 Name += ": %";
1261 Name += A->getName();
1262 } else {
1263 Name += ": argument ";
1264 Name += utostr(i);
1265 }
1266
1267 // Note: We always create a new anonymous root here. This is true regardless
1268 // of the linkage of the callee because the aliasing "scope" is not just a
1269 // property of the callee, but also all control dependencies in the caller.
1270 MDNode *NewScope = MDB.createAnonymousAliasScope(NewDomain, Name);
1271 NewScopes.insert(std::make_pair(A, NewScope));
1272
1273 if (UseNoAliasIntrinsic) {
1274 // Introduce a llvm.experimental.noalias.scope.decl for the noalias
1275 // argument.
1276 MDNode *AScopeList = MDNode::get(CalledFunc->getContext(), NewScope);
1277 auto *NoAliasDecl =
1278 IRBuilder<>(&CB).CreateNoAliasScopeDeclaration(AScopeList);
1279 // Ignore the result for now. The result will be used when the
1280 // llvm.noalias intrinsic is introduced.
1281 (void)NoAliasDecl;
1282 }
1283 }
1284
1285 // Iterate over all new instructions in the map; for all memory-access
1286 // instructions, add the alias scope metadata.
1287 for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
1288 VMI != VMIE; ++VMI) {
1289 if (const Instruction *I = dyn_cast<Instruction>(VMI->first)) {
1290 if (!VMI->second)
1291 continue;
1292
1293 Instruction *NI = dyn_cast<Instruction>(VMI->second);
1294 if (!NI || InlinedFunctionInfo.isSimplified(I, NI))
1295 continue;
1296
1297 bool IsArgMemOnlyCall = false, IsFuncCall = false;
1299
1300 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
1301 PtrArgs.push_back(LI->getPointerOperand());
1302 else if (const StoreInst *SI = dyn_cast<StoreInst>(I))
1303 PtrArgs.push_back(SI->getPointerOperand());
1304 else if (const VAArgInst *VAAI = dyn_cast<VAArgInst>(I))
1305 PtrArgs.push_back(VAAI->getPointerOperand());
1306 else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I))
1307 PtrArgs.push_back(CXI->getPointerOperand());
1308 else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I))
1309 PtrArgs.push_back(RMWI->getPointerOperand());
1310 else if (const auto *Call = dyn_cast<CallBase>(I)) {
1311 // If we know that the call does not access memory, then we'll still
1312 // know that about the inlined clone of this call site, and we don't
1313 // need to add metadata.
1314 if (Call->doesNotAccessMemory())
1315 continue;
1316
1317 IsFuncCall = true;
1318 if (CalleeAAR) {
1319 MemoryEffects ME = CalleeAAR->getMemoryEffects(Call);
1320
1321 // We'll retain this knowledge without additional metadata.
1323 continue;
1324
1325 if (ME.onlyAccessesArgPointees())
1326 IsArgMemOnlyCall = true;
1327 }
1328
1329 for (Value *Arg : Call->args()) {
1330 // Only care about pointer arguments. If a noalias argument is
1331 // accessed through a non-pointer argument, it must be captured
1332 // first (e.g. via ptrtoint), and we protect against captures below.
1333 if (!Arg->getType()->isPointerTy())
1334 continue;
1335
1336 PtrArgs.push_back(Arg);
1337 }
1338 }
1339
1340 // If we found no pointers, then this instruction is not suitable for
1341 // pairing with an instruction to receive aliasing metadata.
1342 // However, if this is a call, this we might just alias with none of the
1343 // noalias arguments.
1344 if (PtrArgs.empty() && !IsFuncCall)
1345 continue;
1346
1347 // It is possible that there is only one underlying object, but you
1348 // need to go through several PHIs to see it, and thus could be
1349 // repeated in the Objects list.
1352
1353 for (const Value *V : PtrArgs) {
1355 getUnderlyingObjects(V, Objects, /* LI = */ nullptr);
1356
1357 ObjSet.insert_range(Objects);
1358 }
1359
1360 // Figure out if we're derived from anything that is not a noalias
1361 // argument.
1362 bool RequiresNoCaptureBefore = false, UsesAliasingPtr = false,
1363 UsesUnknownObject = false;
1364 for (const Value *V : ObjSet) {
1365 // Is this value a constant that cannot be derived from any pointer
1366 // value (we need to exclude constant expressions, for example, that
1367 // are formed from arithmetic on global symbols).
1368 bool IsNonPtrConst = isa<ConstantInt>(V) || isa<ConstantFP>(V) ||
1371 if (IsNonPtrConst)
1372 continue;
1373
1374 // If this is anything other than a noalias argument, then we cannot
1375 // completely describe the aliasing properties using alias.scope
1376 // metadata (and, thus, won't add any).
1377 if (const Argument *A = dyn_cast<Argument>(V)) {
1378 if (!CB.paramHasAttr(A->getArgNo(), Attribute::NoAlias))
1379 UsesAliasingPtr = true;
1380 } else {
1381 UsesAliasingPtr = true;
1382 }
1383
1384 if (isEscapeSource(V)) {
1385 // An escape source can only alias with a noalias argument if it has
1386 // been captured beforehand.
1387 RequiresNoCaptureBefore = true;
1388 } else if (!isa<Argument>(V) && !isIdentifiedObject(V)) {
1389 // If this is neither an escape source, nor some identified object
1390 // (which cannot directly alias a noalias argument), nor some other
1391 // argument (which, by definition, also cannot alias a noalias
1392 // argument), conservatively do not make any assumptions.
1393 UsesUnknownObject = true;
1394 }
1395 }
1396
1397 // Nothing we can do if the used underlying object cannot be reliably
1398 // determined.
1399 if (UsesUnknownObject)
1400 continue;
1401
1402 // A function call can always get captured noalias pointers (via other
1403 // parameters, globals, etc.).
1404 if (IsFuncCall && !IsArgMemOnlyCall)
1405 RequiresNoCaptureBefore = true;
1406
1407 // First, we want to figure out all of the sets to which we might belong.
1408 // We might belong to a set if the noalias argument is in the set of
1409 // underlying objects. If there is some non-noalias argument in our list
1410 // of underlying objects, then we cannot add a scope because the fact
1411 // that some access does not alias with any set of our noalias arguments
1412 // cannot itself guarantee that it does not alias with this access
1413 // (because there is some pointer of unknown origin involved and the
1414 // other access might also depend on this pointer). We also cannot add
1415 // scopes to arbitrary functions unless we know they don't access any
1416 // non-parameter pointer-values.
1417 bool CanAddScopes = !UsesAliasingPtr && (!IsFuncCall || IsArgMemOnlyCall);
1418 if (CanAddScopes) {
1419 for (const Argument *A : NoAliasArgs) {
1420 if (ObjSet.count(A))
1421 Scopes.push_back(NewScopes[A]);
1422 }
1423 }
1424
1425 if (!Scopes.empty()) {
1426 NI->setMetadata(
1427 LLVMContext::MD_alias_scope,
1428 MDNode::concatenate(NI->getMetadata(LLVMContext::MD_alias_scope),
1429 MDNode::get(CalledFunc->getContext(), Scopes)));
1430 // Being in these scopes already means being noalias with the rest.
1431 continue;
1432 }
1433
1434 // Next, we want to figure out all of the sets with which we definitely
1435 // don't alias. Iterate over all noalias set, and add those for which:
1436 // 1. The noalias argument is not in the set of objects from which we
1437 // definitely derive.
1438 // 2. The noalias argument has not yet been captured.
1439 // An arbitrary function that might load pointers could see captured
1440 // noalias arguments via other noalias arguments or globals, and so we
1441 // must always check for prior capture.
1442 for (const Argument *A : NoAliasArgs) {
1443 if (ObjSet.contains(A))
1444 continue; // May be based on a noalias argument.
1445
1446 // It might be tempting to skip the PointerMayBeCapturedBefore check if
1447 // A->hasNoCaptureAttr() is true, but this is incorrect because
1448 // nocapture only guarantees that no copies outlive the function, not
1449 // that the value cannot be locally captured.
1450 if (!RequiresNoCaptureBefore ||
1452 A, /*ReturnCaptures=*/false, I, &DT, /*IncludeI=*/false,
1454 NoAliases.push_back(NewScopes[A]);
1455 }
1456
1457 if (!NoAliases.empty())
1458 NI->setMetadata(LLVMContext::MD_noalias,
1460 NI->getMetadata(LLVMContext::MD_noalias),
1461 MDNode::get(CalledFunc->getContext(), NoAliases)));
1462 }
1463 }
1464}
1465
1467 ReturnInst *End) {
1468
1469 assert(Begin->getParent() == End->getParent() &&
1470 "Expected to be in same basic block!");
1471 auto BeginIt = Begin->getIterator();
1472 assert(BeginIt != End->getIterator() && "Non-empty BB has empty iterator");
1474 ++BeginIt, End->getIterator(), InlinerAttributeWindow + 1);
1475}
1476
1477// Add attributes from CB params and Fn attributes that can always be propagated
1478// to the corresponding argument / inner callbases.
1480 ValueToValueMapTy &VMap,
1481 ClonedCodeInfo &InlinedFunctionInfo) {
1482 auto *CalledFunction = CB.getCalledFunction();
1483 auto &Context = CalledFunction->getContext();
1484
1485 // Collect valid attributes for all params.
1486 SmallVector<AttrBuilder> ValidObjParamAttrs, ValidExactParamAttrs;
1487 bool HasAttrToPropagate = false;
1488
1489 // Attributes we can only propagate if the exact parameter is forwarded.
1490 // We can propagate both poison generating and UB generating attributes
1491 // without any extra checks. The only attribute that is tricky to propagate
1492 // is `noundef` (skipped for now) as that can create new UB where previous
1493 // behavior was just using a poison value.
1494 static const Attribute::AttrKind ExactAttrsToPropagate[] = {
1495 Attribute::Dereferenceable, Attribute::DereferenceableOrNull,
1496 Attribute::NonNull, Attribute::NoFPClass,
1497 Attribute::Alignment, Attribute::Range};
1498
1499 for (unsigned I = 0, E = CB.arg_size(); I < E; ++I) {
1500 ValidObjParamAttrs.emplace_back(AttrBuilder{CB.getContext()});
1501 ValidExactParamAttrs.emplace_back(AttrBuilder{CB.getContext()});
1502 // Access attributes can be propagated to any param with the same underlying
1503 // object as the argument.
1504 if (CB.paramHasAttr(I, Attribute::ReadNone))
1505 ValidObjParamAttrs.back().addAttribute(Attribute::ReadNone);
1506 if (CB.paramHasAttr(I, Attribute::ReadOnly))
1507 ValidObjParamAttrs.back().addAttribute(Attribute::ReadOnly);
1508
1509 for (Attribute::AttrKind AK : ExactAttrsToPropagate) {
1510 Attribute Attr = CB.getParamAttr(I, AK);
1511 if (Attr.isValid())
1512 ValidExactParamAttrs.back().addAttribute(Attr);
1513 }
1514
1515 HasAttrToPropagate |= ValidObjParamAttrs.back().hasAttributes();
1516 HasAttrToPropagate |= ValidExactParamAttrs.back().hasAttributes();
1517 }
1518
1519 // Won't be able to propagate anything.
1520 if (!HasAttrToPropagate)
1521 return;
1522
1523 for (BasicBlock &BB : *CalledFunction) {
1524 for (Instruction &Ins : BB) {
1525 const auto *InnerCB = dyn_cast<CallBase>(&Ins);
1526 if (!InnerCB)
1527 continue;
1528 auto *NewInnerCB = dyn_cast_or_null<CallBase>(VMap.lookup(InnerCB));
1529 if (!NewInnerCB)
1530 continue;
1531 // The InnerCB might have be simplified during the inlining
1532 // process which can make propagation incorrect.
1533 if (InlinedFunctionInfo.isSimplified(InnerCB, NewInnerCB))
1534 continue;
1535
1536 AttributeList AL = NewInnerCB->getAttributes();
1537 for (unsigned I = 0, E = InnerCB->arg_size(); I < E; ++I) {
1538 // It's unsound or requires special handling to propagate
1539 // attributes to byval arguments. Even if CalledFunction
1540 // doesn't e.g. write to the argument (readonly), the call to
1541 // NewInnerCB may write to its by-value copy.
1542 if (NewInnerCB->isByValArgument(I))
1543 continue;
1544
1545 // Don't bother propagating attrs to constants.
1546 if (match(NewInnerCB->getArgOperand(I),
1548 continue;
1549
1550 // Check if the underlying value for the parameter is an argument.
1551 const Argument *Arg = dyn_cast<Argument>(InnerCB->getArgOperand(I));
1552 unsigned ArgNo;
1553 if (Arg) {
1554 ArgNo = Arg->getArgNo();
1555 // For dereferenceable, dereferenceable_or_null, align, etc...
1556 // we don't want to propagate if the existing param has the same
1557 // attribute with "better" constraints. So remove from the
1558 // new AL if the region of the existing param is larger than
1559 // what we can propagate.
1560 AttrBuilder NewAB{
1561 Context, AttributeSet::get(Context, ValidExactParamAttrs[ArgNo])};
1562 if (AL.getParamDereferenceableBytes(I) >
1563 NewAB.getDereferenceableBytes())
1564 NewAB.removeAttribute(Attribute::Dereferenceable);
1565 if (AL.getParamDereferenceableOrNullBytes(I) >
1566 NewAB.getDereferenceableOrNullBytes())
1567 NewAB.removeAttribute(Attribute::DereferenceableOrNull);
1568 if (AL.getParamAlignment(I).valueOrOne() >
1569 NewAB.getAlignment().valueOrOne())
1570 NewAB.removeAttribute(Attribute::Alignment);
1571 if (auto ExistingRange = AL.getParamRange(I)) {
1572 if (auto NewRange = NewAB.getRange()) {
1573 ConstantRange CombinedRange =
1574 ExistingRange->intersectWith(*NewRange);
1575 NewAB.removeAttribute(Attribute::Range);
1576 NewAB.addRangeAttr(CombinedRange);
1577 }
1578 }
1579
1580 if (FPClassTest ExistingNoFP = AL.getParamNoFPClass(I))
1581 NewAB.addNoFPClassAttr(ExistingNoFP | NewAB.getNoFPClass());
1582
1583 AL = AL.addParamAttributes(Context, I, NewAB);
1584 } else if (NewInnerCB->getArgOperand(I)->getType()->isPointerTy()) {
1585 // Check if the underlying value for the parameter is an argument.
1586 const Value *UnderlyingV =
1587 getUnderlyingObject(InnerCB->getArgOperand(I));
1588 Arg = dyn_cast<Argument>(UnderlyingV);
1589 if (!Arg)
1590 continue;
1591 ArgNo = Arg->getArgNo();
1592 } else {
1593 continue;
1594 }
1595
1596 // If so, propagate its access attributes.
1597 AL = AL.addParamAttributes(Context, I, ValidObjParamAttrs[ArgNo]);
1598
1599 // We can have conflicting attributes from the inner callsite and
1600 // to-be-inlined callsite. In that case, choose the most
1601 // restrictive.
1602
1603 // readonly + writeonly means we can never deref so make readnone.
1604 if (AL.hasParamAttr(I, Attribute::ReadOnly) &&
1605 AL.hasParamAttr(I, Attribute::WriteOnly))
1606 AL = AL.addParamAttribute(Context, I, Attribute::ReadNone);
1607
1608 // If have readnone, need to clear readonly/writeonly
1609 if (AL.hasParamAttr(I, Attribute::ReadNone)) {
1610 AL = AL.removeParamAttribute(Context, I, Attribute::ReadOnly);
1611 AL = AL.removeParamAttribute(Context, I, Attribute::WriteOnly);
1612 }
1613
1614 // Writable cannot exist in conjunction w/ readonly/readnone
1615 if (AL.hasParamAttr(I, Attribute::ReadOnly) ||
1616 AL.hasParamAttr(I, Attribute::ReadNone))
1617 AL = AL.removeParamAttribute(Context, I, Attribute::Writable);
1618 }
1619 NewInnerCB->setAttributes(AL);
1620 }
1621 }
1622}
1623
1624// Only allow these white listed attributes to be propagated back to the
1625// callee. This is because other attributes may only be valid on the call
1626// itself, i.e. attributes such as signext and zeroext.
1627
1628// Attributes that are always okay to propagate as if they are violated its
1629// immediate UB.
1631 AttrBuilder Valid(CB.getContext());
1632 if (auto DerefBytes = CB.getRetDereferenceableBytes())
1633 Valid.addDereferenceableAttr(DerefBytes);
1634 if (auto DerefOrNullBytes = CB.getRetDereferenceableOrNullBytes())
1635 Valid.addDereferenceableOrNullAttr(DerefOrNullBytes);
1636 if (CB.hasRetAttr(Attribute::NoAlias))
1637 Valid.addAttribute(Attribute::NoAlias);
1638 if (CB.hasRetAttr(Attribute::NoUndef))
1639 Valid.addAttribute(Attribute::NoUndef);
1640 return Valid;
1641}
1642
1643// Attributes that need additional checks as propagating them may change
1644// behavior or cause new UB.
1646 AttrBuilder Valid(CB.getContext());
1647 if (CB.hasRetAttr(Attribute::NonNull))
1648 Valid.addAttribute(Attribute::NonNull);
1649 if (CB.hasRetAttr(Attribute::Alignment))
1650 Valid.addAlignmentAttr(CB.getRetAlign());
1651 if (std::optional<ConstantRange> Range = CB.getRange())
1652 Valid.addRangeAttr(*Range);
1653 if (CB.hasRetAttr(Attribute::NoFPClass))
1654 Valid.addNoFPClassAttr(CB.getRetNoFPClass());
1655 return Valid;
1656}
1657
1659 ClonedCodeInfo &InlinedFunctionInfo) {
1660 AttrBuilder CallSiteValidUB = IdentifyValidUBGeneratingAttributes(CB);
1661 AttrBuilder CallSiteValidPG = IdentifyValidPoisonGeneratingAttributes(CB);
1662 if (!CallSiteValidUB.hasAttributes() && !CallSiteValidPG.hasAttributes())
1663 return;
1664 auto *CalledFunction = CB.getCalledFunction();
1665 auto &Context = CalledFunction->getContext();
1666
1667 for (auto &BB : *CalledFunction) {
1668 auto *RI = dyn_cast<ReturnInst>(BB.getTerminator());
1669 if (!RI || !isa<CallBase>(RI->getOperand(0)))
1670 continue;
1671 auto *RetVal = cast<CallBase>(RI->getOperand(0));
1672 // Check that the cloned RetVal exists and is a call, otherwise we cannot
1673 // add the attributes on the cloned RetVal. Simplification during inlining
1674 // could have transformed the cloned instruction.
1675 auto *NewRetVal = dyn_cast_or_null<CallBase>(VMap.lookup(RetVal));
1676 if (!NewRetVal)
1677 continue;
1678
1679 // The RetVal might have be simplified during the inlining
1680 // process which can make propagation incorrect.
1681 if (InlinedFunctionInfo.isSimplified(RetVal, NewRetVal))
1682 continue;
1683 // Backward propagation of attributes to the returned value may be incorrect
1684 // if it is control flow dependent.
1685 // Consider:
1686 // @callee {
1687 // %rv = call @foo()
1688 // %rv2 = call @bar()
1689 // if (%rv2 != null)
1690 // return %rv2
1691 // if (%rv == null)
1692 // exit()
1693 // return %rv
1694 // }
1695 // caller() {
1696 // %val = call nonnull @callee()
1697 // }
1698 // Here we cannot add the nonnull attribute on either foo or bar. So, we
1699 // limit the check to both RetVal and RI are in the same basic block and
1700 // there are no throwing/exiting instructions between these instructions.
1701 if (RI->getParent() != RetVal->getParent() ||
1703 continue;
1704 // Add to the existing attributes of NewRetVal, i.e. the cloned call
1705 // instruction.
1706 // NB! When we have the same attribute already existing on NewRetVal, but
1707 // with a differing value, the AttributeList's merge API honours the already
1708 // existing attribute value (i.e. attributes such as dereferenceable,
1709 // dereferenceable_or_null etc). See AttrBuilder::merge for more details.
1710 AttrBuilder ValidUB = IdentifyValidUBGeneratingAttributes(CB);
1711 AttrBuilder ValidPG = IdentifyValidPoisonGeneratingAttributes(CB);
1712 AttributeList AL = NewRetVal->getAttributes();
1713 if (ValidUB.getDereferenceableBytes() < AL.getRetDereferenceableBytes())
1714 ValidUB.removeAttribute(Attribute::Dereferenceable);
1715 if (ValidUB.getDereferenceableOrNullBytes() <
1716 AL.getRetDereferenceableOrNullBytes())
1717 ValidUB.removeAttribute(Attribute::DereferenceableOrNull);
1718 AttributeList NewAL = AL.addRetAttributes(Context, ValidUB);
1719 // Attributes that may generate poison returns are a bit tricky. If we
1720 // propagate them, other uses of the callsite might have their behavior
1721 // change or cause UB (if they have noundef) b.c of the new potential
1722 // poison.
1723 // Take the following three cases:
1724 //
1725 // 1)
1726 // define nonnull ptr @foo() {
1727 // %p = call ptr @bar()
1728 // call void @use(ptr %p) willreturn nounwind
1729 // ret ptr %p
1730 // }
1731 //
1732 // 2)
1733 // define noundef nonnull ptr @foo() {
1734 // %p = call ptr @bar()
1735 // call void @use(ptr %p) willreturn nounwind
1736 // ret ptr %p
1737 // }
1738 //
1739 // 3)
1740 // define nonnull ptr @foo() {
1741 // %p = call noundef ptr @bar()
1742 // ret ptr %p
1743 // }
1744 //
1745 // In case 1, we can't propagate nonnull because poison value in @use may
1746 // change behavior or trigger UB.
1747 // In case 2, we don't need to be concerned about propagating nonnull, as
1748 // any new poison at @use will trigger UB anyways.
1749 // In case 3, we can never propagate nonnull because it may create UB due to
1750 // the noundef on @bar.
1751 if (ValidPG.getAlignment().valueOrOne() < AL.getRetAlignment().valueOrOne())
1752 ValidPG.removeAttribute(Attribute::Alignment);
1753 if (ValidPG.hasAttributes()) {
1754 Attribute CBRange = ValidPG.getAttribute(Attribute::Range);
1755 if (CBRange.isValid()) {
1756 Attribute NewRange = AL.getRetAttr(Attribute::Range);
1757 if (NewRange.isValid()) {
1758 ValidPG.addRangeAttr(
1759 CBRange.getRange().intersectWith(NewRange.getRange()));
1760 }
1761 }
1762
1763 Attribute CBNoFPClass = ValidPG.getAttribute(Attribute::NoFPClass);
1764 if (CBNoFPClass.isValid() && AL.hasRetAttr(Attribute::NoFPClass)) {
1765 ValidPG.addNoFPClassAttr(
1766 CBNoFPClass.getNoFPClass() |
1767 AL.getRetAttr(Attribute::NoFPClass).getNoFPClass());
1768 }
1769
1770 // Three checks.
1771 // If the callsite has `noundef`, then a poison due to violating the
1772 // return attribute will create UB anyways so we can always propagate.
1773 // Otherwise, if the return value (callee to be inlined) has `noundef`, we
1774 // can't propagate as a new poison return will cause UB.
1775 // Finally, check if the return value has no uses whose behavior may
1776 // change/may cause UB if we potentially return poison. At the moment this
1777 // is implemented overly conservatively with a single-use check.
1778 // TODO: Update the single-use check to iterate through uses and only bail
1779 // if we have a potentially dangerous use.
1780
1781 if (CB.hasRetAttr(Attribute::NoUndef) ||
1782 (RetVal->hasOneUse() && !RetVal->hasRetAttr(Attribute::NoUndef)))
1783 NewAL = NewAL.addRetAttributes(Context, ValidPG);
1784 }
1785 NewRetVal->setAttributes(NewAL);
1786 }
1787}
1788
1789/// If the inlined function has non-byval align arguments, then
1790/// add @llvm.assume-based alignment assumptions to preserve this information.
1793 return;
1794
1796 auto &DL = CB.getDataLayout();
1797
1798 // To avoid inserting redundant assumptions, we should check for assumptions
1799 // already in the caller. To do this, we might need a DT of the caller.
1800 DominatorTree DT;
1801 bool DTCalculated = false;
1802
1803 Function *CalledFunc = CB.getCalledFunction();
1804 for (Argument &Arg : CalledFunc->args()) {
1805 if (!Arg.getType()->isPointerTy() || Arg.hasPassPointeeByValueCopyAttr() ||
1806 Arg.use_empty())
1807 continue;
1808 MaybeAlign Alignment = Arg.getParamAlign();
1809 if (!Alignment)
1810 continue;
1811
1812 if (!DTCalculated) {
1813 DT.recalculate(*CB.getCaller());
1814 DTCalculated = true;
1815 }
1816 // If we can already prove the asserted alignment in the context of the
1817 // caller, then don't bother inserting the assumption.
1818 Value *ArgVal = CB.getArgOperand(Arg.getArgNo());
1819 if (getKnownAlignment(ArgVal, DL, &CB, AC, &DT) >= *Alignment)
1820 continue;
1821
1822 CallInst *NewAsmp = IRBuilder<>(&CB).CreateAlignmentAssumption(
1823 DL, ArgVal, Alignment->value());
1825 }
1826}
1827
1828static void HandleByValArgumentInit(Type *ByValType, Value *Dst, Value *Src,
1829 MaybeAlign SrcAlign, Module *M,
1830 BasicBlock *InsertBlock,
1831 InlineFunctionInfo &IFI,
1832 Function *CalledFunc) {
1833 IRBuilder<> Builder(InsertBlock->begin());
1834
1835 Value *Size =
1836 Builder.getInt64(M->getDataLayout().getTypeAllocSize(ByValType));
1837
1838 Align DstAlign = Dst->getPointerAlignment(M->getDataLayout());
1839
1840 // Generate a memcpy with the correct alignments.
1841 CallInst *CI = Builder.CreateMemCpy(Dst, DstAlign, Src, SrcAlign, Size);
1842
1843 // The verifier requires that all calls of debug-info-bearing functions
1844 // from debug-info-bearing functions have a debug location (for inlining
1845 // purposes). Assign a dummy location to satisfy the constraint.
1846 if (!CI->getDebugLoc() && InsertBlock->getParent()->getSubprogram())
1847 if (DISubprogram *SP = CalledFunc->getSubprogram())
1848 CI->setDebugLoc(DILocation::get(SP->getContext(), 0, 0, SP));
1849}
1850
1851/// When inlining a call site that has a byval argument,
1852/// we have to make the implicit memcpy explicit by adding it.
1853static Value *HandleByValArgument(Type *ByValType, Value *Arg,
1854 Instruction *TheCall,
1855 const Function *CalledFunc,
1856 InlineFunctionInfo &IFI,
1857 MaybeAlign ByValAlignment) {
1858 Function *Caller = TheCall->getFunction();
1859 const DataLayout &DL = Caller->getDataLayout();
1860
1861 // If the called function is readonly, then it could not mutate the caller's
1862 // copy of the byval'd memory. In this case, it is safe to elide the copy and
1863 // temporary.
1864 if (CalledFunc->onlyReadsMemory()) {
1865 // If the byval argument has a specified alignment that is greater than the
1866 // passed in pointer, then we either have to round up the input pointer or
1867 // give up on this transformation.
1868 if (ByValAlignment.valueOrOne() == 1)
1869 return Arg;
1870
1871 AssumptionCache *AC =
1872 IFI.GetAssumptionCache ? &IFI.GetAssumptionCache(*Caller) : nullptr;
1873
1874 // If the pointer is already known to be sufficiently aligned, or if we can
1875 // round it up to a larger alignment, then we don't need a temporary.
1876 if (getOrEnforceKnownAlignment(Arg, *ByValAlignment, DL, TheCall, AC) >=
1877 *ByValAlignment)
1878 return Arg;
1879
1880 // Otherwise, we have to make a memcpy to get a safe alignment. This is bad
1881 // for code quality, but rarely happens and is required for correctness.
1882 }
1883
1884 // Create the alloca. If we have DataLayout, use nice alignment.
1885 Align Alignment = DL.getPrefTypeAlign(ByValType);
1886
1887 // If the byval had an alignment specified, we *must* use at least that
1888 // alignment, as it is required by the byval argument (and uses of the
1889 // pointer inside the callee).
1890 if (ByValAlignment)
1891 Alignment = std::max(Alignment, *ByValAlignment);
1892
1893 AllocaInst *NewAlloca =
1894 new AllocaInst(ByValType, Arg->getType()->getPointerAddressSpace(),
1895 nullptr, Alignment, Arg->getName());
1897 NewAlloca->insertBefore(Caller->begin()->begin());
1898 IFI.StaticAllocas.push_back(NewAlloca);
1899
1900 // Uses of the argument in the function should use our new alloca
1901 // instead.
1902 return NewAlloca;
1903}
1904
1905/// Return the result of AI->isStaticAlloca() if AI were moved to the entry
1906/// block. Allocas used in inalloca calls and allocas of dynamic array size
1907/// cannot be static.
1909 return isa<Constant>(AI->getArraySize()) && !AI->isUsedWithInAlloca();
1910}
1911
1912/// Returns a DebugLoc for a new DILocation which is a clone of \p OrigDL
1913/// inlined at \p InlinedAt. \p IANodes is an inlined-at cache.
1915 DebugLoc OrigDL, DILocation *InlinedAt, LLVMContext &Ctx,
1918 if (DILocation *Cached = InlineLocs.lookup(OrigDL.get()))
1919 return DebugLoc(Cached);
1920 DILocation *IA =
1921 OrigDL->getInlinedAt()
1922 ? DebugLoc::appendInlinedAt(OrigDL, InlinedAt, Ctx, IANodes).get()
1923 : InlinedAt;
1925 Ctx, OrigDL.getLine(), OrigDL.getCol(), OrigDL.getScope(), IA,
1926 OrigDL.isImplicitCode(), OrigDL->getAtomGroup(), OrigDL->getAtomRank());
1927 InlineLocs[OrigDL.get()] = Result;
1928 return DebugLoc(Result);
1929}
1930
1931/// Update inlined instructions' line numbers to
1932/// to encode location where these instructions are inlined.
1934 Instruction *TheCall, bool CalleeHasDebugInfo) {
1935 if (!TheCall->getDebugLoc())
1936 return;
1937
1938 // Don't propagate the source location atom from the call to inlined nodebug
1939 // instructions, and avoid putting it in the InlinedAt field of inlined
1940 // not-nodebug instructions. FIXME: Possibly worth transferring/generating
1941 // an atom for the returned value, otherwise we miss stepping on inlined
1942 // nodebug functions (which is different to existing behaviour).
1943 DebugLoc TheCallDL = TheCall->getDebugLoc()->getWithoutAtom();
1944
1945 // A call receiving the outer callsite's fallback location has no usable
1946 // callsite probe of its own. Do not let it inherit the outer call's probe
1947 // discriminator, but preserve any packed DWARF base discriminator.
1948 DebugLoc TheCallDLForInlinedCall = TheCallDL;
1949 uint32_t Discriminator = TheCallDLForInlinedCall->getDiscriminator();
1950 if (DILocation::isPseudoProbeDiscriminator(Discriminator)) {
1951 std::optional<uint32_t> DwarfDiscriminator =
1953 Discriminator);
1954 TheCallDLForInlinedCall = TheCallDLForInlinedCall->cloneWithDiscriminator(
1955 DwarfDiscriminator.value_or(0));
1956 }
1957
1958 auto &Ctx = Fn->getContext();
1959 DILocation *InlinedAtNode = TheCallDL;
1960
1961 // Create a unique call site, not to be confused with any other call from the
1962 // same location.
1963 InlinedAtNode = DILocation::getDistinct(
1964 Ctx, InlinedAtNode->getLine(), InlinedAtNode->getColumn(),
1965 InlinedAtNode->getScope(), InlinedAtNode->getInlinedAt());
1966
1967 // Cache the inlined-at nodes as they're built so they are reused, without
1968 // this every instruction's inlined-at chain would become distinct from each
1969 // other.
1972
1973 // Check if we are not generating inline line tables and want to use
1974 // the call site location instead.
1975 bool NoInlineLineTables = Fn->hasFnAttribute("no-inline-line-tables");
1976
1977 // Helper-util for updating the metadata attached to an instruction.
1978 auto UpdateInst = [&](Instruction &I) {
1979 // Loop metadata needs to be updated so that the start and end locs
1980 // reference inlined-at locations.
1981 auto updateLoopInfoLoc = [&Ctx, &InlinedAtNode, &IANodes,
1982 &InlineLocs](Metadata *MD) -> Metadata * {
1983 if (auto *Loc = dyn_cast_or_null<DILocation>(MD))
1984 return inlineDebugLoc(Loc, InlinedAtNode, Ctx, IANodes, InlineLocs)
1985 .get();
1986 return MD;
1987 };
1988 updateLoopMetadataDebugLocations(I, updateLoopInfoLoc);
1989
1990 if (!NoInlineLineTables)
1991 if (DebugLoc DL = I.getDebugLoc()) {
1992 DebugLoc IDL = inlineDebugLoc(DL, InlinedAtNode, I.getContext(),
1993 IANodes, InlineLocs);
1994 I.setDebugLoc(IDL);
1995 return;
1996 }
1997
1998 if (CalleeHasDebugInfo && !NoInlineLineTables)
1999 return;
2000
2001 // If the inlined instruction has no line number, or if inline info
2002 // is not being generated, make it look as if it originates from the call
2003 // location. This is important for ((__always_inline, __nodebug__))
2004 // functions which must use caller location for all instructions in their
2005 // function body.
2006
2007 // Don't update static allocas, as they may get moved later.
2008 if (auto *AI = dyn_cast<AllocaInst>(&I))
2010 return;
2011
2012 // Do not force a debug loc for pseudo probes, since they do not need to
2013 // be debuggable, and also they are expected to have a zero/null dwarf
2014 // discriminator at this point which could be violated otherwise.
2016 return;
2017
2018 I.setDebugLoc(isa<CallBase>(I) ? TheCallDLForInlinedCall : TheCallDL);
2019 };
2020
2021 // Helper-util for updating debug-info records attached to instructions.
2022 auto UpdateDVR = [&](DbgRecord *DVR) {
2023 assert(DVR->getDebugLoc() && "Debug Value must have debug loc");
2024 if (NoInlineLineTables) {
2025 DVR->setDebugLoc(TheCallDL);
2026 return;
2027 }
2028 DebugLoc DL = DVR->getDebugLoc();
2029 DebugLoc IDL = inlineDebugLoc(DL, InlinedAtNode,
2030 DVR->getMarker()->getParent()->getContext(),
2031 IANodes, InlineLocs);
2032 DVR->setDebugLoc(IDL);
2033 };
2034
2035 // Iterate over all instructions, updating metadata and debug-info records.
2036 for (; FI != Fn->end(); ++FI) {
2037 for (Instruction &I : *FI) {
2038 UpdateInst(I);
2039 for (DbgRecord &DVR : I.getDbgRecordRange()) {
2040 UpdateDVR(&DVR);
2041 }
2042 }
2043
2044 // Remove debug info records if we're not keeping inline info.
2045 if (NoInlineLineTables) {
2046 BasicBlock::iterator BI = FI->begin();
2047 while (BI != FI->end()) {
2048 BI->dropDbgRecords();
2049 ++BI;
2050 }
2051 }
2052 }
2053}
2054
2055#undef DEBUG_TYPE
2056#define DEBUG_TYPE "assignment-tracking"
2057/// Find Alloca and linked DbgAssignIntrinsic for locals escaped by \p CB.
2059 const CallBase &CB) {
2060 at::StorageToVarsMap EscapedLocals;
2062
2063 LLVM_DEBUG(
2064 errs() << "# Finding caller local variables escaped by callee\n");
2065 for (const Value *Arg : CB.args()) {
2066 LLVM_DEBUG(errs() << "INSPECT: " << *Arg << "\n");
2067 if (!Arg->getType()->isPointerTy()) {
2068 LLVM_DEBUG(errs() << " | SKIP: Not a pointer\n");
2069 continue;
2070 }
2071
2072 const Instruction *I = dyn_cast<Instruction>(Arg);
2073 if (!I) {
2074 LLVM_DEBUG(errs() << " | SKIP: Not result of instruction\n");
2075 continue;
2076 }
2077
2078 // Walk back to the base storage.
2079 assert(Arg->getType()->isPtrOrPtrVectorTy());
2080 APInt TmpOffset(DL.getIndexTypeSizeInBits(Arg->getType()), 0, false);
2082 Arg->stripAndAccumulateConstantOffsets(DL, TmpOffset, true));
2083 if (!Base) {
2084 LLVM_DEBUG(errs() << " | SKIP: Couldn't walk back to base storage\n");
2085 continue;
2086 }
2087
2088 assert(Base);
2089 LLVM_DEBUG(errs() << " | BASE: " << *Base << "\n");
2090 // We only need to process each base address once - skip any duplicates.
2091 if (!SeenBases.insert(Base).second)
2092 continue;
2093
2094 // Find all local variables associated with the backing storage.
2095 auto CollectAssignsForStorage = [&](DbgVariableRecord *DbgAssign) {
2096 // Skip variables from inlined functions - they are not local variables.
2097 if (DbgAssign->getDebugLoc().getInlinedAt())
2098 return;
2099 LLVM_DEBUG(errs() << " > DEF : " << *DbgAssign << "\n");
2100 EscapedLocals[Base].insert(at::VarRecord(DbgAssign));
2101 };
2102 for_each(at::getDVRAssignmentMarkers(Base), CollectAssignsForStorage);
2103 }
2104 return EscapedLocals;
2105}
2106
2108 const CallBase &CB) {
2109 LLVM_DEBUG(errs() << "trackInlinedStores into "
2110 << Start->getParent()->getName() << " from "
2111 << CB.getCalledFunction()->getName() << "\n");
2112 const DataLayout &DL = CB.getDataLayout();
2114}
2115
2116/// Update inlined instructions' DIAssignID metadata. We need to do this
2117/// otherwise a function inlined more than once into the same function
2118/// will cause DIAssignID to be shared by many instructions.
2121 // Loop over all the inlined instructions. If we find a DIAssignID
2122 // attachment or use, replace it with a new version.
2123 for (auto BBI = Start; BBI != End; ++BBI) {
2124 for (Instruction &I : *BBI)
2125 at::remapAssignID(Map, I);
2126 }
2127}
2128#undef DEBUG_TYPE
2129#define DEBUG_TYPE "inline-function"
2130
2131/// Update the block frequencies of the caller after a callee has been inlined.
2132///
2133/// Each block cloned into the caller has its block frequency scaled by the
2134/// ratio of CallSiteFreq/CalleeEntryFreq. This ensures that the cloned copy of
2135/// callee's entry block gets the same frequency as the callsite block and the
2136/// relative frequencies of all cloned blocks remain the same after cloning.
2137static void updateCallerBFI(BasicBlock *CallSiteBlock,
2138 const ValueToValueMapTy &VMap,
2139 BlockFrequencyInfo *CallerBFI,
2140 BlockFrequencyInfo *CalleeBFI,
2141 const BasicBlock &CalleeEntryBlock) {
2143 for (auto Entry : VMap) {
2144 if (!isa<BasicBlock>(Entry.first) || !Entry.second)
2145 continue;
2146 auto *OrigBB = cast<BasicBlock>(Entry.first);
2147 auto *ClonedBB = cast<BasicBlock>(Entry.second);
2148 BlockFrequency Freq = CalleeBFI->getBlockFreq(OrigBB);
2149 if (!ClonedBBs.insert(ClonedBB).second) {
2150 // Multiple blocks in the callee might get mapped to one cloned block in
2151 // the caller since we prune the callee as we clone it. When that happens,
2152 // we want to use the maximum among the original blocks' frequencies.
2153 BlockFrequency NewFreq = CallerBFI->getBlockFreq(ClonedBB);
2154 if (NewFreq > Freq)
2155 Freq = NewFreq;
2156 }
2157 CallerBFI->setBlockFreq(ClonedBB, Freq);
2158 }
2159 BasicBlock *EntryClone = cast<BasicBlock>(VMap.lookup(&CalleeEntryBlock));
2160 CallerBFI->setBlockFreqAndScale(
2161 EntryClone, CallerBFI->getBlockFreq(CallSiteBlock), ClonedBBs);
2162}
2163
2164/// Update the branch metadata for cloned call instructions.
2165static void updateCallProfile(Function *Callee, const ValueToValueMapTy &VMap,
2166 const uint64_t &CalleeEntryCount,
2167 const CallBase &TheCall, ProfileSummaryInfo *PSI,
2168 BlockFrequencyInfo *CallerBFI) {
2169 if (CalleeEntryCount < 1)
2170 return;
2171 auto CallSiteCount =
2172 PSI ? PSI->getProfileCount(TheCall, CallerBFI) : std::nullopt;
2173 int64_t CallCount = std::min(CallSiteCount.value_or(0), CalleeEntryCount);
2174 updateProfileCallee(Callee, -CallCount, &VMap);
2175}
2176
2178 Function *Callee, int64_t EntryDelta,
2180 auto CalleeCount = Callee->getEntryCount();
2181 if (!CalleeCount)
2182 return;
2183
2184 // Since CallSiteCount is an estimate, it could exceed the original callee
2185 // count and has to be set to 0 so guard against underflow.
2186 const uint64_t NewEntryCount =
2187 (EntryDelta < 0 && static_cast<uint64_t>(-EntryDelta) > *CalleeCount)
2188 ? 0
2189 : *CalleeCount + EntryDelta;
2190
2191 auto updateVTableProfWeight = [](CallBase *CB, const uint64_t NewEntryCount,
2192 const uint64_t PriorEntryCount) {
2194 if (VPtr)
2195 scaleProfData(*VPtr, NewEntryCount, PriorEntryCount);
2196 };
2197
2198 // During inlining ?
2199 if (VMap) {
2200 uint64_t CloneEntryCount = *CalleeCount - NewEntryCount;
2201 for (auto Entry : *VMap) {
2202 if (isa<CallInst>(Entry.first))
2203 if (auto *CI = dyn_cast_or_null<CallInst>(Entry.second)) {
2204 CI->updateProfWeight(CloneEntryCount, *CalleeCount);
2205 updateVTableProfWeight(CI, CloneEntryCount, *CalleeCount);
2206 }
2207
2208 if (isa<InvokeInst>(Entry.first))
2209 if (auto *II = dyn_cast_or_null<InvokeInst>(Entry.second)) {
2210 II->updateProfWeight(CloneEntryCount, *CalleeCount);
2211 updateVTableProfWeight(II, CloneEntryCount, *CalleeCount);
2212 }
2213 }
2214 }
2215
2216 if (EntryDelta) {
2217 Callee->setEntryCount(NewEntryCount);
2218
2219 for (BasicBlock &BB : *Callee)
2220 // No need to update the callsite if it is pruned during inlining.
2221 if (!VMap || VMap->count(&BB))
2222 for (Instruction &I : BB) {
2223 if (CallInst *CI = dyn_cast<CallInst>(&I)) {
2224 CI->updateProfWeight(NewEntryCount, *CalleeCount);
2225 updateVTableProfWeight(CI, NewEntryCount, *CalleeCount);
2226 }
2228 II->updateProfWeight(NewEntryCount, *CalleeCount);
2229 updateVTableProfWeight(II, NewEntryCount, *CalleeCount);
2230 }
2231 }
2232 }
2233}
2234
2235/// An operand bundle "clang.arc.attachedcall" on a call indicates the call
2236/// result is implicitly consumed by a call to retainRV or claimRV immediately
2237/// after the call. This function inlines the retainRV/claimRV calls.
2238///
2239/// There are three cases to consider:
2240///
2241/// 1. If there is a call to autoreleaseRV that takes a pointer to the returned
2242/// object in the callee return block, the autoreleaseRV call and the
2243/// retainRV/claimRV call in the caller cancel out. If the call in the caller
2244/// is a claimRV call, a call to objc_release is emitted.
2245///
2246/// 2. If there is a call in the callee return block that doesn't have operand
2247/// bundle "clang.arc.attachedcall", the operand bundle on the original call
2248/// is transferred to the call in the callee.
2249///
2250/// 3. Otherwise, a call to objc_retain is inserted if the call in the caller is
2251/// a retainRV call.
2252static void
2254 const SmallVectorImpl<ReturnInst *> &Returns) {
2255 assert(objcarc::isRetainOrClaimRV(RVCallKind) && "unexpected ARC function");
2256 bool IsRetainRV = RVCallKind == objcarc::ARCInstKind::RetainRV,
2257 IsUnsafeClaimRV = !IsRetainRV;
2258
2259 for (auto *RI : Returns) {
2260 Value *RetOpnd = objcarc::GetRCIdentityRoot(RI->getOperand(0));
2261 bool InsertRetainCall = IsRetainRV;
2262 IRBuilder<> Builder(*RI->getModule());
2263
2264 // Walk backwards through the basic block looking for either a matching
2265 // autoreleaseRV call or an unannotated call.
2266 auto InstRange = llvm::make_range(++(RI->getIterator().getReverse()),
2267 RI->getParent()->rend());
2268 for (Instruction &I : llvm::make_early_inc_range(InstRange)) {
2269 // Ignore casts.
2270 if (isa<CastInst>(I))
2271 continue;
2272
2273 if (auto *II = dyn_cast<IntrinsicInst>(&I)) {
2274 if (II->getIntrinsicID() != Intrinsic::objc_autoreleaseReturnValue ||
2275 !II->use_empty() ||
2276 objcarc::GetRCIdentityRoot(II->getOperand(0)) != RetOpnd)
2277 break;
2278
2279 // If we've found a matching authoreleaseRV call:
2280 // - If claimRV is attached to the call, insert a call to objc_release
2281 // and erase the autoreleaseRV call.
2282 // - If retainRV is attached to the call, just erase the autoreleaseRV
2283 // call.
2284 if (IsUnsafeClaimRV) {
2285 Builder.SetInsertPoint(II);
2286 Builder.CreateIntrinsic(Intrinsic::objc_release, RetOpnd);
2287 }
2288 II->eraseFromParent();
2289 InsertRetainCall = false;
2290 break;
2291 }
2292
2293 auto *CI = dyn_cast<CallInst>(&I);
2294
2295 if (!CI)
2296 break;
2297
2298 if (objcarc::GetRCIdentityRoot(CI) != RetOpnd ||
2300 break;
2301
2302 // If we've found an unannotated call that defines RetOpnd, add a
2303 // "clang.arc.attachedcall" operand bundle.
2304 Value *BundleArgs[] = {*objcarc::getAttachedARCFunction(&CB)};
2305 OperandBundleDef OB("clang.arc.attachedcall", BundleArgs);
2306 auto *NewCall = CallBase::addOperandBundle(
2307 CI, LLVMContext::OB_clang_arc_attachedcall, OB, CI->getIterator());
2308 NewCall->copyMetadata(*CI);
2309 CI->replaceAllUsesWith(NewCall);
2310 CI->eraseFromParent();
2311 InsertRetainCall = false;
2312 break;
2313 }
2314
2315 if (InsertRetainCall) {
2316 // The retainRV is attached to the call and we've failed to find a
2317 // matching autoreleaseRV or an annotated call in the callee. Emit a call
2318 // to objc_retain.
2319 Builder.SetInsertPoint(RI);
2320 Builder.CreateIntrinsic(Intrinsic::objc_retain, RetOpnd);
2321 }
2322 }
2323}
2324
2325// In contextual profiling, when an inline succeeds, we want to remap the
2326// indices of the callee into the index space of the caller. We can't just leave
2327// them as-is because the same callee may appear in other places in this caller
2328// (other callsites), and its (callee's) counters and sub-contextual profile
2329// tree would be potentially different.
2330// Not all BBs of the callee may survive the opportunistic DCE InlineFunction
2331// does (same goes for callsites in the callee).
2332// We will return a pair of vectors, one for basic block IDs and one for
2333// callsites. For such a vector V, V[Idx] will be -1 if the callee
2334// instrumentation with index Idx did not survive inlining, and a new value
2335// otherwise.
2336// This function will update the caller's instrumentation intrinsics
2337// accordingly, mapping indices as described above. We also replace the "name"
2338// operand because we use it to distinguish between "own" instrumentation and
2339// "from callee" instrumentation when performing the traversal of the CFG of the
2340// caller. We traverse depth-first from the callsite's BB and up to the point we
2341// hit BBs owned by the caller.
2342// The return values will be then used to update the contextual
2343// profile. Note: we only update the "name" and "index" operands in the
2344// instrumentation intrinsics, we leave the hash and total nr of indices as-is,
2345// it's not worth updating those.
2346static std::pair<std::vector<int64_t>, std::vector<int64_t>>
2348 PGOContextualProfile &CtxProf, uint32_t CalleeCounters,
2349 uint32_t CalleeCallsites) {
2350 // We'll allocate a new ID to imported callsite counters and callsites. We're
2351 // using -1 to indicate a counter we delete. Most likely the entry ID, for
2352 // example, will be deleted - we don't want 2 IDs in the same BB, and the
2353 // entry would have been cloned in the callsite's old BB.
2354 std::vector<int64_t> CalleeCounterMap;
2355 std::vector<int64_t> CalleeCallsiteMap;
2356 CalleeCounterMap.resize(CalleeCounters, -1);
2357 CalleeCallsiteMap.resize(CalleeCallsites, -1);
2358
2359 auto RewriteInstrIfNeeded = [&](InstrProfIncrementInst &Ins) -> bool {
2360 if (Ins.getNameValue() == &Caller)
2361 return false;
2362 const auto OldID = static_cast<uint32_t>(Ins.getIndex()->getZExtValue());
2363 if (CalleeCounterMap[OldID] == -1)
2364 CalleeCounterMap[OldID] = CtxProf.allocateNextCounterIndex(Caller);
2365 const auto NewID = static_cast<uint32_t>(CalleeCounterMap[OldID]);
2366
2367 Ins.setNameValue(&Caller);
2368 Ins.setIndex(NewID);
2369 return true;
2370 };
2371
2372 auto RewriteCallsiteInsIfNeeded = [&](InstrProfCallsite &Ins) -> bool {
2373 if (Ins.getNameValue() == &Caller)
2374 return false;
2375 const auto OldID = static_cast<uint32_t>(Ins.getIndex()->getZExtValue());
2376 if (CalleeCallsiteMap[OldID] == -1)
2377 CalleeCallsiteMap[OldID] = CtxProf.allocateNextCallsiteIndex(Caller);
2378 const auto NewID = static_cast<uint32_t>(CalleeCallsiteMap[OldID]);
2379
2380 Ins.setNameValue(&Caller);
2381 Ins.setIndex(NewID);
2382 return true;
2383 };
2384
2385 std::deque<BasicBlock *> Worklist;
2387 // We will traverse the BBs starting from the callsite BB. The callsite BB
2388 // will have at least a BB ID - maybe its own, and in any case the one coming
2389 // from the cloned function's entry BB. The other BBs we'll start seeing from
2390 // there on may or may not have BB IDs. BBs with IDs belonging to our caller
2391 // are definitely not coming from the imported function and form a boundary
2392 // past which we don't need to traverse anymore. BBs may have no
2393 // instrumentation (because we originally inserted instrumentation as per
2394 // MST), in which case we'll traverse past them. An invariant we'll keep is
2395 // that a BB will have at most 1 BB ID. For example, in the callsite BB, we
2396 // will delete the callee BB's instrumentation. This doesn't result in
2397 // information loss: the entry BB of the callee will have the same count as
2398 // the callsite's BB. At the end of this traversal, all the callee's
2399 // instrumentation would be mapped into the caller's instrumentation index
2400 // space. Some of the callee's counters may be deleted (as mentioned, this
2401 // should result in no loss of information).
2402 Worklist.push_back(StartBB);
2403 while (!Worklist.empty()) {
2404 auto *BB = Worklist.front();
2405 Worklist.pop_front();
2406 bool Changed = false;
2407 auto *BBID = CtxProfAnalysis::getBBInstrumentation(*BB);
2408 if (BBID) {
2409 Changed |= RewriteInstrIfNeeded(*BBID);
2410 // this may be the entryblock from the inlined callee, coming into a BB
2411 // that didn't have instrumentation because of MST decisions. Let's make
2412 // sure it's placed accordingly. This is a noop elsewhere.
2413 BBID->moveBefore(BB->getFirstInsertionPt());
2414 }
2415 for (auto &I : llvm::make_early_inc_range(*BB)) {
2416 if (auto *Inc = dyn_cast<InstrProfIncrementInst>(&I)) {
2418 // Step instrumentation is used for select instructions. Inlining may
2419 // have propagated a constant resulting in the condition of the select
2420 // being resolved, case in which function cloning resolves the value
2421 // of the select, and elides the select instruction. If that is the
2422 // case, the step parameter of the instrumentation will reflect that.
2423 // We can delete the instrumentation in that case.
2424 if (isa<Constant>(Inc->getStep())) {
2425 assert(!Inc->getNextNode() || !isa<SelectInst>(Inc->getNextNode()));
2426 Inc->eraseFromParent();
2427 } else {
2428 assert(isa_and_nonnull<SelectInst>(Inc->getNextNode()));
2429 RewriteInstrIfNeeded(*Inc);
2430 }
2431 } else if (Inc != BBID) {
2432 // If we're here it means that the BB had more than 1 IDs, presumably
2433 // some coming from the callee. We "made up our mind" to keep the
2434 // first one (which may or may not have been originally the caller's).
2435 // All the others are superfluous and we delete them.
2436 Inc->eraseFromParent();
2437 Changed = true;
2438 }
2439 } else if (auto *CS = dyn_cast<InstrProfCallsite>(&I)) {
2440 Changed |= RewriteCallsiteInsIfNeeded(*CS);
2441 }
2442 }
2443 if (!BBID || Changed)
2444 for (auto *Succ : successors(BB))
2445 if (Seen.insert(Succ).second)
2446 Worklist.push_back(Succ);
2447 }
2448
2449 assert(!llvm::is_contained(CalleeCounterMap, 0) &&
2450 "Counter index mapping should be either to -1 or to non-zero index, "
2451 "because the 0 "
2452 "index corresponds to the entry BB of the caller");
2453 assert(!llvm::is_contained(CalleeCallsiteMap, 0) &&
2454 "Callsite index mapping should be either to -1 or to non-zero index, "
2455 "because there should have been at least a callsite - the inlined one "
2456 "- which would have had a 0 index.");
2457
2458 return {std::move(CalleeCounterMap), std::move(CalleeCallsiteMap)};
2459}
2460
2461// Inline. If successful, update the contextual profile (if a valid one is
2462// given).
2463// The contextual profile data is organized in trees, as follows:
2464// - each node corresponds to a function
2465// - the root of each tree corresponds to an "entrypoint" - e.g.
2466// RPC handler for server side
2467// - the path from the root to a node is a particular call path
2468// - the counters stored in a node are counter values observed in that
2469// particular call path ("context")
2470// - the edges between nodes are annotated with callsite IDs.
2471//
2472// Updating the contextual profile after an inlining means, at a high level,
2473// copying over the data of the callee, **intentionally without any value
2474// scaling**, and copying over the callees of the inlined callee.
2475llvm::InlineResult
2477 PGOContextualProfile &CtxProf, bool MergeAttributes,
2478 AAResults *CalleeAAR, bool InsertLifetime,
2479 bool TrackInlineHistory, Function *ForwardVarArgsTo,
2481 if (!CtxProf.isInSpecializedModule())
2482 return InlineFunction(CB, IFI, MergeAttributes, CalleeAAR, InsertLifetime,
2483 TrackInlineHistory, ForwardVarArgsTo, ORE);
2484
2485 auto &Caller = *CB.getCaller();
2486 auto &Callee = *CB.getCalledFunction();
2487 auto *StartBB = CB.getParent();
2488
2489 // Get some preliminary data about the callsite before it might get inlined.
2490 // Inlining shouldn't delete the callee, but it's cleaner (and low-cost) to
2491 // get this data upfront and rely less on InlineFunction's behavior.
2492 const auto CalleeGUID = Callee.getGUID();
2493 auto *CallsiteIDIns = CtxProfAnalysis::getCallsiteInstrumentation(CB);
2494 const auto CallsiteID =
2495 static_cast<uint32_t>(CallsiteIDIns->getIndex()->getZExtValue());
2496
2497 const auto NumCalleeCounters = CtxProf.getNumCounters(Callee);
2498 const auto NumCalleeCallsites = CtxProf.getNumCallsites(Callee);
2499
2500 auto Ret = InlineFunction(CB, IFI, MergeAttributes, CalleeAAR, InsertLifetime,
2501 TrackInlineHistory, ForwardVarArgsTo, ORE);
2502 if (!Ret.isSuccess())
2503 return Ret;
2504
2505 // Inlining succeeded, we don't need the instrumentation of the inlined
2506 // callsite.
2507 CallsiteIDIns->eraseFromParent();
2508
2509 // Assinging Maps and then capturing references into it in the lambda because
2510 // captured structured bindings are a C++20 extension. We do also need a
2511 // capture here, though.
2512 const auto IndicesMaps = remapIndices(Caller, StartBB, CtxProf,
2513 NumCalleeCounters, NumCalleeCallsites);
2514 const uint32_t NewCountersSize = CtxProf.getNumCounters(Caller);
2515
2516 auto Updater = [&](PGOCtxProfContext &Ctx) {
2517 assert(Ctx.guid() == Caller.getGUID());
2518 const auto &[CalleeCounterMap, CalleeCallsiteMap] = IndicesMaps;
2519 assert(
2520 (Ctx.counters().size() +
2521 llvm::count_if(CalleeCounterMap, [](auto V) { return V != -1; }) ==
2522 NewCountersSize) &&
2523 "The caller's counters size should have grown by the number of new "
2524 "distinct counters inherited from the inlined callee.");
2525 Ctx.resizeCounters(NewCountersSize);
2526 // If the callsite wasn't exercised in this context, the value of the
2527 // counters coming from it is 0 - which it is right now, after resizing them
2528 // - and so we're done.
2529 auto CSIt = Ctx.callsites().find(CallsiteID);
2530 if (CSIt == Ctx.callsites().end())
2531 return;
2532 auto CalleeCtxIt = CSIt->second.find(CalleeGUID);
2533 // The callsite was exercised, but not with this callee (so presumably this
2534 // is an indirect callsite). Again, we're done here.
2535 if (CalleeCtxIt == CSIt->second.end())
2536 return;
2537
2538 // Let's pull in the counter values and the subcontexts coming from the
2539 // inlined callee.
2540 auto &CalleeCtx = CalleeCtxIt->second;
2541 assert(CalleeCtx.guid() == CalleeGUID);
2542
2543 for (auto I = 0U; I < CalleeCtx.counters().size(); ++I) {
2544 const int64_t NewIndex = CalleeCounterMap[I];
2545 if (NewIndex >= 0) {
2546 assert(NewIndex != 0 && "counter index mapping shouldn't happen to a 0 "
2547 "index, that's the caller's entry BB");
2548 Ctx.counters()[NewIndex] = CalleeCtx.counters()[I];
2549 }
2550 }
2551 for (auto &[I, OtherSet] : CalleeCtx.callsites()) {
2552 const int64_t NewCSIdx = CalleeCallsiteMap[I];
2553 if (NewCSIdx >= 0) {
2554 assert(NewCSIdx != 0 &&
2555 "callsite index mapping shouldn't happen to a 0 index, the "
2556 "caller must've had at least one callsite (with such an index)");
2557 Ctx.ingestAllContexts(NewCSIdx, std::move(OtherSet));
2558 }
2559 }
2560 // We know the traversal is preorder, so it wouldn't have yet looked at the
2561 // sub-contexts of this context that it's currently visiting. Meaning, the
2562 // erase below invalidates no iterators.
2563 auto Deleted = Ctx.callsites().erase(CallsiteID);
2564 assert(Deleted);
2565 (void)Deleted;
2566 };
2567 CtxProf.update(Updater, Caller);
2568 return Ret;
2569}
2570
2572 InlineFunctionInfo &IFI) {
2573 assert(CB.getParent() && CB.getFunction() && "Instruction not in function!");
2574
2575 // FIXME: we don't inline callbr yet.
2576 if (isa<CallBrInst>(CB))
2577 return InlineResult::failure("We don't inline callbr yet.");
2578
2579 // If IFI has any state in it, zap it before we fill it in.
2580 IFI.reset();
2581
2582 Function *CalledFunc = CB.getCalledFunction();
2583 if (!CalledFunc || // Can't inline external function or indirect
2584 CalledFunc->isDeclaration()) // call!
2585 return InlineResult::failure("external or indirect");
2586
2587 // Don't inline if we've already inlined this callee through this call site
2588 // before to prevent infinite inlining through mutually recursive functions.
2589 if (MDNode *InlineHistory = CB.getMetadata(LLVMContext::MD_inline_history)) {
2590 for (const auto &Op : InlineHistory->operands()) {
2591 if (auto *MD = dyn_cast_or_null<ValueAsMetadata>(Op)) {
2592 if (MD->getValue() == CalledFunc) {
2593 return InlineResult::failure("inline history");
2594 }
2595 }
2596 }
2597 }
2598
2599 // The inliner does not know how to inline through calls with operand bundles
2600 // in general ...
2601 if (CB.hasOperandBundles()) {
2602 for (int i = 0, e = CB.getNumOperandBundles(); i != e; ++i) {
2603 auto OBUse = CB.getOperandBundleAt(i);
2604 uint32_t Tag = OBUse.getTagID();
2605 // ... but it knows how to inline through "deopt" operand bundles ...
2607 continue;
2608 // ... and "funclet" operand bundles.
2610 continue;
2612 continue;
2614 continue;
2616 IFI.ConvergenceControlToken = OBUse.Inputs[0].get();
2617 continue;
2618 }
2619
2620 return InlineResult::failure("unsupported operand bundle");
2621 }
2622 }
2623
2624 // FIXME: The check below is redundant and incomplete. According to spec, if a
2625 // convergent call is missing a token, then the caller is using uncontrolled
2626 // convergence. If the callee has an entry intrinsic, then the callee is using
2627 // controlled convergence, and the call cannot be inlined. A proper
2628 // implemenation of this check requires a whole new analysis that identifies
2629 // convergence in every function. For now, we skip that and just do this one
2630 // cursory check. The underlying assumption is that in a compiler flow that
2631 // fully implements convergence control tokens, there is no mixing of
2632 // controlled and uncontrolled convergent operations in the whole program.
2633 if (CB.isConvergent()) {
2634 if (!IFI.ConvergenceControlToken &&
2635 getConvergenceEntry(CalledFunc->getEntryBlock())) {
2636 return InlineResult::failure(
2637 "convergent call needs convergencectrl operand");
2638 }
2639 }
2640
2641 const BasicBlock *OrigBB = CB.getParent();
2642 const Function *Caller = OrigBB->getParent();
2643
2644 // GC poses two hazards to inlining, which only occur when the callee has GC:
2645 // 1. If the caller has no GC, then the callee's GC must be propagated to the
2646 // caller.
2647 // 2. If the caller has a differing GC, it is invalid to inline.
2648 if (CalledFunc->hasGC()) {
2649 if (Caller->hasGC() && CalledFunc->getGC() != Caller->getGC())
2650 return InlineResult::failure("incompatible GC");
2651 }
2652
2653 // Get the personality function from the callee if it contains a landing pad.
2654 Constant *CalledPersonality =
2655 CalledFunc->hasPersonalityFn()
2656 ? CalledFunc->getPersonalityFn()->stripPointerCasts()
2657 : nullptr;
2658
2659 // Find the personality function used by the landing pads of the caller. If it
2660 // exists, then check to see that it matches the personality function used in
2661 // the callee.
2662 Constant *CallerPersonality =
2663 Caller->hasPersonalityFn()
2664 ? Caller->getPersonalityFn()->stripPointerCasts()
2665 : nullptr;
2666 if (CalledPersonality) {
2667 // If the personality functions match, then we can perform the
2668 // inlining. Otherwise, we can't inline.
2669 // TODO: This isn't 100% true. Some personality functions are proper
2670 // supersets of others and can be used in place of the other.
2671 if (CallerPersonality && CalledPersonality != CallerPersonality)
2672 return InlineResult::failure("incompatible personality");
2673 }
2674
2675 // We need to figure out which funclet the callsite was in so that we may
2676 // properly nest the callee.
2677 if (CallerPersonality) {
2678 EHPersonality Personality = classifyEHPersonality(CallerPersonality);
2679 if (isScopedEHPersonality(Personality)) {
2680 std::optional<OperandBundleUse> ParentFunclet =
2682 if (ParentFunclet)
2683 IFI.CallSiteEHPad = cast<FuncletPadInst>(ParentFunclet->Inputs.front());
2684
2685 // OK, the inlining site is legal. What about the target function?
2686
2687 if (IFI.CallSiteEHPad) {
2688 if (Personality == EHPersonality::MSVC_CXX) {
2689 // The MSVC personality cannot tolerate catches getting inlined into
2690 // cleanup funclets.
2692 // Ok, the call site is within a cleanuppad. Let's check the callee
2693 // for catchpads.
2694 for (const BasicBlock &CalledBB : *CalledFunc) {
2695 if (isa<CatchSwitchInst>(CalledBB.getFirstNonPHIIt()))
2696 return InlineResult::failure("catch in cleanup funclet");
2697 }
2698 }
2699 } else if (isAsynchronousEHPersonality(Personality)) {
2700 // SEH is even less tolerant, there may not be any sort of exceptional
2701 // funclet in the callee.
2702 for (const BasicBlock &CalledBB : *CalledFunc) {
2703 if (CalledBB.isEHPad())
2704 return InlineResult::failure("SEH in cleanup funclet");
2705 }
2706 }
2707 }
2708 }
2709 }
2710
2711 return InlineResult::success();
2712}
2713
2714/// This function inlines the called function into the basic block of the
2715/// caller. This returns false if it is not possible to inline this call.
2716/// The program is still in a well defined state if this occurs though.
2717///
2718/// Note that this only does one level of inlining. For example, if the
2719/// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
2720/// exists in the instruction stream. Similarly this will inline a recursive
2721/// function by one level.
2723 bool MergeAttributes, AAResults *CalleeAAR,
2724 bool InsertLifetime, bool TrackInlineHistory,
2725 Function *ForwardVarArgsTo,
2727 BasicBlock *OrigBB = CB.getParent();
2728 Function *Caller = OrigBB->getParent();
2729 Function *CalledFunc = CB.getCalledFunction();
2730 assert(CalledFunc && !CalledFunc->isDeclaration() &&
2731 "CanInlineCallSite should have verified direct call to definition");
2732
2733 // Determine if we are dealing with a call in an EHPad which does not unwind
2734 // to caller.
2735 bool EHPadForCallUnwindsLocally = false;
2736 if (IFI.CallSiteEHPad && isa<CallInst>(CB)) {
2737 UnwindDestMemoTy FuncletUnwindMap;
2738 Value *CallSiteUnwindDestToken =
2739 getUnwindDestToken(IFI.CallSiteEHPad, FuncletUnwindMap);
2740
2741 EHPadForCallUnwindsLocally =
2742 CallSiteUnwindDestToken &&
2743 !isa<ConstantTokenNone>(CallSiteUnwindDestToken);
2744 }
2745
2746 // Get an iterator to the last basic block in the function, which will have
2747 // the new function inlined after it.
2748 Function::iterator LastBlock = --Caller->end();
2749
2750 // Make sure to capture all of the return instructions from the cloned
2751 // function.
2753 ClonedCodeInfo InlinedFunctionInfo;
2754 Function::iterator FirstNewBlock;
2755
2756 // GC poses two hazards to inlining, which only occur when the callee has GC:
2757 // 1. If the caller has no GC, then the callee's GC must be propagated to the
2758 // caller.
2759 // 2. If the caller has a differing GC, it is invalid to inline.
2760 if (CalledFunc->hasGC()) {
2761 if (!Caller->hasGC())
2762 Caller->setGC(CalledFunc->getGC());
2763 else {
2764 assert(CalledFunc->getGC() == Caller->getGC() &&
2765 "CanInlineCallSite should have verified compatible GCs");
2766 }
2767 }
2768
2769 if (CalledFunc->hasPersonalityFn()) {
2770 Constant *CalledPersonality =
2771 CalledFunc->getPersonalityFn()->stripPointerCasts();
2772 if (!Caller->hasPersonalityFn()) {
2773 Caller->setPersonalityFn(CalledPersonality);
2774 } else
2775 assert(Caller->getPersonalityFn()->stripPointerCasts() ==
2776 CalledPersonality &&
2777 "CanInlineCallSite should have verified compatible personality");
2778 }
2779
2780 { // Scope to destroy VMap after cloning.
2781 ValueToValueMapTy VMap;
2782 struct ByValInit {
2783 Value *Dst;
2784 Value *Src;
2785 MaybeAlign SrcAlign;
2786 Type *Ty;
2787 };
2788 // Keep a list of tuples (dst, src, src_align) to emit byval
2789 // initializations. Src Alignment is only available though the callbase,
2790 // therefore has to be saved.
2791 SmallVector<ByValInit, 4> ByValInits;
2792
2793 // When inlining a function that contains noalias scope metadata,
2794 // this metadata needs to be cloned so that the inlined blocks
2795 // have different "unique scopes" at every call site.
2796 // Track the metadata that must be cloned. Do this before other changes to
2797 // the function, so that we do not get in trouble when inlining caller ==
2798 // callee.
2799 ScopedAliasMetadataDeepCloner SAMetadataCloner(CB.getCalledFunction());
2800
2801 auto &DL = Caller->getDataLayout();
2802
2803 // Calculate the vector of arguments to pass into the function cloner, which
2804 // matches up the formal to the actual argument values.
2805 auto AI = CB.arg_begin();
2806 unsigned ArgNo = 0;
2807 for (Function::arg_iterator I = CalledFunc->arg_begin(),
2808 E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) {
2809 Value *ActualArg = *AI;
2810
2811 // When byval arguments actually inlined, we need to make the copy implied
2812 // by them explicit. However, we don't do this if the callee is readonly
2813 // or readnone, because the copy would be unneeded: the callee doesn't
2814 // modify the struct.
2815 if (CB.isByValArgument(ArgNo)) {
2816 ActualArg = HandleByValArgument(CB.getParamByValType(ArgNo), ActualArg,
2817 &CB, CalledFunc, IFI,
2818 CalledFunc->getParamAlign(ArgNo));
2819 if (ActualArg != *AI)
2820 ByValInits.push_back({ActualArg, (Value *)*AI,
2821 CB.getParamAlign(ArgNo),
2822 CB.getParamByValType(ArgNo)});
2823 }
2824
2825 VMap[&*I] = ActualArg;
2826 }
2827
2828 // TODO: Remove this when users have been updated to the assume bundles.
2829 // Add alignment assumptions if necessary. We do this before the inlined
2830 // instructions are actually cloned into the caller so that we can easily
2831 // check what will be known at the start of the inlined code.
2832 AddAlignmentAssumptions(CB, IFI);
2833
2834 AssumptionCache *AC =
2835 IFI.GetAssumptionCache ? &IFI.GetAssumptionCache(*Caller) : nullptr;
2836
2837 /// Preserve all attributes on of the call and its parameters.
2838 salvageKnowledge(&CB, AC);
2839
2840 // We want the inliner to prune the code as it copies. We would LOVE to
2841 // have no dead or constant instructions leftover after inlining occurs
2842 // (which can happen, e.g., because an argument was constant), but we'll be
2843 // happy with whatever the cloner can do.
2844 CloneAndPruneFunctionInto(Caller, CalledFunc, VMap,
2845 /*ModuleLevelChanges=*/false, Returns, ".i",
2846 InlinedFunctionInfo);
2847 // Remember the first block that is newly cloned over.
2848 FirstNewBlock = LastBlock; ++FirstNewBlock;
2849
2850 // Insert retainRV/clainRV runtime calls.
2852 if (RVCallKind != objcarc::ARCInstKind::None)
2853 inlineRetainOrClaimRVCalls(CB, RVCallKind, Returns);
2854
2855 // Updated caller/callee profiles only when requested. For sample loader
2856 // inlining, the context-sensitive inlinee profile doesn't need to be
2857 // subtracted from callee profile, and the inlined clone also doesn't need
2858 // to be scaled based on call site count.
2859 if (IFI.UpdateProfile) {
2860 if (IFI.CallerBFI != nullptr && IFI.CalleeBFI != nullptr)
2861 // Update the BFI of blocks cloned into the caller.
2862 updateCallerBFI(OrigBB, VMap, IFI.CallerBFI, IFI.CalleeBFI,
2863 CalledFunc->front());
2864
2865 if (auto Profile = CalledFunc->getEntryCount())
2866 updateCallProfile(CalledFunc, VMap, *Profile, CB, IFI.PSI,
2867 IFI.CallerBFI);
2868 }
2869
2870 // Inject byval arguments initialization.
2871 for (ByValInit &Init : ByValInits)
2872 HandleByValArgumentInit(Init.Ty, Init.Dst, Init.Src, Init.SrcAlign,
2873 Caller->getParent(), &*FirstNewBlock, IFI,
2874 CalledFunc);
2875
2876 std::optional<OperandBundleUse> ParentDeopt =
2878 if (ParentDeopt) {
2880
2881 for (auto &VH : InlinedFunctionInfo.OperandBundleCallSites) {
2883 if (!ICS)
2884 continue; // instruction was DCE'd or RAUW'ed to undef
2885
2886 OpDefs.clear();
2887
2888 OpDefs.reserve(ICS->getNumOperandBundles());
2889
2890 for (unsigned COBi = 0, COBe = ICS->getNumOperandBundles(); COBi < COBe;
2891 ++COBi) {
2892 auto ChildOB = ICS->getOperandBundleAt(COBi);
2893 if (ChildOB.getTagID() != LLVMContext::OB_deopt) {
2894 // If the inlined call has other operand bundles, let them be
2895 OpDefs.emplace_back(ChildOB);
2896 continue;
2897 }
2898
2899 // It may be useful to separate this logic (of handling operand
2900 // bundles) out to a separate "policy" component if this gets crowded.
2901 // Prepend the parent's deoptimization continuation to the newly
2902 // inlined call's deoptimization continuation.
2903 std::vector<Value *> MergedDeoptArgs;
2904 MergedDeoptArgs.reserve(ParentDeopt->Inputs.size() +
2905 ChildOB.Inputs.size());
2906
2907 llvm::append_range(MergedDeoptArgs, ParentDeopt->Inputs);
2908 llvm::append_range(MergedDeoptArgs, ChildOB.Inputs);
2909
2910 OpDefs.emplace_back("deopt", std::move(MergedDeoptArgs));
2911 }
2912
2913 Instruction *NewI = CallBase::Create(ICS, OpDefs, ICS->getIterator());
2914
2915 // Note: the RAUW does the appropriate fixup in VMap, so we need to do
2916 // this even if the call returns void.
2917 ICS->replaceAllUsesWith(NewI);
2918
2919 VH = nullptr;
2920 ICS->eraseFromParent();
2921 }
2922 }
2923
2924 // For 'nodebug' functions, the associated DISubprogram is always null.
2925 // Conservatively avoid propagating the callsite debug location to
2926 // instructions inlined from a function whose DISubprogram is not null.
2927 fixupLineNumbers(Caller, FirstNewBlock, &CB,
2928 CalledFunc->getSubprogram() != nullptr);
2929
2930 if (isAssignmentTrackingEnabled(*Caller->getParent())) {
2931 // Interpret inlined stores to caller-local variables as assignments.
2932 trackInlinedStores(FirstNewBlock, Caller->end(), CB);
2933
2934 // Update DIAssignID metadata attachments and uses so that they are
2935 // unique to this inlined instance.
2936 fixupAssignments(FirstNewBlock, Caller->end());
2937 }
2938
2939 // Now clone the inlined noalias scope metadata.
2940 SAMetadataCloner.clone();
2941 SAMetadataCloner.remap(FirstNewBlock, Caller->end());
2942
2943 // Add noalias metadata if necessary.
2944 AddAliasScopeMetadata(CB, VMap, DL, CalleeAAR, InlinedFunctionInfo);
2945
2946 // Clone return attributes on the callsite into the calls within the inlined
2947 // function which feed into its return value.
2948 AddReturnAttributes(CB, VMap, InlinedFunctionInfo);
2949
2950 // Clone attributes on the params of the callsite to calls within the
2951 // inlined function which use the same param.
2952 AddParamAndFnBasicAttributes(CB, VMap, InlinedFunctionInfo);
2953
2955 CalledFunc, CB, InlinedFunctionInfo.ContainsMemProfMetadata, VMap, ORE);
2956
2957 // Propagate metadata on the callsite if necessary.
2958 PropagateCallSiteMetadata(CB, FirstNewBlock, Caller->end());
2959
2960 // Propagate an allocation wrapper's !alloc_token if necessary.
2961 propagateAllocTokenMetadata(CalledFunc, CB, VMap, InlinedFunctionInfo);
2962
2963 // Propagate implicit ref metadata.
2964 if (CalledFunc->hasMetadata(LLVMContext::MD_implicit_ref)) {
2966 CalledFunc->getMetadata(LLVMContext::MD_implicit_ref, MDs);
2967 for (MDNode *MD : MDs) {
2968 Caller->addMetadata(LLVMContext::MD_implicit_ref, *MD);
2969 }
2970 }
2971
2972 // Propagate inlined.from metadata for dontcall diagnostics.
2973 PropagateInlinedFromMetadata(CB, CalledFunc->getName(), Caller->getName(),
2974 FirstNewBlock, Caller->end());
2975
2976 // Register any cloned assumptions.
2977 if (IFI.GetAssumptionCache)
2978 for (BasicBlock &NewBlock :
2979 make_range(FirstNewBlock->getIterator(), Caller->end()))
2980 for (Instruction &I : NewBlock)
2981 if (auto *II = dyn_cast<AssumeInst>(&I))
2982 IFI.GetAssumptionCache(*Caller).registerAssumption(II);
2983 }
2984
2985 if (IFI.ConvergenceControlToken) {
2986 IntrinsicInst *IntrinsicCall = getConvergenceEntry(*FirstNewBlock);
2987 if (IntrinsicCall) {
2988 IntrinsicCall->replaceAllUsesWith(IFI.ConvergenceControlToken);
2989 IntrinsicCall->eraseFromParent();
2990 }
2991 }
2992
2993 // If there are any alloca instructions in the block that used to be the entry
2994 // block for the callee, move them to the entry block of the caller. First
2995 // calculate which instruction they should be inserted before. We insert the
2996 // instructions at the end of the current alloca list.
2997 {
2998 BasicBlock::iterator InsertPoint = Caller->begin()->begin();
2999 for (BasicBlock::iterator I = FirstNewBlock->begin(),
3000 E = FirstNewBlock->end(); I != E; ) {
3002 if (!AI) continue;
3003
3004 // If the alloca is now dead, remove it. This often occurs due to code
3005 // specialization.
3006 if (AI->use_empty()) {
3007 AI->eraseFromParent();
3008 continue;
3009 }
3010
3012 continue;
3013
3014 // Keep track of the static allocas that we inline into the caller.
3015 IFI.StaticAllocas.push_back(AI);
3016
3017 // Scan for the block of allocas that we can move over, and move them
3018 // all at once.
3019 while (isa<AllocaInst>(I) &&
3020 !cast<AllocaInst>(I)->use_empty() &&
3022 IFI.StaticAllocas.push_back(cast<AllocaInst>(I));
3023 ++I;
3024 }
3025
3026 // Transfer all of the allocas over in a block. Using splice means
3027 // that the instructions aren't removed from the symbol table, then
3028 // reinserted.
3029 I.setTailBit(true);
3030 Caller->getEntryBlock().splice(InsertPoint, &*FirstNewBlock,
3031 AI->getIterator(), I);
3032 }
3033 }
3034
3035 // If the call to the callee cannot throw, set the 'nounwind' flag on any
3036 // calls that we inline.
3037 bool MarkNoUnwind = CB.doesNotThrow();
3038
3039 SmallVector<Value*,4> VarArgsToForward;
3040 SmallVector<AttributeSet, 4> VarArgsAttrs;
3041 for (unsigned i = CalledFunc->getFunctionType()->getNumParams();
3042 i < CB.arg_size(); i++) {
3043 VarArgsToForward.push_back(CB.getArgOperand(i));
3044 VarArgsAttrs.push_back(CB.getAttributes().getParamAttrs(i));
3045 }
3046
3047 bool InlinedMustTailCalls = false, InlinedDeoptimizeCalls = false;
3048 if (InlinedFunctionInfo.ContainsCalls) {
3049 CallInst::TailCallKind CallSiteTailKind = CallInst::TCK_None;
3050 if (CallInst *CI = dyn_cast<CallInst>(&CB))
3051 CallSiteTailKind = CI->getTailCallKind();
3052
3053 // For inlining purposes, the "notail" marker is the same as no marker.
3054 if (CallSiteTailKind == CallInst::TCK_NoTail)
3055 CallSiteTailKind = CallInst::TCK_None;
3056
3057 for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E;
3058 ++BB) {
3061 if (!CI)
3062 continue;
3063
3064 // Forward varargs from inlined call site to calls to the
3065 // ForwardVarArgsTo function, if requested, and to musttail calls.
3066 if (!VarArgsToForward.empty() &&
3067 ((ForwardVarArgsTo &&
3068 CI->getCalledFunction() == ForwardVarArgsTo) ||
3069 CI->isMustTailCall())) {
3070 // Collect attributes for non-vararg parameters.
3071 AttributeList Attrs = CI->getAttributes();
3073 if (!Attrs.isEmpty() || !VarArgsAttrs.empty()) {
3074 for (unsigned ArgNo = 0;
3075 ArgNo < CI->getFunctionType()->getNumParams(); ++ArgNo)
3076 ArgAttrs.push_back(Attrs.getParamAttrs(ArgNo));
3077 }
3078
3079 // Add VarArg attributes.
3080 ArgAttrs.append(VarArgsAttrs.begin(), VarArgsAttrs.end());
3081 Attrs = AttributeList::get(CI->getContext(), Attrs.getFnAttrs(),
3082 Attrs.getRetAttrs(), ArgAttrs);
3083 // Add VarArgs to existing parameters.
3084 SmallVector<Value *, 6> Params(CI->args());
3085 Params.append(VarArgsToForward.begin(), VarArgsToForward.end());
3086 CallInst *NewCI = CallInst::Create(
3087 CI->getFunctionType(), CI->getCalledOperand(), Params, "", CI->getIterator());
3088 NewCI->setDebugLoc(CI->getDebugLoc());
3089 NewCI->setAttributes(Attrs);
3090 NewCI->setCallingConv(CI->getCallingConv());
3091 CI->replaceAllUsesWith(NewCI);
3092 CI->eraseFromParent();
3093 CI = NewCI;
3094 }
3095
3096 if (Function *F = CI->getCalledFunction())
3097 InlinedDeoptimizeCalls |=
3098 F->getIntrinsicID() == Intrinsic::experimental_deoptimize;
3099
3100 // We need to reduce the strength of any inlined tail calls. For
3101 // musttail, we have to avoid introducing potential unbounded stack
3102 // growth. For example, if functions 'f' and 'g' are mutually recursive
3103 // with musttail, we can inline 'g' into 'f' so long as we preserve
3104 // musttail on the cloned call to 'f'. If either the inlined call site
3105 // or the cloned call site is *not* musttail, the program already has
3106 // one frame of stack growth, so it's safe to remove musttail. Here is
3107 // a table of example transformations:
3108 //
3109 // f -> musttail g -> musttail f ==> f -> musttail f
3110 // f -> musttail g -> tail f ==> f -> tail f
3111 // f -> g -> musttail f ==> f -> f
3112 // f -> g -> tail f ==> f -> f
3113 //
3114 // Inlined notail calls should remain notail calls.
3115 CallInst::TailCallKind ChildTCK = CI->getTailCallKind();
3116 if (ChildTCK != CallInst::TCK_NoTail)
3117 ChildTCK = std::min(CallSiteTailKind, ChildTCK);
3118 CI->setTailCallKind(ChildTCK);
3119 InlinedMustTailCalls |= CI->isMustTailCall();
3120
3121 // Call sites inlined through a 'nounwind' call site should be
3122 // 'nounwind' as well. However, avoid marking call sites explicitly
3123 // where possible. This helps expose more opportunities for CSE after
3124 // inlining, commonly when the callee is an intrinsic.
3125 if (MarkNoUnwind && !CI->doesNotThrow())
3126 CI->setDoesNotThrow();
3127 }
3128 }
3129 }
3130
3131 // Leave lifetime markers for the static alloca's, scoping them to the
3132 // function we just inlined.
3133 // We need to insert lifetime intrinsics even at O0 to avoid invalid
3134 // access caused by multithreaded coroutines. The check
3135 // `Caller->isPresplitCoroutine()` would affect AlwaysInliner at O0 only.
3136 if ((InsertLifetime || Caller->isPresplitCoroutine()) &&
3137 !IFI.StaticAllocas.empty()) {
3138 IRBuilder<> builder(FirstNewBlock->begin());
3139 for (AllocaInst *AI : IFI.StaticAllocas) {
3140 // Don't mark swifterror allocas. They can't have bitcast uses.
3141 if (AI->isSwiftError())
3142 continue;
3143
3144 // If the alloca is already scoped to something smaller than the whole
3145 // function then there's no need to add redundant, less accurate markers.
3147 continue;
3148
3149 std::optional<TypeSize> Size = AI->getAllocationSize(AI->getDataLayout());
3150 if (Size && Size->isZero())
3151 continue;
3152
3153 builder.CreateLifetimeStart(AI);
3154 for (ReturnInst *RI : Returns) {
3155 // Don't insert llvm.lifetime.end calls between a musttail or deoptimize
3156 // call and a return. The return kills all local allocas.
3157 if (InlinedMustTailCalls &&
3158 RI->getParent()->getTerminatingMustTailCall())
3159 continue;
3160 if (InlinedDeoptimizeCalls &&
3161 RI->getParent()->getTerminatingDeoptimizeCall())
3162 continue;
3163 IRBuilder<>(RI).CreateLifetimeEnd(AI);
3164 }
3165 }
3166 }
3167
3168 // If the inlined code contained dynamic alloca instructions, wrap the inlined
3169 // code with llvm.stacksave/llvm.stackrestore intrinsics.
3170 if (InlinedFunctionInfo.ContainsDynamicAllocas) {
3171 // Insert the llvm.stacksave.
3172 CallInst *SavedPtr =
3173 IRBuilder<>(FirstNewBlock->begin()).CreateStackSave("savedstack");
3174
3175 // Insert a call to llvm.stackrestore before any return instructions in the
3176 // inlined function.
3177 for (ReturnInst *RI : Returns) {
3178 // Don't insert llvm.stackrestore calls between a musttail or deoptimize
3179 // call and a return. The return will restore the stack pointer.
3180 if (InlinedMustTailCalls && RI->getParent()->getTerminatingMustTailCall())
3181 continue;
3182 if (InlinedDeoptimizeCalls && RI->getParent()->getTerminatingDeoptimizeCall())
3183 continue;
3184 IRBuilder<>(RI).CreateStackRestore(SavedPtr);
3185 }
3186 }
3187
3188 // If we are inlining for an invoke instruction, we must make sure to rewrite
3189 // any call instructions into invoke instructions. This is sensitive to which
3190 // funclet pads were top-level in the inlinee, so must be done before
3191 // rewriting the "parent pad" links.
3192 if (auto *II = dyn_cast<InvokeInst>(&CB)) {
3193 BasicBlock *UnwindDest = II->getUnwindDest();
3194 BasicBlock::iterator FirstNonPHI = UnwindDest->getFirstNonPHIIt();
3195 if (isa<LandingPadInst>(FirstNonPHI)) {
3196 HandleInlinedLandingPad(II, &*FirstNewBlock, InlinedFunctionInfo);
3197 } else {
3198 HandleInlinedEHPad(II, &*FirstNewBlock, InlinedFunctionInfo);
3199 }
3200 }
3201
3202 // Update the lexical scopes of the new funclets and callsites.
3203 // Anything that had 'none' as its parent is now nested inside the callsite's
3204 // EHPad.
3205 if (IFI.CallSiteEHPad) {
3206 for (Function::iterator BB = FirstNewBlock->getIterator(),
3207 E = Caller->end();
3208 BB != E; ++BB) {
3209 // Add bundle operands to inlined call sites.
3211
3212 // It is problematic if the inlinee has a cleanupret which unwinds to
3213 // caller and we inline it into a call site which doesn't unwind but into
3214 // an EH pad that does. Such an edge must be dynamically unreachable.
3215 // As such, we replace the cleanupret with unreachable.
3216 if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(BB->getTerminator()))
3217 if (CleanupRet->unwindsToCaller() && EHPadForCallUnwindsLocally)
3218 changeToUnreachable(CleanupRet);
3219
3220 BasicBlock::iterator I = BB->getFirstNonPHIIt();
3221 if (!I->isEHPad())
3222 continue;
3223
3224 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I)) {
3225 if (isa<ConstantTokenNone>(CatchSwitch->getParentPad()))
3226 CatchSwitch->setParentPad(IFI.CallSiteEHPad);
3227 } else {
3228 auto *FPI = cast<FuncletPadInst>(I);
3229 if (isa<ConstantTokenNone>(FPI->getParentPad()))
3230 FPI->setParentPad(IFI.CallSiteEHPad);
3231 }
3232 }
3233 }
3234
3235 if (InlinedDeoptimizeCalls) {
3236 // We need to at least remove the deoptimizing returns from the Return set,
3237 // so that the control flow from those returns does not get merged into the
3238 // caller (but terminate it instead). If the caller's return type does not
3239 // match the callee's return type, we also need to change the return type of
3240 // the intrinsic.
3241 if (Caller->getReturnType() == CB.getType()) {
3242 llvm::erase_if(Returns, [](ReturnInst *RI) {
3243 return RI->getParent()->getTerminatingDeoptimizeCall() != nullptr;
3244 });
3245 } else {
3246 SmallVector<ReturnInst *, 8> NormalReturns;
3247 Function *NewDeoptIntrinsic = Intrinsic::getOrInsertDeclaration(
3248 Caller->getParent(), Intrinsic::experimental_deoptimize,
3249 {Caller->getReturnType()});
3250
3251 for (ReturnInst *RI : Returns) {
3252 CallInst *DeoptCall = RI->getParent()->getTerminatingDeoptimizeCall();
3253 if (!DeoptCall) {
3254 NormalReturns.push_back(RI);
3255 continue;
3256 }
3257
3258 // The calling convention on the deoptimize call itself may be bogus,
3259 // since the code we're inlining may have undefined behavior (and may
3260 // never actually execute at runtime); but all
3261 // @llvm.experimental.deoptimize declarations have to have the same
3262 // calling convention in a well-formed module.
3263 auto CallingConv = DeoptCall->getCalledFunction()->getCallingConv();
3264 NewDeoptIntrinsic->setCallingConv(CallingConv);
3265 auto *CurBB = RI->getParent();
3266 RI->eraseFromParent();
3267
3268 SmallVector<Value *, 4> CallArgs(DeoptCall->args());
3269
3271 DeoptCall->getOperandBundlesAsDefs(OpBundles);
3272 auto DeoptAttributes = DeoptCall->getAttributes();
3273 DeoptCall->eraseFromParent();
3274 assert(!OpBundles.empty() &&
3275 "Expected at least the deopt operand bundle");
3276
3277 IRBuilder<> Builder(CurBB);
3278 CallInst *NewDeoptCall =
3279 Builder.CreateCall(NewDeoptIntrinsic, CallArgs, OpBundles);
3280 NewDeoptCall->setCallingConv(CallingConv);
3281 NewDeoptCall->setAttributes(DeoptAttributes);
3282 if (NewDeoptCall->getType()->isVoidTy())
3283 Builder.CreateRetVoid();
3284 else
3285 Builder.CreateRet(NewDeoptCall);
3286 // Since the ret type is changed, remove the incompatible attributes.
3287 NewDeoptCall->removeRetAttrs(AttributeFuncs::typeIncompatible(
3288 NewDeoptCall->getType(), NewDeoptCall->getRetAttributes()));
3289 }
3290
3291 // Leave behind the normal returns so we can merge control flow.
3292 std::swap(Returns, NormalReturns);
3293 }
3294 }
3295
3296 // Handle any inlined musttail call sites. In order for a new call site to be
3297 // musttail, the source of the clone and the inlined call site must have been
3298 // musttail. Therefore it's safe to return without merging control into the
3299 // phi below.
3300 if (InlinedMustTailCalls) {
3301 // Handle the returns preceded by musttail calls separately.
3302 SmallVector<ReturnInst *, 8> NormalReturns;
3303 for (ReturnInst *RI : Returns) {
3304 CallInst *ReturnedMustTail =
3305 RI->getParent()->getTerminatingMustTailCall();
3306 if (!ReturnedMustTail)
3307 NormalReturns.push_back(RI);
3308 }
3309
3310 // Leave behind the normal returns so we can merge control flow.
3311 std::swap(Returns, NormalReturns);
3312 }
3313
3314 // Now that all of the transforms on the inlined code have taken place but
3315 // before we splice the inlined code into the CFG and lose track of which
3316 // blocks were actually inlined, collect the call sites. We only do this if
3317 // call graph updates weren't requested, as those provide value handle based
3318 // tracking of inlined call sites instead. Calls to intrinsics are not
3319 // collected because they are not inlineable.
3320 if (InlinedFunctionInfo.ContainsCalls) {
3321 // Otherwise just collect the raw call sites that were inlined.
3322 for (BasicBlock &NewBB :
3323 make_range(FirstNewBlock->getIterator(), Caller->end()))
3324 for (Instruction &I : NewBB)
3325 if (auto *CB = dyn_cast<CallBase>(&I))
3326 if (!(CB->getCalledFunction() &&
3328 IFI.InlinedCallSites.push_back(CB);
3329 }
3330
3331 for (CallBase *ICB : IFI.InlinedCallSites) {
3332 // We only track inline history if requested, or if the inlined call site
3333 // was originally an indirect call (it may have become a direct call
3334 // during inlining).
3335 if (TrackInlineHistory ||
3336 InlinedFunctionInfo.OriginallyIndirectCalls.contains(ICB)) {
3337 // !inline_history is {Callee, CB.inline_history, ICB.inline_history}.
3338 // Metadata nodes may be null if the referenced function was erased from
3339 // the module.
3341 History.push_back(ValueAsMetadata::get(CalledFunc));
3342 if (MDNode *CBHistory = CB.getMetadata(LLVMContext::MD_inline_history)) {
3343 for (const auto &Op : CBHistory->operands()) {
3344 if (Op)
3345 History.push_back(Op.get());
3346 }
3347 }
3348 if (MDNode *CBHistory =
3349 ICB->getMetadata(LLVMContext::MD_inline_history)) {
3350 for (const auto &Op : CBHistory->operands()) {
3351 if (Op)
3352 History.push_back(Op.get());
3353 }
3354 }
3355 MDNode *NewHistory = MDNode::get(Caller->getContext(), History);
3356 ICB->setMetadata(LLVMContext::MD_inline_history, NewHistory);
3357 }
3358 }
3359
3360 // If we cloned in _exactly one_ basic block, and if that block ends in a
3361 // return instruction, we splice the body of the inlined callee directly into
3362 // the calling basic block.
3363 if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
3364 // Move all of the instructions right before the call.
3365 OrigBB->splice(CB.getIterator(), &*FirstNewBlock, FirstNewBlock->begin(),
3366 FirstNewBlock->end());
3367 // Remove the cloned basic block.
3368 Caller->back().eraseFromParent();
3369
3370 // If the call site was an invoke instruction, add a branch to the normal
3371 // destination.
3372 if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) {
3373 UncondBrInst *NewBr =
3374 UncondBrInst::Create(II->getNormalDest(), CB.getIterator());
3375 NewBr->setDebugLoc(Returns[0]->getDebugLoc());
3376 }
3377
3378 // If the return instruction returned a value, replace uses of the call with
3379 // uses of the returned value.
3380 if (!CB.use_empty()) {
3381 ReturnInst *R = Returns[0];
3382 if (&CB == R->getReturnValue())
3384 else
3385 CB.replaceAllUsesWith(R->getReturnValue());
3386 }
3387 // Since we are now done with the Call/Invoke, we can delete it.
3388 CB.eraseFromParent();
3389
3390 // Since we are now done with the return instruction, delete it also.
3391 Returns[0]->eraseFromParent();
3392
3393 if (MergeAttributes)
3394 AttributeFuncs::mergeAttributesForInlining(*Caller, *CalledFunc);
3395
3396 // We are now done with the inlining.
3397 return;
3398 }
3399
3400 // Otherwise, we have the normal case, of more than one block to inline or
3401 // multiple return sites.
3402
3403 // We want to clone the entire callee function into the hole between the
3404 // "starter" and "ender" blocks. How we accomplish this depends on whether
3405 // this is an invoke instruction or a call instruction.
3406 BasicBlock *AfterCallBB;
3407 UncondBrInst *CreatedBranchToNormalDest = nullptr;
3408 if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) {
3409
3410 // Add an unconditional branch to make this look like the CallInst case...
3411 CreatedBranchToNormalDest =
3412 UncondBrInst::Create(II->getNormalDest(), CB.getIterator());
3413 // We intend to replace this DebugLoc with another later.
3414 CreatedBranchToNormalDest->setDebugLoc(DebugLoc::getTemporary());
3415
3416 // Split the basic block. This guarantees that no PHI nodes will have to be
3417 // updated due to new incoming edges, and make the invoke case more
3418 // symmetric to the call case.
3419 AfterCallBB =
3420 OrigBB->splitBasicBlock(CreatedBranchToNormalDest->getIterator(),
3421 CalledFunc->getName() + ".exit");
3422
3423 } else { // It's a call
3424 // If this is a call instruction, we need to split the basic block that
3425 // the call lives in.
3426 //
3427 AfterCallBB = OrigBB->splitBasicBlock(CB.getIterator(),
3428 CalledFunc->getName() + ".exit");
3429 }
3430
3431 if (IFI.CallerBFI) {
3432 // Copy original BB's block frequency to AfterCallBB
3433 IFI.CallerBFI->setBlockFreq(AfterCallBB,
3434 IFI.CallerBFI->getBlockFreq(OrigBB));
3435 }
3436
3437 // Change the branch that used to go to AfterCallBB to branch to the first
3438 // basic block of the inlined function.
3439 //
3441 Br->setSuccessor(&*FirstNewBlock);
3442
3443 // Now that the function is correct, make it a little bit nicer. In
3444 // particular, move the basic blocks inserted from the end of the function
3445 // into the space made by splitting the source basic block.
3446 Caller->splice(AfterCallBB->getIterator(), Caller, FirstNewBlock,
3447 Caller->end());
3448
3449 // Handle all of the return instructions that we just cloned in, and eliminate
3450 // any users of the original call/invoke instruction.
3451 Type *RTy = CalledFunc->getReturnType();
3452
3453 PHINode *PHI = nullptr;
3454 if (Returns.size() > 1) {
3455 // The PHI node should go at the front of the new basic block to merge all
3456 // possible incoming values.
3457 if (!CB.use_empty()) {
3458 PHI = PHINode::Create(RTy, Returns.size(), CB.getName());
3459 PHI->insertBefore(AfterCallBB->begin());
3460 // Anything that used the result of the function call should now use the
3461 // PHI node as their operand.
3463 }
3464
3465 // Loop over all of the return instructions adding entries to the PHI node
3466 // as appropriate.
3467 if (PHI) {
3468 for (ReturnInst *RI : Returns) {
3469 assert(RI->getReturnValue()->getType() == PHI->getType() &&
3470 "Ret value not consistent in function!");
3471 PHI->addIncoming(RI->getReturnValue(), RI->getParent());
3472 }
3473 }
3474
3475 // Add a branch to the merge points and remove return instructions.
3476 DebugLoc Loc;
3477 for (ReturnInst *RI : Returns) {
3478 UncondBrInst *BI = UncondBrInst::Create(AfterCallBB, RI->getIterator());
3479 Loc = RI->getDebugLoc();
3480 BI->setDebugLoc(Loc);
3481 RI->eraseFromParent();
3482 }
3483 // We need to set the debug location to *somewhere* inside the
3484 // inlined function. The line number may be nonsensical, but the
3485 // instruction will at least be associated with the right
3486 // function.
3487 if (CreatedBranchToNormalDest)
3488 CreatedBranchToNormalDest->setDebugLoc(Loc);
3489 } else if (!Returns.empty()) {
3490 // Otherwise, if there is exactly one return value, just replace anything
3491 // using the return value of the call with the computed value.
3492 if (!CB.use_empty()) {
3493 if (&CB == Returns[0]->getReturnValue())
3495 else
3496 CB.replaceAllUsesWith(Returns[0]->getReturnValue());
3497 }
3498
3499 // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
3500 BasicBlock *ReturnBB = Returns[0]->getParent();
3501 ReturnBB->replaceAllUsesWith(AfterCallBB);
3502
3503 // Splice the code from the return block into the block that it will return
3504 // to, which contains the code that was after the call.
3505 AfterCallBB->splice(AfterCallBB->begin(), ReturnBB);
3506
3507 if (CreatedBranchToNormalDest)
3508 CreatedBranchToNormalDest->setDebugLoc(Returns[0]->getDebugLoc());
3509
3510 // Delete the return instruction now and empty ReturnBB now.
3511 Returns[0]->eraseFromParent();
3512 ReturnBB->eraseFromParent();
3513 } else if (!CB.use_empty()) {
3514 // In this case there are no returns to use, so there is no clear source
3515 // location for the "return".
3516 // FIXME: It may be correct to use the scope end line of the function here,
3517 // since this likely means we are falling out of the function.
3518 if (CreatedBranchToNormalDest)
3519 CreatedBranchToNormalDest->setDebugLoc(DebugLoc::getUnknown());
3520 // No returns, but something is using the return value of the call. Just
3521 // nuke the result.
3523 }
3524
3525 // Since we are now done with the Call/Invoke, we can delete it.
3526 CB.eraseFromParent();
3527
3528 // If we inlined any musttail calls and the original return is now
3529 // unreachable, delete it. It can only contain a ret.
3530 if (InlinedMustTailCalls && pred_empty(AfterCallBB))
3531 AfterCallBB->eraseFromParent();
3532
3533 // We should always be able to fold the entry block of the function into the
3534 // single predecessor of the block...
3535 BasicBlock *CalleeEntry = Br->getSuccessor();
3536
3537 // Splice the code entry block into calling block, right before the
3538 // unconditional branch.
3539 CalleeEntry->replaceAllUsesWith(OrigBB); // Update PHI nodes
3540 OrigBB->splice(Br->getIterator(), CalleeEntry);
3541
3542 // Remove the unconditional branch.
3543 Br->eraseFromParent();
3544
3545 // Now we can remove the CalleeEntry block, which is now empty.
3546 CalleeEntry->eraseFromParent();
3547
3548 // If we inserted a phi node, check to see if it has a single value (e.g. all
3549 // the entries are the same or undef). If so, remove the PHI so it doesn't
3550 // block other optimizations.
3551 if (PHI) {
3552 AssumptionCache *AC =
3553 IFI.GetAssumptionCache ? &IFI.GetAssumptionCache(*Caller) : nullptr;
3554 auto &DL = Caller->getDataLayout();
3555 if (Value *V = simplifyInstruction(PHI, {DL, nullptr, nullptr, AC})) {
3556 PHI->replaceAllUsesWith(V);
3557 PHI->eraseFromParent();
3558 }
3559 }
3560
3561 if (MergeAttributes)
3562 AttributeFuncs::mergeAttributesForInlining(*Caller, *CalledFunc);
3563}
3564
3566 CallBase &CB, InlineFunctionInfo &IFI, bool MergeAttributes,
3567 AAResults *CalleeAAR, bool InsertLifetime, bool TrackInlineHistory,
3568 Function *ForwardVarArgsTo, OptimizationRemarkEmitter *ORE) {
3569 llvm::InlineResult Result = CanInlineCallSite(CB, IFI);
3570 if (Result.isSuccess()) {
3571 InlineFunctionImpl(CB, IFI, MergeAttributes, CalleeAAR, InsertLifetime,
3572 TrackInlineHistory, ForwardVarArgsTo, ORE);
3573 }
3574
3575 return Result;
3576}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
Rewrite undef for PHI
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file contains the simple types necessary to represent the attributes associated with functions a...
static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB, ArrayRef< BasicBlock * > Preds, Instruction *BI, bool HasLoopExit)
Update the PHI nodes in OrigBB to include the values coming from NewBB.
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file provides interfaces used to build and manipulate a call graph, which is a very useful tool ...
This file contains the declarations for the subclasses of Constant, which represent the different fla...
dxil translate DXIL Translate Metadata
This file defines the DenseMap class.
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.
static AttrBuilder IdentifyValidUBGeneratingAttributes(CallBase &CB)
static void collectPointerReturningCalls(Value *RetVal, SmallVectorImpl< CallBase * > &Out)
Collect all calls that produce RetVal, following only pointer-preserving instructions (cast,...
DenseMap< Instruction *, Value * > UnwindDestMemoTy
static BasicBlock * HandleCallsInBlockInlinedThroughInvoke(BasicBlock *BB, BasicBlock *UnwindEdge, SmallSetVector< const Value *, 4 > &OriginallyIndirectCalls, UnwindDestMemoTy *FuncletUnwindMap=nullptr)
When we inline a basic block into an invoke, we have to turn all of the calls that can throw into inv...
static at::StorageToVarsMap collectEscapedLocals(const DataLayout &DL, const CallBase &CB)
Find Alloca and linked DbgAssignIntrinsic for locals escaped by CB.
static void fixupLineNumbers(Function *Fn, Function::iterator FI, Instruction *TheCall, bool CalleeHasDebugInfo)
Update inlined instructions' line numbers to to encode location where these instructions are inlined.
static void removeCallsiteMetadata(CallBase *Call)
static void PropagateInlinedFromMetadata(CallBase &CB, StringRef CalledFuncName, StringRef CallerFuncName, Function::iterator FStart, Function::iterator FEnd)
Track inlining chain via inlined.from metadata for dontcall diagnostics.
static Value * getUnwindDestToken(Instruction *EHPad, UnwindDestMemoTy &MemoMap)
Given an EH pad, find where it unwinds.
static void propagateMemProfMetadata(Function *Callee, CallBase &CB, bool ContainsMemProfMetadata, const ValueMap< const Value *, WeakTrackingVH > &VMap, OptimizationRemarkEmitter *ORE)
static cl::opt< bool > PreserveAlignmentAssumptions("preserve-alignment-assumptions-during-inlining", cl::init(false), cl::Hidden, cl::desc("Convert align attributes to assumptions during inlining."))
static void HandleInlinedLandingPad(InvokeInst *II, BasicBlock *FirstNewBlock, ClonedCodeInfo &InlinedCodeInfo)
If we inlined an invoke site, we need to convert calls in the body of the inlined function into invok...
static Value * getUnwindDestTokenHelper(Instruction *EHPad, UnwindDestMemoTy &MemoMap)
Helper for getUnwindDestToken that does the descendant-ward part of the search.
static void updateCallProfile(Function *Callee, const ValueToValueMapTy &VMap, const uint64_t &CalleeEntryCount, const CallBase &TheCall, ProfileSummaryInfo *PSI, BlockFrequencyInfo *CallerBFI)
Update the branch metadata for cloned call instructions.
static cl::opt< bool > UseNoAliasIntrinsic("use-noalias-intrinsic-during-inlining", cl::Hidden, cl::init(true), cl::desc("Use the llvm.experimental.noalias.scope.decl " "intrinsic during inlining."))
static void propagateAllocTokenMetadata(Function *CalledFunc, CallBase &CB, const ValueMap< const Value *, WeakTrackingVH > &VMap, ClonedCodeInfo &InlinedFunctionInfo)
When inlining a call that carries !alloc_token metadata, propagate that metadata onto calls exposed b...
static DebugLoc inlineDebugLoc(DebugLoc OrigDL, DILocation *InlinedAt, LLVMContext &Ctx, DenseMap< const MDNode *, MDNode * > &IANodes, SmallDenseMap< const DILocation *, DILocation *, 16 > &InlineLocs)
Returns a DebugLoc for a new DILocation which is a clone of OrigDL inlined at InlinedAt.
static void PropagateCallSiteMetadata(CallBase &CB, Function::iterator FStart, Function::iterator FEnd)
When inlining a call site that has !llvm.mem.parallel_loop_access, !llvm.access.group,...
static std::pair< std::vector< int64_t >, std::vector< int64_t > > remapIndices(Function &Caller, BasicBlock *StartBB, PGOContextualProfile &CtxProf, uint32_t CalleeCounters, uint32_t CalleeCallsites)
static AttrBuilder IdentifyValidPoisonGeneratingAttributes(CallBase &CB)
static void updateMemprofMetadata(CallBase *CI, const std::vector< Metadata * > &MIBList, OptimizationRemarkEmitter *ORE)
static void updateCallerBFI(BasicBlock *CallSiteBlock, const ValueToValueMapTy &VMap, BlockFrequencyInfo *CallerBFI, BlockFrequencyInfo *CalleeBFI, const BasicBlock &CalleeEntryBlock)
Update the block frequencies of the caller after a callee has been inlined.
static void AddReturnAttributes(CallBase &CB, ValueToValueMapTy &VMap, ClonedCodeInfo &InlinedFunctionInfo)
static void HandleByValArgumentInit(Type *ByValType, Value *Dst, Value *Src, MaybeAlign SrcAlign, Module *M, BasicBlock *InsertBlock, InlineFunctionInfo &IFI, Function *CalledFunc)
static bool MayContainThrowingOrExitingCallAfterCB(CallBase *Begin, ReturnInst *End)
static cl::opt< bool > EnableNoAliasConversion("enable-noalias-to-md-conversion", cl::init(true), cl::Hidden, cl::desc("Convert noalias attributes to metadata during inlining."))
static void AddAliasScopeMetadata(CallBase &CB, ValueToValueMapTy &VMap, const DataLayout &DL, AAResults *CalleeAAR, ClonedCodeInfo &InlinedFunctionInfo)
If the inlined function has noalias arguments, then add new alias scopes for each noalias argument,...
static IntrinsicInst * getConvergenceEntry(BasicBlock &BB)
static void HandleInlinedEHPad(InvokeInst *II, BasicBlock *FirstNewBlock, ClonedCodeInfo &InlinedCodeInfo)
If we inlined an invoke site, we need to convert calls in the body of the inlined function into invok...
static void inlineRetainOrClaimRVCalls(CallBase &CB, objcarc::ARCInstKind RVCallKind, const SmallVectorImpl< ReturnInst * > &Returns)
An operand bundle "clang.arc.attachedcall" on a call indicates the call result is implicitly consumed...
static void fixupAssignments(Function::iterator Start, Function::iterator End)
Update inlined instructions' DIAssignID metadata.
static void propagateMemProfHelper(const CallBase *OrigCall, CallBase *ClonedCall, MDNode *InlinedCallsiteMD, OptimizationRemarkEmitter *ORE)
static bool allocaWouldBeStaticInEntry(const AllocaInst *AI)
Return the result of AI->isStaticAlloca() if AI were moved to the entry block.
static void removeMemProfMetadata(CallBase *Call)
static Value * HandleByValArgument(Type *ByValType, Value *Arg, Instruction *TheCall, const Function *CalledFunc, InlineFunctionInfo &IFI, MaybeAlign ByValAlignment)
When inlining a call site that has a byval argument, we have to make the implicit memcpy explicit by ...
static void AddAlignmentAssumptions(CallBase &CB, InlineFunctionInfo &IFI)
If the inlined function has non-byval align arguments, then add @llvm.assume-based alignment assumpti...
static void trackInlinedStores(Function::iterator Start, Function::iterator End, const CallBase &CB)
static cl::opt< unsigned > InlinerAttributeWindow("max-inst-checked-for-throw-during-inlining", cl::Hidden, cl::desc("the maximum number of instructions analyzed for may throw during " "attribute inference in inlined body"), cl::init(4))
static void AddParamAndFnBasicAttributes(const CallBase &CB, ValueToValueMapTy &VMap, ClonedCodeInfo &InlinedFunctionInfo)
static bool haveCommonPrefix(MDNode *MIBStackContext, MDNode *CallsiteStackContext)
static void PropagateOperandBundles(Function::iterator InlinedBB, Instruction *CallSiteEHPad)
Bundle operands of the inlined function must be added to inlined call sites.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static cl::opt< bool > NoAliases("loongarch-no-aliases", cl::desc("Disable the emission of assembler pseudo instructions"), cl::init(false), cl::Hidden)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Load MIR Sample Profile
This file contains the declarations for metadata subclasses.
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
This file defines common analysis utilities used by the ObjC ARC Optimizer.
This file defines ARC utility functions which are used by various parts of the compiler.
This file contains the declarations for profiling metadata utility functions.
Func MI getDebugLoc()))
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.
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static Value * getParentPad(Value *EHPad)
LLVM_ABI MemoryEffects getMemoryEffects(const CallBase *Call)
Return the behavior of the given call site.
Class for arbitrary precision integers.
Definition APInt.h:78
an instruction to allocate memory on the stack
bool isSwiftError() const
Return true if this alloca is used as a swifterror argument to a call.
bool isUsedWithInAlloca() const
Return true if this alloca is used as an inalloca argument to a call.
LLVM_ABI std::optional< TypeSize > getAllocationSize(const DataLayout &DL) const
Get allocation size in bytes.
const Value * getArraySize() const
Get the number of elements allocated.
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
unsigned getArgNo() const
Return the index of this formal argument in its containing function.
Definition Argument.h:50
A cache of @llvm.assume calls within a function.
LLVM_ABI void registerAssumption(AssumeInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
An instruction that atomically checks whether a specified value is in a memory location,...
an instruction that atomically reads a memory location, combines it with another value,...
static LLVM_ABI AttributeSet get(LLVMContext &C, const AttrBuilder &B)
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:106
LLVM_ABI const ConstantRange & getRange() const
Returns the value of the range attribute.
LLVM_ABI FPClassTest getNoFPClass() const
Return the FPClassTest for nofpclass.
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:125
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:262
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:453
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:440
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:509
LLVM_ABI BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
void splice(BasicBlock::iterator ToIt, BasicBlock *FromBB)
Transfer all instructions from FromBB to this basic block at ToIt.
Definition BasicBlock.h:638
LLVM_ABI void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Update PHI nodes in this BasicBlock before removal of predecessor Pred.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
LLVM_ABI void setBlockFreq(const BasicBlock *BB, BlockFrequency Freq)
LLVM_ABI void setBlockFreqAndScale(const BasicBlock *ReferenceBB, BlockFrequency Freq, SmallPtrSetImpl< BasicBlock * > &BlocksToScale)
Set the frequency of ReferenceBB to Freq and scale the frequencies of the blocks in BlocksToScale suc...
LLVM_ABI BlockFrequency getBlockFreq(const BasicBlock *BB) const
getblockFreq - Return block frequency.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
void setCallingConv(CallingConv::ID CC)
LLVM_ABI FPClassTest getRetNoFPClass() const
Extract a test mask for disallowed floating-point value classes for the return value.
void setDoesNotThrow()
MaybeAlign getRetAlign() const
Extract the alignment of the return value.
LLVM_ABI void getOperandBundlesAsDefs(SmallVectorImpl< OperandBundleDef > &Defs) const
Return the list of operand bundles attached to this instruction as a vector of OperandBundleDefs.
OperandBundleUse getOperandBundleAt(unsigned Index) const
Return the operand bundle at a specific index.
std::optional< OperandBundleUse > getOperandBundle(StringRef Name) const
Return an operand bundle by name, if present.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
void removeRetAttrs(const AttributeMask &AttrsToRemove)
Removes the attributes from the return value.
bool hasRetAttr(Attribute::AttrKind Kind) const
Determine whether the return value has the given attribute.
unsigned getNumOperandBundles() const
Return the number of operand bundles associated with this User.
CallingConv::ID getCallingConv() const
LLVM_ABI bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
User::op_iterator arg_begin()
Return the iterator pointing to the beginning of the argument list.
Attribute getParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Get the attribute of a given kind from a given arg.
bool isByValArgument(unsigned ArgNo) const
Determine whether this argument is passed by value.
static LLVM_ABI CallBase * addOperandBundle(CallBase *CB, uint32_t ID, OperandBundleDef OB, InsertPosition InsertPt=nullptr)
Create a clone of CB with operand bundle OB added.
MaybeAlign getParamAlign(unsigned ArgNo) const
Extract the alignment for a call or parameter (0=unknown).
AttributeSet getRetAttributes() const
Return the return attributes for this call.
Type * getParamByValType(unsigned ArgNo) const
Extract the byval type for a call or parameter.
Value * getCalledOperand() const
void setAttributes(AttributeList A)
Set the attributes for this call.
LLVM_ABI std::optional< ConstantRange > getRange() const
If this return value has a range attribute, return the value range of the argument.
bool doesNotThrow() const
Determine if the call cannot unwind.
Value * getArgOperand(unsigned i) const
uint64_t getRetDereferenceableBytes() const
Extract the number of dereferenceable bytes for a call or parameter (0=unknown).
bool isConvergent() const
Determine if the invoke is convergent.
FunctionType * getFunctionType() const
static LLVM_ABI CallBase * Create(CallBase *CB, ArrayRef< OperandBundleDef > Bundles, InsertPosition InsertPt=nullptr)
Create a clone of CB with a different set of operand bundles and insert it before InsertPt.
uint64_t getRetDereferenceableOrNullBytes() const
Extract the number of dereferenceable_or_null bytes for a call (0=unknown).
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
bool hasOperandBundles() const
Return true if this User has any operand bundles.
LLVM_ABI Function * getCaller()
Helper to get the caller (the parent function).
This class represents a function call, abstracting a target machine's calling convention.
void setTailCallKind(TailCallKind TCK)
TailCallKind getTailCallKind() const
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
bool isMustTailCall() const
static CatchSwitchInst * Create(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumHandlers, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB=nullptr, InsertPosition InsertBefore=nullptr)
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:548
This class represents a range of values.
LLVM_ABI ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
static LLVM_ABI ConstantTokenNone * get(LLVMContext &Context)
Return the ConstantTokenNone.
This is an important base class in LLVM.
Definition Constant.h:44
const Constant * stripPointerCasts() const
Definition Constant.h:243
static LLVM_ABI InstrProfIncrementInst * getBBInstrumentation(BasicBlock &BB)
Get the instruction instrumenting a BB, or nullptr if not present.
static LLVM_ABI InstrProfCallsite * getCallsiteInstrumentation(CallBase &CB)
Get the instruction instrumenting a callsite, or nullptr if that cannot be found.
const DILocation * getWithoutAtom() const
static bool isPseudoProbeDiscriminator(unsigned Discriminator)
uint64_t getAtomGroup() const
const DILocation * cloneWithDiscriminator(unsigned Discriminator) const
Returns a new DILocation with updated Discriminator.
uint8_t getAtomRank() const
Subprogram description. Uses SubclassData1.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Base class for non-instruction debug metadata records that have positions within IR.
Record of a variable value-assignment, aka a non instruction representation of the dbg....
A debug info location.
Definition DebugLoc.h:126
static DebugLoc getCompilerGenerated()
Definition DebugLoc.h:154
LLVM_ABI unsigned getLine() const
Definition DebugLoc.cpp:43
DILocation * get() const
Get the underlying DILocation.
Definition DebugLoc.h:226
LLVM_ABI MDNode * getScope() const
Definition DebugLoc.cpp:53
static LLVM_ABI DebugLoc appendInlinedAt(const DebugLoc &DL, DILocation *InlinedAt, LLVMContext &Ctx, DenseMap< const MDNode *, MDNode * > &Cache)
Rebuild the entire inlined-at chain for this instruction so that the top of the chain now is inlined-...
Definition DebugLoc.cpp:138
static DebugLoc getTemporary()
Definition DebugLoc.h:152
LLVM_ABI unsigned getCol() const
Definition DebugLoc.cpp:48
LLVM_ABI bool isImplicitCode() const
Check if the DebugLoc corresponds to an implicit code.
Definition DebugLoc.cpp:83
static DebugLoc getUnknown()
Definition DebugLoc.h:153
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:762
bool empty() const
Definition DenseMap.h:716
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
void recalculate(ParentType &Func)
recalculate - compute a dominator tree for the given function
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
const BasicBlock & getEntryBlock() const
Definition Function.h:794
BasicBlockListType::iterator iterator
Definition Function.h:70
Argument * arg_iterator
Definition Function.h:73
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition Function.h:212
const BasicBlock & front() const
Definition Function.h:845
iterator_range< arg_iterator > args()
Definition Function.h:877
DISubprogram * getSubprogram() const
Get the attached subprogram.
bool hasGC() const
hasGC/getGC/setGC/clearGC - The name of the garbage collection algorithm to use during code generatio...
Definition Function.h:321
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:273
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition Function.h:890
Constant * getPersonalityFn() const
Get the personality function associated with this function.
arg_iterator arg_end()
Definition Function.h:862
arg_iterator arg_begin()
Definition Function.h:853
bool isIntrinsic() const
isIntrinsic - Returns true if the function's name starts with "llvm.".
Definition Function.h:252
MaybeAlign getParamAlign(unsigned ArgNo) const
Definition Function.h:464
std::optional< uint64_t > getEntryCount() const
Get the entry count for this function.
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:352
const std::string & getGC() const
Definition Function.cpp:821
Type * getReturnType() const
Returns the type of the ret val.
Definition Function.h:217
iterator end()
Definition Function.h:840
void setCallingConv(CallingConv::ID CC)
Definition Function.h:277
bool onlyReadsMemory() const
Determine if the function does not access or only reads memory.
Definition Function.cpp:878
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:731
bool hasMetadata() const
Return true if this GlobalObject has any metadata attached to it.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this GlobalObject.
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition Globals.cpp:408
LLVM_ABI CallInst * CreateLifetimeStart(Value *Ptr)
Create a lifetime.start intrinsic.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2909
This class captures the data input to the InlineFunction call, and records the auxiliary results prod...
Definition Cloning.h:259
Value * ConvergenceControlToken
Definition Cloning.h:284
ProfileSummaryInfo * PSI
Definition Cloning.h:272
bool UpdateProfile
Update profile for callee as well as cloned version.
Definition Cloning.h:289
Instruction * CallSiteEHPad
Definition Cloning.h:285
function_ref< AssumptionCache &(Function &)> GetAssumptionCache
If non-null, InlineFunction will update the callgraph to reflect the changes it makes.
Definition Cloning.h:271
BlockFrequencyInfo * CalleeBFI
Definition Cloning.h:273
SmallVector< AllocaInst *, 4 > StaticAllocas
InlineFunction fills this in with all static allocas that get copied into the caller.
Definition Cloning.h:277
BlockFrequencyInfo * CallerBFI
Definition Cloning.h:273
SmallVector< CallBase *, 8 > InlinedCallSites
All of the new call sites inlined into the caller.
Definition Cloning.h:282
InlineResult is basically true or false.
Definition InlineCost.h:181
static InlineResult success()
Definition InlineCost.h:186
static InlineResult failure(const char *Reason)
Definition InlineCost.h:187
This represents the llvm.instrprof.callsite intrinsic.
This represents the llvm.instrprof.increment intrinsic.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
iterator_range< user_iterator > users()
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
A wrapper class for inspecting calls to intrinsic functions.
static LLVM_ABI bool mayLowerToFunctionCall(Intrinsic::ID IID)
Check if the intrinsic might lower into a regular function call in the course of IR transformations.
Invoke instruction.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
The landingpad instruction holds all of the information necessary to generate correct exception handl...
bool isCleanup() const
Return 'true' if this landingpad instruction is a cleanup.
unsigned getNumClauses() const
Get the number of clauses for this landing pad.
Constant * getClause(unsigned Idx) const
Get the value of the clause at index Idx.
An instruction for reading from memory.
MDNode * createAnonymousAliasScope(MDNode *Domain, StringRef Name=StringRef())
Return metadata appropriate for an alias scope root node.
Definition MDBuilder.h:195
LLVM_ABI MDNode * createAnonymousAliasScopeDomain(StringRef Description=StringRef(), bool DisjointScopes=false)
Return metadata appropriate for an alias scope domain node, described by Description,...
Metadata node.
Definition Metadata.h:1081
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1587
void replaceAllUsesWith(Metadata *MD)
RAUW a temporary.
Definition Metadata.h:1277
static LLVM_ABI MDNode * concatenate(MDNode *A, MDNode *B)
Methods for metadata merging.
bool isTemporary() const
Definition Metadata.h:1265
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1435
op_iterator op_end() const
Definition Metadata.h:1431
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1579
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1443
op_iterator op_begin() const
Definition Metadata.h:1427
LLVMContext & getContext() const
Definition Metadata.h:1245
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:597
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a temporary node.
Definition Metadata.h:1545
bool onlyAccessesInaccessibleMem() const
Whether this function only (at most) accesses inaccessible memory.
Definition ModRef.h:265
bool onlyAccessesArgPointees() const
Whether this function only (at most) accesses argument memory.
Definition ModRef.h:255
Root of the metadata hierarchy.
Definition Metadata.h:64
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
The optimization diagnostic interface.
The instrumented contextual profile, produced by the CtxProfAnalysis.
LLVM_ABI bool isInSpecializedModule() const
LLVM_ABI void update(Visitor, const Function &F)
uint32_t getNumCounters(const Function &F) const
uint32_t allocateNextCounterIndex(const Function &F)
uint32_t getNumCallsites(const Function &F) const
uint32_t allocateNextCallsiteIndex(const Function &F)
A node (context) in the loaded contextual profile, suitable for mutation during IPO passes.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Analysis providing profile information.
LLVM_ABI std::optional< uint64_t > getProfileCount(const CallBase &CallInst, BlockFrequencyInfo *BFI) const
Returns the profile count for CallInst.
Resume the propagation of an exception.
Return a value (possibly void), from a function.
bool remove(const value_type &X)
Remove an item from the set vector.
Definition SetVector.h:187
bool contains(const_arg_type key) const
Check if the SetVector contains the given key.
Definition SetVector.h:258
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:345
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:300
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
Unconditional Branch instruction.
void setSuccessor(BasicBlock *NewSucc)
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
BasicBlock * getSuccessor(unsigned i=0) const
Value * getOperand(unsigned i) const
Definition User.h:207
This class represents the va_arg llvm instruction, which returns an argument of the specified type gi...
static LLVM_ABI ValueAsMetadata * get(Value *V)
Definition Metadata.cpp:514
See the file comment.
Definition ValueMap.h:84
ValueT lookup(const KeyT &Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition ValueMap.h:167
size_type count(const KeyT &Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition ValueMap.h:156
iterator begin()
Definition ValueMap.h:138
iterator end()
Definition ValueMap.h:139
ValueMapIteratorImpl< MapT, const Value *, false > iterator
Definition ValueMap.h:135
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:549
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
iterator_range< user_iterator > users()
Definition Value.h:428
bool use_empty() const
Definition Value.h:348
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:315
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:396
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
Class to build a trie of call stack contexts for a particular profiled allocation call,...
Helper class to iterate through stack ids in both metadata (memprof MIB and callsite) and the corresp...
CallInst * Call
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
CallingConv Namespace - This namespace contains an enum with a value for the well-known calling conve...
Definition CallingConv.h:21
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
bool match(Val *V, const Pattern &P)
match_immconstant_ty m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
LLVM_ABI void trackAssignments(Function::iterator Start, Function::iterator End, const StorageToVarsMap &Vars, const DataLayout &DL, bool DebugPrints=false)
Track assignments to Vars between Start and End.
LLVM_ABI void remapAssignID(DenseMap< DIAssignID *, DIAssignID * > &Map, Instruction &I)
Replace DIAssignID uses and attachments with IDs from Map.
SmallVector< DbgVariableRecord * > getDVRAssignmentMarkers(const Instruction *Inst)
Return a range of dbg_assign records for which Inst performs the assignment they encode.
Definition DebugInfo.h:209
DenseMap< const AllocaInst *, SmallSetVector< VarRecord, 2 > > StorageToVarsMap
Map of backing storage to a set of variables that are stored to it.
Definition DebugInfo.h:282
initializer< Ty > init(const Ty &Val)
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract(Y &&MD)
Extract a Value from Metadata, if any.
Definition Metadata.h:707
LLVM_ABI MDNode * getMIBStackNode(const MDNode *MIB)
Returns the stack node from an MIB metadata node.
constexpr double phi
ARCInstKind getAttachedARCFunctionKind(const CallBase *CB)
This function returns the ARCInstKind of the function attached to operand bundle clang_arc_attachedca...
Definition ObjCARCUtil.h:75
ARCInstKind
Equivalence classes of instructions in the ARC Model.
@ None
anything that is inert from an ARC perspective.
@ RetainRV
objc_retainAutoreleasedReturnValue
std::optional< Function * > getAttachedARCFunction(const CallBase *CB)
This function returns operand bundle clang_arc_attachedcall's argument, which is the address of the A...
Definition ObjCARCUtil.h:43
bool isRetainOrClaimRV(ARCInstKind Kind)
Check whether the function is retainRV/unsafeClaimRV.
Definition ObjCARCUtil.h:67
const Value * GetRCIdentityRoot(const Value *V)
The RCIdentity root of a value V is a dominating value U for which retaining or releasing U is equiva...
bool hasAttachedCallOpBundle(const CallBase *CB)
Definition ObjCARCUtil.h:29
This is an optimization pass for GlobalISel generic memory operations.
UnaryFunction for_each(R &&Range, UnaryFunction F)
Provide wrappers to std::for_each which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1748
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
LLVM_ABI BasicBlock * changeToInvokeAndSplitBasicBlock(CallInst *CI, BasicBlock *UnwindEdge, DomTreeUpdater *DTU=nullptr)
Convert the CallInst to InvokeInst with the specified unwind edge basic block.
Definition Local.cpp:2634
LLVM_ABI Align getOrEnforceKnownAlignment(Value *V, MaybeAlign PrefAlign, const DataLayout &DL, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr)
Try to ensure that the alignment of V is at least PrefAlign bytes.
Definition Local.cpp:1560
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
LLVM_ABI void CloneAndPruneFunctionInto(Function *NewFunc, const Function *OldFunc, ValueToValueMapTy &VMap, bool ModuleLevelChanges, SmallVectorImpl< ReturnInst * > &Returns, const char *NameSuffix, ClonedCodeInfo &CodeInfo)
This works exactly like CloneFunctionInto, except that it does some simple constant prop and DCE on t...
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
std::string utostr(uint64_t X, bool isNeg=false)
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
Definition ModRef.h:356
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
LLVM_ABI InlineResult InlineFunction(CallBase &CB, InlineFunctionInfo &IFI, bool MergeAttributes=false, AAResults *CalleeAAR=nullptr, bool InsertLifetime=true, bool TrackInlineHistory=false, Function *ForwardVarArgsTo=nullptr, OptimizationRemarkEmitter *ORE=nullptr)
This function inlines the called function into the basic block of the caller.
LLVM_ABI bool PointerMayBeCapturedBefore(const Value *V, bool ReturnCaptures, const Instruction *I, const DominatorTree *DT, bool IncludeI=false, unsigned MaxUsesToExplore=0, const LoopInfo *LI=nullptr)
PointerMayBeCapturedBefore - Return true if this pointer value may be captured by the enclosing funct...
LLVM_ABI InlineResult CanInlineCallSite(const CallBase &CB, InlineFunctionInfo &IFI)
Check if it is legal to perform inlining of the function called by CB into the caller at this particu...
bool isScopedEHPersonality(EHPersonality Pers)
Returns true if this personality uses scope-style EH IR instructions: catchswitch,...
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI unsigned changeToUnreachable(Instruction *I, bool PreserveLCSSA=false, DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Insert an unreachable instruction before the specified instruction, making it and the rest of the cod...
Definition Local.cpp:2545
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
LLVM_ABI bool salvageKnowledge(Instruction *I, AssumptionCache *AC=nullptr, DominatorTree *DT=nullptr)
Calls BuildAssumeFromInst and if the resulting llvm.assume is valid insert if before I.
LLVM_ABI void updateProfileCallee(Function *Callee, int64_t EntryDelta, const ValueMap< const Value *, WeakTrackingVH > *VMap=nullptr)
Updates profile information by adjusting the entry count by adding EntryDelta then scaling callsite i...
OperandBundleDefT< Value * > OperandBundleDef
Definition AutoUpgrade.h:34
LLVM_ABI bool isAssignmentTrackingEnabled(const Module &M)
Return true if assignment tracking is enabled for module M.
LLVM_ABI void InlineFunctionImpl(CallBase &CB, InlineFunctionInfo &IFI, bool MergeAttributes=false, AAResults *CalleeAAR=nullptr, bool InsertLifetime=true, bool TrackInlineHistory=false, Function *ForwardVarArgsTo=nullptr, OptimizationRemarkEmitter *ORE=nullptr)
This should generally not be used, use InlineFunction instead.
LLVM_ABI MDNode * uniteAccessGroups(MDNode *AccGroups1, MDNode *AccGroups2)
Compute the union of two access-group lists.
DWARFExpression::Operation Op
bool isAsynchronousEHPersonality(EHPersonality Pers)
Returns true if this personality function catches asynchronous exceptions.
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
LLVM_ABI bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
LLVM_ABI bool isEscapeSource(const Value *V)
Returns true if the pointer is one which would have been considered an escape by isNotCapturedBefore.
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2035
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2208
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
Align getKnownAlignment(Value *V, const DataLayout &DL, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr)
Try to infer an alignment for the specified pointer.
Definition Local.h:240
bool capturesAnything(CaptureComponents CC)
Definition ModRef.h:379
bool pred_empty(const BasicBlock *BB)
Definition CFG.h:107
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
LLVM_ABI void getUnderlyingObjects(const Value *V, SmallVectorImpl< const Value * > &Objects, const LoopInfo *LI=nullptr, unsigned MaxLookup=MaxLookupSearchDepth)
This method is similar to getUnderlyingObject except that it can look through phi and select instruct...
LLVM_ABI void updateLoopMetadataDebugLocations(Instruction &I, function_ref< Metadata *(Metadata *)> Updater)
Update the debug locations contained within the MD_loop metadata attached to the instruction I,...
LLVM_ABI bool isIdentifiedObject(const Value *V)
Return true if this pointer refers to a distinct and identifiable object.
LLVM_ABI void scaleProfData(Instruction &I, uint64_t S, uint64_t T)
Scaling the profile data attached to 'I' using the ratio of S/T.
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
This struct can be used to capture information about code being cloned, while it is being cloned.
Definition Cloning.h:69
bool ContainsDynamicAllocas
This is set to true if the cloned code contains a 'dynamic' alloca.
Definition Cloning.h:80
bool isSimplified(const Value *From, const Value *To) const
Definition Cloning.h:98
bool ContainsCalls
This is set to true if the cloned code contains a normal call instruction.
Definition Cloning.h:71
bool ContainsMemProfMetadata
This is set to true if there is memprof related metadata (memprof or callsite metadata) in the cloned...
Definition Cloning.h:75
SmallSetVector< const Value *, 4 > OriginallyIndirectCalls
Definition Cloning.h:94
std::vector< WeakTrackingVH > OperandBundleCallSites
All cloned call sites that have operand bundles attached are appended to this vector.
Definition Cloning.h:85
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:111
Align valueOrOne() const
For convenience, returns a valid alignment or 1 if undefined.
Definition Alignment.h:135
static Instruction * tryGetVTableInstruction(CallBase *CB)
static std::optional< uint32_t > extractDwarfBaseDiscriminator(uint32_t Value)
Definition PseudoProbe.h:81
Helper struct for trackAssignments, below.
Definition DebugInfo.h:250