36 #define DEBUG_TYPE "coro-suspend-crossing"
42 class BlockToIndexMapping {
46 size_t size()
const {
return V.
size(); }
55 auto *
I = std::lower_bound(V.begin(), V.end(), BB);
56 assert(
I != V.end() && *
I == BB &&
"BasicBlockNumberng: Unknown block");
60 BasicBlock *indexToBlock(
unsigned Index)
const {
return V[Index]; }
77 struct SuspendCrossingInfo {
78 BlockToIndexMapping Mapping;
89 BasicBlock *BB = Mapping.indexToBlock(&BD - &Block[0]);
94 return Block[Mapping.blockToIndex(BB)];
103 size_t const DefIndex = Mapping.blockToIndex(DefBB);
104 size_t const UseIndex = Mapping.blockToIndex(UseBB);
106 assert(Block[UseIndex].Consumes[DefIndex] &&
"use must consume def");
107 bool const Result =
Block[UseIndex].Kills[DefIndex];
109 <<
" answer is " << Result <<
"\n");
113 bool isDefinitionAcrossSuspend(
BasicBlock *DefBB,
User *U)
const {
114 auto *
I = cast<Instruction>(U);
118 if (
auto *PN = dyn_cast<PHINode>(
I))
119 if (PN->getNumIncomingValues() > 1)
123 return hasPathCrossingSuspendPoint(DefBB, UseBB);
131 return isDefinitionAcrossSuspend(I.
getParent(), U);
136 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
139 dbgs() << Label <<
":";
140 for (
size_t I = 0,
N = BV.
size();
I <
N; ++
I)
142 dbgs() <<
" " << Mapping.indexToBlock(I)->getName();
147 for (
size_t I = 0, N =
Block.size(); I <
N; ++
I) {
150 dump(
" Consumes", Block[I].Consumes);
151 dump(
" Kills", Block[I].Kills);
159 const size_t N = Mapping.size();
163 for (
size_t I = 0; I <
N; ++
I) {
165 B.Consumes.resize(N);
174 getBlockData(
CE->getParent()).
End =
true;
182 auto &B = getBlockData(SuspendBlock);
184 B.Kills |= B.Consumes;
187 markSuspendBlock(CSI);
197 DEBUG(
dbgs() <<
"iteration " << ++Iteration);
201 for (
size_t I = 0; I <
N; ++
I) {
205 auto SuccNo = Mapping.blockToIndex(
SI);
209 auto &S =
Block[SuccNo];
210 auto SavedConsumes = S.Consumes;
211 auto SavedKills = S.Kills;
214 S.Consumes |= B.Consumes;
220 S.Kills |= B.Consumes;
225 S.Kills |= S.Consumes;
235 S.Kills.reset(SuccNo);
239 Changed |= (S.Kills != SavedKills) || (S.Consumes != SavedConsumes);
241 if (S.Kills != SavedKills) {
242 DEBUG(
dbgs() <<
"\nblock " << I <<
" follower " <<
SI->getName()
247 if (S.Consumes != SavedConsumes) {
248 DEBUG(
dbgs() <<
"\nblock " << I <<
" follower " <<
SI <<
"\n");
258 #undef DEBUG_TYPE // "coro-suspend-crossing"
259 #define DEBUG_TYPE "coro-frame"
264 struct Spill : std::pair<Value *, Instruction *> {
265 using base = std::pair<Value *, Instruction *>;
273 std::pair<Value *, BasicBlock *>
getKey()
const {
286 dbgs() <<
"------------- " << Title <<
"--------------\n";
287 Value *CurrentValue =
nullptr;
288 for (
auto const &
E : Spills) {
289 if (CurrentValue !=
E.def()) {
290 CurrentValue =
E.def();
291 CurrentValue->
dump();
311 Name.append(
".Frame");
314 auto *FnTy = FunctionType::get(Type::getVoidTy(C), FramePtrTy,
316 auto *FnPtrTy = FnTy->getPointerTo();
322 : Type::getInt1Ty(C);
324 Type::getIntNTy(C, IndexBits)};
325 Value *CurrentDef =
nullptr;
328 for (
auto const &S : Spills) {
329 if (CurrentDef == S.def())
332 CurrentDef = S.def();
338 if (
auto *AI = dyn_cast<AllocaInst>(CurrentDef))
339 Ty = AI->getAllocatedType();
365 CleanupPadInst::Create(CatchSwitch->
getParentPad(), {},
"", CurrentBlock);
367 CleanupReturnInst::Create(CleanupPad, NewBlock, CurrentBlock);
398 cast<Instruction>(Builder.CreateBitCast(CB, FramePtrTy,
"FramePtr"));
399 Type *FrameTy = FramePtrTy->getElementType();
401 Value *CurrentValue =
nullptr;
403 Value *CurrentReload =
nullptr;
404 unsigned Index = coro::Shape::LastKnownField;
418 auto CreateReload = [&](
Instruction *InsertBefore) {
419 Builder.SetInsertPoint(InsertBefore);
420 auto *
G = Builder.CreateConstInBoundsGEP2_32(FrameTy,
FramePtr, 0, Index,
422 Twine(
".reload.addr"));
423 return isa<AllocaInst>(CurrentValue)
425 : Builder.CreateLoad(
G,
429 for (
auto const &
E : Spills) {
431 if (CurrentValue !=
E.def()) {
432 CurrentValue =
E.def();
433 CurrentBlock =
nullptr;
434 CurrentReload =
nullptr;
438 if (
auto *AI = dyn_cast<AllocaInst>(CurrentValue)) {
442 if (!AI->isStaticAlloca())
449 if (isa<Argument>(CurrentValue)) {
454 }
else if (
auto *II = dyn_cast<InvokeInst>(CurrentValue)) {
457 auto NewBB =
SplitEdge(II->getParent(), II->getNormalDest());
458 InsertPt = NewBB->getTerminator();
459 }
else if (dyn_cast<PHINode>(CurrentValue)) {
462 if (
auto *CSI = dyn_cast<CatchSwitchInst>(DefBlock->
getTerminator()))
469 assert(!isa<TerminatorInst>(
E.def()) &&
"unexpected terminator");
470 InsertPt = cast<Instruction>(
E.def())->getNextNode();
473 Builder.SetInsertPoint(InsertPt);
474 auto *
G = Builder.CreateConstInBoundsGEP2_32(
477 Builder.CreateStore(CurrentValue,
G);
482 if (CurrentBlock !=
E.userBlock()) {
483 CurrentBlock =
E.userBlock();
490 if (
auto *PN = dyn_cast<PHINode>(
E.user())) {
491 assert(PN->getNumIncomingValues() == 1 &&
"unexpected number of incoming "
492 "values in the PHINode");
493 PN->replaceAllUsesWith(CurrentReload);
494 PN->eraseFromParent();
499 E.user()->replaceUsesOfWith(CurrentValue, CurrentReload);
510 for (
auto &
P : Allocas) {
512 Builder.CreateConstInBoundsGEP2_32(FrameTy,
FramePtr, 0,
P.second);
515 G->takeName(
P.first);
516 P.first->replaceAllUsesWith(
G);
517 P.first->eraseFromParent();
524 if (
auto *II = dyn_cast<InvokeInst>(TI))
525 II->setUnwindDest(Succ);
526 else if (
auto *CS = dyn_cast<CatchSwitchInst>(TI))
527 CS->setUnwindDest(Succ);
528 else if (
auto *CR = dyn_cast<CleanupReturnInst>(TI))
529 CR->setUnwindDest(Succ);
538 PHINode *LandingPadReplacement) {
545 if (LandingPadReplacement == PN)
556 assert(BBIdx != (
unsigned)-1 &&
"Invalid PHI Index!");
565 PHINode *LandingPadReplacement) {
567 if (!LandingPadReplacement && !PadInst->
isEHPad())
574 if (LandingPadReplacement) {
575 auto *NewLP = OriginalPad->
clone();
576 auto *
Terminator = BranchInst::Create(Succ, NewBB);
581 Value *ParentPad =
nullptr;
582 if (
auto *FuncletPad = dyn_cast<FuncletPadInst>(PadInst))
583 ParentPad = FuncletPad->getParentPad();
584 else if (
auto *CatchSwitch = dyn_cast<CatchSwitchInst>(PadInst))
585 ParentPad = CatchSwitch->getParentPad();
589 auto *NewCleanupPad = CleanupPadInst::Create(ParentPad, {},
"", NewBB);
590 CleanupReturnInst::Create(NewCleanupPad, Succ, NewBB);
618 if ((LandingPad = dyn_cast_or_null<LandingPadInst>(BB.
getFirstNonPHI()))) {
622 ReplPHI = PHINode::Create(LandingPad->
getType(), 1,
"", LandingPad);
632 IncomingBB->setName(BB.
getName() +
Twine(
".from.") + Pred->getName());
633 auto *PN = cast<PHINode>(&BB.
front());
635 int Index = PN->getBasicBlockIndex(IncomingBB);
636 Value *V = PN->getIncomingValue(Index);
637 PHINode *InputV = PHINode::Create(
639 &IncomingBB->
front());
641 PN->setIncomingValue(Index, InputV);
643 }
while (PN != ReplPHI);
658 if (
auto *PN = dyn_cast<PHINode>(&BB.
front()))
659 if (PN->getNumIncomingValues() > 1)
669 return isa<CastInst>(&V) || isa<GetElementPtrInst>(&V) ||
670 isa<BinaryOperator>(&V) || isa<CmpInst>(&V) || isa<SelectInst>(&V);
676 return isa<CoroIdInst>(&
I) || isa<CoroBeginInst>(&I) ||
677 isa<CoroSaveInst>(&
I) || isa<CoroSuspendInst>(&I);
688 for (
auto const &
E : Spills) {
690 if (CurrentDef !=
E.def()) {
691 CurrentDef = cast<Instruction>(
E.def());
692 CurrentBlock =
nullptr;
693 CurrentMaterialization =
nullptr;
697 if (CurrentBlock !=
E.userBlock()) {
698 CurrentBlock =
E.userBlock();
699 CurrentMaterialization = cast<Instruction>(CurrentDef)->clone();
705 if (
auto *PN = dyn_cast<PHINode>(
E.user())) {
706 assert(PN->getNumIncomingValues() == 1 &&
"unexpected number of incoming "
707 "values in the PHINode");
708 PN->replaceAllUsesWith(CurrentMaterialization);
709 PN->eraseFromParent();
715 E.user()->replaceUsesOfWith(CurrentDef, CurrentMaterialization);
733 Value *CurrentValue =
nullptr;
735 for (
auto const &
E : Spills) {
736 if (CurrentValue ==
E.def())
739 CurrentValue =
E.def();
748 if (!DT.
dominates(CoroBegin, cast<Instruction>(UI)))
750 " dominated by CoroBegin");
753 DEBUG(
dbgs() <<
"will move: " << *I <<
"\n");
811 SuspendCrossingInfo Checker(F, Shape);
816 for (
int Repeat = 0; Repeat < 4; ++Repeat) {
821 if (Checker.isDefinitionAcrossSuspend(I, U))
822 Spills.emplace_back(&I, U);
836 if (Checker.isDefinitionAcrossSuspend(A, U))
837 Spills.emplace_back(&A, U);
850 if (Checker.isDefinitionAcrossSuspend(I, U)) {
852 if (I.getType()->isTokenTy())
854 "token definition is separated from the use by a suspend point");
855 Spills.emplace_back(&I, U);
static Instruction * splitBeforeCatchSwitch(CatchSwitchInst *CatchSwitch)
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void push_back(const T &Elt)
size_type size() const
size - Returns the number of bits in this bitvector.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
This class represents an incoming formal argument to a Function.
CoroBeginInst * CoroBegin
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
static void updatePhiNodes(BasicBlock *DestBB, BasicBlock *OldPred, BasicBlock *NewPred, PHINode *LandingPadReplacement)
static void rewritePHIs(BasicBlock &BB)
BasicBlock * userBlock() const
static void dump(StringRef Title, SpillInfo const &Spills)
const Function * getParent() const
Return the enclosing method, or null if none.
const Instruction & front() const
Type * getElementType() const
StringRef getName() const
Return a constant reference to the value's name.
iterator begin()
Instruction iterator methods.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Class to represent struct types.
static bool materializable(Instruction &V)
This represents the llvm.coro.suspend instruction.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Windows NT (Windows on ARM)
void setName(const Twine &Name)
Change the name of the value.
CoroIdInst * getId() const
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following: ...
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
CoroSaveInst * getCoroSave() const
LLVM_NODISCARD char front() const
front - Get the first character in the string.
SmallVector< CoroSuspendInst *, 4 > CoroSuspends
void takeName(Value *V)
Transfer the name from V to this value.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Spill(Value *Def, User *U)
std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type cast(const Y &Val)
Class to represent pointers.
Instruction * user() const
The landingpad instruction holds all of the information necessary to generate correct exception handl...
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
Subclasses of this class are all able to terminate a basic block.
static void moveSpillUsesAfterCoroBegin(Function &F, SpillInfo const &Spills, CoroBeginInst *CoroBegin)
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction...
LLVM Basic Block Representation.
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.
const Function * getParent() const
PointerType * getType() const
Overload to return most specific pointer type.
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
This represents the llvm.coro.end instruction.
Select target instructions out of generic instructions
bool operator<(Spill const &rhs) const
static const unsigned End
Interval::pred_iterator pred_end(Interval *I)
std::pair< Value *, BasicBlock * > getKey() const
bool LowerDbgDeclare(Function &F)
Lowers llvm.dbg.declare intrinsics into appropriate set of llvm.dbg.value intrinsics.
void setBody(ArrayRef< Type * > Elements, bool isPacked=false)
Specify a body for an opaque identified type.
void dump() const
Support for debugging, callable in GDB: V->dump()
static bool isCoroutineStructureIntrinsic(Instruction &I)
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Iterator for intrusive lists based on ilist_node.
void setIncomingBlock(unsigned i, BasicBlock *BB)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Type * getType() const
All values are typed, get the type of this value.
void buildCoroutineFrame(Function &F, Shape &Shape)
const BasicBlock & getEntryBlock() const
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
unsigned Log2_64_Ceil(uint64_t Value)
Return the ceil log base 2 of the specified value, 64 if the value is zero.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
This class represents the llvm.coro.begin instruction.
A range adaptor for a pair of iterators.
iterator_range< user_iterator > users()
static BasicBlock * splitBlockIfNotFirst(Instruction *I, const Twine &Name)
llvm_unreachable("Unknown RegBank!")
Value * getParentPad() const
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
static void rewriteMaterializableInstructions(IRBuilder<> &IRB, SpillInfo const &Spills)
void emplace_back(ArgTypes &&...Args)
static Instruction * insertSpills(SpillInfo &Spills, coro::Shape &Shape)
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
SmallVector< CoroEndInst *, 4 > CoroEnds
LLVMContext & getContext() const
Get the context in which this basic block lives.
AllocaInst * PromiseAlloca
static BasicBlock * ehAwareSplitEdge(BasicBlock *BB, BasicBlock *Succ, LandingPadInst *OriginalPad, PHINode *LandingPadReplacement)
static StructType * buildFrameType(Function &F, coro::Shape &Shape, SpillInfo &Spills)
LLVM Value Representation.
succ_range successors(BasicBlock *BB)
static const Function * getParent(const Value *V)
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
AllocaInst * getPromise() const
static const unsigned FramePtr
BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr)
Split the edge connecting specified block.
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
StringRef - Represent a constant reference to a string, i.e.
void sort(Policy policy, RandomAccessIterator Start, RandomAccessIterator End, const Comparator &Comp=Comparator())
BasicBlock * AllocaSpillBlock
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
static void setUnwindEdgeTo(TerminatorInst *TI, BasicBlock *Succ)
std::pair< Value *, Instruction * > base
static void splitAround(Instruction *I, const Twine &Name)
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
const BasicBlock * getParent() const
iterator_range< arg_iterator > args()
A wrapper class for inspecting calls to intrinsic functions.