68 #include <initializer_list> 73 #define DEBUG_TYPE "coro-split" 101 Value *NewFramePtr =
nullptr;
102 Value *SwiftErrorSlot =
nullptr;
111 : OrigF(OrigF), NewF(
nullptr), Suffix(Suffix), Shape(Shape),
119 : OrigF(OrigF), NewF(NewF), Suffix(Suffix), Shape(Shape),
120 FKind(Kind::Continuation), Builder(OrigF.
getContext()),
121 ActiveSuspend(ActiveSuspend) {
124 assert(NewF &&
"need existing function for continuation");
125 assert(ActiveSuspend &&
"need active suspend point for continuation");
129 assert(NewF !=
nullptr &&
"declaration not yet set");
136 bool isSwitchDestroyFunction() {
138 case Kind::Continuation:
139 case Kind::SwitchResume:
141 case Kind::SwitchUnwind:
142 case Kind::SwitchCleanup:
148 void createDeclaration();
149 void replaceEntryBlock();
150 Value *deriveNewFramePointer();
151 void replaceRetconSuspendUses();
152 void replaceCoroSuspends();
153 void replaceCoroEnds();
155 void handleFinalSuspend();
156 void maybeFreeContinuationStorage();
204 cast<PointerType>(RetStructTy ? RetStructTy->getElementType(0) : RetTy);
243 auto *FromPad = cast<CleanupPadInst>(Bundle->Inputs[0]);
292 size_t SuspendIndex = 0;
294 auto *S = cast<CoroSuspendInst>(AnyS);
300 auto *Save = S->getCoroSave();
308 cast<PointerType>(GepIndex->getType())->getElementType()));
316 Save->eraseFromParent();
341 auto *SuspendBB = S->getParent();
343 SuspendBB->splitBasicBlock(S,
"resume." +
Twine(SuspendIndex));
344 auto *LandingBB = ResumeBB->splitBasicBlock(
345 S->getNextNode(), ResumeBB->getName() +
Twine(
".landing"));
346 Switch->addCase(IndexVal, ResumeBB);
348 cast<BranchInst>(SuspendBB->getTerminator())->setSuccessor(0, LandingBB);
351 PN->addIncoming(Builder.
getInt8(-1), SuspendBB);
352 PN->addIncoming(S, ResumeBB);
373 void CoroCloner::handleFinalSuspend() {
375 Shape.SwitchLowering.HasFinalSuspend);
376 auto *Switch = cast<SwitchInst>(VMap[Shape.SwitchLowering.ResumeSwitch]);
377 auto FinalCaseIt = std::prev(Switch->case_end());
378 BasicBlock *ResumeBB = FinalCaseIt->getCaseSuccessor();
379 Switch->removeCase(FinalCaseIt);
380 if (isSwitchDestroyFunction()) {
381 BasicBlock *OldSwitchBB = Switch->getParent();
384 auto *GepIndex = Builder.CreateStructGEP(Shape.FrameTy, NewFramePtr,
387 auto *
Load = Builder.CreateLoad(Shape.getSwitchResumePointerType(),
389 auto *Cond = Builder.CreateIsNull(
Load);
390 Builder.CreateCondBr(Cond, ResumeBB, NewSwitchBB);
416 void CoroCloner::replaceRetconSuspendUses() {
420 auto NewS = VMap[ActiveSuspend];
421 if (NewS->use_empty())
return;
426 for (
auto I = std::next(NewF->arg_begin()),
E = NewF->arg_end();
I !=
E; ++
I)
431 if (!isa<StructType>(NewS->getType())) {
433 NewS->replaceAllUsesWith(Args.
front());
438 for (
auto UI = NewS->use_begin(), UE = NewS->use_end(); UI != UE; ) {
440 if (!EVI || EVI->getNumIndices() != 1)
444 EVI->eraseFromParent();
448 if (NewS->use_empty())
return;
452 for (
size_t I = 0,
E = Args.
size();
I !=
E; ++
I)
453 Agg = Builder.CreateInsertValue(Agg, Args[
I], I);
458 void CoroCloner::replaceCoroSuspends() {
459 Value *SuspendResult;
469 SuspendResult = Builder.getInt8(isSwitchDestroyFunction() ? 1 : 0);
482 if (CS == ActiveSuspend)
continue;
484 auto *MappedCS = cast<AnyCoroSuspendInst>(VMap[CS]);
485 MappedCS->replaceAllUsesWith(SuspendResult);
486 MappedCS->eraseFromParent();
490 void CoroCloner::replaceCoroEnds() {
494 auto NewCE = cast<CoroEndInst>(VMap[CE]);
501 Value *CachedSlot =
nullptr;
502 auto getSwiftErrorSlot = [&](
Type *ValueTy) ->
Value * {
505 "multiple swifterror slots in function with different types");
511 if (
Arg.isSwiftError()) {
513 assert(
Arg.getType()->getPointerElementType() == ValueTy &&
514 "swifterror argument does not have expected type");
522 Alloca->setSwiftError(
true);
529 auto MappedOp = VMap ? cast<CallInst>((*VMap)[
Op]) : Op;
536 auto Slot = getSwiftErrorSlot(ValueTy);
537 MappedResult = Builder.CreateLoad(ValueTy, Slot);
540 auto Value = MappedOp->getArgOperand(0);
541 auto ValueTy = Value->
getType();
542 auto Slot = getSwiftErrorSlot(ValueTy);
543 Builder.CreateStore(Value, Slot);
547 MappedOp->replaceAllUsesWith(MappedResult);
548 MappedOp->eraseFromParent();
552 if (VMap ==
nullptr) {
561 void CoroCloner::replaceEntryBlock() {
567 auto *
Entry = cast<BasicBlock>(VMap[Shape.AllocaSpillBlock]);
568 Entry->setName(
"entry" + Suffix);
569 Entry->moveBefore(&NewF->getEntryBlock());
570 Entry->getTerminator()->eraseFromParent();
576 auto BranchToEntry = cast<BranchInst>(
Entry->user_back());
577 assert(BranchToEntry->isUnconditional());
578 Builder.SetInsertPoint(BranchToEntry);
579 Builder.CreateUnreachable();
580 BranchToEntry->eraseFromParent();
586 Builder.SetInsertPoint(
Entry);
592 cast<BasicBlock>(VMap[Shape.SwitchLowering.ResumeEntryBlock]);
593 Builder.CreateBr(SwitchBB);
602 auto MappedCS = cast<CoroSuspendRetconInst>(VMap[ActiveSuspend]);
603 auto Branch = cast<BranchInst>(MappedCS->getNextNode());
604 assert(Branch->isUnconditional());
605 Builder.CreateBr(Branch->getSuccessor(0));
612 Value *CoroCloner::deriveNewFramePointer() {
618 return &*NewF->arg_begin();
623 Argument *NewStorage = &*NewF->arg_begin();
624 auto FramePtrTy = Shape.FrameTy->getPointerTo();
627 if (Shape.RetconLowering.IsFrameInlineInStorage)
628 return Builder.CreateBitCast(NewStorage, FramePtrTy);
632 Builder.CreateBitCast(NewStorage, FramePtrTy->getPointerTo());
633 return Builder.CreateLoad(FramePtrPtr);
641 void CoroCloner::create() {
645 OrigF.getParent()->end());
658 auto savedVisibility = NewF->getVisibility();
659 auto savedUnnamedAddr = NewF->getUnnamedAddr();
660 auto savedDLLStorageClass = NewF->getDLLStorageClass();
665 auto savedLinkage = NewF->getLinkage();
670 NewF->setLinkage(savedLinkage);
671 NewF->setVisibility(savedVisibility);
672 NewF->setUnnamedAddr(savedUnnamedAddr);
673 NewF->setDLLStorageClass(savedDLLStorageClass);
675 auto &
Context = NewF->getContext();
678 auto OrigAttrs = NewF->getAttributes();
686 OrigAttrs.getFnAttributes());
693 NewAttrs = Shape.RetconLowering.ResumePrototype->getAttributes();
698 NewAttrs = NewAttrs.addParamAttribute(
Context, 0, Attribute::NonNull);
720 NewF->setAttributes(NewAttrs);
721 NewF->setCallingConv(Shape.getResumeFunctionCC());
726 Builder.SetInsertPoint(&NewF->getEntryBlock().front());
727 NewFramePtr = deriveNewFramePointer();
730 Value *OldFramePtr = VMap[Shape.FramePtr];
735 auto *NewVFrame = Builder.CreateBitCast(
737 Value *OldVFrame = cast<Value>(VMap[Shape.CoroBegin]);
745 if (Shape.SwitchLowering.HasFinalSuspend)
746 handleFinalSuspend();
753 assert(ActiveSuspend !=
nullptr &&
754 "no active suspend when lowering a continuation-style coroutine");
755 replaceRetconSuspendUses();
760 replaceCoroSuspends();
772 FKind == CoroCloner::Kind::SwitchCleanup);
780 CoroCloner Cloner(F, Suffix, Shape, FKind);
782 return Cloner.getFunction();
797 auto *SizeIntrin = Shape.
CoroSizes.back();
798 Module *M = SizeIntrin->getModule();
829 Module *M = Part->getParent();
852 Builder.CreateStore(ResumeFn, ResumeAddr);
854 Value *DestroyOrCleanupFn = DestroyFn;
860 DestroyOrCleanupFn = Builder.CreateSelect(CA, DestroyFn, CleanupFn);
863 auto *DestroyAddr = Builder.CreateStructGEP(
866 Builder.CreateStore(DestroyOrCleanupFn, DestroyAddr);
884 FPM.doInitialization();
886 FPM.doFinalization();
896 auto V = PN.getIncomingValueForBlock(PrevBB);
898 auto VI = ResolvedValues.
find(V);
899 if (
VI != ResolvedValues.
end())
902 ResolvedValues[&PN] = V;
915 if (isa<ReturnInst>(I)) {
916 if (I != InitialInst) {
919 if (UnconditionalSucc)
921 int idx = PN.getBasicBlockIndex(InitialInst->
getParent());
923 PN.removeIncomingValue(idx);
929 if (
auto *
BR = dyn_cast<BranchInst>(I)) {
930 if (
BR->isUnconditional()) {
932 if (I == InitialInst)
933 UnconditionalSucc = BB;
938 }
else if (
auto *
SI = dyn_cast<SwitchInst>(I)) {
940 auto it = ResolvedValues.
find(V);
941 if (it != ResolvedValues.
end())
944 BasicBlock *BB =
SI->findCaseValue(Cond)->getCaseSuccessor();
961 bool changed =
false;
966 if (
auto *Call = dyn_cast<CallInst>(&
I))
967 if (
auto *CalledValue = Call->getCalledValue())
970 if (isa<CoroSubFnInst>(CalledValue->stripPointerCasts()))
988 auto *CoroId = CoroBegin->
getId();
992 auto SwitchId = cast<CoroIdInst>(CoroId);
1000 AllocInst->eraseFromParent();
1001 CoroBegin->replaceAllUsesWith(VFrame);
1003 CoroBegin->replaceAllUsesWith(CoroBegin->getMem());
1014 CoroBegin->eraseFromParent();
1023 if (isa<IntrinsicInst>(
I))
1042 while (!Worklist.
empty()) {
1046 if (Set.
count(Pred) == 0)
1052 Set.
erase(ResDesBB);
1054 for (
auto *BB : Set)
1063 auto *ResumeOrDestroyBB = ResumeOrDestroy->
getParent();
1065 if (SaveBB == ResumeOrDestroyBB)
1093 Prev = Pred->getTerminator();
1100 auto *CallInstr = CS.getInstruction();
1102 auto *
Callee = CS.getCalledValue()->stripPointerCasts();
1110 if (SubFn->getFrame() != CoroBegin)
1124 Save->eraseFromParent();
1127 if (
auto *Invoke = dyn_cast<InvokeInst>(CallInstr)) {
1132 auto *CalledValue = CS.getCalledValue();
1136 if (CalledValue != SubFn && CalledValue->user_empty())
1137 if (
auto *
I = dyn_cast<Instruction>(CalledValue))
1138 I->eraseFromParent();
1141 if (SubFn->user_empty())
1142 SubFn->eraseFromParent();
1154 size_t I = 0,
N = S.size();
1175 auto ResumeClone =
createClone(F,
".resume", Shape,
1176 CoroCloner::Kind::SwitchResume);
1177 auto DestroyClone =
createClone(F,
".destroy", Shape,
1178 CoroCloner::Kind::SwitchUnwind);
1179 auto CleanupClone =
createClone(F,
".cleanup", Shape,
1180 CoroCloner::Kind::SwitchCleanup);
1218 RawFramePtr =
Id->getStorage();
1234 RawFramePtr->getType()->getPointerTo());
1256 auto Suspend = cast<CoroSuspendRetconInst>(Shape.
CoroSuspends[i]);
1265 auto SuspendBB = Suspend->getParent();
1266 auto NewSuspendBB = SuspendBB->splitBasicBlock(Suspend);
1267 auto Branch = cast<BranchInst>(SuspendBB->getTerminator());
1296 auto CastedContinuationTy =
1297 (ReturnPHIs.
size() == 1 ? RetTy : RetTy->getStructElementType(0));
1298 auto *CastedContinuation =
1302 if (ReturnPHIs.
size() == 1) {
1303 RetV = CastedContinuation;
1307 for (
size_t I = 1,
E = ReturnPHIs.
size();
I !=
E; ++
I)
1315 Branch->setSuccessor(0, ReturnBB);
1316 ReturnPHIs[0]->addIncoming(Continuation, SuspendBB);
1317 size_t NextPHIIndex = 1;
1318 for (
auto &VUse : Suspend->value_operands())
1319 ReturnPHIs[NextPHIIndex++]->addIncoming(&*VUse, SuspendBB);
1326 auto Clone = Clones[i];
1328 CoroCloner(F,
"resume." +
Twine(i), Shape, Clone, Suspend).create();
1336 PrettyStackTraceFunction(
Function &F) :
F(F) {}
1338 OS <<
"While splitting coroutine ";
1347 switch (Shape.
ABI) {
1358 PrettyStackTraceFunction prettyStackTrace(F);
1401 assert(DevirtFn &&
"coro.devirt.trigger function not found");
1414 auto *DevirtFnAddr =
1418 auto *IndirectCall =
CallInst::Create(FnTy, DevirtFnAddr, Null,
"", InsertPt);
1439 DevirtFn->
addFnAttr(Attribute::AlwaysInline);
1456 CallGraphNode *PrepareUserNode =
nullptr, *FnNode =
nullptr;
1457 if (
auto ConcreteFn = dyn_cast<Function>(Fn)) {
1459 FnNode = CG[ConcreteFn];
1472 if (!Cast || Cast->getType() != Fn->getType())
continue;
1476 if (PrepareUserNode) {
1477 for (
auto &
Use : Cast->
uses()) {
1478 if (
auto *CB = dyn_cast<CallBase>(
Use.
getUser())) {
1479 if (!CB->isCallee(&
Use))
1488 Cast->replaceAllUsesWith(Fn);
1489 Cast->eraseFromParent();
1498 while (
auto *Cast = dyn_cast<BitCastInst>(CastFn)) {
1499 if (!Cast->use_empty())
break;
1500 CastFn = Cast->getOperand(0);
1501 Cast->eraseFromParent();
1512 bool Changed =
false;
1516 auto *Prepare = cast<CallInst>((PI++)->getUser());
1541 bool doInitialization(
CallGraph &CG)
override {
1544 "llvm.coro.prepare.retcon"});
1555 if (PrepareFn && PrepareFn->use_empty())
1556 PrepareFn =
nullptr;
1561 if (
auto *
F = CGN->getFunction())
1565 if (Coroutines.
empty() && !PrepareFn)
1568 CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
1570 if (Coroutines.
empty())
1579 LLVM_DEBUG(
dbgs() <<
"CoroSplit: Processing coroutine '" <<
F->getName()
1580 <<
"' state: " << Value <<
"\n");
1599 StringRef getPassName()
const override {
return "Coroutine Splitting"; }
1607 CoroSplitLegacy,
"coro-split",
1608 "Split coroutine into a set of functions driving its state machine",
false,
1612 CoroSplitLegacy,
"coro-split",
1613 "Split coroutine into a set of functions driving its state machine",
false,
Pass interface - Implemented by all 'passes'.
Return a value (possibly void), from a function.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
The "returned-continuation" lowering, where each suspend point creates a single continuation function...
A parsed version of the target data layout string in and methods for querying it. ...
static ConstantInt * getFalse(LLVMContext &Context)
static void createDevirtTriggerFunc(CallGraph &CG, CallGraphSCC &SCC)
void ReplaceInstWithInst(BasicBlock::InstListType &BIL, BasicBlock::iterator &BI, Instruction *I)
Replace the instruction specified by BI with the instruction specified by I.
iterator_range< use_iterator > uses()
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
This class represents an incoming formal argument to a Function.
AllocaInst * CreateAlloca(Type *Ty, unsigned AddrSpace, Value *ArraySize=nullptr, const Twine &Name="")
The "resume-switch" lowering, where there are separate resume and destroy functions that are shared b...
The "unique returned-continuation" lowering, where each suspend point creates a single continuation f...
CoroBeginInst * CoroBegin
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
This represents the llvm.coro.id instruction.
This class represents lattice values for constants.
static void addMustTailToCoroResumes(Function &F)
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
adds the attribute to the list of attributes for the given arg.
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
A Module instance is used to store all the information related to an LLVM module. ...
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
IntegerType * getIndexType() const
void push_back(const T &Elt)
INITIALIZE_PASS_BEGIN(CoroSplitLegacy, "coro-split", "Split coroutine into a set of functions driving its state machine", false, false) INITIALIZE_PASS_END(CoroSplitLegacy
This class represents a function call, abstracting a target machine's calling convention.
SmallVector< CallInst *, 2 > SwiftErrorOps
virtual bool doInitialization(CallGraph &CG)
doInitialization - This method is called before the SCC's of the program has been processed...
The two locations do not alias at all.
Like Internal, but omit from symbol table.
Externally visible function.
LLVMContext & getContext() const
All values hold a context through their type.
bool isTerminator() const
RetconLoweringStorage RetconLowering
static void replaceUnwindCoroEnd(CoroEndInst *End, const coro::Shape &Shape, Value *FramePtr, bool InResume, CallGraph *CG)
Replace an unwind call to llvm.coro.end.
static void replaceFrameSize(coro::Shape &Shape)
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
void reserve(size_type N)
A node in the call graph for a module.
void getAnalysisUsage(AnalysisUsage &Info) const override
getAnalysisUsage - For this class, we declare that we require and preserve the call graph...
Module & getModule() const
Returns the module the call graph corresponds to.
static Constant * get(ArrayType *T, ArrayRef< Constant *> V)
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, Instruction *InsertBefore=nullptr)
Value * getArgOperand(unsigned i) const
FunctionPass * createCFGSimplificationPass(unsigned Threshold=1, bool ForwardSwitchCond=false, bool ConvertSwitch=false, bool KeepLoops=true, bool SinkCommon=false, std::function< bool(const Function &)> Ftor=nullptr)
static bool simplifySuspendPoint(CoroSuspendInst *Suspend, CoroBeginInst *CoroBegin)
#define INITIALIZE_PASS_DEPENDENCY(depName)
FunctionType * getResumeFunctionType() const
void CloneFunctionInto(Function *NewFunc, const Function *OldFunc, ValueToValueMapTy &VMap, bool ModuleLevelChanges, 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...
Type * getPointerElementType() const
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Class to represent struct types.
LLVMContext & getContext() const
Get the global data context.
A Use represents the edge between a Value definition and its users.
This represents the llvm.coro.suspend instruction.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
SwitchInst * ResumeSwitch
ReturnInst * CreateRet(Value *V)
Create a 'ret <val>' instruction.
const CallGraph & getCallGraph()
This file contains the simple types necessary to represent the attributes associated with functions a...
static void scanPHIsAndUpdateValueMap(Instruction *Prev, BasicBlock *NewBlock, DenseMap< Value *, Value *> &ResolvedValues)
FunctionPass * createSCCPPass()
This class represents the llvm.coro.subfn.addr instruction.
#define PREPARED_FOR_SPLIT
static void setCoroInfo(Function &F, coro::Shape &Shape, ArrayRef< Function *> Fns)
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following: ...
const Instruction * getFirstNonPHIOrDbgOrLifetime() const
Returns a pointer to the first instruction in this block that is not a PHINode, a debug intrinsic...
This file provides interfaces used to build and manipulate a call graph, which is a very useful tool ...
ConstantInt * getIndex(uint64_t Value) const
User * getUser() const LLVM_READONLY
Returns the User that contains this Use.
Class to represent function types.
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Type * getType() const
All values are typed, get the type of this value.
static bool replaceAllPrepares(Function *PrepareFn, CallGraph &CG)
Remove calls to llvm.coro.prepare.retcon, a barrier meant to prevent IPO from operating on calls to a...
CoroIdInst * getSwitchCoroId() const
static void replaceCoroEnd(CoroEndInst *End, const coro::Shape &Shape, Value *FramePtr, bool InResume, CallGraph *CG)
This represents the llvm.coro.alloc instruction.
SmallVector< CoroSizeInst *, 2 > CoroSizes
Value * emitAlloc(IRBuilder<> &Builder, Value *Size, CallGraph *CG) const
Allocate memory according to the rules of the active lowering.
static void splitCoroutine(Function &F, coro::Shape &Shape, SmallVectorImpl< Function *> &Clones)
This class represents a no-op cast from one type to another.
void add(Pass *P) override
Add a pass to the queue of passes to run.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
static void simplifySuspendPoints(coro::Shape &Shape)
static Function * getFunction(Constant *C)
void takeName(Value *V)
Transfer the name from V to this value.
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
Class to represent pointers.
Optional< OperandBundleUse > getOperandBundle(StringRef Name) const
Return an operand bundle by name, if present.
iterator find(const_arg_type_t< KeyT > Val)
const BasicBlock & getEntryBlock() const
This represents the llvm.coro.size instruction.
Type * getReturnType() const
Returns the type of the ret val.
static Function * createCloneDeclaration(Function &OrigF, coro::Shape &Shape, const Twine &Suffix, Module::iterator InsertBefore)
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
static void postSplitCleanup(Function &F)
Control flow instructions. These all have token chains.
bool IsFrameInlineInStorage
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
The ModulePass which wraps up a CallGraph and the logic to build it.
CallGraphNode * getCallsExternalNode() const
const FunctionListType & getFunctionList() const
Get the Module's list of functions (constant).
LLVM Basic Block Representation.
#define CORO_PRESPLIT_ATTR
The instances of the Type class are immutable: once they are created, they are never changed...
This is an important class for using LLVM in a threaded context.
UnreachableInst * CreateUnreachable()
Value handle that tracks a Value across RAUW.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
void removeAttribute(unsigned i, Attribute::AttrKind Kind)
removes the attribute from the list of attributes.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
static void prepareForSplit(Function &F, CallGraph &CG)
Represent the analysis usage information of a pass.
static Type * getVoidTy(LLVMContext &C)
This represents the llvm.coro.end instruction.
static void replaceFallthroughCoroEnd(CoroEndInst *End, const coro::Shape &Shape, Value *FramePtr, bool InResume, CallGraph *CG)
Replace a non-unwind call to llvm.coro.end.
static bool hasCallsBetween(Instruction *Save, Instruction *ResumeOrDestroy)
void removeCallEdgeFor(CallBase &Call)
Removes the edge in the node for the specified call site.
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
static FunctionType * get(Type *Result, ArrayRef< Type *> Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
self_iterator getIterator()
void initialize(ArrayRef< CallGraphNode *> NewNodes)
ConstantInt * getInt64(uint64_t C)
Get a constant 64-bit value.
static bool hasCallsInBlocksBetween(BasicBlock *SaveBB, BasicBlock *ResDesBB)
const Function * getFunction() const
Return the function this instruction belongs to.
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
FunctionPassManager manages FunctionPasses.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
PrettyStackTraceEntry - This class is used to represent a frame of the "pretty" stack trace that is d...
PointerType * getInt8PtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer to an 8-bit integer value.
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
CoroAllocInst * getCoroAlloc()
static void createResumeEntryBlock(Function &F, coro::Shape &Shape)
static bool hasCallsInBlockBetween(Instruction *From, Instruction *To)
SwitchLoweringStorage SwitchLowering
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
static Constant * getPointerCast(Constant *C, Type *Ty)
Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant expression.
AnyCoroIdInst * getId() const
Iterator for intrusive lists based on ilist_node.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
bool declaresIntrinsics(const Module &M, const std::initializer_list< StringRef >)
This is the shared class of boolean and integer constants.
BlockVerifier::State From
bool erase(PtrType Ptr)
erase - If the set contains the specified pointer, remove it and return true, otherwise return false...
Module.h This file contains the declarations for the Module class.
static void splitSwitchCoroutine(Function &F, coro::Shape &Shape, SmallVectorImpl< Function *> &Clones)
Type * getReturnType() const
LLVM_NODISCARD T pop_back_val()
void buildCoroutineFrame(Function &F, Shape &Shape)
#define UNPREPARED_FOR_SPLIT
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
pred_range predecessors(BasicBlock *BB)
static ConstantInt * getTrue(LLVMContext &Context)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
This class represents the llvm.coro.begin instruction.
Value * makeSubFnCall(Value *Arg, int Index, Instruction *InsertPt)
SmallVector< AnyCoroSuspendInst *, 4 > CoroSuspends
static void handleNoSuspendCoroutine(coro::Shape &Shape)
amdgpu Simplify well known AMD library false FunctionCallee Callee
IntegerType * getInt8Ty()
Fetch the type representing an 8-bit integer.
static void replaceSwiftErrorOps(Function &F, coro::Shape &Shape, ValueToValueMapTy *VMap)
static void updateCoroFrame(coro::Shape &Shape, Function *ResumeFn, Function *DestroyFn, Function *CleanupFn)
BasicBlock * ResumeEntryBlock
ConstantInt * getFalse()
Get the constant value for i1 false.
SwitchInst * CreateSwitch(Value *V, BasicBlock *Dest, unsigned NumCases=10, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a switch instruction with the specified value, default dest, and with a hint for the number of...
ReturnInst * CreateRetVoid()
Create a 'ret void' instruction.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
The basic data container for the call graph of a Module of IR.
unsigned getNumArgOperands() const
iterator insert(iterator where, pointer New)
LLVM_NODISCARD bool empty() const
StringRef getValueAsString() const
Return the attribute's value as a string.
StringRef getName() const
Return a constant reference to the value's name.
const Function * getParent() const
Return the enclosing method, or null if none.
CleanupReturnInst * CreateCleanupRet(CleanupPadInst *CleanupPad, BasicBlock *UnwindBB=nullptr)
Pass * createCoroSplitLegacyPass()
Split up coroutines into multiple functions driving their state machines.
static void maybeFreeRetconStorage(IRBuilder<> &Builder, const coro::Shape &Shape, Value *FramePtr, CallGraph *CG)
void emitDealloc(IRBuilder<> &Builder, Value *Ptr, CallGraph *CG) const
Deallocate memory according to the rules of the active lowering.
bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
#define CORO_DEVIRT_TRIGGER_FN
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
static Function * createClone(Function &F, const Twine &Suffix, coro::Shape &Shape, CoroCloner::Kind FKind)
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
static ConstantTokenNone * get(LLVMContext &Context)
Return the ConstantTokenNone.
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it...
BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
bool removeUnreachableBlocks(Function &F, DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Remove all blocks that can not be reached from the function's entry.
void replaceCoroFree(CoroIdInst *CoroId, bool Elide)
void removeFnAttr(Attribute::AttrKind Kind)
Remove function attributes from this function.
static void removeCoroEnds(const coro::Shape &Shape, CallGraph *CG)
Remove calls to llvm.coro.end in the original function.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
SmallVector< CoroEndInst *, 4 > CoroEnds
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
void setInfo(Constant *C)
CallGraphSCC - This is a single SCC that a CallGraphSCCPass is run on.
CallGraphNode * getOrInsertFunction(const Function *F)
Similar to operator[], but this will insert a new CallGraphNode for F if one does not already exist...
static bool simplifyTerminatorLeadingToRet(Instruction *InitialInst)
Value * CreateStructGEP(Type *Ty, Value *Ptr, unsigned Idx, const Twine &Name="")
This class implements an extremely fast bulk output stream that can only output to a stream...
void addFnAttr(Attribute::AttrKind Kind)
Add function attributes to this function.
FunctionPass * createEarlyCSEPass(bool UseMemorySSA=false)
ConstantInt * getInt8(uint8_t C)
Get a constant 8-bit value.
StringRef - Represent a constant reference to a string, i.e.
inst_range instructions(Function *F)
static void splitRetconCoroutine(Function &F, coro::Shape &Shape, SmallVectorImpl< Function *> &Clones)
const Instruction * getFirstNonPHIOrDbg() const
Returns a pointer to the first instruction in this block that is not a PHINode or a debug intrinsic...
void initializeCoroSplitLegacyPass(PassRegistry &)
Value * CreateInsertValue(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &Name="")
static void replacePrepare(CallInst *Prepare, CallGraph &CG)
Replace a call to llvm.coro.prepare.retcon.
unsigned changeToUnreachable(Instruction *I, bool UseLLVMTrap, 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...
CoroSaveInst * getCoroSave() const
ValueTy * getValPtr() const
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
void updateCallGraph(Function &Caller, ArrayRef< Function *> Funcs, CallGraph &CG, CallGraphSCC &SCC)
iterator_range< arg_iterator > args()
void addCalledFunction(CallBase *Call, CallGraphNode *M)
Adds a function to the list of functions called by this one.
const BasicBlock * getParent() const
ArrayRef< Type * > getRetconResultTypes() const