77#include <initializer_list>
82#define DEBUG_TYPE "coro-split"
94 Builder.SetInsertPoint(CB);
105 Builder.CreateInvoke(
Wrapper, Invoke->getNormalDest(),
106 Invoke->getUnwindDest(), {Awaiter, FramePtr});
108 WrapperInvoke->setCallingConv(Invoke->getCallingConv());
109 std::copy(Invoke->bundle_op_info_begin(), Invoke->bundle_op_info_end(),
110 WrapperInvoke->bundle_op_info_begin());
111 WrapperInvoke->setAttributes(NewAttributes);
112 WrapperInvoke->setDebugLoc(Invoke->getDebugLoc());
113 NewCall = WrapperInvoke;
117 WrapperCall->setAttributes(NewAttributes);
118 WrapperCall->setDebugLoc(
Call->getDebugLoc());
119 NewCall = WrapperCall;
125 Intrinsic::coro_await_suspend_handle) {
130 Builder.SetInsertPoint(Invoke->getNormalDest()->getFirstInsertionPt());
135 &*Builder.GetInsertPoint());
140 auto *ResumeCall = Builder.CreateCall(ResumeTy, ResumeAddr, {NewCall});
146 NewCall = ResumeCall;
175 return Builder.CreateInBoundsPtrAdd(
FramePtr,
Offset,
"destroy.addr");
191 DestroyAddr,
"destroy");
195 EntryBuilder.
CreateICmpEQ(DestroyFn, CleanupFn,
"is.elided");
207 Builder.CreateSelect(IsElided,
Null,
FramePtr,
"coro.free");
215 CF->eraseFromParent();
227 Builder.CreateRetVoid();
231 auto *MustTailCallFunc = EndAsync->getMustTailCallFunction();
232 if (!MustTailCallFunc) {
233 Builder.CreateRetVoid();
239 auto *MustTailCallFuncBlock = CoroEndBlock->getSinglePredecessor();
240 assert(MustTailCallFuncBlock &&
"Must have a single predecessor block");
241 auto It = MustTailCallFuncBlock->getTerminator()->getIterator();
243 CoroEndBlock->splice(End->
getIterator(), MustTailCallFuncBlock,
244 MustTailCall->getIterator());
247 Builder.SetInsertPoint(End);
248 Builder.CreateRetVoid();
253 BB->splitBasicBlock(End);
254 BB->getTerminator()->eraseFromParent();
257 assert(InlineRes.isSuccess() &&
"Expected inlining to succeed");
276 "switch coroutine should not return any values");
281 Builder.CreateRetVoid();
287 if (!CoroEndBlockNeedsCleanup)
299 if (!CoroEnd->hasResults()) {
300 assert(RetTy->isVoidTy());
301 Builder.CreateRetVoid();
305 auto *CoroResults = CoroEnd->getResults();
306 unsigned NumReturns = CoroResults->numReturns();
309 assert(RetStructTy->getNumElements() == NumReturns &&
310 "numbers of returns should match resume function singature");
313 for (
Value *RetValEl : CoroResults->return_values())
314 ReturnValue = Builder.CreateInsertValue(ReturnValue, RetValEl, Idx++);
315 Builder.CreateRet(ReturnValue);
316 }
else if (NumReturns == 0) {
317 assert(RetTy->isVoidTy());
318 Builder.CreateRetVoid();
321 Builder.CreateRet(*CoroResults->retval_begin());
323 CoroResults->replaceAllUsesWith(
325 CoroResults->eraseFromParent();
333 "retcon coroutine should not return any values");
345 Builder.CreateRet(ReturnValue);
352 BB->splitBasicBlock(End);
353 BB->getTerminator()->eraseFromParent();
361 return Builder.CreateInBoundsPtrAdd(
FramePtr,
Offset,
"index.addr");
376 "markCoroutineAsDone is only supported for Switch-Resumed ABI for now.");
379 Builder.CreateStore(NullPtr,
FramePtr);
392 "The final suspend should only live in the last position of "
396 Builder.CreateStore(IndexVal, FinalIndex);
432 auto *CleanupRet = Builder.CreateCleanupRet(FromPad,
nullptr);
434 CleanupRet->getParent()->getTerminator()->eraseFromParent();
458 Shape.SwitchLowering.HasFinalSuspend);
464 auto FinalCaseIt = std::prev(
Switch->case_end());
465 BasicBlock *ResumeBB = FinalCaseIt->getCaseSuccessor();
476 if (
NewF->isCoroOnlyDestroyWhenComplete()) {
485 auto *Br =
Builder.CreateCondBr(
Cond, ResumeBB, NewSwitchBB);
499 auto &Context = Suspend->
getParent()->getParent()->getContext();
517 M->getFunctionList().insert(InsertBefore, NewF);
531 if (NewS->use_empty())
539 for (
auto I = IsAsyncABI ?
NewF->arg_begin() : std::next(
NewF->arg_begin()),
548 NewS->replaceAllUsesWith(Args.front());
555 if (!EVI || EVI->getNumIndices() != 1)
558 EVI->replaceAllUsesWith(Args[EVI->getIndices().front()]);
559 EVI->eraseFromParent();
563 if (NewS->use_empty())
569 Aggr =
Builder.CreateInsertValue(Aggr, Arg, Idx);
571 NewS->replaceAllUsesWith(Aggr);
575 Value *SuspendResult;
606 MappedCS->replaceAllUsesWith(SuspendResult);
607 MappedCS->eraseFromParent();
621 auto &Ctx =
OrigF.getContext();
622 for (
auto *
II :
Shape.CoroIsInRampInsts) {
625 NewII->eraseFromParent();
633 Value *CachedSlot =
nullptr;
634 auto getSwiftErrorSlot = [&](
Type *ValueTy) ->
Value * {
639 for (
auto &Arg :
F.args()) {
640 if (Arg.isSwiftError()) {
647 IRBuilder<> Builder(
F.getEntryBlock().getFirstNonPHIOrDbg());
648 auto Alloca = Builder.CreateAlloca(ValueTy);
649 Alloca->setSwiftError(
true);
661 if (
Op->arg_empty()) {
662 auto ValueTy =
Op->getType();
663 auto Slot = getSwiftErrorSlot(ValueTy);
664 MappedResult = Builder.CreateLoad(ValueTy, Slot);
667 auto Value = MappedOp->getArgOperand(0);
669 auto Slot = getSwiftErrorSlot(ValueTy);
670 Builder.CreateStore(
Value, Slot);
675 MappedOp->eraseFromParent();
679 if (VMap ==
nullptr) {
692 return DbgVariableRecords;
704 bool UseEntryValue =
OrigF.getParent()->getTargetTriple().isArch64Bit();
711 auto IsUnreachableBlock = [&](
BasicBlock *BB) {
716 if (IsUnreachableBlock(DVI->getParent()))
717 DVI->eraseFromParent();
721 for (
auto *
User : DVI->getVariableLocationOp(0)->
users())
726 DVI->eraseFromParent();
729 for_each(DbgVariableRecords, RemoveOne);
739 auto *OldEntry = &
NewF->getEntryBlock();
740 Entry->setName(
"entry" +
Suffix);
741 Entry->moveBefore(OldEntry);
742 Entry->getTerminator()->eraseFromParent();
747 assert(Entry->hasOneUse());
749 Builder.SetInsertPoint(BranchToEntry);
751 BranchToEntry->eraseFromParent();
762 SwitchBB->moveAfter(Entry);
778 Builder.CreateBr(Branch->getSuccessor(0));
789 if (!Alloca ||
I.use_empty())
794 I.moveBefore(*Entry, Entry->getFirstInsertionPt());
805 return &*
NewF->arg_begin();
813 auto ContextIdx = ActiveAsyncSuspend->getStorageArgumentIndex() & 0xff;
814 auto *CalleeContext =
NewF->getArg(ContextIdx);
815 auto *ProjectionFunc =
816 ActiveAsyncSuspend->getAsyncContextProjectionFunction();
820 auto *CallerContext =
Builder.CreateCall(ProjectionFunc->getFunctionType(),
821 ProjectionFunc, CalleeContext);
822 CallerContext->setCallingConv(ProjectionFunc->getCallingConv());
823 CallerContext->setDebugLoc(DbgLoc);
825 auto &Context =
Builder.getContext();
826 auto *FramePtrAddr =
Builder.CreateInBoundsPtrAdd(
829 Shape.AsyncLowering.FrameOffset),
830 "async.ctx.frameptr");
834 assert(InlineRes.isSuccess());
845 if (
Shape.RetconLowering.IsFrameInlineInStorage)
849 return Builder.CreateLoad(FramePtrTy, NewStorage);
869 if (SPToUpdate.
getFile() ==
DL->getFile())
870 SPToUpdate.setScopeLine(
DL->getLine());
878 for (
unsigned Repeat = 0; Repeat < 2; Repeat++) {
882 Successor = Branch->getSuccessor()->getFirstNonPHIOrDbg();
891 if (!
DL ||
DL.getLine() == 0)
894 if (SPToUpdate.
getFile() ==
DL->getFile()) {
895 SPToUpdate.setScopeLine(
DL.getLine());
904 if (SPToUpdate.
getFile() ==
DL->getFile())
905 SPToUpdate.setScopeLine(
DL->getLine());
910 Align Alignment,
bool NoAlias) {
911 AttrBuilder ParamAttrs(Context);
912 ParamAttrs.addAttribute(Attribute::NonNull);
913 ParamAttrs.addAttribute(Attribute::NoUndef);
916 ParamAttrs.addAttribute(Attribute::NoAlias);
918 ParamAttrs.addAlignmentAttr(Alignment);
919 ParamAttrs.addDereferenceableAttr(
Size);
920 Attrs = Attrs.addParamAttributes(Context, ParamIndex, ParamAttrs);
924 unsigned ParamIndex) {
925 AttrBuilder ParamAttrs(Context);
926 ParamAttrs.addAttribute(Attribute::SwiftAsync);
927 Attrs = Attrs.addParamAttributes(Context, ParamIndex, ParamAttrs);
931 unsigned ParamIndex) {
932 AttrBuilder ParamAttrs(Context);
933 ParamAttrs.addAttribute(Attribute::SwiftSelf);
934 Attrs = Attrs.addParamAttributes(Context, ParamIndex, ParamAttrs);
957 auto savedVisibility =
NewF->getVisibility();
958 auto savedUnnamedAddr =
NewF->getUnnamedAddr();
959 auto savedDLLStorageClass =
NewF->getDLLStorageClass();
964 auto savedLinkage =
NewF->getLinkage();
970 auto &Context =
NewF->getContext();
973 assert(SP !=
OrigF.getSubprogram() && SP->isDistinct());
979 SP->replaceLinkageName(NewLinkageName);
981 TempDISubprogram NewDecl = Decl->clone();
982 NewDecl->replaceLinkageName(NewLinkageName);
987 NewF->setLinkage(savedLinkage);
988 NewF->setVisibility(savedVisibility);
989 NewF->setUnnamedAddr(savedUnnamedAddr);
990 NewF->setDLLStorageClass(savedDLLStorageClass);
995 NewF->hasMetadata(LLVMContext::MD_func_sanitize))
996 NewF->eraseMetadata(LLVMContext::MD_func_sanitize);
999 auto OrigAttrs =
NewF->getAttributes();
1002 switch (
Shape.ABI) {
1006 NewAttrs = NewAttrs.addFnAttributes(
1007 Context, AttrBuilder(Context, OrigAttrs.getFnAttrs()));
1010 Shape.FrameAlign,
false);
1014 if (
OrigF.hasParamAttribute(
Shape.AsyncLowering.ContextArgNo,
1015 Attribute::SwiftAsync)) {
1017 ActiveAsyncSuspend->getStorageArgumentIndex();
1018 auto ContextArgIndex = ArgAttributeIndices & 0xff;
1023 auto SwiftSelfIndex = ArgAttributeIndices >> 8;
1029 auto FnAttrs =
OrigF.getAttributes().getFnAttrs();
1030 NewAttrs = NewAttrs.addFnAttributes(Context, AttrBuilder(Context, FnAttrs));
1037 NewAttrs =
Shape.RetconLowering.ResumePrototype->getAttributes();
1041 Shape.getRetconCoroId()->getStorageSize(),
1042 Shape.getRetconCoroId()->getStorageAlignment(),
1048 switch (
Shape.ABI) {
1073 NewF->setAttributes(NewAttrs);
1074 NewF->setCallingConv(
Shape.getResumeFunctionCC());
1082 if (
TTI.supportsTailCallFor(ResumeCall)) {
1097 Builder.SetInsertPoint(&
NewF->getEntryBlock().front());
1106 auto *NewVFrame =
Builder.CreateBitCast(
1109 if (OldVFrame != NewVFrame)
1116 DummyArg->deleteValue();
1119 switch (
Shape.ABI) {
1124 if (
Shape.SwitchLowering.HasFinalSuspend)
1133 "no active suspend when lowering a continuation-style coroutine");
1164 Shape.ResumeEntryCount.has_value()) {
1165 NewF->setEntryCount(
Shape.ResumeEntryCount.value());
1178 auto *OrigRelativeFunOffset = FuncPtrStruct->getOperand(0);
1179 auto *OrigContextSize = FuncPtrStruct->getOperand(1);
1180 auto *NewContextSize = ConstantInt::get(OrigContextSize->getType(),
1183 FuncPtrStruct->getType(), OrigRelativeFunOffset, NewContextSize);
1202 auto *SizeIntrin = Shape.
CoroSizes.back();
1203 auto *SizeConstant = ConstantInt::get(SizeIntrin->getType(),
1228 switch (Shape.
ABI) {
1237 auto *Frame = Builder.CreateAlloca(
1238 FrameTy,
nullptr, AllocInst->getFunction()->getName() +
".Frame");
1240 AllocInst->replaceAllUsesWith(Builder.getFalse());
1241 AllocInst->eraseFromParent();
1242 CoroBegin->replaceAllUsesWith(Frame);
1244 CoroBegin->replaceAllUsesWith(CoroBegin->getMem());
1285 while (!Worklist.
empty()) {
1289 if (!Set.contains(Pred))
1295 Set.erase(ResDesBB);
1297 for (
auto *BB : Set)
1306 auto *ResumeOrDestroyBB = ResumeOrDestroy->
getParent();
1310 if (SaveBB == ResumeOrDestroyBB)
1319 {ResumeOrDestroyBB->getFirstNonPHIIt(), ResumeOrDestroyIt}))
1335 auto *Pred = Suspend->
getParent()->getSinglePredecessor();
1338 Prev = Pred->getTerminator();
1353 if (SubFn->getFrame() != CoroBegin)
1367 Save->eraseFromParent();
1379 if (CalledValue != SubFn && CalledValue->user_empty())
1381 I->eraseFromParent();
1384 if (SubFn->user_empty())
1385 SubFn->eraseFromParent();
1397 size_t I = 0,
N = S.size();
1401 size_t ChangedFinalIndex = std::numeric_limits<size_t>::max();
1414 ChangedFinalIndex =
I;
1426 if (ChangedFinalIndex <
N) {
1428 std::swap(S[ChangedFinalIndex], S.back());
1434struct SwitchCoroutineSplitter {
1436 SmallVectorImpl<Function *> &Clones,
1437 TargetTransformInfo &
TTI) {
1443 createResumeEntryBlock(
F, Shape);
1445 F,
".resume", Shape, coro::CloneKind::SwitchResume,
TTI);
1447 F,
".destroy", Shape, coro::CloneKind::SwitchUnwind,
TTI);
1449 F,
".cleanup", Shape, coro::CloneKind::SwitchCleanup,
TTI);
1459 updateCoroFrame(Shape, ResumeClone, DestroyClone, CleanupClone);
1469 setCoroInfo(
F, Shape, Clones);
1480 SmallVectorImpl<Function *> &Clones) {
1482 auto *OrigFnTy =
F.getFunctionType();
1483 auto OldParams = OrigFnTy->params();
1486 NewParams.
reserve(OldParams.size() + 1);
1487 NewParams.
append(OldParams.begin(), OldParams.end());
1490 auto *NewFnTy = FunctionType::get(OrigFnTy->getReturnType(), NewParams,
1491 OrigFnTy->isVarArg());
1493 NewFnTy,
F.getLinkage(),
F.getAddressSpace(),
F.getName() +
".noalloc");
1496 unsigned int Idx = 0;
1497 for (
const auto &
I :
F.args()) {
1498 VMap[&
I] = NoAllocF->
getArg(Idx++);
1502 auto FrameIdx = NoAllocF->
arg_size() - 1;
1505 CloneFunctionChangeType::LocalChangesOnly, Returns);
1508 auto *NewCoroBegin =
1512 NewCoroBegin->replaceAllUsesWith(NoAllocF->
getArg(FrameIdx));
1513 NewCoroBegin->eraseFromParent();
1517 M->getFunctionList().insert(
M->end(), NoAllocF);
1532 setCoroInfo(
F, Shape, Clones);
1543 static void createResumeEntryBlock(
Function &
F, coro::Shape &Shape) {
1546 DIBuilder DBuilder(*
F.getParent(),
false);
1547 DISubprogram *DIS =
F.getSubprogram();
1551 bool AddDebugLabels = DIS && DIS->getUnit() &&
1552 (DIS->getUnit()->getEmissionKind() ==
1553 DICompileUnit::DebugEmissionKind::FullDebug);
1572 Builder.CreateSwitch(Index, UnreachBB, Shape.
CoroSuspends.size());
1576 size_t SuspendIndex = 0;
1577 SmallVector<uint64_t, 8> SwitchWeights64;
1583 ConstantInt *IndexVal = Shape.
getIndex(SuspendIndex);
1588 auto *Save = S->getCoroSave();
1589 Builder.SetInsertPoint(Save);
1596 Builder.CreateStore(IndexVal, GepIndex);
1600 Save->eraseFromParent();
1626 auto *SuspendBB = S->getParent();
1628 SuspendBB->splitBasicBlock(S,
"resume." + Twine(SuspendIndex));
1629 auto *LandingBB = ResumeBB->splitBasicBlock(
1630 S->getNextNode(), ResumeBB->getName() + Twine(
".landing"));
1631 Switch->addCase(IndexVal, ResumeBB);
1637 Weight = It->second;
1643 PN->insertBefore(LandingBB->begin());
1644 S->replaceAllUsesWith(PN);
1645 PN->addIncoming(Builder.getInt8(-1), SuspendBB);
1646 PN->addIncoming(S, ResumeBB);
1648 if (AddDebugLabels) {
1649 if (
DebugLoc SuspendLoc = S->getDebugLoc()) {
1650 std::string LabelName =
1651 (
"__coro_resume_" + Twine(SuspendIndex)).str();
1657 DILocation *DILoc = SuspendLoc;
1658 while (DILocation *InlinedAt = DILoc->getInlinedAt())
1661 DILabel *ResumeLabel =
1662 DBuilder.createLabel(DIS, LabelName, DILoc->getFile(),
1663 SuspendLoc.getLine(), SuspendLoc.getCol(),
1667 DBuilder.insertLabel(ResumeLabel, DILoc, ResumeBB->begin());
1677 Switch->setMetadata(LLVMContext::MD_prof,
1678 MDB.createBranchWeights(SwitchWeights32));
1681 Builder.SetInsertPoint(UnreachBB);
1682 Builder.CreateUnreachable();
1683 DBuilder.finalize();
1689 static void updateCoroFrame(coro::Shape &Shape,
Function *ResumeFn,
1696 Builder.CreateStore(ResumeFn, ResumeAddr);
1698 Value *DestroyOrCleanupFn = DestroyFn;
1704 DestroyOrCleanupFn = Builder.CreateSelect(CA, DestroyFn, CleanupFn);
1712 Value *DestroyAddr = Builder.CreateInBoundsPtrAdd(
1714 ConstantInt::get(Type::getInt64Ty(
C),
1717 Builder.CreateStore(DestroyOrCleanupFn, DestroyAddr);
1733 static void setCoroInfo(
Function &
F, coro::Shape &Shape,
1737 SmallVector<Constant *, 4>
Args(Fns);
1741 auto *ArrTy = ArrayType::get(Part->
getType(),
Args.size());
1744 auto *GV =
new GlobalVariable(*M, ConstVal->getType(),
true,
1745 GlobalVariable::PrivateLinkage, ConstVal,
1746 F.getName() + Twine(
".resumers"));
1749 LLVMContext &
C =
F.getContext();
1760 auto &Context = Suspend->
getParent()->getParent()->getContext();
1764 auto *Val = Builder.CreateBitOrPointerCast(
Continuation, Int8PtrTy);
1765 ResumeIntrinsic->replaceAllUsesWith(Val);
1766 ResumeIntrinsic->eraseFromParent();
1776 for (
auto *paramTy : FnTy->params()) {
1778 if (paramTy != FnArgs[ArgIdx]->
getType())
1780 Builder.CreateBitOrPointerCast(FnArgs[ArgIdx], paramTy));
1797 auto *TailCall = Builder.CreateCall(FnTy, MustTailCallFn, CallArgs);
1799 if (
TTI.supportsTailCallFor(TailCall)) {
1802 TailCall->setDebugLoc(
Loc);
1814 F.removeFnAttr(Attribute::NoReturn);
1815 F.removeRetAttr(Attribute::NoAlias);
1816 F.removeRetAttr(Attribute::NonNull);
1818 auto &Context =
F.getContext();
1821 auto *Id =
Shape.getAsyncCoroId();
1826 FramePtr = Builder.CreateInBoundsPtrAdd(
1829 Shape.AsyncLowering.FrameOffset),
1830 "async.ctx.frameptr");
1841 auto NextF = std::next(
F.getIterator());
1849 auto ResumeNameSuffix =
".resume.";
1850 auto ProjectionFunctionName =
1851 Suspend->getAsyncContextProjectionFunction()->getName();
1852 bool UseSwiftMangling =
false;
1853 if (ProjectionFunctionName ==
"__swift_async_resume_project_context") {
1854 ResumeNameSuffix =
"TQ";
1855 UseSwiftMangling =
true;
1856 }
else if (ProjectionFunctionName ==
"__swift_async_resume_get_context") {
1857 ResumeNameSuffix =
"TY";
1858 UseSwiftMangling =
true;
1862 UseSwiftMangling ? ResumeNameSuffix +
Twine(Idx) +
"_"
1863 : ResumeNameSuffix +
Twine(Idx),
1869 auto *SuspendBB = Suspend->getParent();
1870 auto *NewSuspendBB = SuspendBB->splitBasicBlock(Suspend);
1876 Branch->setSuccessor(0, ReturnBB);
1881 auto *Fn = Suspend->getMustTailCallFunction();
1887 Builder.CreateRetVoid();
1899 auto *Clone = Clones[Idx];
1914 F.removeFnAttr(Attribute::NoReturn);
1915 F.removeRetAttr(Attribute::NoAlias);
1916 F.removeRetAttr(Attribute::NonNull);
1919 auto *Id =
Shape.getRetconCoroId();
1921 if (
Shape.RetconLowering.IsFrameInlineInStorage) {
1922 RawFramePtr = Id->getStorage();
1926 auto FrameSize = Builder.getInt64(
Shape.FrameSize);
1931 RawFramePtr =
Shape.emitAlloc(Builder, FrameSize,
nullptr);
1933 Builder.CreateBitCast(RawFramePtr,
Shape.CoroBegin->getType());
1936 Builder.CreateStore(RawFramePtr, Id->getStorage());
1943 Shape.CoroBegin->replaceAllUsesWith(RawFramePtr);
1949 PHINode *ContinuationPhi =
nullptr;
1953 auto NextF = std::next(
F.getIterator());
1962 F,
Shape,
".resume." +
Twine(Idx), NextF,
nullptr);
1967 auto SuspendBB = Suspend->getParent();
1968 auto NewSuspendBB = SuspendBB->splitBasicBlock(Suspend);
1976 Shape.RetconLowering.ReturnBlock = ReturnBB;
1988 for (
auto *ResultTy :
Shape.getRetconResultTypes())
1990 Builder.CreatePHI(ResultTy,
Shape.CoroSuspends.size()));
1993 auto RetTy =
F.getReturnType();
1998 auto CastedContinuationTy =
1999 (ReturnPHIs.
empty() ? RetTy : RetTy->getStructElementType(0));
2000 auto *CastedContinuation =
2001 Builder.CreateBitCast(ContinuationPhi, CastedContinuationTy);
2003 Value *RetV = CastedContinuation;
2004 if (!ReturnPHIs.
empty()) {
2007 RetV = Builder.CreateInsertValue(RetV, CastedContinuation, ValueIdx++);
2009 for (
auto Phi : ReturnPHIs)
2010 RetV = Builder.CreateInsertValue(RetV, Phi, ValueIdx++);
2013 Builder.CreateRet(RetV);
2017 Branch->setSuccessor(0, ReturnBB);
2020 for (
auto [Phi, VUse] :
2022 Phi->addIncoming(VUse, SuspendBB);
2029 auto Clone = Clones[Idx];
2043 OS <<
"While splitting coroutine ";
2044 F.printAsOperand(OS,
false,
F.getParent());
2064 auto &Ctx =
II->getContext();
2066 II->eraseFromParent();
2071 for (
auto *U :
F.users()) {
2073 auto *Caller = CB->getFunction();
2074 if (Caller && Caller->isPresplitCoroutine() &&
2075 CB->hasFnAttr(llvm::Attribute::CoroElideSafe))
2085 SwitchCoroutineSplitter::split(
F,
Shape, Clones,
TTI);
2090 bool OptimizeFrame) {
2091 PrettyStackTraceFunction prettyStackTrace(
F);
2093 auto &Shape = ABI.
Shape;
2101 ABI.buildCoroutineFrame(OptimizeFrame);
2104 bool isNoSuspendCoroutine = Shape.
CoroSuspends.empty();
2106 bool shouldCreateNoAllocVariant =
2111 shouldCreateNoAllocVariant;
2115 if (isNoSuspendCoroutine) {
2118 ABI.splitCoroutine(
F, Shape, Clones,
TTI);
2136 if (shouldCreateNoAllocVariant)
2137 SwitchCoroutineSplitter::createNoAllocVariant(
F, Shape, Clones);
2146 auto *CurrentSCC = &
C;
2147 if (!Clones.
empty()) {
2148 switch (Shape.
ABI) {
2154 assert(Clones.
size() >= 3 &&
"expected switch coroutine clones");
2172 if (!Clones.
empty())
2205 if (!Cast || Cast->getType() != Fn->getType())
2209 Cast->replaceAllUsesWith(Fn);
2210 Cast->eraseFromParent();
2220 if (!Cast->use_empty())
2222 CastFn = Cast->getOperand(0);
2223 Cast->eraseFromParent();
2243 auto *PrepareFn = M.getFunction(Name);
2244 if (PrepareFn && !PrepareFn->use_empty())
2248static std::unique_ptr<coro::BaseABI>
2254 if (CustomABI >= GenCustomABIs.
size())
2256 return GenCustomABIs[CustomABI](
F, S);
2261 return std::make_unique<coro::SwitchABI>(
F, S, IsMatCallback);
2263 return std::make_unique<coro::AsyncABI>(
F, S, IsMatCallback);
2265 return std::make_unique<coro::AnyRetconABI>(
F, S, IsMatCallback);
2267 return std::make_unique<coro::AnyRetconABI>(
F, S, IsMatCallback);
2274 std::unique_ptr<coro::BaseABI> ABI =
2279 OptimizeFrame(OptimizeFrame) {}
2284 std::unique_ptr<coro::BaseABI> ABI =
2289 OptimizeFrame(OptimizeFrame) {}
2296 std::unique_ptr<coro::BaseABI> ABI =
2301 OptimizeFrame(OptimizeFrame) {}
2309 std::unique_ptr<coro::BaseABI> ABI =
2314 OptimizeFrame(OptimizeFrame) {}
2322 Module &M = *
C.begin()->getFunction().getParent();
2334 if (
N.getFunction().isPresplitCoroutine())
2337 if (Coroutines.
empty() && PrepareFns.
empty())
2340 auto *CurrentSCC = &
C;
2344 LLVM_DEBUG(
dbgs() <<
"CoroSplit: Processing coroutine '" <<
F.getName()
2356 F.setSplittedCoroutine();
2362 uint64_t Freq = BFI.getBlockFreq(BB).getFrequency();
2367 std::optional<uint64_t>
Count = BFI.getBlockProfileCount(BB);
2368 if (
Count.has_value()) {
2386 *
N, Shape, Clones, *CurrentSCC, CG, AM, UR,
FAM);
2391 <<
"Split '" <<
ore::NV(
"function",
F.getName())
2408 for (
auto *PrepareFn : PrepareFns) {
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
amdgpu aa AMDGPU Address space based Alias Analysis Wrapper
AMDGPU Lower Kernel Arguments
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
Expand Atomic instructions
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
This file provides interfaces used to manipulate a call graph, regardless if it is a "old style" Call...
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...
static void addSwiftSelfAttrs(AttributeList &Attrs, LLVMContext &Context, unsigned ParamIndex)
static bool hasCallsBetween(Instruction *Save, Instruction *ResumeOrDestroy)
static LazyCallGraph::SCC & updateCallGraphAfterCoroutineSplit(LazyCallGraph::Node &N, const coro::Shape &Shape, const SmallVectorImpl< Function * > &Clones, LazyCallGraph::SCC &C, LazyCallGraph &CG, CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR, FunctionAnalysisManager &FAM)
static void replaceFallthroughCoroEnd(AnyCoroEndInst *End, const coro::Shape &Shape, Value *FramePtr, bool InRamp, CallGraph *CG)
Replace a non-unwind call to llvm.coro.end.
static void replaceSwiftErrorOps(Function &F, coro::Shape &Shape, ValueToValueMapTy *VMap)
static void replaceCoroEnd(AnyCoroEndInst *End, const coro::Shape &Shape, Value *FramePtr, bool InRamp, CallGraph *CG)
static void addAsyncContextAttrs(AttributeList &Attrs, LLVMContext &Context, unsigned ParamIndex)
static void maybeFreeRetconStorage(IRBuilder<> &Builder, const coro::Shape &Shape, Value *FramePtr, CallGraph *CG)
static bool hasCallsInBlocksBetween(BasicBlock *SaveBB, BasicBlock *ResDesBB)
static Function * createCloneDeclaration(Function &OrigF, coro::Shape &Shape, const Twine &Suffix, Module::iterator InsertBefore, AnyCoroSuspendInst *ActiveSuspend)
static FunctionType * getFunctionTypeFromAsyncSuspend(AnyCoroSuspendInst *Suspend)
static void updateScopeLine(Instruction *ActiveSuspend, DISubprogram &SPToUpdate)
Adjust the scope line of the funclet to the first line number after the suspend point.
static void removeCoroIsInRampFromRampFunction(const coro::Shape &Shape)
static void replaceSwitchResumeCoroFree(const coro::Shape &Shape, Function &Resume, Function &Cleanup)
Make resume-clone coro.free conditional on whether the frame is elided.
static void addPrepareFunction(const Module &M, SmallVectorImpl< Function * > &Fns, StringRef Name)
static Value * createSwitchDestroyPtr(const coro::Shape &Shape, IRBuilder<> &Builder, Value *FramePtr)
Create a pointer to the switch destroy function field in the coroutine frame.
static SmallVector< DbgVariableRecord * > collectDbgVariableRecords(Function &F)
Returns all debug records in F.
static void simplifySuspendPoints(coro::Shape &Shape)
static void addFramePointerAttrs(AttributeList &Attrs, LLVMContext &Context, unsigned ParamIndex, uint64_t Size, Align Alignment, bool NoAlias)
static bool hasSafeElideCaller(Function &F)
static bool replaceAllPrepares(Function *PrepareFn, LazyCallGraph &CG, LazyCallGraph::SCC &C)
static void replaceFrameSizeAndAlignment(coro::Shape &Shape)
static std::unique_ptr< coro::BaseABI > CreateNewABI(Function &F, coro::Shape &S, std::function< bool(Instruction &)> IsMatCallback, const SmallVector< CoroSplitPass::BaseABITy > GenCustomABIs)
static bool replaceCoroEndAsync(AnyCoroEndInst *End)
Replace an llvm.coro.end.async.
static void doSplitCoroutine(Function &F, SmallVectorImpl< Function * > &Clones, coro::BaseABI &ABI, TargetTransformInfo &TTI, bool OptimizeFrame)
static bool hasCallsInBlockBetween(iterator_range< BasicBlock::iterator > R)
static bool simplifySuspendPoint(CoroSuspendInst *Suspend, CoroBeginInst *CoroBegin)
static Value * createSwitchIndexPtr(const coro::Shape &Shape, IRBuilder<> &Builder, Value *FramePtr)
Create a pointer to the switch index field in the coroutine frame.
static void removeCoroEndsFromRampFunction(const coro::Shape &Shape)
Remove calls to llvm.coro.end in the original function.
static void markCoroutineAsDone(IRBuilder<> &Builder, const coro::Shape &Shape, Value *FramePtr)
static void updateAsyncFuncPointerContextSize(coro::Shape &Shape)
static void coerceArguments(IRBuilder<> &Builder, FunctionType *FnTy, ArrayRef< Value * > FnArgs, SmallVectorImpl< Value * > &CallArgs)
Coerce the arguments in FnArgs according to FnTy in CallArgs.
static void replaceUnwindCoroEnd(AnyCoroEndInst *End, const coro::Shape &Shape, Value *FramePtr, bool InRamp, CallGraph *CG)
Replace an unwind call to llvm.coro.end.
static void lowerAwaitSuspend(IRBuilder<> &Builder, CoroAwaitSuspendInst *CB, coro::Shape &Shape)
static void lowerAwaitSuspends(Function &F, coro::Shape &Shape)
static void handleNoSuspendCoroutine(coro::Shape &Shape)
static void postSplitCleanup(Function &F)
static void replacePrepare(CallInst *Prepare, LazyCallGraph &CG, LazyCallGraph::SCC &C)
Replace a call to llvm.coro.prepare.retcon.
static void replaceAsyncResumeFunction(CoroSuspendAsyncInst *Suspend, Value *Continuation)
This file defines the DenseMap class.
This file contains constants used for implementing Dwarf debug support.
ManagedStatic< HTTPClientCleanup > Cleanup
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.
Implements a lazy call graph analysis and related passes for the new pass manager.
Machine Check Debug Module
uint64_t IntrinsicInst * II
FunctionAnalysisManager FAM
This file provides a priority worklist.
This file contains the declarations for profiling metadata utility functions.
const SmallVectorImpl< MachineOperand > & Cond
Remove Loads Into Fake Uses
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
static SymbolRef::Type getType(const Symbol *Sym)
static const unsigned FramePtr
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
CoroAllocInst * getCoroAlloc()
This class represents an incoming formal argument to a Function.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
Get the array size.
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
LLVM Basic Block Representation.
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.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
InstListType::iterator iterator
Instruction iterators...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Analysis pass which computes BlockFrequencyInfo.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
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...
Value * getCalledOperand() const
Value * getArgOperand(unsigned i) const
AttributeList getAttributes() const
Return the attributes for this call.
The basic data container for the call graph of a Module of IR.
This class represents a function call, abstracting a target machine's calling convention.
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * getPointerCast(Constant *C, Type *Ty)
Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant expression.
This is the shared class of boolean and integer constants.
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
static LLVM_ABI ConstantTokenNone * get(LLVMContext &Context)
Return the ConstantTokenNone.
This represents the llvm.coro.align instruction.
This represents the llvm.coro.await.suspend.{void,bool,handle} instructions.
Value * getAwaiter() const
Function * getWrapperFunction() const
This class represents the llvm.coro.begin or llvm.coro.begin.custom.abi instructions.
bool hasCustomABI() const
This represents the llvm.coro.free instruction.
void setInfo(Constant *C)
This represents the llvm.coro.size instruction.
This represents the llvm.coro.suspend.async instruction.
CoroAsyncResumeInst * getResumeFunction() const
This represents the llvm.coro.suspend instruction.
CoroSaveInst * getCoroSave() const
Subprogram description. Uses SubclassData1.
Record of a variable value-assignment, aka a non instruction representation of the dbg....
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
LLVM_ABI bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
This class represents a freeze function that returns random concrete value if an operand is either a ...
A proxy from a FunctionAnalysisManager to an SCC.
Class to represent function types.
Type * getReturnType() const
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
const BasicBlock & getEntryBlock() const
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
AttributeList getAttributes() const
Return the attribute list for this Function.
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Argument * getArg(unsigned i) const
void setLinkage(LinkageTypes LT)
unsigned getAddressSpace() const
Module * getParent()
Get the module that this global value is contained inside of...
PointerType * getType() const
Global values are always pointers.
@ InternalLinkage
Rename collisions when linking (static functions).
@ ExternalLinkage
Externally visible function.
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
LLVM_ABI void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
Value * CreatePointerCast(Value *V, Type *DestTy, const Twine &Name="")
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
This class captures the data input to the InlineFunction call, and records the auxiliary results prod...
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
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.
This is an important class for using LLVM in a threaded context.
A node in the call graph.
An SCC of the call graph.
A lazily constructed view of the call graph of a module.
LLVM_ABI void addSplitFunction(Function &OriginalFunction, Function &NewFunction)
Add a new function split/outlined from an existing function.
LLVM_ABI void addSplitRefRecursiveFunctions(Function &OriginalFunction, ArrayRef< Function * > NewFunctions)
Add new ref-recursive functions split/outlined from an existing function.
Node & get(Function &F)
Get a graph node for a given function, scanning it to populate the graph data as necessary.
SCC * lookupSCC(Node &N) const
Lookup a function's SCC in the graph.
static std::enable_if_t< std::is_base_of< MDNode, T >::value, T * > replaceWithUniqued(std::unique_ptr< T, TempMDNodeDeleter > N)
Replace a temporary node with a uniqued one.
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
A Module instance is used to store all the information related to an LLVM module.
FunctionListType::iterator iterator
The Function iterators.
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 PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
PrettyStackTraceEntry - This class is used to represent a frame of the "pretty" stack trace that is d...
Return a value (possibly void), from a function.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void 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.
Represent a constant reference to a string, i.e.
A wrapper class to simplify modification of SwitchInst cases along with their prof branch_weights met...
LLVM_ABI SwitchInst::CaseIt removeCase(SwitchInst::CaseIt I)
Delegate the call to the underlying SwitchInst::removeCase() and remove correspondent branch weight.
Analysis pass providing the TargetTransformInfo.
Value handle that tracks a Value across RAUW.
ValueTy * getValPtr() const
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
static constexpr TypeSize getFixed(ScalarTy ExactSize)
The instances of the Type class are immutable: once they are created, they are never changed.
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
A Use represents the edge between a Value definition and its users.
void setOperand(unsigned i, Value *Val)
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
LLVMContext & getContext() const
All values hold a context through their type.
iterator_range< user_iterator > users()
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
iterator_range< use_iterator > uses()
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
void splitCoroutine(Function &F, coro::Shape &Shape, SmallVectorImpl< Function * > &Clones, TargetTransformInfo &TTI) override
void splitCoroutine(Function &F, coro::Shape &Shape, SmallVectorImpl< Function * > &Clones, TargetTransformInfo &TTI) override
void replaceSwiftErrorOps()
AnyCoroSuspendInst * ActiveSuspend
The active suspend instruction; meaningful only for continuation and async ABIs.
Value * deriveNewFramePointer()
Derive the value of the new frame pointer.
void replaceCoroSuspends()
void handleFinalSuspend()
TargetTransformInfo & TTI
static Function * createClone(Function &OrigF, const Twine &Suffix, coro::Shape &Shape, Function *NewF, AnyCoroSuspendInst *ActiveSuspend, TargetTransformInfo &TTI)
Create a clone for a continuation lowering.
void replaceCoroIsInRamp()
bool isSwitchDestroyFunction()
void replaceRetconOrAsyncSuspendUses()
Replace uses of the active llvm.coro.suspend.retcon/async call with the arguments to the continuation...
virtual void create()
Clone the body of the original function into a resume function of some sort.
void splitCoroutine(Function &F, coro::Shape &Shape, SmallVectorImpl< Function * > &Clones, TargetTransformInfo &TTI) override
static Function * createClone(Function &OrigF, const Twine &Suffix, coro::Shape &Shape, CloneKind FKind, TargetTransformInfo &TTI)
Create a clone for a switch lowering.
void create() override
Clone the body of the original function into a resume function of some sort.
const ParentTy * getParent() const
self_iterator getIterator()
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
A range adaptor for a pair of iterators.
This class implements an extremely fast bulk output stream that can only output to a stream.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
@ Async
The "async continuation" lowering, where each suspend point creates a single continuation function.
@ RetconOnce
The "unique returned-continuation" lowering, where each suspend point creates a single continuation f...
@ Retcon
The "returned-continuation" lowering, where each suspend point creates a single continuation function...
@ Switch
The "resume-switch" lowering, where there are separate resume and destroy functions that are shared b...
void suppressCoroAllocs(CoroIdInst *CoroId)
Replaces all @llvm.coro.alloc intrinsics calls associated with a given call @llvm....
void normalizeCoroutine(Function &F, coro::Shape &Shape, TargetTransformInfo &TTI)
CallInst * createMustTailCall(DebugLoc Loc, Function *MustTailCallFn, TargetTransformInfo &TTI, ArrayRef< Value * > Arguments, IRBuilder<> &)
LLVM_ABI bool isTriviallyMaterializable(Instruction &I)
@ SwitchCleanup
The shared cleanup function for a switch lowering.
@ SwitchResume
The shared resume function for a switch lowering.
@ Continuation
An individual continuation function.
void elideCoroFree(Value *FramePtr)
void salvageDebugInfo(SmallDenseMap< Argument *, AllocaInst *, 4 > &ArgToAllocaMap, DbgVariableRecord &DVR, bool UseEntryValue)
Attempts to rewrite the location operand of debug records in terms of the coroutine frame pointer,...
DiagnosticInfoOptimizationBase::Argument NV
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
auto cast_if_present(const Y &Val)
cast_if_present<X> - Functionally identical to cast, except that a null value is accepted.
UnaryFunction for_each(R &&Range, UnaryFunction F)
Provide wrappers to std::for_each which take ranges instead of having to pass begin/end explicitly.
detail::zippy< detail::zip_first, T, U, Args... > zip_equal(T &&t, U &&u, Args &&...args)
zip iterator that assumes that all iteratees have the same length.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
LLVM_ABI void setExplicitlyUnknownBranchWeightsIfProfiled(Instruction &I, StringRef PassName, const Function *F=nullptr)
Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch weights in the new instruct...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
@ Load
The value being inserted comes from a load (InsertElement only).
LLVM_ABI LazyCallGraph::SCC & updateCGAndAnalysisManagerForFunctionPass(LazyCallGraph &G, LazyCallGraph::SCC &C, LazyCallGraph::Node &N, CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR, FunctionAnalysisManager &FAM)
Helper to update the call graph after running a function pass.
LLVM_ABI LazyCallGraph::SCC & updateCGAndAnalysisManagerForCGSCCPass(LazyCallGraph &G, LazyCallGraph::SCC &C, LazyCallGraph::Node &N, CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR, FunctionAnalysisManager &FAM)
Helper to update the call graph after running a CGSCC pass.
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...
LLVM_ABI void applyProfMetadataIfEnabled(Value *V, llvm::function_ref< void(Instruction *)> setMetadataCallback)
bool isa_and_nonnull(const Y &Val)
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.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
AnalysisManager< LazyCallGraph::SCC, LazyCallGraph & > CGSCCAnalysisManager
The CGSCC analysis manager.
LLVM_ABI bool removeUnreachableBlocks(Function &F, DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool FoldInstsToUnreachable=true)
Remove all blocks that can not be reached from the function's entry.
auto dyn_cast_or_null(const Y &Val)
LLVM_ABI BasicBlock::iterator skipDebugIntrinsics(BasicBlock::iterator It)
Advance It while it points to a debug instruction and return the result.
LLVM_ABI SmallVector< uint32_t > fitWeights(ArrayRef< uint64_t > Weights)
Push the weights right to fit in uint32_t.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
iterator_range< SplittingIterator > split(StringRef Str, StringRef Separator)
Split the specified string over a separator and return a range-compatible iterable over its partition...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
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...
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
LLVM_ABI bool isPotentiallyReachable(const Instruction *From, const Instruction *To, const SmallPtrSetImpl< BasicBlock * > *ExclusionSet=nullptr, const DominatorTree *DT=nullptr, const LoopInfo *LI=nullptr, const CycleInfo *CI=nullptr)
Determine whether instruction 'To' is reachable from 'From', without passing through any blocks in Ex...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
LLVM_ABI void CloneFunctionInto(Function *NewFunc, const Function *OldFunc, ValueToValueMapTy &VMap, CloneFunctionChangeType Changes, SmallVectorImpl< ReturnInst * > &Returns, const char *NameSuffix="", ClonedCodeInfo *CodeInfo=nullptr, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Clone OldFunc into NewFunc, transforming the old arguments into references to VMap values.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
auto predecessors(const MachineBasicBlock *BB)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
This struct is a compact representation of a valid (non-zero power of two) alignment.
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Support structure for SCC passes to communicate updates the call graph back to the CGSCC pass manager...
SmallPriorityWorklist< LazyCallGraph::SCC *, 1 > & CWorklist
Worklist of the SCCs queued for processing.
LLVM_ABI PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &AM, LazyCallGraph &CG, CGSCCUpdateResult &UR)
LLVM_ABI CoroSplitPass(bool OptimizeFrame=false)
BaseABITy CreateAndInitABI
CallInst * makeSubFnCall(Value *Arg, int Index, Instruction *InsertPt)
GlobalVariable * AsyncFuncPointer
bool IsFrameInlineInStorage
bool HasCoroElideNoAllocVariant
SwitchInst * ResumeSwitch
BasicBlock * ResumeEntryBlock
SmallVector< CallInst *, 2 > SymmetricTransfers
SmallVector< CoroAwaitSuspendInst *, 4 > CoroAwaitSuspends
AsyncLoweringStorage AsyncLowering
FunctionType * getResumeFunctionType() const
IntegerType * getIndexType() const
PointerType * getSwitchResumePointerType() const
CoroIdInst * getSwitchCoroId() const
SmallVector< CoroSizeInst *, 2 > CoroSizes
SmallVector< AnyCoroSuspendInst *, 4 > CoroSuspends
std::optional< uint64_t > ResumeEntryCount
ConstantInt * getIndex(uint64_t Value) const
SwitchLoweringStorage SwitchLowering
CoroBeginInst * CoroBegin
SmallDenseMap< AnyCoroSuspendInst *, uint64_t, 4 > SuspendFreqs
BasicBlock::iterator getInsertPtAfterFramePtr() const
SmallVector< CoroIsInRampInst *, 2 > CoroIsInRampInsts
LLVM_ABI void emitDealloc(IRBuilder<> &Builder, Value *Ptr, CallGraph *CG) const
Deallocate memory according to the rules of the active lowering.
RetconLoweringStorage RetconLowering
SmallVector< CoroAlignInst *, 2 > CoroAligns
SmallVector< AnyCoroEndInst *, 4 > CoroEnds
SmallVector< CallInst *, 2 > SwiftErrorOps