1//===- CoroEarly.cpp - Coroutine Early Function Pass ----------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "llvm/Transforms/Coroutines/CoroEarly.h"
10#include "CoroInternal.h"
11#include "llvm/IR/Function.h"
12#include "llvm/IR/IRBuilder.h"
13#include "llvm/IR/InstIterator.h"
14#include "llvm/IR/Module.h"
15
16using namespace llvm;
17
18#define DEBUG_TYPE "coro-early"
19
20namespace {
21// Created on demand if the coro-early pass has work to do.
22class Lowerer : public coro::LowererBase {
23 IRBuilder<> Builder;
24 PointerType *const AnyResumeFnPtrTy;
25
26 void lowerResumeOrDestroy(CallBase &CB, CoroSubFnInst::ResumeKind);
27 void lowerCoroPromise(CoroPromiseInst *Intrin);
28 void lowerCoroDone(IntrinsicInst *II);
29
30public:
31 Lowerer(Module &M)
32 : LowererBase(M), Builder(Context),
33 AnyResumeFnPtrTy(PointerType::getUnqual(C&: Context)) {}
34 void lowerEarlyIntrinsics(Function &F);
35};
36} // namespace
37
38// Replace a direct call to coro.resume or coro.destroy with an indirect call to
39// an address returned by coro.subfn.addr intrinsic. This is done so that
40// CGPassManager recognizes devirtualization when CoroElide pass replaces a call
41// to coro.subfn.addr with an appropriate function address.
42void Lowerer::lowerResumeOrDestroy(CallBase &CB,
43 CoroSubFnInst::ResumeKind Index) {
44 Value *ResumeAddr = makeSubFnCall(Arg: CB.getArgOperand(i: 0), Index, InsertPt: &CB);
45 CB.setCalledOperand(ResumeAddr);
46}
47
48// Coroutine promise field is always at the fixed offset from the beginning of
49// the coroutine frame. i8* coro.promise(i8*, i1 from) intrinsic adds an offset
50// to a passed pointer to move from coroutine frame to coroutine promise and
51// vice versa. Since we don't know exactly which coroutine frame it is, we build
52// a coroutine frame mock up starting with two function pointers, followed by a
53// properly aligned coroutine promise field.
54// TODO: Handle the case when coroutine promise alloca has align override.
55void Lowerer::lowerCoroPromise(CoroPromiseInst *Intrin) {
56 Value *Operand = Intrin->getArgOperand(i: 0);
57 Align Alignment = Intrin->getAlignment();
58 Type *Int8Ty = Builder.getInt8Ty();
59
60 auto *SampleStruct =
61 StructType::get(Context, Elements: {AnyResumeFnPtrTy, AnyResumeFnPtrTy, Int8Ty});
62 const DataLayout &DL = TheModule.getDataLayout();
63 int64_t Offset = alignTo(
64 Size: DL.getStructLayout(Ty: SampleStruct)->getElementOffset(Idx: 2), A: Alignment);
65 if (Intrin->isFromPromise())
66 Offset = -Offset;
67
68 Builder.SetInsertPoint(Intrin);
69 Value *Replacement =
70 Builder.CreateConstInBoundsGEP1_32(Ty: Int8Ty, Ptr: Operand, Idx0: Offset);
71
72 Intrin->replaceAllUsesWith(V: Replacement);
73 Intrin->eraseFromParent();
74}
75
76// When a coroutine reaches final suspend point, it zeros out ResumeFnAddr in
77// the coroutine frame (it is UB to resume from a final suspend point).
78// The llvm.coro.done intrinsic is used to check whether a coroutine is
79// suspended at the final suspend point or not.
80void Lowerer::lowerCoroDone(IntrinsicInst *II) {
81 Value *Operand = II->getArgOperand(i: 0);
82
83 // ResumeFnAddr is the first pointer sized element of the coroutine frame.
84 auto *FrameTy = Int8Ptr;
85
86 Builder.SetInsertPoint(II);
87 auto *Load = Builder.CreateLoad(Ty: FrameTy, Ptr: Operand);
88 auto *Cond = Builder.CreateICmpEQ(LHS: Load, RHS: NullPtr);
89
90 II->replaceAllUsesWith(V: Cond);
91 II->eraseFromParent();
92}
93
94// Prior to CoroSplit, calls to coro.begin needs to be marked as NoDuplicate,
95// as CoroSplit assumes there is exactly one coro.begin. After CoroSplit,
96// NoDuplicate attribute will be removed from coro.begin otherwise, it will
97// interfere with inlining.
98static void setCannotDuplicate(CoroIdInst *CoroId) {
99 for (User *U : CoroId->users())
100 if (auto *CB = dyn_cast<CoroBeginInst>(Val: U))
101 CB->setCannotDuplicate();
102}
103
104void Lowerer::lowerEarlyIntrinsics(Function &F) {
105 CoroIdInst *CoroId = nullptr;
106 CoroBeginInst *CoroBegin = nullptr;
107 SmallVector<CoroFreeInst *, 4> CoroFrees;
108 bool HasCoroSuspend = false;
109 for (Instruction &I : llvm::make_early_inc_range(Range: instructions(F))) {
110 auto *CB = dyn_cast<CallBase>(Val: &I);
111 if (!CB)
112 continue;
113
114 switch (CB->getIntrinsicID()) {
115 default:
116 continue;
117 case Intrinsic::coro_begin:
118 case Intrinsic::coro_begin_custom_abi:
119 if (CoroBegin)
120 report_fatal_error(
121 reason: "coroutine should have exactly one defining @llvm.coro.begin");
122 CoroBegin = cast<CoroBeginInst>(Val: &I);
123 break;
124 case Intrinsic::coro_free:
125 CoroFrees.push_back(Elt: cast<CoroFreeInst>(Val: &I));
126 break;
127 case Intrinsic::coro_suspend:
128 // Make sure that final suspend point is not duplicated as CoroSplit
129 // pass expects that there is at most one final suspend point.
130 if (cast<CoroSuspendInst>(Val: &I)->isFinal())
131 CB->setCannotDuplicate();
132 HasCoroSuspend = true;
133 break;
134 case Intrinsic::coro_end_async:
135 case Intrinsic::coro_end:
136 // Make sure that fallthrough coro.end is not duplicated as CoroSplit
137 // pass expects that there is at most one fallthrough coro.end.
138 if (cast<AnyCoroEndInst>(Val: &I)->isFallthrough())
139 CB->setCannotDuplicate();
140 break;
141 case Intrinsic::coro_id:
142 if (auto *CII = cast<CoroIdInst>(Val: &I)) {
143 if (CII->getInfo().isPreSplit()) {
144 assert(F.isPresplitCoroutine() &&
145 "The frontend uses Switch-Resumed ABI should emit "
146 "\"presplitcoroutine\" attribute for the coroutine.");
147 setCannotDuplicate(CII);
148 CII->setCoroutineSelf();
149 CoroId = cast<CoroIdInst>(Val: &I);
150 }
151 }
152 break;
153 case Intrinsic::coro_id_retcon:
154 case Intrinsic::coro_id_retcon_once:
155 case Intrinsic::coro_id_async:
156 F.setPresplitCoroutine();
157 break;
158 case Intrinsic::coro_resume:
159 lowerResumeOrDestroy(CB&: *CB, Index: CoroSubFnInst::ResumeIndex);
160 break;
161 case Intrinsic::coro_destroy:
162 lowerResumeOrDestroy(CB&: *CB, Index: CoroSubFnInst::DestroyIndex);
163 break;
164 case Intrinsic::coro_promise:
165 lowerCoroPromise(Intrin: cast<CoroPromiseInst>(Val: &I));
166 break;
167 case Intrinsic::coro_done:
168 lowerCoroDone(II: cast<IntrinsicInst>(Val: &I));
169 break;
170 }
171 }
172
173 if (CoroId) {
174 // Make sure that all CoroFree reference the coro.id intrinsic.
175 // Token type is not exposed through coroutine C/C++ builtins to plain C, so
176 // we allow specifying none and fixing it up here.
177 for (CoroFreeInst *CF : CoroFrees)
178 CF->setArgOperand(i: 0, v: CoroId);
179 }
180
181 // Coroutine suspention could potentially lead to any argument modified
182 // outside of the function, hence arguments should not have noalias
183 // attributes.
184 if (HasCoroSuspend)
185 for (Argument &A : F.args())
186 if (A.hasNoAliasAttr())
187 A.removeAttr(Kind: Attribute::NoAlias);
188}
189
190static bool declaresCoroEarlyIntrinsics(const Module &M) {
191 // coro_suspend omitted as it is overloaded.
192 return coro::declaresIntrinsics(
193 M, List: {Intrinsic::coro_id, Intrinsic::coro_id_retcon,
194 Intrinsic::coro_id_retcon_once, Intrinsic::coro_id_async,
195 Intrinsic::coro_destroy, Intrinsic::coro_done, Intrinsic::coro_end,
196 Intrinsic::coro_end_async, Intrinsic::coro_free,
197 Intrinsic::coro_promise, Intrinsic::coro_resume});
198}
199
200PreservedAnalyses CoroEarlyPass::run(Module &M, ModuleAnalysisManager &) {
201 if (!declaresCoroEarlyIntrinsics(M))
202 return PreservedAnalyses::all();
203
204 Lowerer L(M);
205 for (auto &F : M)
206 L.lowerEarlyIntrinsics(F);
207
208 PreservedAnalyses PA;
209 PA.preserveSet<CFGAnalyses>();
210 return PA;
211}
212