LLVM 20.0.0git
CoroSplit.cpp
Go to the documentation of this file.
1//===- CoroSplit.cpp - Converts a coroutine into a state machine ----------===//
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// This pass builds the coroutine frame and outlines resume and destroy parts
9// of the coroutine into separate functions.
10//
11// We present a coroutine to an LLVM as an ordinary function with suspension
12// points marked up with intrinsics. We let the optimizer party on the coroutine
13// as a single function for as long as possible. Shortly before the coroutine is
14// eligible to be inlined into its callers, we split up the coroutine into parts
15// corresponding to an initial, resume and destroy invocations of the coroutine,
16// add them to the current SCC and restart the IPO pipeline to optimize the
17// coroutine subfunctions we extracted before proceeding to the caller of the
18// coroutine.
19//===----------------------------------------------------------------------===//
20
22#include "CoroCloner.h"
23#include "CoroInternal.h"
24#include "llvm/ADT/DenseMap.h"
26#include "llvm/ADT/STLExtras.h"
30#include "llvm/ADT/StringRef.h"
31#include "llvm/ADT/Twine.h"
32#include "llvm/Analysis/CFG.h"
39#include "llvm/IR/Argument.h"
40#include "llvm/IR/Attributes.h"
41#include "llvm/IR/BasicBlock.h"
42#include "llvm/IR/CFG.h"
43#include "llvm/IR/CallingConv.h"
44#include "llvm/IR/Constants.h"
45#include "llvm/IR/DataLayout.h"
47#include "llvm/IR/Dominators.h"
48#include "llvm/IR/GlobalValue.h"
51#include "llvm/IR/InstrTypes.h"
52#include "llvm/IR/Instruction.h"
55#include "llvm/IR/LLVMContext.h"
56#include "llvm/IR/Module.h"
57#include "llvm/IR/Type.h"
58#include "llvm/IR/Value.h"
59#include "llvm/IR/Verifier.h"
61#include "llvm/Support/Debug.h"
70#include <cassert>
71#include <cstddef>
72#include <cstdint>
73#include <initializer_list>
74#include <iterator>
75
76using namespace llvm;
77
78#define DEBUG_TYPE "coro-split"
79
80// FIXME:
81// Lower the intrinisc in CoroEarly phase if coroutine frame doesn't escape
82// and it is known that other transformations, for example, sanitizers
83// won't lead to incorrect code.
85 coro::Shape &Shape) {
86 auto Wrapper = CB->getWrapperFunction();
87 auto Awaiter = CB->getAwaiter();
88 auto FramePtr = CB->getFrame();
89
90 Builder.SetInsertPoint(CB);
91
92 CallBase *NewCall = nullptr;
93 // await_suspend has only 2 parameters, awaiter and handle.
94 // Copy parameter attributes from the intrinsic call, but remove the last,
95 // because the last parameter now becomes the function that is being called.
96 AttributeList NewAttributes =
98
99 if (auto Invoke = dyn_cast<InvokeInst>(CB)) {
100 auto WrapperInvoke =
101 Builder.CreateInvoke(Wrapper, Invoke->getNormalDest(),
102 Invoke->getUnwindDest(), {Awaiter, FramePtr});
103
104 WrapperInvoke->setCallingConv(Invoke->getCallingConv());
105 std::copy(Invoke->bundle_op_info_begin(), Invoke->bundle_op_info_end(),
106 WrapperInvoke->bundle_op_info_begin());
107 WrapperInvoke->setAttributes(NewAttributes);
108 WrapperInvoke->setDebugLoc(Invoke->getDebugLoc());
109 NewCall = WrapperInvoke;
110 } else if (auto Call = dyn_cast<CallInst>(CB)) {
111 auto WrapperCall = Builder.CreateCall(Wrapper, {Awaiter, FramePtr});
112
113 WrapperCall->setAttributes(NewAttributes);
114 WrapperCall->setDebugLoc(Call->getDebugLoc());
115 NewCall = WrapperCall;
116 } else {
117 llvm_unreachable("Unexpected coro_await_suspend invocation method");
118 }
119
120 if (CB->getCalledFunction()->getIntrinsicID() ==
121 Intrinsic::coro_await_suspend_handle) {
122 // Follow the lowered await_suspend call above with a lowered resume call
123 // to the returned coroutine.
124 if (auto *Invoke = dyn_cast<InvokeInst>(CB)) {
125 // If the await_suspend call is an invoke, we continue in the next block.
126 Builder.SetInsertPoint(Invoke->getNormalDest()->getFirstInsertionPt());
127 }
128
129 coro::LowererBase LB(*Wrapper->getParent());
130 auto *ResumeAddr = LB.makeSubFnCall(NewCall, CoroSubFnInst::ResumeIndex,
131 &*Builder.GetInsertPoint());
132
133 LLVMContext &Ctx = Builder.getContext();
134 FunctionType *ResumeTy = FunctionType::get(
135 Type::getVoidTy(Ctx), PointerType::getUnqual(Ctx), false);
136 auto *ResumeCall = Builder.CreateCall(ResumeTy, ResumeAddr, {NewCall});
138
139 // We can't insert the 'ret' instruction and adjust the cc until the
140 // function has been split, so remember this for later.
141 Shape.SymmetricTransfers.push_back(ResumeCall);
142
143 NewCall = ResumeCall;
144 }
145
146 CB->replaceAllUsesWith(NewCall);
147 CB->eraseFromParent();
148}
149
151 IRBuilder<> Builder(F.getContext());
152 for (auto *AWS : Shape.CoroAwaitSuspends)
153 lowerAwaitSuspend(Builder, AWS, Shape);
154}
155
157 const coro::Shape &Shape, Value *FramePtr,
158 CallGraph *CG) {
159 assert(Shape.ABI == coro::ABI::Retcon || Shape.ABI == coro::ABI::RetconOnce);
161 return;
162
163 Shape.emitDealloc(Builder, FramePtr, CG);
164}
165
166/// Replace an llvm.coro.end.async.
167/// Will inline the must tail call function call if there is one.
168/// \returns true if cleanup of the coro.end block is needed, false otherwise.
170 IRBuilder<> Builder(End);
171
172 auto *EndAsync = dyn_cast<CoroAsyncEndInst>(End);
173 if (!EndAsync) {
174 Builder.CreateRetVoid();
175 return true /*needs cleanup of coro.end block*/;
176 }
177
178 auto *MustTailCallFunc = EndAsync->getMustTailCallFunction();
179 if (!MustTailCallFunc) {
180 Builder.CreateRetVoid();
181 return true /*needs cleanup of coro.end block*/;
182 }
183
184 // Move the must tail call from the predecessor block into the end block.
185 auto *CoroEndBlock = End->getParent();
186 auto *MustTailCallFuncBlock = CoroEndBlock->getSinglePredecessor();
187 assert(MustTailCallFuncBlock && "Must have a single predecessor block");
188 auto It = MustTailCallFuncBlock->getTerminator()->getIterator();
189 auto *MustTailCall = cast<CallInst>(&*std::prev(It));
190 CoroEndBlock->splice(End->getIterator(), MustTailCallFuncBlock,
191 MustTailCall->getIterator());
192
193 // Insert the return instruction.
194 Builder.SetInsertPoint(End);
195 Builder.CreateRetVoid();
196 InlineFunctionInfo FnInfo;
197
198 // Remove the rest of the block, by splitting it into an unreachable block.
199 auto *BB = End->getParent();
200 BB->splitBasicBlock(End);
201 BB->getTerminator()->eraseFromParent();
202
203 auto InlineRes = InlineFunction(*MustTailCall, FnInfo);
204 assert(InlineRes.isSuccess() && "Expected inlining to succeed");
205 (void)InlineRes;
206
207 // We have cleaned up the coro.end block above.
208 return false;
209}
210
211/// Replace a non-unwind call to llvm.coro.end.
213 const coro::Shape &Shape, Value *FramePtr,
214 bool InResume, CallGraph *CG) {
215 // Start inserting right before the coro.end.
216 IRBuilder<> Builder(End);
217
218 // Create the return instruction.
219 switch (Shape.ABI) {
220 // The cloned functions in switch-lowering always return void.
221 case coro::ABI::Switch:
222 assert(!cast<CoroEndInst>(End)->hasResults() &&
223 "switch coroutine should not return any values");
224 // coro.end doesn't immediately end the coroutine in the main function
225 // in this lowering, because we need to deallocate the coroutine.
226 if (!InResume)
227 return;
228 Builder.CreateRetVoid();
229 break;
230
231 // In async lowering this returns.
232 case coro::ABI::Async: {
233 bool CoroEndBlockNeedsCleanup = replaceCoroEndAsync(End);
234 if (!CoroEndBlockNeedsCleanup)
235 return;
236 break;
237 }
238
239 // In unique continuation lowering, the continuations always return void.
240 // But we may have implicitly allocated storage.
241 case coro::ABI::RetconOnce: {
242 maybeFreeRetconStorage(Builder, Shape, FramePtr, CG);
243 auto *CoroEnd = cast<CoroEndInst>(End);
244 auto *RetTy = Shape.getResumeFunctionType()->getReturnType();
245
246 if (!CoroEnd->hasResults()) {
247 assert(RetTy->isVoidTy());
248 Builder.CreateRetVoid();
249 break;
250 }
251
252 auto *CoroResults = CoroEnd->getResults();
253 unsigned NumReturns = CoroResults->numReturns();
254
255 if (auto *RetStructTy = dyn_cast<StructType>(RetTy)) {
256 assert(RetStructTy->getNumElements() == NumReturns &&
257 "numbers of returns should match resume function singature");
258 Value *ReturnValue = PoisonValue::get(RetStructTy);
259 unsigned Idx = 0;
260 for (Value *RetValEl : CoroResults->return_values())
261 ReturnValue = Builder.CreateInsertValue(ReturnValue, RetValEl, Idx++);
262 Builder.CreateRet(ReturnValue);
263 } else if (NumReturns == 0) {
264 assert(RetTy->isVoidTy());
265 Builder.CreateRetVoid();
266 } else {
267 assert(NumReturns == 1);
268 Builder.CreateRet(*CoroResults->retval_begin());
269 }
270 CoroResults->replaceAllUsesWith(
271 ConstantTokenNone::get(CoroResults->getContext()));
272 CoroResults->eraseFromParent();
273 break;
274 }
275
276 // In non-unique continuation lowering, we signal completion by returning
277 // a null continuation.
278 case coro::ABI::Retcon: {
279 assert(!cast<CoroEndInst>(End)->hasResults() &&
280 "retcon coroutine should not return any values");
281 maybeFreeRetconStorage(Builder, Shape, FramePtr, CG);
282 auto RetTy = Shape.getResumeFunctionType()->getReturnType();
283 auto RetStructTy = dyn_cast<StructType>(RetTy);
284 PointerType *ContinuationTy =
285 cast<PointerType>(RetStructTy ? RetStructTy->getElementType(0) : RetTy);
286
287 Value *ReturnValue = ConstantPointerNull::get(ContinuationTy);
288 if (RetStructTy) {
289 ReturnValue = Builder.CreateInsertValue(PoisonValue::get(RetStructTy),
290 ReturnValue, 0);
291 }
292 Builder.CreateRet(ReturnValue);
293 break;
294 }
295 }
296
297 // Remove the rest of the block, by splitting it into an unreachable block.
298 auto *BB = End->getParent();
299 BB->splitBasicBlock(End);
300 BB->getTerminator()->eraseFromParent();
301}
302
303// Mark a coroutine as done, which implies that the coroutine is finished and
304// never get resumed.
305//
306// In resume-switched ABI, the done state is represented by storing zero in
307// ResumeFnAddr.
308//
309// NOTE: We couldn't omit the argument `FramePtr`. It is necessary because the
310// pointer to the frame in splitted function is not stored in `Shape`.
311static void markCoroutineAsDone(IRBuilder<> &Builder, const coro::Shape &Shape,
312 Value *FramePtr) {
313 assert(
314 Shape.ABI == coro::ABI::Switch &&
315 "markCoroutineAsDone is only supported for Switch-Resumed ABI for now.");
316 auto *GepIndex = Builder.CreateStructGEP(
318 "ResumeFn.addr");
319 auto *NullPtr = ConstantPointerNull::get(cast<PointerType>(
321 Builder.CreateStore(NullPtr, GepIndex);
322
323 // If the coroutine don't have unwind coro end, we could omit the store to
324 // the final suspend point since we could infer the coroutine is suspended
325 // at the final suspend point by the nullness of ResumeFnAddr.
326 // However, we can't skip it if the coroutine have unwind coro end. Since
327 // the coroutine reaches unwind coro end is considered suspended at the
328 // final suspend point (the ResumeFnAddr is null) but in fact the coroutine
329 // didn't complete yet. We need the IndexVal for the final suspend point
330 // to make the states clear.
333 assert(cast<CoroSuspendInst>(Shape.CoroSuspends.back())->isFinal() &&
334 "The final suspend should only live in the last position of "
335 "CoroSuspends.");
336 ConstantInt *IndexVal = Shape.getIndex(Shape.CoroSuspends.size() - 1);
337 auto *FinalIndex = Builder.CreateStructGEP(
338 Shape.FrameTy, FramePtr, Shape.getSwitchIndexField(), "index.addr");
339
340 Builder.CreateStore(IndexVal, FinalIndex);
341 }
342}
343
344/// Replace an unwind call to llvm.coro.end.
346 Value *FramePtr, bool InResume,
347 CallGraph *CG) {
348 IRBuilder<> Builder(End);
349
350 switch (Shape.ABI) {
351 // In switch-lowering, this does nothing in the main function.
352 case coro::ABI::Switch: {
353 // In C++'s specification, the coroutine should be marked as done
354 // if promise.unhandled_exception() throws. The frontend will
355 // call coro.end(true) along this path.
356 //
357 // FIXME: We should refactor this once there is other language
358 // which uses Switch-Resumed style other than C++.
359 markCoroutineAsDone(Builder, Shape, FramePtr);
360 if (!InResume)
361 return;
362 break;
363 }
364 // In async lowering this does nothing.
365 case coro::ABI::Async:
366 break;
367 // In continuation-lowering, this frees the continuation storage.
368 case coro::ABI::Retcon:
369 case coro::ABI::RetconOnce:
370 maybeFreeRetconStorage(Builder, Shape, FramePtr, CG);
371 break;
372 }
373
374 // If coro.end has an associated bundle, add cleanupret instruction.
375 if (auto Bundle = End->getOperandBundle(LLVMContext::OB_funclet)) {
376 auto *FromPad = cast<CleanupPadInst>(Bundle->Inputs[0]);
377 auto *CleanupRet = Builder.CreateCleanupRet(FromPad, nullptr);
378 End->getParent()->splitBasicBlock(End);
379 CleanupRet->getParent()->getTerminator()->eraseFromParent();
380 }
381}
382
383static void replaceCoroEnd(AnyCoroEndInst *End, const coro::Shape &Shape,
384 Value *FramePtr, bool InResume, CallGraph *CG) {
385 if (End->isUnwind())
386 replaceUnwindCoroEnd(End, Shape, FramePtr, InResume, CG);
387 else
388 replaceFallthroughCoroEnd(End, Shape, FramePtr, InResume, CG);
389
390 auto &Context = End->getContext();
391 End->replaceAllUsesWith(InResume ? ConstantInt::getTrue(Context)
392 : ConstantInt::getFalse(Context));
393 End->eraseFromParent();
394}
395
396// In the resume function, we remove the last case (when coro::Shape is built,
397// the final suspend point (if present) is always the last element of
398// CoroSuspends array) since it is an undefined behavior to resume a coroutine
399// suspended at the final suspend point.
400// In the destroy function, if it isn't possible that the ResumeFnAddr is NULL
401// and the coroutine doesn't suspend at the final suspend point actually (this
402// is possible since the coroutine is considered suspended at the final suspend
403// point if promise.unhandled_exception() exits via an exception), we can
404// remove the last case.
408
410 return;
411
412 auto *Switch = cast<SwitchInst>(VMap[Shape.SwitchLowering.ResumeSwitch]);
413 auto FinalCaseIt = std::prev(Switch->case_end());
414 BasicBlock *ResumeBB = FinalCaseIt->getCaseSuccessor();
415 Switch->removeCase(FinalCaseIt);
417 BasicBlock *OldSwitchBB = Switch->getParent();
418 auto *NewSwitchBB = OldSwitchBB->splitBasicBlock(Switch, "Switch");
419 Builder.SetInsertPoint(OldSwitchBB->getTerminator());
420
422 // When the coroutine can only be destroyed when complete, we don't need
423 // to generate code for other cases.
424 Builder.CreateBr(ResumeBB);
425 } else {
426 auto *GepIndex = Builder.CreateStructGEP(
428 "ResumeFn.addr");
429 auto *Load =
431 auto *Cond = Builder.CreateIsNull(Load);
432 Builder.CreateCondBr(Cond, ResumeBB, NewSwitchBB);
433 }
434 OldSwitchBB->getTerminator()->eraseFromParent();
435 }
436}
437
438static FunctionType *
440 auto *AsyncSuspend = cast<CoroSuspendAsyncInst>(Suspend);
441 auto *StructTy = cast<StructType>(AsyncSuspend->getType());
442 auto &Context = Suspend->getParent()->getParent()->getContext();
443 auto *VoidTy = Type::getVoidTy(Context);
444 return FunctionType::get(VoidTy, StructTy->elements(), false);
445}
446
448 const Twine &Suffix,
449 Module::iterator InsertBefore,
450 AnyCoroSuspendInst *ActiveSuspend) {
451 Module *M = OrigF.getParent();
452 auto *FnTy = (Shape.ABI != coro::ABI::Async)
453 ? Shape.getResumeFunctionType()
454 : getFunctionTypeFromAsyncSuspend(ActiveSuspend);
455
456 Function *NewF =
458 OrigF.getName() + Suffix);
459
460 M->getFunctionList().insert(InsertBefore, NewF);
461
462 return NewF;
463}
464
465/// Replace uses of the active llvm.coro.suspend.retcon/async call with the
466/// arguments to the continuation function.
467///
468/// This assumes that the builder has a meaningful insertion point.
472
473 auto NewS = VMap[ActiveSuspend];
474 if (NewS->use_empty())
475 return;
476
477 // Copy out all the continuation arguments after the buffer pointer into
478 // an easily-indexed data structure for convenience.
480 // The async ABI includes all arguments -- including the first argument.
481 bool IsAsyncABI = Shape.ABI == coro::ABI::Async;
482 for (auto I = IsAsyncABI ? NewF->arg_begin() : std::next(NewF->arg_begin()),
483 E = NewF->arg_end();
484 I != E; ++I)
485 Args.push_back(&*I);
486
487 // If the suspend returns a single scalar value, we can just do a simple
488 // replacement.
489 if (!isa<StructType>(NewS->getType())) {
490 assert(Args.size() == 1);
491 NewS->replaceAllUsesWith(Args.front());
492 return;
493 }
494
495 // Try to peephole extracts of an aggregate return.
496 for (Use &U : llvm::make_early_inc_range(NewS->uses())) {
497 auto *EVI = dyn_cast<ExtractValueInst>(U.getUser());
498 if (!EVI || EVI->getNumIndices() != 1)
499 continue;
500
501 EVI->replaceAllUsesWith(Args[EVI->getIndices().front()]);
502 EVI->eraseFromParent();
503 }
504
505 // If we have no remaining uses, we're done.
506 if (NewS->use_empty())
507 return;
508
509 // Otherwise, we need to create an aggregate.
510 Value *Aggr = PoisonValue::get(NewS->getType());
511 for (auto [Idx, Arg] : llvm::enumerate(Args))
512 Aggr = Builder.CreateInsertValue(Aggr, Arg, Idx);
513
514 NewS->replaceAllUsesWith(Aggr);
515}
516
518 Value *SuspendResult;
519
520 switch (Shape.ABI) {
521 // In switch lowering, replace coro.suspend with the appropriate value
522 // for the type of function we're extracting.
523 // Replacing coro.suspend with (0) will result in control flow proceeding to
524 // a resume label associated with a suspend point, replacing it with (1) will
525 // result in control flow proceeding to a cleanup label associated with this
526 // suspend point.
528 SuspendResult = Builder.getInt8(isSwitchDestroyFunction() ? 1 : 0);
529 break;
530
531 // In async lowering there are no uses of the result.
532 case coro::ABI::Async:
533 return;
534
535 // In returned-continuation lowering, the arguments from earlier
536 // continuations are theoretically arbitrary, and they should have been
537 // spilled.
540 return;
541 }
542
544 // The active suspend was handled earlier.
545 if (CS == ActiveSuspend)
546 continue;
547
548 auto *MappedCS = cast<AnyCoroSuspendInst>(VMap[CS]);
549 MappedCS->replaceAllUsesWith(SuspendResult);
550 MappedCS->eraseFromParent();
551 }
552}
553
555 for (AnyCoroEndInst *CE : Shape.CoroEnds) {
556 // We use a null call graph because there's no call graph node for
557 // the cloned function yet. We'll just be rebuilding that later.
558 auto *NewCE = cast<AnyCoroEndInst>(VMap[CE]);
559 replaceCoroEnd(NewCE, Shape, NewFramePtr, /*in resume*/ true, nullptr);
560 }
561}
562
564 ValueToValueMapTy *VMap) {
565 if (Shape.ABI == coro::ABI::Async && Shape.CoroSuspends.empty())
566 return;
567 Value *CachedSlot = nullptr;
568 auto getSwiftErrorSlot = [&](Type *ValueTy) -> Value * {
569 if (CachedSlot)
570 return CachedSlot;
571
572 // Check if the function has a swifterror argument.
573 for (auto &Arg : F.args()) {
574 if (Arg.isSwiftError()) {
575 CachedSlot = &Arg;
576 return &Arg;
577 }
578 }
579
580 // Create a swifterror alloca.
581 IRBuilder<> Builder(F.getEntryBlock().getFirstNonPHIOrDbg());
582 auto Alloca = Builder.CreateAlloca(ValueTy);
583 Alloca->setSwiftError(true);
584
585 CachedSlot = Alloca;
586 return Alloca;
587 };
588
589 for (CallInst *Op : Shape.SwiftErrorOps) {
590 auto MappedOp = VMap ? cast<CallInst>((*VMap)[Op]) : Op;
591 IRBuilder<> Builder(MappedOp);
592
593 // If there are no arguments, this is a 'get' operation.
594 Value *MappedResult;
595 if (Op->arg_empty()) {
596 auto ValueTy = Op->getType();
597 auto Slot = getSwiftErrorSlot(ValueTy);
598 MappedResult = Builder.CreateLoad(ValueTy, Slot);
599 } else {
600 assert(Op->arg_size() == 1);
601 auto Value = MappedOp->getArgOperand(0);
602 auto ValueTy = Value->getType();
603 auto Slot = getSwiftErrorSlot(ValueTy);
604 Builder.CreateStore(Value, Slot);
605 MappedResult = Slot;
606 }
607
608 MappedOp->replaceAllUsesWith(MappedResult);
609 MappedOp->eraseFromParent();
610 }
611
612 // If we're updating the original function, we've invalidated SwiftErrorOps.
613 if (VMap == nullptr) {
614 Shape.SwiftErrorOps.clear();
615 }
616}
617
618/// Returns all DbgVariableIntrinsic in F.
619static std::pair<SmallVector<DbgVariableIntrinsic *, 8>,
623 SmallVector<DbgVariableRecord *> DbgVariableRecords;
624 for (auto &I : instructions(F)) {
625 for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange()))
626 DbgVariableRecords.push_back(&DVR);
627 if (auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I))
628 Intrinsics.push_back(DVI);
629 }
630 return {Intrinsics, DbgVariableRecords};
631}
632
634 ::replaceSwiftErrorOps(*NewF, Shape, &VMap);
635}
636
638 auto [Worklist, DbgVariableRecords] = collectDbgVariableIntrinsics(*NewF);
640
641 // Only 64-bit ABIs have a register we can refer to with the entry value.
642 bool UseEntryValue =
643 llvm::Triple(OrigF.getParent()->getTargetTriple()).isArch64Bit();
644 for (DbgVariableIntrinsic *DVI : Worklist)
645 coro::salvageDebugInfo(ArgToAllocaMap, *DVI, UseEntryValue);
646 for (DbgVariableRecord *DVR : DbgVariableRecords)
647 coro::salvageDebugInfo(ArgToAllocaMap, *DVR, UseEntryValue);
648
649 // Remove all salvaged dbg.declare intrinsics that became
650 // either unreachable or stale due to the CoroSplit transformation.
651 DominatorTree DomTree(*NewF);
652 auto IsUnreachableBlock = [&](BasicBlock *BB) {
653 return !isPotentiallyReachable(&NewF->getEntryBlock(), BB, nullptr,
654 &DomTree);
655 };
656 auto RemoveOne = [&](auto *DVI) {
657 if (IsUnreachableBlock(DVI->getParent()))
658 DVI->eraseFromParent();
659 else if (isa_and_nonnull<AllocaInst>(DVI->getVariableLocationOp(0))) {
660 // Count all non-debuginfo uses in reachable blocks.
661 unsigned Uses = 0;
662 for (auto *User : DVI->getVariableLocationOp(0)->users())
663 if (auto *I = dyn_cast<Instruction>(User))
664 if (!isa<AllocaInst>(I) && !IsUnreachableBlock(I->getParent()))
665 ++Uses;
666 if (!Uses)
667 DVI->eraseFromParent();
668 }
669 };
670 for_each(Worklist, RemoveOne);
671 for_each(DbgVariableRecords, RemoveOne);
672}
673
675 // In the original function, the AllocaSpillBlock is a block immediately
676 // following the allocation of the frame object which defines GEPs for
677 // all the allocas that have been moved into the frame, and it ends by
678 // branching to the original beginning of the coroutine. Make this
679 // the entry block of the cloned function.
680 auto *Entry = cast<BasicBlock>(VMap[Shape.AllocaSpillBlock]);
681 auto *OldEntry = &NewF->getEntryBlock();
682 Entry->setName("entry" + Suffix);
683 Entry->moveBefore(OldEntry);
684 Entry->getTerminator()->eraseFromParent();
685
686 // Clear all predecessors of the new entry block. There should be
687 // exactly one predecessor, which we created when splitting out
688 // AllocaSpillBlock to begin with.
689 assert(Entry->hasOneUse());
690 auto BranchToEntry = cast<BranchInst>(Entry->user_back());
691 assert(BranchToEntry->isUnconditional());
692 Builder.SetInsertPoint(BranchToEntry);
693 Builder.CreateUnreachable();
694 BranchToEntry->eraseFromParent();
695
696 // Branch from the entry to the appropriate place.
697 Builder.SetInsertPoint(Entry);
698 switch (Shape.ABI) {
699 case coro::ABI::Switch: {
700 // In switch-lowering, we built a resume-entry block in the original
701 // function. Make the entry block branch to this.
702 auto *SwitchBB =
703 cast<BasicBlock>(VMap[Shape.SwitchLowering.ResumeEntryBlock]);
704 Builder.CreateBr(SwitchBB);
705 break;
706 }
707 case coro::ABI::Async:
710 // In continuation ABIs, we want to branch to immediately after the
711 // active suspend point. Earlier phases will have put the suspend in its
712 // own basic block, so just thread our jump directly to its successor.
714 isa<CoroSuspendAsyncInst>(ActiveSuspend)) ||
717 isa<CoroSuspendRetconInst>(ActiveSuspend)));
718 auto *MappedCS = cast<AnyCoroSuspendInst>(VMap[ActiveSuspend]);
719 auto Branch = cast<BranchInst>(MappedCS->getNextNode());
720 assert(Branch->isUnconditional());
721 Builder.CreateBr(Branch->getSuccessor(0));
722 break;
723 }
724 }
725
726 // Any static alloca that's still being used but not reachable from the new
727 // entry needs to be moved to the new entry.
728 Function *F = OldEntry->getParent();
729 DominatorTree DT{*F};
731 auto *Alloca = dyn_cast<AllocaInst>(&I);
732 if (!Alloca || I.use_empty())
733 continue;
734 if (DT.isReachableFromEntry(I.getParent()) ||
735 !isa<ConstantInt>(Alloca->getArraySize()))
736 continue;
737 I.moveBefore(*Entry, Entry->getFirstInsertionPt());
738 }
739}
740
741/// Derive the value of the new frame pointer.
743 // Builder should be inserting to the front of the new entry block.
744
745 switch (Shape.ABI) {
746 // In switch-lowering, the argument is the frame pointer.
748 return &*NewF->arg_begin();
749 // In async-lowering, one of the arguments is an async context as determined
750 // by the `llvm.coro.id.async` intrinsic. We can retrieve the async context of
751 // the resume function from the async context projection function associated
752 // with the active suspend. The frame is located as a tail to the async
753 // context header.
754 case coro::ABI::Async: {
755 auto *ActiveAsyncSuspend = cast<CoroSuspendAsyncInst>(ActiveSuspend);
756 auto ContextIdx = ActiveAsyncSuspend->getStorageArgumentIndex() & 0xff;
757 auto *CalleeContext = NewF->getArg(ContextIdx);
758 auto *ProjectionFunc =
759 ActiveAsyncSuspend->getAsyncContextProjectionFunction();
760 auto DbgLoc =
761 cast<CoroSuspendAsyncInst>(VMap[ActiveSuspend])->getDebugLoc();
762 // Calling i8* (i8*)
763 auto *CallerContext = Builder.CreateCall(ProjectionFunc->getFunctionType(),
764 ProjectionFunc, CalleeContext);
765 CallerContext->setCallingConv(ProjectionFunc->getCallingConv());
766 CallerContext->setDebugLoc(DbgLoc);
767 // The frame is located after the async_context header.
768 auto &Context = Builder.getContext();
769 auto *FramePtrAddr = Builder.CreateConstInBoundsGEP1_32(
770 Type::getInt8Ty(Context), CallerContext,
771 Shape.AsyncLowering.FrameOffset, "async.ctx.frameptr");
772 // Inline the projection function.
774 auto InlineRes = InlineFunction(*CallerContext, InlineInfo);
775 assert(InlineRes.isSuccess());
776 (void)InlineRes;
777 return FramePtrAddr;
778 }
779 // In continuation-lowering, the argument is the opaque storage.
782 Argument *NewStorage = &*NewF->arg_begin();
783 auto FramePtrTy = PointerType::getUnqual(Shape.FrameTy->getContext());
784
785 // If the storage is inline, just bitcast to the storage to the frame type.
787 return NewStorage;
788
789 // Otherwise, load the real frame from the opaque storage.
790 return Builder.CreateLoad(FramePtrTy, NewStorage);
791 }
792 }
793 llvm_unreachable("bad ABI");
794}
795
796/// Adjust the scope line of the funclet to the first line number after the
797/// suspend point. This avoids a jump in the line table from the function
798/// declaration (where prologue instructions are attributed to) to the suspend
799/// point.
800/// Only adjust the scope line when the files are the same.
801/// If no candidate line number is found, fallback to the line of ActiveSuspend.
802static void updateScopeLine(Instruction *ActiveSuspend,
803 DISubprogram &SPToUpdate) {
804 if (!ActiveSuspend)
805 return;
806
807 auto *Successor = ActiveSuspend->getNextNonDebugInstruction();
808 // Corosplit splits the BB around ActiveSuspend, so the meaningful
809 // instructions are not in the same BB.
810 if (auto *Branch = dyn_cast_or_null<BranchInst>(Successor);
811 Branch && Branch->isUnconditional())
812 Successor = Branch->getSuccessor(0)->getFirstNonPHIOrDbg();
813
814 // Find the first successor of ActiveSuspend with a non-zero line location.
815 // If that matches the file of ActiveSuspend, use it.
816 for (; Successor; Successor = Successor->getNextNonDebugInstruction()) {
817 auto DL = Successor->getDebugLoc();
818 if (!DL || DL.getLine() == 0)
819 continue;
820
821 if (SPToUpdate.getFile() == DL->getFile()) {
822 SPToUpdate.setScopeLine(DL.getLine());
823 return;
824 }
825
826 break;
827 }
828
829 // If the search above failed, fallback to the location of ActiveSuspend.
830 if (auto DL = ActiveSuspend->getDebugLoc())
831 if (SPToUpdate.getFile() == DL->getFile())
832 SPToUpdate.setScopeLine(DL->getLine());
833}
834
835static void addFramePointerAttrs(AttributeList &Attrs, LLVMContext &Context,
836 unsigned ParamIndex, uint64_t Size,
837 Align Alignment, bool NoAlias) {
838 AttrBuilder ParamAttrs(Context);
839 ParamAttrs.addAttribute(Attribute::NonNull);
840 ParamAttrs.addAttribute(Attribute::NoUndef);
841
842 if (NoAlias)
843 ParamAttrs.addAttribute(Attribute::NoAlias);
844
845 ParamAttrs.addAlignmentAttr(Alignment);
846 ParamAttrs.addDereferenceableAttr(Size);
847 Attrs = Attrs.addParamAttributes(Context, ParamIndex, ParamAttrs);
848}
849
850static void addAsyncContextAttrs(AttributeList &Attrs, LLVMContext &Context,
851 unsigned ParamIndex) {
852 AttrBuilder ParamAttrs(Context);
853 ParamAttrs.addAttribute(Attribute::SwiftAsync);
854 Attrs = Attrs.addParamAttributes(Context, ParamIndex, ParamAttrs);
855}
856
857static void addSwiftSelfAttrs(AttributeList &Attrs, LLVMContext &Context,
858 unsigned ParamIndex) {
859 AttrBuilder ParamAttrs(Context);
860 ParamAttrs.addAttribute(Attribute::SwiftSelf);
861 Attrs = Attrs.addParamAttributes(Context, ParamIndex, ParamAttrs);
862}
863
864/// Clone the body of the original function into a resume function of
865/// some sort.
867 assert(NewF);
868
869 // Replace all args with dummy instructions. If an argument is the old frame
870 // pointer, the dummy will be replaced by the new frame pointer once it is
871 // computed below. Uses of all other arguments should have already been
872 // rewritten by buildCoroutineFrame() to use loads/stores on the coroutine
873 // frame.
875 for (Argument &A : OrigF.args()) {
876 DummyArgs.push_back(new FreezeInst(PoisonValue::get(A.getType())));
877 VMap[&A] = DummyArgs.back();
878 }
879
881
882 // Ignore attempts to change certain attributes of the function.
883 // TODO: maybe there should be a way to suppress this during cloning?
884 auto savedVisibility = NewF->getVisibility();
885 auto savedUnnamedAddr = NewF->getUnnamedAddr();
886 auto savedDLLStorageClass = NewF->getDLLStorageClass();
887
888 // NewF's linkage (which CloneFunctionInto does *not* change) might not
889 // be compatible with the visibility of OrigF (which it *does* change),
890 // so protect against that.
891 auto savedLinkage = NewF->getLinkage();
892 NewF->setLinkage(llvm::GlobalValue::ExternalLinkage);
893
894 CloneFunctionInto(NewF, &OrigF, VMap,
896
897 auto &Context = NewF->getContext();
898
899 if (DISubprogram *SP = NewF->getSubprogram()) {
900 assert(SP != OrigF.getSubprogram() && SP->isDistinct());
901 updateScopeLine(ActiveSuspend, *SP);
902
903 // Update the linkage name to reflect the modified symbol name. It
904 // is necessary to update the linkage name in Swift, since the
905 // mangling changes for resume functions. It might also be the
906 // right thing to do in C++, but due to a limitation in LLVM's
907 // AsmPrinter we can only do this if the function doesn't have an
908 // abstract specification, since the DWARF backend expects the
909 // abstract specification to contain the linkage name and asserts
910 // that they are identical.
911 if (SP->getUnit() &&
912 SP->getUnit()->getSourceLanguage() == dwarf::DW_LANG_Swift) {
913 SP->replaceLinkageName(MDString::get(Context, NewF->getName()));
914 if (auto *Decl = SP->getDeclaration()) {
915 auto *NewDecl = DISubprogram::get(
916 Decl->getContext(), Decl->getScope(), Decl->getName(),
917 NewF->getName(), Decl->getFile(), Decl->getLine(), Decl->getType(),
918 Decl->getScopeLine(), Decl->getContainingType(),
919 Decl->getVirtualIndex(), Decl->getThisAdjustment(),
920 Decl->getFlags(), Decl->getSPFlags(), Decl->getUnit(),
921 Decl->getTemplateParams(), nullptr, Decl->getRetainedNodes(),
922 Decl->getThrownTypes(), Decl->getAnnotations(),
923 Decl->getTargetFuncName());
924 SP->replaceDeclaration(NewDecl);
925 }
926 }
927 }
928
929 NewF->setLinkage(savedLinkage);
930 NewF->setVisibility(savedVisibility);
931 NewF->setUnnamedAddr(savedUnnamedAddr);
932 NewF->setDLLStorageClass(savedDLLStorageClass);
933 // The function sanitizer metadata needs to match the signature of the
934 // function it is being attached to. However this does not hold for split
935 // functions here. Thus remove the metadata for split functions.
936 if (Shape.ABI == coro::ABI::Switch &&
937 NewF->hasMetadata(LLVMContext::MD_func_sanitize))
938 NewF->eraseMetadata(LLVMContext::MD_func_sanitize);
939
940 // Replace the attributes of the new function:
941 auto OrigAttrs = NewF->getAttributes();
942 auto NewAttrs = AttributeList();
943
944 switch (Shape.ABI) {
946 // Bootstrap attributes by copying function attributes from the
947 // original function. This should include optimization settings and so on.
948 NewAttrs = NewAttrs.addFnAttributes(
949 Context, AttrBuilder(Context, OrigAttrs.getFnAttrs()));
950
951 addFramePointerAttrs(NewAttrs, Context, 0, Shape.FrameSize,
952 Shape.FrameAlign, /*NoAlias=*/false);
953 break;
954 case coro::ABI::Async: {
955 auto *ActiveAsyncSuspend = cast<CoroSuspendAsyncInst>(ActiveSuspend);
956 if (OrigF.hasParamAttribute(Shape.AsyncLowering.ContextArgNo,
957 Attribute::SwiftAsync)) {
958 uint32_t ArgAttributeIndices =
959 ActiveAsyncSuspend->getStorageArgumentIndex();
960 auto ContextArgIndex = ArgAttributeIndices & 0xff;
961 addAsyncContextAttrs(NewAttrs, Context, ContextArgIndex);
962
963 // `swiftasync` must preceed `swiftself` so 0 is not a valid index for
964 // `swiftself`.
965 auto SwiftSelfIndex = ArgAttributeIndices >> 8;
966 if (SwiftSelfIndex)
967 addSwiftSelfAttrs(NewAttrs, Context, SwiftSelfIndex);
968 }
969
970 // Transfer the original function's attributes.
971 auto FnAttrs = OrigF.getAttributes().getFnAttrs();
972 NewAttrs = NewAttrs.addFnAttributes(Context, AttrBuilder(Context, FnAttrs));
973 break;
974 }
977 // If we have a continuation prototype, just use its attributes,
978 // full-stop.
980
981 /// FIXME: Is it really good to add the NoAlias attribute?
982 addFramePointerAttrs(NewAttrs, Context, 0,
985 /*NoAlias=*/true);
986
987 break;
988 }
989
990 switch (Shape.ABI) {
991 // In these ABIs, the cloned functions always return 'void', and the
992 // existing return sites are meaningless. Note that for unique
993 // continuations, this includes the returns associated with suspends;
994 // this is fine because we can't suspend twice.
997 // Remove old returns.
998 for (ReturnInst *Return : Returns)
999 changeToUnreachable(Return);
1000 break;
1001
1002 // With multi-suspend continuations, we'll already have eliminated the
1003 // original returns and inserted returns before all the suspend points,
1004 // so we want to leave any returns in place.
1005 case coro::ABI::Retcon:
1006 break;
1007 // Async lowering will insert musttail call functions at all suspend points
1008 // followed by a return.
1009 // Don't change returns to unreachable because that will trip up the verifier.
1010 // These returns should be unreachable from the clone.
1011 case coro::ABI::Async:
1012 break;
1013 }
1014
1015 NewF->setAttributes(NewAttrs);
1016 NewF->setCallingConv(Shape.getResumeFunctionCC());
1017
1018 // Set up the new entry block.
1019 replaceEntryBlock();
1020
1021 // Turn symmetric transfers into musttail calls.
1022 for (CallInst *ResumeCall : Shape.SymmetricTransfers) {
1023 ResumeCall = cast<CallInst>(VMap[ResumeCall]);
1024 if (TTI.supportsTailCallFor(ResumeCall)) {
1025 // FIXME: Could we support symmetric transfer effectively without
1026 // musttail?
1027 ResumeCall->setTailCallKind(CallInst::TCK_MustTail);
1028 }
1029
1030 // Put a 'ret void' after the call, and split any remaining instructions to
1031 // an unreachable block.
1032 BasicBlock *BB = ResumeCall->getParent();
1033 BB->splitBasicBlock(ResumeCall->getNextNode());
1034 Builder.SetInsertPoint(BB->getTerminator());
1035 Builder.CreateRetVoid();
1037 }
1038
1039 Builder.SetInsertPoint(&NewF->getEntryBlock().front());
1040 NewFramePtr = deriveNewFramePointer();
1041
1042 // Remap frame pointer.
1043 Value *OldFramePtr = VMap[Shape.FramePtr];
1044 NewFramePtr->takeName(OldFramePtr);
1045 OldFramePtr->replaceAllUsesWith(NewFramePtr);
1046
1047 // Remap vFrame pointer.
1048 auto *NewVFrame = Builder.CreateBitCast(
1049 NewFramePtr, PointerType::getUnqual(Builder.getContext()), "vFrame");
1050 Value *OldVFrame = cast<Value>(VMap[Shape.CoroBegin]);
1051 if (OldVFrame != NewVFrame)
1052 OldVFrame->replaceAllUsesWith(NewVFrame);
1053
1054 // All uses of the arguments should have been resolved by this point,
1055 // so we can safely remove the dummy values.
1056 for (Instruction *DummyArg : DummyArgs) {
1057 DummyArg->replaceAllUsesWith(PoisonValue::get(DummyArg->getType()));
1058 DummyArg->deleteValue();
1059 }
1060
1061 switch (Shape.ABI) {
1062 case coro::ABI::Switch:
1063 // Rewrite final suspend handling as it is not done via switch (allows to
1064 // remove final case from the switch, since it is undefined behavior to
1065 // resume the coroutine suspended at the final suspend point.
1067 handleFinalSuspend();
1068 break;
1069 case coro::ABI::Async:
1070 case coro::ABI::Retcon:
1072 // Replace uses of the active suspend with the corresponding
1073 // continuation-function arguments.
1074 assert(ActiveSuspend != nullptr &&
1075 "no active suspend when lowering a continuation-style coroutine");
1076 replaceRetconOrAsyncSuspendUses();
1077 break;
1078 }
1079
1080 // Handle suspends.
1081 replaceCoroSuspends();
1082
1083 // Handle swifterror.
1085
1086 // Remove coro.end intrinsics.
1087 replaceCoroEnds();
1088
1089 // Salvage debug info that points into the coroutine frame.
1091}
1092
1094 // Create a new function matching the original type
1095 NewF = createCloneDeclaration(OrigF, Shape, Suffix, OrigF.getParent()->end(),
1096 ActiveSuspend);
1097
1098 // Clone the function
1100
1101 // Eliminate coro.free from the clones, replacing it with 'null' in cleanup,
1102 // to suppress deallocation code.
1103 coro::replaceCoroFree(cast<CoroIdInst>(VMap[Shape.CoroBegin->getId()]),
1104 /*Elide=*/FKind == coro::CloneKind::SwitchCleanup);
1105}
1106
1108 assert(Shape.ABI == coro::ABI::Async);
1109
1110 auto *FuncPtrStruct = cast<ConstantStruct>(
1112 auto *OrigRelativeFunOffset = FuncPtrStruct->getOperand(0);
1113 auto *OrigContextSize = FuncPtrStruct->getOperand(1);
1114 auto *NewContextSize = ConstantInt::get(OrigContextSize->getType(),
1116 auto *NewFuncPtrStruct = ConstantStruct::get(
1117 FuncPtrStruct->getType(), OrigRelativeFunOffset, NewContextSize);
1118
1119 Shape.AsyncLowering.AsyncFuncPointer->setInitializer(NewFuncPtrStruct);
1120}
1121
1123 // In the same function all coro.sizes should have the same result type.
1124 auto *SizeIntrin = Shape.CoroSizes.back();
1125 Module *M = SizeIntrin->getModule();
1126 const DataLayout &DL = M->getDataLayout();
1127 return DL.getTypeAllocSize(Shape.FrameTy);
1128}
1129
1131 if (Shape.ABI == coro::ABI::Async)
1133
1134 for (CoroAlignInst *CA : Shape.CoroAligns) {
1136 ConstantInt::get(CA->getType(), Shape.FrameAlign.value()));
1137 CA->eraseFromParent();
1138 }
1139
1140 if (Shape.CoroSizes.empty())
1141 return;
1142
1143 // In the same function all coro.sizes should have the same result type.
1144 auto *SizeIntrin = Shape.CoroSizes.back();
1145 auto *SizeConstant =
1146 ConstantInt::get(SizeIntrin->getType(), getFrameSizeForShape(Shape));
1147
1148 for (CoroSizeInst *CS : Shape.CoroSizes) {
1149 CS->replaceAllUsesWith(SizeConstant);
1150 CS->eraseFromParent();
1151 }
1152}
1153
1156
1157#ifndef NDEBUG
1158 // For now, we do a mandatory verification step because we don't
1159 // entirely trust this pass. Note that we don't want to add a verifier
1160 // pass to FPM below because it will also verify all the global data.
1161 if (verifyFunction(F, &errs()))
1162 report_fatal_error("Broken function");
1163#endif
1164}
1165
1166// Coroutine has no suspend points. Remove heap allocation for the coroutine
1167// frame if possible.
1169 auto *CoroBegin = Shape.CoroBegin;
1170 switch (Shape.ABI) {
1171 case coro::ABI::Switch: {
1172 auto SwitchId = Shape.getSwitchCoroId();
1173 auto *AllocInst = SwitchId->getCoroAlloc();
1174 coro::replaceCoroFree(SwitchId, /*Elide=*/AllocInst != nullptr);
1175 if (AllocInst) {
1176 IRBuilder<> Builder(AllocInst);
1177 auto *Frame = Builder.CreateAlloca(Shape.FrameTy);
1178 Frame->setAlignment(Shape.FrameAlign);
1179 AllocInst->replaceAllUsesWith(Builder.getFalse());
1180 AllocInst->eraseFromParent();
1181 CoroBegin->replaceAllUsesWith(Frame);
1182 } else {
1183 CoroBegin->replaceAllUsesWith(CoroBegin->getMem());
1184 }
1185
1186 break;
1187 }
1188 case coro::ABI::Async:
1189 case coro::ABI::Retcon:
1191 CoroBegin->replaceAllUsesWith(PoisonValue::get(CoroBegin->getType()));
1192 break;
1193 }
1194
1195 CoroBegin->eraseFromParent();
1196 Shape.CoroBegin = nullptr;
1197}
1198
1199// SimplifySuspendPoint needs to check that there is no calls between
1200// coro_save and coro_suspend, since any of the calls may potentially resume
1201// the coroutine and if that is the case we cannot eliminate the suspend point.
1203 for (Instruction *I = From; I != To; I = I->getNextNode()) {
1204 // Assume that no intrinsic can resume the coroutine.
1205 if (isa<IntrinsicInst>(I))
1206 continue;
1207
1208 if (isa<CallBase>(I))
1209 return true;
1210 }
1211 return false;
1212}
1213
1214static bool hasCallsInBlocksBetween(BasicBlock *SaveBB, BasicBlock *ResDesBB) {
1217
1218 Set.insert(SaveBB);
1219 Worklist.push_back(ResDesBB);
1220
1221 // Accumulate all blocks between SaveBB and ResDesBB. Because CoroSaveIntr
1222 // returns a token consumed by suspend instruction, all blocks in between
1223 // will have to eventually hit SaveBB when going backwards from ResDesBB.
1224 while (!Worklist.empty()) {
1225 auto *BB = Worklist.pop_back_val();
1226 Set.insert(BB);
1227 for (auto *Pred : predecessors(BB))
1228 if (!Set.contains(Pred))
1229 Worklist.push_back(Pred);
1230 }
1231
1232 // SaveBB and ResDesBB are checked separately in hasCallsBetween.
1233 Set.erase(SaveBB);
1234 Set.erase(ResDesBB);
1235
1236 for (auto *BB : Set)
1237 if (hasCallsInBlockBetween(BB->getFirstNonPHI(), nullptr))
1238 return true;
1239
1240 return false;
1241}
1242
1243static bool hasCallsBetween(Instruction *Save, Instruction *ResumeOrDestroy) {
1244 auto *SaveBB = Save->getParent();
1245 auto *ResumeOrDestroyBB = ResumeOrDestroy->getParent();
1246
1247 if (SaveBB == ResumeOrDestroyBB)
1248 return hasCallsInBlockBetween(Save->getNextNode(), ResumeOrDestroy);
1249
1250 // Any calls from Save to the end of the block?
1251 if (hasCallsInBlockBetween(Save->getNextNode(), nullptr))
1252 return true;
1253
1254 // Any calls from begging of the block up to ResumeOrDestroy?
1255 if (hasCallsInBlockBetween(ResumeOrDestroyBB->getFirstNonPHI(),
1256 ResumeOrDestroy))
1257 return true;
1258
1259 // Any calls in all of the blocks between SaveBB and ResumeOrDestroyBB?
1260 if (hasCallsInBlocksBetween(SaveBB, ResumeOrDestroyBB))
1261 return true;
1262
1263 return false;
1264}
1265
1266// If a SuspendIntrin is preceded by Resume or Destroy, we can eliminate the
1267// suspend point and replace it with nornal control flow.
1269 CoroBeginInst *CoroBegin) {
1270 Instruction *Prev = Suspend->getPrevNode();
1271 if (!Prev) {
1272 auto *Pred = Suspend->getParent()->getSinglePredecessor();
1273 if (!Pred)
1274 return false;
1275 Prev = Pred->getTerminator();
1276 }
1277
1278 CallBase *CB = dyn_cast<CallBase>(Prev);
1279 if (!CB)
1280 return false;
1281
1282 auto *Callee = CB->getCalledOperand()->stripPointerCasts();
1283
1284 // See if the callsite is for resumption or destruction of the coroutine.
1285 auto *SubFn = dyn_cast<CoroSubFnInst>(Callee);
1286 if (!SubFn)
1287 return false;
1288
1289 // Does not refer to the current coroutine, we cannot do anything with it.
1290 if (SubFn->getFrame() != CoroBegin)
1291 return false;
1292
1293 // See if the transformation is safe. Specifically, see if there are any
1294 // calls in between Save and CallInstr. They can potenitally resume the
1295 // coroutine rendering this optimization unsafe.
1296 auto *Save = Suspend->getCoroSave();
1297 if (hasCallsBetween(Save, CB))
1298 return false;
1299
1300 // Replace llvm.coro.suspend with the value that results in resumption over
1301 // the resume or cleanup path.
1302 Suspend->replaceAllUsesWith(SubFn->getRawIndex());
1303 Suspend->eraseFromParent();
1304 Save->eraseFromParent();
1305
1306 // No longer need a call to coro.resume or coro.destroy.
1307 if (auto *Invoke = dyn_cast<InvokeInst>(CB)) {
1308 BranchInst::Create(Invoke->getNormalDest(), Invoke->getIterator());
1309 }
1310
1311 // Grab the CalledValue from CB before erasing the CallInstr.
1312 auto *CalledValue = CB->getCalledOperand();
1313 CB->eraseFromParent();
1314
1315 // If no more users remove it. Usually it is a bitcast of SubFn.
1316 if (CalledValue != SubFn && CalledValue->user_empty())
1317 if (auto *I = dyn_cast<Instruction>(CalledValue))
1318 I->eraseFromParent();
1319
1320 // Now we are good to remove SubFn.
1321 if (SubFn->user_empty())
1322 SubFn->eraseFromParent();
1323
1324 return true;
1325}
1326
1327// Remove suspend points that are simplified.
1329 // Currently, the only simplification we do is switch-lowering-specific.
1330 if (Shape.ABI != coro::ABI::Switch)
1331 return;
1332
1333 auto &S = Shape.CoroSuspends;
1334 size_t I = 0, N = S.size();
1335 if (N == 0)
1336 return;
1337
1338 size_t ChangedFinalIndex = std::numeric_limits<size_t>::max();
1339 while (true) {
1340 auto SI = cast<CoroSuspendInst>(S[I]);
1341 // Leave final.suspend to handleFinalSuspend since it is undefined behavior
1342 // to resume a coroutine suspended at the final suspend point.
1343 if (!SI->isFinal() && simplifySuspendPoint(SI, Shape.CoroBegin)) {
1344 if (--N == I)
1345 break;
1346
1347 std::swap(S[I], S[N]);
1348
1349 if (cast<CoroSuspendInst>(S[I])->isFinal()) {
1351 ChangedFinalIndex = I;
1352 }
1353
1354 continue;
1355 }
1356 if (++I == N)
1357 break;
1358 }
1359 S.resize(N);
1360
1361 // Maintain final.suspend in case final suspend was swapped.
1362 // Due to we requrie the final suspend to be the last element of CoroSuspends.
1363 if (ChangedFinalIndex < N) {
1364 assert(cast<CoroSuspendInst>(S[ChangedFinalIndex])->isFinal());
1365 std::swap(S[ChangedFinalIndex], S.back());
1366 }
1367}
1368
1369namespace {
1370
1371struct SwitchCoroutineSplitter {
1372 static void split(Function &F, coro::Shape &Shape,
1375 assert(Shape.ABI == coro::ABI::Switch);
1376
1377 // Create a resume clone by cloning the body of the original function,
1378 // setting new entry block and replacing coro.suspend an appropriate value
1379 // to force resume or cleanup pass for every suspend point.
1380 createResumeEntryBlock(F, Shape);
1381 auto *ResumeClone = coro::SwitchCloner::createClone(
1382 F, ".resume", Shape, coro::CloneKind::SwitchResume, TTI);
1383 auto *DestroyClone = coro::SwitchCloner::createClone(
1384 F, ".destroy", Shape, coro::CloneKind::SwitchUnwind, TTI);
1385 auto *CleanupClone = coro::SwitchCloner::createClone(
1386 F, ".cleanup", Shape, coro::CloneKind::SwitchCleanup, TTI);
1387
1388 postSplitCleanup(*ResumeClone);
1389 postSplitCleanup(*DestroyClone);
1390 postSplitCleanup(*CleanupClone);
1391
1392 // Store addresses resume/destroy/cleanup functions in the coroutine frame.
1393 updateCoroFrame(Shape, ResumeClone, DestroyClone, CleanupClone);
1394
1395 assert(Clones.empty());
1396 Clones.push_back(ResumeClone);
1397 Clones.push_back(DestroyClone);
1398 Clones.push_back(CleanupClone);
1399
1400 // Create a constant array referring to resume/destroy/clone functions
1401 // pointed by the last argument of @llvm.coro.info, so that CoroElide pass
1402 // can determined correct function to call.
1403 setCoroInfo(F, Shape, Clones);
1404 }
1405
1406 // Create a variant of ramp function that does not perform heap allocation
1407 // for a switch ABI coroutine.
1408 //
1409 // The newly split `.noalloc` ramp function has the following differences:
1410 // - Has one additional frame pointer parameter in lieu of dynamic
1411 // allocation.
1412 // - Suppressed allocations by replacing coro.alloc and coro.free.
1413 static Function *createNoAllocVariant(Function &F, coro::Shape &Shape,
1415 assert(Shape.ABI == coro::ABI::Switch);
1416 auto *OrigFnTy = F.getFunctionType();
1417 auto OldParams = OrigFnTy->params();
1418
1419 SmallVector<Type *> NewParams;
1420 NewParams.reserve(OldParams.size() + 1);
1421 NewParams.append(OldParams.begin(), OldParams.end());
1422 NewParams.push_back(PointerType::getUnqual(Shape.FrameTy));
1423
1424 auto *NewFnTy = FunctionType::get(OrigFnTy->getReturnType(), NewParams,
1425 OrigFnTy->isVarArg());
1426 Function *NoAllocF =
1427 Function::Create(NewFnTy, F.getLinkage(), F.getName() + ".noalloc");
1428
1429 ValueToValueMapTy VMap;
1430 unsigned int Idx = 0;
1431 for (const auto &I : F.args()) {
1432 VMap[&I] = NoAllocF->getArg(Idx++);
1433 }
1434 // We just appended the frame pointer as the last argument of the new
1435 // function.
1436 auto FrameIdx = NoAllocF->arg_size() - 1;
1438 CloneFunctionInto(NoAllocF, &F, VMap,
1439 CloneFunctionChangeType::LocalChangesOnly, Returns);
1440
1441 if (Shape.CoroBegin) {
1442 auto *NewCoroBegin =
1443 cast_if_present<CoroBeginInst>(VMap[Shape.CoroBegin]);
1444 auto *NewCoroId = cast<CoroIdInst>(NewCoroBegin->getId());
1445 coro::replaceCoroFree(NewCoroId, /*Elide=*/true);
1446 coro::suppressCoroAllocs(NewCoroId);
1447 NewCoroBegin->replaceAllUsesWith(NoAllocF->getArg(FrameIdx));
1448 NewCoroBegin->eraseFromParent();
1449 }
1450
1451 Module *M = F.getParent();
1452 M->getFunctionList().insert(M->end(), NoAllocF);
1453
1454 removeUnreachableBlocks(*NoAllocF);
1455 auto NewAttrs = NoAllocF->getAttributes();
1456 // When we elide allocation, we read these attributes to determine the
1457 // frame size and alignment.
1458 addFramePointerAttrs(NewAttrs, NoAllocF->getContext(), FrameIdx,
1459 Shape.FrameSize, Shape.FrameAlign,
1460 /*NoAlias=*/false);
1461
1462 NoAllocF->setAttributes(NewAttrs);
1463
1464 Clones.push_back(NoAllocF);
1465 // Reset the original function's coro info, make the new noalloc variant
1466 // connected to the original ramp function.
1467 setCoroInfo(F, Shape, Clones);
1468 // After copying, set the linkage to internal linkage. Original function
1469 // may have different linkage, but optimization dependent on this function
1470 // generally relies on LTO.
1472 return NoAllocF;
1473 }
1474
1475private:
1476 // Create an entry block for a resume function with a switch that will jump to
1477 // suspend points.
1478 static void createResumeEntryBlock(Function &F, coro::Shape &Shape) {
1479 LLVMContext &C = F.getContext();
1480
1481 // resume.entry:
1482 // %index.addr = getelementptr inbounds %f.Frame, %f.Frame* %FramePtr, i32
1483 // 0, i32 2 % index = load i32, i32* %index.addr switch i32 %index, label
1484 // %unreachable [
1485 // i32 0, label %resume.0
1486 // i32 1, label %resume.1
1487 // ...
1488 // ]
1489
1490 auto *NewEntry = BasicBlock::Create(C, "resume.entry", &F);
1491 auto *UnreachBB = BasicBlock::Create(C, "unreachable", &F);
1492
1493 IRBuilder<> Builder(NewEntry);
1494 auto *FramePtr = Shape.FramePtr;
1495 auto *FrameTy = Shape.FrameTy;
1496 auto *GepIndex = Builder.CreateStructGEP(
1497 FrameTy, FramePtr, Shape.getSwitchIndexField(), "index.addr");
1498 auto *Index = Builder.CreateLoad(Shape.getIndexType(), GepIndex, "index");
1499 auto *Switch =
1500 Builder.CreateSwitch(Index, UnreachBB, Shape.CoroSuspends.size());
1502
1503 size_t SuspendIndex = 0;
1504 for (auto *AnyS : Shape.CoroSuspends) {
1505 auto *S = cast<CoroSuspendInst>(AnyS);
1506 ConstantInt *IndexVal = Shape.getIndex(SuspendIndex);
1507
1508 // Replace CoroSave with a store to Index:
1509 // %index.addr = getelementptr %f.frame... (index field number)
1510 // store i32 %IndexVal, i32* %index.addr1
1511 auto *Save = S->getCoroSave();
1512 Builder.SetInsertPoint(Save);
1513 if (S->isFinal()) {
1514 // The coroutine should be marked done if it reaches the final suspend
1515 // point.
1516 markCoroutineAsDone(Builder, Shape, FramePtr);
1517 } else {
1518 auto *GepIndex = Builder.CreateStructGEP(
1519 FrameTy, FramePtr, Shape.getSwitchIndexField(), "index.addr");
1520 Builder.CreateStore(IndexVal, GepIndex);
1521 }
1522
1523 Save->replaceAllUsesWith(ConstantTokenNone::get(C));
1524 Save->eraseFromParent();
1525
1526 // Split block before and after coro.suspend and add a jump from an entry
1527 // switch:
1528 //
1529 // whateverBB:
1530 // whatever
1531 // %0 = call i8 @llvm.coro.suspend(token none, i1 false)
1532 // switch i8 %0, label %suspend[i8 0, label %resume
1533 // i8 1, label %cleanup]
1534 // becomes:
1535 //
1536 // whateverBB:
1537 // whatever
1538 // br label %resume.0.landing
1539 //
1540 // resume.0: ; <--- jump from the switch in the resume.entry
1541 // %0 = tail call i8 @llvm.coro.suspend(token none, i1 false)
1542 // br label %resume.0.landing
1543 //
1544 // resume.0.landing:
1545 // %1 = phi i8[-1, %whateverBB], [%0, %resume.0]
1546 // switch i8 % 1, label %suspend [i8 0, label %resume
1547 // i8 1, label %cleanup]
1548
1549 auto *SuspendBB = S->getParent();
1550 auto *ResumeBB =
1551 SuspendBB->splitBasicBlock(S, "resume." + Twine(SuspendIndex));
1552 auto *LandingBB = ResumeBB->splitBasicBlock(
1553 S->getNextNode(), ResumeBB->getName() + Twine(".landing"));
1554 Switch->addCase(IndexVal, ResumeBB);
1555
1556 cast<BranchInst>(SuspendBB->getTerminator())->setSuccessor(0, LandingBB);
1557 auto *PN = PHINode::Create(Builder.getInt8Ty(), 2, "");
1558 PN->insertBefore(LandingBB->begin());
1559 S->replaceAllUsesWith(PN);
1560 PN->addIncoming(Builder.getInt8(-1), SuspendBB);
1561 PN->addIncoming(S, ResumeBB);
1562
1563 ++SuspendIndex;
1564 }
1565
1566 Builder.SetInsertPoint(UnreachBB);
1567 Builder.CreateUnreachable();
1568
1569 Shape.SwitchLowering.ResumeEntryBlock = NewEntry;
1570 }
1571
1572 // Store addresses of Resume/Destroy/Cleanup functions in the coroutine frame.
1573 static void updateCoroFrame(coro::Shape &Shape, Function *ResumeFn,
1574 Function *DestroyFn, Function *CleanupFn) {
1575 IRBuilder<> Builder(&*Shape.getInsertPtAfterFramePtr());
1576
1577 auto *ResumeAddr = Builder.CreateStructGEP(
1579 "resume.addr");
1580 Builder.CreateStore(ResumeFn, ResumeAddr);
1581
1582 Value *DestroyOrCleanupFn = DestroyFn;
1583
1584 CoroIdInst *CoroId = Shape.getSwitchCoroId();
1585 if (CoroAllocInst *CA = CoroId->getCoroAlloc()) {
1586 // If there is a CoroAlloc and it returns false (meaning we elide the
1587 // allocation, use CleanupFn instead of DestroyFn).
1588 DestroyOrCleanupFn = Builder.CreateSelect(CA, DestroyFn, CleanupFn);
1589 }
1590
1591 auto *DestroyAddr = Builder.CreateStructGEP(
1593 "destroy.addr");
1594 Builder.CreateStore(DestroyOrCleanupFn, DestroyAddr);
1595 }
1596
1597 // Create a global constant array containing pointers to functions provided
1598 // and set Info parameter of CoroBegin to point at this constant. Example:
1599 //
1600 // @f.resumers = internal constant [2 x void(%f.frame*)*]
1601 // [void(%f.frame*)* @f.resume, void(%f.frame*)*
1602 // @f.destroy]
1603 // define void @f() {
1604 // ...
1605 // call i8* @llvm.coro.begin(i8* null, i32 0, i8* null,
1606 // i8* bitcast([2 x void(%f.frame*)*] * @f.resumers to
1607 // i8*))
1608 //
1609 // Assumes that all the functions have the same signature.
1610 static void setCoroInfo(Function &F, coro::Shape &Shape,
1612 // This only works under the switch-lowering ABI because coro elision
1613 // only works on the switch-lowering ABI.
1615 assert(!Args.empty());
1616 Function *Part = *Fns.begin();
1617 Module *M = Part->getParent();
1618 auto *ArrTy = ArrayType::get(Part->getType(), Args.size());
1619
1620 auto *ConstVal = ConstantArray::get(ArrTy, Args);
1621 auto *GV = new GlobalVariable(*M, ConstVal->getType(), /*isConstant=*/true,
1622 GlobalVariable::PrivateLinkage, ConstVal,
1623 F.getName() + Twine(".resumers"));
1624
1625 // Update coro.begin instruction to refer to this constant.
1626 LLVMContext &C = F.getContext();
1627 auto *BC = ConstantExpr::getPointerCast(GV, PointerType::getUnqual(C));
1628 Shape.getSwitchCoroId()->setInfo(BC);
1629 }
1630};
1631
1632} // namespace
1633
1636 auto *ResumeIntrinsic = Suspend->getResumeFunction();
1637 auto &Context = Suspend->getParent()->getParent()->getContext();
1638 auto *Int8PtrTy = PointerType::getUnqual(Context);
1639
1640 IRBuilder<> Builder(ResumeIntrinsic);
1641 auto *Val = Builder.CreateBitOrPointerCast(Continuation, Int8PtrTy);
1642 ResumeIntrinsic->replaceAllUsesWith(Val);
1643 ResumeIntrinsic->eraseFromParent();
1645 PoisonValue::get(Int8PtrTy));
1646}
1647
1648/// Coerce the arguments in \p FnArgs according to \p FnTy in \p CallArgs.
1649static void coerceArguments(IRBuilder<> &Builder, FunctionType *FnTy,
1650 ArrayRef<Value *> FnArgs,
1651 SmallVectorImpl<Value *> &CallArgs) {
1652 size_t ArgIdx = 0;
1653 for (auto *paramTy : FnTy->params()) {
1654 assert(ArgIdx < FnArgs.size());
1655 if (paramTy != FnArgs[ArgIdx]->getType())
1656 CallArgs.push_back(
1657 Builder.CreateBitOrPointerCast(FnArgs[ArgIdx], paramTy));
1658 else
1659 CallArgs.push_back(FnArgs[ArgIdx]);
1660 ++ArgIdx;
1661 }
1662}
1663
1667 IRBuilder<> &Builder) {
1668 auto *FnTy = MustTailCallFn->getFunctionType();
1669 // Coerce the arguments, llvm optimizations seem to ignore the types in
1670 // vaarg functions and throws away casts in optimized mode.
1671 SmallVector<Value *, 8> CallArgs;
1672 coerceArguments(Builder, FnTy, Arguments, CallArgs);
1673
1674 auto *TailCall = Builder.CreateCall(FnTy, MustTailCallFn, CallArgs);
1675 // Skip targets which don't support tail call.
1676 if (TTI.supportsTailCallFor(TailCall)) {
1677 TailCall->setTailCallKind(CallInst::TCK_MustTail);
1678 }
1679 TailCall->setDebugLoc(Loc);
1680 TailCall->setCallingConv(MustTailCallFn->getCallingConv());
1681 return TailCall;
1682}
1683
1688 assert(Clones.empty());
1689 // Reset various things that the optimizer might have decided it
1690 // "knows" about the coroutine function due to not seeing a return.
1691 F.removeFnAttr(Attribute::NoReturn);
1692 F.removeRetAttr(Attribute::NoAlias);
1693 F.removeRetAttr(Attribute::NonNull);
1694
1695 auto &Context = F.getContext();
1696 auto *Int8PtrTy = PointerType::getUnqual(Context);
1697
1698 auto *Id = Shape.getAsyncCoroId();
1699 IRBuilder<> Builder(Id);
1700
1701 auto *FramePtr = Id->getStorage();
1702 FramePtr = Builder.CreateBitOrPointerCast(FramePtr, Int8PtrTy);
1705 "async.ctx.frameptr");
1706
1707 // Map all uses of llvm.coro.begin to the allocated frame pointer.
1708 {
1709 // Make sure we don't invalidate Shape.FramePtr.
1712 Shape.FramePtr = Handle.getValPtr();
1713 }
1714
1715 // Create all the functions in order after the main function.
1716 auto NextF = std::next(F.getIterator());
1717
1718 // Create a continuation function for each of the suspend points.
1719 Clones.reserve(Shape.CoroSuspends.size());
1720 for (auto [Idx, CS] : llvm::enumerate(Shape.CoroSuspends)) {
1721 auto *Suspend = cast<CoroSuspendAsyncInst>(CS);
1722
1723 // Create the clone declaration.
1724 auto ResumeNameSuffix = ".resume.";
1725 auto ProjectionFunctionName =
1726 Suspend->getAsyncContextProjectionFunction()->getName();
1727 bool UseSwiftMangling = false;
1728 if (ProjectionFunctionName == "__swift_async_resume_project_context") {
1729 ResumeNameSuffix = "TQ";
1730 UseSwiftMangling = true;
1731 } else if (ProjectionFunctionName == "__swift_async_resume_get_context") {
1732 ResumeNameSuffix = "TY";
1733 UseSwiftMangling = true;
1734 }
1736 F, Shape,
1737 UseSwiftMangling ? ResumeNameSuffix + Twine(Idx) + "_"
1738 : ResumeNameSuffix + Twine(Idx),
1739 NextF, Suspend);
1740 Clones.push_back(Continuation);
1741
1742 // Insert a branch to a new return block immediately before the suspend
1743 // point.
1744 auto *SuspendBB = Suspend->getParent();
1745 auto *NewSuspendBB = SuspendBB->splitBasicBlock(Suspend);
1746 auto *Branch = cast<BranchInst>(SuspendBB->getTerminator());
1747
1748 // Place it before the first suspend.
1749 auto *ReturnBB =
1750 BasicBlock::Create(F.getContext(), "coro.return", &F, NewSuspendBB);
1751 Branch->setSuccessor(0, ReturnBB);
1752
1753 IRBuilder<> Builder(ReturnBB);
1754
1755 // Insert the call to the tail call function and inline it.
1756 auto *Fn = Suspend->getMustTailCallFunction();
1757 SmallVector<Value *, 8> Args(Suspend->args());
1758 auto FnArgs = ArrayRef<Value *>(Args).drop_front(
1760 auto *TailCall = coro::createMustTailCall(Suspend->getDebugLoc(), Fn, TTI,
1761 FnArgs, Builder);
1762 Builder.CreateRetVoid();
1763 InlineFunctionInfo FnInfo;
1764 (void)InlineFunction(*TailCall, FnInfo);
1765
1766 // Replace the lvm.coro.async.resume intrisic call.
1768 }
1769
1770 assert(Clones.size() == Shape.CoroSuspends.size());
1771 for (auto [Idx, CS] : llvm::enumerate(Shape.CoroSuspends)) {
1772 auto *Suspend = CS;
1773 auto *Clone = Clones[Idx];
1774
1775 coro::BaseCloner::createClone(F, "resume." + Twine(Idx), Shape, Clone,
1776 Suspend, TTI);
1777 }
1778}
1779
1784 assert(Clones.empty());
1785
1786 // Reset various things that the optimizer might have decided it
1787 // "knows" about the coroutine function due to not seeing a return.
1788 F.removeFnAttr(Attribute::NoReturn);
1789 F.removeRetAttr(Attribute::NoAlias);
1790 F.removeRetAttr(Attribute::NonNull);
1791
1792 // Allocate the frame.
1793 auto *Id = Shape.getRetconCoroId();
1794 Value *RawFramePtr;
1796 RawFramePtr = Id->getStorage();
1797 } else {
1798 IRBuilder<> Builder(Id);
1799
1800 // Determine the size of the frame.
1801 const DataLayout &DL = F.getDataLayout();
1802 auto Size = DL.getTypeAllocSize(Shape.FrameTy);
1803
1804 // Allocate. We don't need to update the call graph node because we're
1805 // going to recompute it from scratch after splitting.
1806 // FIXME: pass the required alignment
1807 RawFramePtr = Shape.emitAlloc(Builder, Builder.getInt64(Size), nullptr);
1808 RawFramePtr =
1809 Builder.CreateBitCast(RawFramePtr, Shape.CoroBegin->getType());
1810
1811 // Stash the allocated frame pointer in the continuation storage.
1812 Builder.CreateStore(RawFramePtr, Id->getStorage());
1813 }
1814
1815 // Map all uses of llvm.coro.begin to the allocated frame pointer.
1816 {
1817 // Make sure we don't invalidate Shape.FramePtr.
1819 Shape.CoroBegin->replaceAllUsesWith(RawFramePtr);
1820 Shape.FramePtr = Handle.getValPtr();
1821 }
1822
1823 // Create a unique return block.
1824 BasicBlock *ReturnBB = nullptr;
1825 PHINode *ContinuationPhi = nullptr;
1826 SmallVector<PHINode *, 4> ReturnPHIs;
1827
1828 // Create all the functions in order after the main function.
1829 auto NextF = std::next(F.getIterator());
1830
1831 // Create a continuation function for each of the suspend points.
1832 Clones.reserve(Shape.CoroSuspends.size());
1833 for (auto [Idx, CS] : llvm::enumerate(Shape.CoroSuspends)) {
1834 auto Suspend = cast<CoroSuspendRetconInst>(CS);
1835
1836 // Create the clone declaration.
1838 F, Shape, ".resume." + Twine(Idx), NextF, nullptr);
1839 Clones.push_back(Continuation);
1840
1841 // Insert a branch to the unified return block immediately before
1842 // the suspend point.
1843 auto SuspendBB = Suspend->getParent();
1844 auto NewSuspendBB = SuspendBB->splitBasicBlock(Suspend);
1845 auto Branch = cast<BranchInst>(SuspendBB->getTerminator());
1846
1847 // Create the unified return block.
1848 if (!ReturnBB) {
1849 // Place it before the first suspend.
1850 ReturnBB =
1851 BasicBlock::Create(F.getContext(), "coro.return", &F, NewSuspendBB);
1852 Shape.RetconLowering.ReturnBlock = ReturnBB;
1853
1854 IRBuilder<> Builder(ReturnBB);
1855
1856 // First, the continuation.
1857 ContinuationPhi =
1858 Builder.CreatePHI(Continuation->getType(), Shape.CoroSuspends.size());
1859
1860 // Create PHIs for all other return values.
1861 assert(ReturnPHIs.empty());
1862
1863 // Next, all the directly-yielded values.
1864 for (auto *ResultTy : Shape.getRetconResultTypes())
1865 ReturnPHIs.push_back(
1866 Builder.CreatePHI(ResultTy, Shape.CoroSuspends.size()));
1867
1868 // Build the return value.
1869 auto RetTy = F.getReturnType();
1870
1871 // Cast the continuation value if necessary.
1872 // We can't rely on the types matching up because that type would
1873 // have to be infinite.
1874 auto CastedContinuationTy =
1875 (ReturnPHIs.empty() ? RetTy : RetTy->getStructElementType(0));
1876 auto *CastedContinuation =
1877 Builder.CreateBitCast(ContinuationPhi, CastedContinuationTy);
1878
1879 Value *RetV = CastedContinuation;
1880 if (!ReturnPHIs.empty()) {
1881 auto ValueIdx = 0;
1882 RetV = PoisonValue::get(RetTy);
1883 RetV = Builder.CreateInsertValue(RetV, CastedContinuation, ValueIdx++);
1884
1885 for (auto Phi : ReturnPHIs)
1886 RetV = Builder.CreateInsertValue(RetV, Phi, ValueIdx++);
1887 }
1888
1889 Builder.CreateRet(RetV);
1890 }
1891
1892 // Branch to the return block.
1893 Branch->setSuccessor(0, ReturnBB);
1894 assert(ContinuationPhi);
1895 ContinuationPhi->addIncoming(Continuation, SuspendBB);
1896 for (auto [Phi, VUse] :
1897 llvm::zip_equal(ReturnPHIs, Suspend->value_operands()))
1898 Phi->addIncoming(VUse, SuspendBB);
1899 }
1900
1901 assert(Clones.size() == Shape.CoroSuspends.size());
1902 for (auto [Idx, CS] : llvm::enumerate(Shape.CoroSuspends)) {
1903 auto Suspend = CS;
1904 auto Clone = Clones[Idx];
1905
1906 coro::BaseCloner::createClone(F, "resume." + Twine(Idx), Shape, Clone,
1907 Suspend, TTI);
1908 }
1909}
1910
1911namespace {
1912class PrettyStackTraceFunction : public PrettyStackTraceEntry {
1913 Function &F;
1914
1915public:
1916 PrettyStackTraceFunction(Function &F) : F(F) {}
1917 void print(raw_ostream &OS) const override {
1918 OS << "While splitting coroutine ";
1919 F.printAsOperand(OS, /*print type*/ false, F.getParent());
1920 OS << "\n";
1921 }
1922};
1923} // namespace
1924
1925/// Remove calls to llvm.coro.end in the original function.
1927 if (Shape.ABI != coro::ABI::Switch) {
1928 for (auto *End : Shape.CoroEnds) {
1929 replaceCoroEnd(End, Shape, Shape.FramePtr, /*in resume*/ false, nullptr);
1930 }
1931 } else {
1932 for (llvm::AnyCoroEndInst *End : Shape.CoroEnds) {
1933 auto &Context = End->getContext();
1934 End->replaceAllUsesWith(ConstantInt::getFalse(Context));
1935 End->eraseFromParent();
1936 }
1937 }
1938}
1939
1941 for (auto *U : F.users()) {
1942 if (auto *CB = dyn_cast<CallBase>(U)) {
1943 auto *Caller = CB->getFunction();
1944 if (Caller && Caller->isPresplitCoroutine() &&
1945 CB->hasFnAttr(llvm::Attribute::CoroElideSafe))
1946 return true;
1947 }
1948 }
1949 return false;
1950}
1951
1955 SwitchCoroutineSplitter::split(F, Shape, Clones, TTI);
1956}
1957
1960 bool OptimizeFrame) {
1961 PrettyStackTraceFunction prettyStackTrace(F);
1962
1963 auto &Shape = ABI.Shape;
1964 assert(Shape.CoroBegin);
1965
1966 lowerAwaitSuspends(F, Shape);
1967
1968 simplifySuspendPoints(Shape);
1969
1970 normalizeCoroutine(F, Shape, TTI);
1971 ABI.buildCoroutineFrame(OptimizeFrame);
1973
1974 bool isNoSuspendCoroutine = Shape.CoroSuspends.empty();
1975
1976 bool shouldCreateNoAllocVariant =
1977 !isNoSuspendCoroutine && Shape.ABI == coro::ABI::Switch &&
1978 hasSafeElideCaller(F) && !F.hasFnAttribute(llvm::Attribute::NoInline);
1979
1980 // If there are no suspend points, no split required, just remove
1981 // the allocation and deallocation blocks, they are not needed.
1982 if (isNoSuspendCoroutine) {
1984 } else {
1985 ABI.splitCoroutine(F, Shape, Clones, TTI);
1986 }
1987
1988 // Replace all the swifterror operations in the original function.
1989 // This invalidates SwiftErrorOps in the Shape.
1990 replaceSwiftErrorOps(F, Shape, nullptr);
1991
1992 // Salvage debug intrinsics that point into the coroutine frame in the
1993 // original function. The Cloner has already salvaged debug info in the new
1994 // coroutine funclets.
1996 auto [DbgInsts, DbgVariableRecords] = collectDbgVariableIntrinsics(F);
1997 for (auto *DDI : DbgInsts)
1998 coro::salvageDebugInfo(ArgToAllocaMap, *DDI, false /*UseEntryValue*/);
1999 for (DbgVariableRecord *DVR : DbgVariableRecords)
2000 coro::salvageDebugInfo(ArgToAllocaMap, *DVR, false /*UseEntryValue*/);
2001
2003
2004 if (shouldCreateNoAllocVariant)
2005 SwitchCoroutineSplitter::createNoAllocVariant(F, Shape, Clones);
2006}
2007
2009 LazyCallGraph::Node &N, const coro::Shape &Shape,
2013
2014 auto *CurrentSCC = &C;
2015 if (!Clones.empty()) {
2016 switch (Shape.ABI) {
2017 case coro::ABI::Switch:
2018 // Each clone in the Switch lowering is independent of the other clones.
2019 // Let the LazyCallGraph know about each one separately.
2020 for (Function *Clone : Clones)
2021 CG.addSplitFunction(N.getFunction(), *Clone);
2022 break;
2023 case coro::ABI::Async:
2024 case coro::ABI::Retcon:
2026 // Each clone in the Async/Retcon lowering references of the other clones.
2027 // Let the LazyCallGraph know about all of them at once.
2028 if (!Clones.empty())
2029 CG.addSplitRefRecursiveFunctions(N.getFunction(), Clones);
2030 break;
2031 }
2032
2033 // Let the CGSCC infra handle the changes to the original function.
2034 CurrentSCC = &updateCGAndAnalysisManagerForCGSCCPass(CG, *CurrentSCC, N, AM,
2035 UR, FAM);
2036 }
2037
2038 // Do some cleanup and let the CGSCC infra see if we've cleaned up any edges
2039 // to the split functions.
2040 postSplitCleanup(N.getFunction());
2041 CurrentSCC = &updateCGAndAnalysisManagerForFunctionPass(CG, *CurrentSCC, N,
2042 AM, UR, FAM);
2043 return *CurrentSCC;
2044}
2045
2046/// Replace a call to llvm.coro.prepare.retcon.
2047static void replacePrepare(CallInst *Prepare, LazyCallGraph &CG,
2049 auto CastFn = Prepare->getArgOperand(0); // as an i8*
2050 auto Fn = CastFn->stripPointerCasts(); // as its original type
2051
2052 // Attempt to peephole this pattern:
2053 // %0 = bitcast [[TYPE]] @some_function to i8*
2054 // %1 = call @llvm.coro.prepare.retcon(i8* %0)
2055 // %2 = bitcast %1 to [[TYPE]]
2056 // ==>
2057 // %2 = @some_function
2058 for (Use &U : llvm::make_early_inc_range(Prepare->uses())) {
2059 // Look for bitcasts back to the original function type.
2060 auto *Cast = dyn_cast<BitCastInst>(U.getUser());
2061 if (!Cast || Cast->getType() != Fn->getType())
2062 continue;
2063
2064 // Replace and remove the cast.
2065 Cast->replaceAllUsesWith(Fn);
2066 Cast->eraseFromParent();
2067 }
2068
2069 // Replace any remaining uses with the function as an i8*.
2070 // This can never directly be a callee, so we don't need to update CG.
2071 Prepare->replaceAllUsesWith(CastFn);
2072 Prepare->eraseFromParent();
2073
2074 // Kill dead bitcasts.
2075 while (auto *Cast = dyn_cast<BitCastInst>(CastFn)) {
2076 if (!Cast->use_empty())
2077 break;
2078 CastFn = Cast->getOperand(0);
2079 Cast->eraseFromParent();
2080 }
2081}
2082
2083static bool replaceAllPrepares(Function *PrepareFn, LazyCallGraph &CG,
2085 bool Changed = false;
2086 for (Use &P : llvm::make_early_inc_range(PrepareFn->uses())) {
2087 // Intrinsics can only be used in calls.
2088 auto *Prepare = cast<CallInst>(P.getUser());
2089 replacePrepare(Prepare, CG, C);
2090 Changed = true;
2091 }
2092
2093 return Changed;
2094}
2095
2096static void addPrepareFunction(const Module &M,
2098 StringRef Name) {
2099 auto *PrepareFn = M.getFunction(Name);
2100 if (PrepareFn && !PrepareFn->use_empty())
2101 Fns.push_back(PrepareFn);
2102}
2103
2104static std::unique_ptr<coro::BaseABI>
2106 std::function<bool(Instruction &)> IsMatCallback,
2107 const SmallVector<CoroSplitPass::BaseABITy> GenCustomABIs) {
2108 if (S.CoroBegin->hasCustomABI()) {
2109 unsigned CustomABI = S.CoroBegin->getCustomABI();
2110 if (CustomABI >= GenCustomABIs.size())
2111 llvm_unreachable("Custom ABI not found amoung those specified");
2112 return GenCustomABIs[CustomABI](F, S);
2113 }
2114
2115 switch (S.ABI) {
2116 case coro::ABI::Switch:
2117 return std::make_unique<coro::SwitchABI>(F, S, IsMatCallback);
2118 case coro::ABI::Async:
2119 return std::make_unique<coro::AsyncABI>(F, S, IsMatCallback);
2120 case coro::ABI::Retcon:
2121 return std::make_unique<coro::AnyRetconABI>(F, S, IsMatCallback);
2123 return std::make_unique<coro::AnyRetconABI>(F, S, IsMatCallback);
2124 }
2125 llvm_unreachable("Unknown ABI");
2126}
2127
2129 : CreateAndInitABI([](Function &F, coro::Shape &S) {
2130 std::unique_ptr<coro::BaseABI> ABI =
2132 ABI->init();
2133 return ABI;
2134 }),
2135 OptimizeFrame(OptimizeFrame) {}
2136
2138 SmallVector<CoroSplitPass::BaseABITy> GenCustomABIs, bool OptimizeFrame)
2139 : CreateAndInitABI([=](Function &F, coro::Shape &S) {
2140 std::unique_ptr<coro::BaseABI> ABI =
2142 ABI->init();
2143 return ABI;
2144 }),
2145 OptimizeFrame(OptimizeFrame) {}
2146
2147// For back compatibility, constructor takes a materializable callback and
2148// creates a generator for an ABI with a modified materializable callback.
2149CoroSplitPass::CoroSplitPass(std::function<bool(Instruction &)> IsMatCallback,
2150 bool OptimizeFrame)
2151 : CreateAndInitABI([=](Function &F, coro::Shape &S) {
2152 std::unique_ptr<coro::BaseABI> ABI =
2153 CreateNewABI(F, S, IsMatCallback, {});
2154 ABI->init();
2155 return ABI;
2156 }),
2157 OptimizeFrame(OptimizeFrame) {}
2158
2159// For back compatibility, constructor takes a materializable callback and
2160// creates a generator for an ABI with a modified materializable callback.
2162 std::function<bool(Instruction &)> IsMatCallback,
2163 SmallVector<CoroSplitPass::BaseABITy> GenCustomABIs, bool OptimizeFrame)
2164 : CreateAndInitABI([=](Function &F, coro::Shape &S) {
2165 std::unique_ptr<coro::BaseABI> ABI =
2166 CreateNewABI(F, S, IsMatCallback, GenCustomABIs);
2167 ABI->init();
2168 return ABI;
2169 }),
2170 OptimizeFrame(OptimizeFrame) {}
2171
2175 // NB: One invariant of a valid LazyCallGraph::SCC is that it must contain a
2176 // non-zero number of nodes, so we assume that here and grab the first
2177 // node's function's module.
2178 Module &M = *C.begin()->getFunction().getParent();
2179 auto &FAM =
2180 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager();
2181
2182 // Check for uses of llvm.coro.prepare.retcon/async.
2183 SmallVector<Function *, 2> PrepareFns;
2184 addPrepareFunction(M, PrepareFns, "llvm.coro.prepare.retcon");
2185 addPrepareFunction(M, PrepareFns, "llvm.coro.prepare.async");
2186
2187 // Find coroutines for processing.
2189 for (LazyCallGraph::Node &N : C)
2190 if (N.getFunction().isPresplitCoroutine())
2191 Coroutines.push_back(&N);
2192
2193 if (Coroutines.empty() && PrepareFns.empty())
2194 return PreservedAnalyses::all();
2195
2196 auto *CurrentSCC = &C;
2197 // Split all the coroutines.
2198 for (LazyCallGraph::Node *N : Coroutines) {
2199 Function &F = N->getFunction();
2200 LLVM_DEBUG(dbgs() << "CoroSplit: Processing coroutine '" << F.getName()
2201 << "\n");
2202
2203 // The suspend-crossing algorithm in buildCoroutineFrame gets tripped up
2204 // by unreachable blocks, so remove them as a first pass. Remove the
2205 // unreachable blocks before collecting intrinsics into Shape.
2207
2208 coro::Shape Shape(F);
2209 if (!Shape.CoroBegin)
2210 continue;
2211
2212 F.setSplittedCoroutine();
2213
2214 std::unique_ptr<coro::BaseABI> ABI = CreateAndInitABI(F, Shape);
2215
2218 doSplitCoroutine(F, Clones, *ABI, TTI, OptimizeFrame);
2220 *N, Shape, Clones, *CurrentSCC, CG, AM, UR, FAM);
2221
2223 ORE.emit([&]() {
2224 return OptimizationRemark(DEBUG_TYPE, "CoroSplit", &F)
2225 << "Split '" << ore::NV("function", F.getName())
2226 << "' (frame_size=" << ore::NV("frame_size", Shape.FrameSize)
2227 << ", align=" << ore::NV("align", Shape.FrameAlign.value()) << ")";
2228 });
2229
2230 if (!Shape.CoroSuspends.empty()) {
2231 // Run the CGSCC pipeline on the original and newly split functions.
2232 UR.CWorklist.insert(CurrentSCC);
2233 for (Function *Clone : Clones)
2234 UR.CWorklist.insert(CG.lookupSCC(CG.get(*Clone)));
2235 }
2236 }
2237
2238 for (auto *PrepareFn : PrepareFns) {
2239 replaceAllPrepares(PrepareFn, CG, *CurrentSCC);
2240 }
2241
2242 return PreservedAnalyses::none();
2243}
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...
BlockVerifier::State From
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)
Definition: CoroSplit.cpp:857
static bool hasCallsBetween(Instruction *Save, Instruction *ResumeOrDestroy)
Definition: CoroSplit.cpp:1243
static std::pair< SmallVector< DbgVariableIntrinsic *, 8 >, SmallVector< DbgVariableRecord * > > collectDbgVariableIntrinsics(Function &F)
Returns all DbgVariableIntrinsic in F.
Definition: CoroSplit.cpp:621
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)
Definition: CoroSplit.cpp:2008
static void replaceSwiftErrorOps(Function &F, coro::Shape &Shape, ValueToValueMapTy *VMap)
Definition: CoroSplit.cpp:563
static void addAsyncContextAttrs(AttributeList &Attrs, LLVMContext &Context, unsigned ParamIndex)
Definition: CoroSplit.cpp:850
static void maybeFreeRetconStorage(IRBuilder<> &Builder, const coro::Shape &Shape, Value *FramePtr, CallGraph *CG)
Definition: CoroSplit.cpp:156
static bool hasCallsInBlocksBetween(BasicBlock *SaveBB, BasicBlock *ResDesBB)
Definition: CoroSplit.cpp:1214
static Function * createCloneDeclaration(Function &OrigF, coro::Shape &Shape, const Twine &Suffix, Module::iterator InsertBefore, AnyCoroSuspendInst *ActiveSuspend)
Definition: CoroSplit.cpp:447
Remove calls to llvm coro end in the original static function void removeCoroEndsFromRampFunction(const coro::Shape &Shape)
Definition: CoroSplit.cpp:1926
static FunctionType * getFunctionTypeFromAsyncSuspend(AnyCoroSuspendInst *Suspend)
Definition: CoroSplit.cpp:439
static void updateScopeLine(Instruction *ActiveSuspend, DISubprogram &SPToUpdate)
Adjust the scope line of the funclet to the first line number after the suspend point.
Definition: CoroSplit.cpp:802
static void addPrepareFunction(const Module &M, SmallVectorImpl< Function * > &Fns, StringRef Name)
Definition: CoroSplit.cpp:2096
static void simplifySuspendPoints(coro::Shape &Shape)
Definition: CoroSplit.cpp:1328
static void addFramePointerAttrs(AttributeList &Attrs, LLVMContext &Context, unsigned ParamIndex, uint64_t Size, Align Alignment, bool NoAlias)
Definition: CoroSplit.cpp:835
static bool hasSafeElideCaller(Function &F)
Definition: CoroSplit.cpp:1940
static bool replaceAllPrepares(Function *PrepareFn, LazyCallGraph &CG, LazyCallGraph::SCC &C)
Definition: CoroSplit.cpp:2083
static void replaceFallthroughCoroEnd(AnyCoroEndInst *End, const coro::Shape &Shape, Value *FramePtr, bool InResume, CallGraph *CG)
Replace a non-unwind call to llvm.coro.end.
Definition: CoroSplit.cpp:212
static void replaceFrameSizeAndAlignment(coro::Shape &Shape)
Definition: CoroSplit.cpp:1130
static std::unique_ptr< coro::BaseABI > CreateNewABI(Function &F, coro::Shape &S, std::function< bool(Instruction &)> IsMatCallback, const SmallVector< CoroSplitPass::BaseABITy > GenCustomABIs)
Definition: CoroSplit.cpp:2105
static bool replaceCoroEndAsync(AnyCoroEndInst *End)
Replace an llvm.coro.end.async.
Definition: CoroSplit.cpp:169
static void doSplitCoroutine(Function &F, SmallVectorImpl< Function * > &Clones, coro::BaseABI &ABI, TargetTransformInfo &TTI, bool OptimizeFrame)
Definition: CoroSplit.cpp:1958
Replace a call to llvm coro prepare static retcon void replacePrepare(CallInst *Prepare, LazyCallGraph &CG, LazyCallGraph::SCC &C)
Definition: CoroSplit.cpp:2047
static void replaceUnwindCoroEnd(AnyCoroEndInst *End, const coro::Shape &Shape, Value *FramePtr, bool InResume, CallGraph *CG)
Replace an unwind call to llvm.coro.end.
Definition: CoroSplit.cpp:345
static bool simplifySuspendPoint(CoroSuspendInst *Suspend, CoroBeginInst *CoroBegin)
Definition: CoroSplit.cpp:1268
static bool hasCallsInBlockBetween(Instruction *From, Instruction *To)
Definition: CoroSplit.cpp:1202
static void markCoroutineAsDone(IRBuilder<> &Builder, const coro::Shape &Shape, Value *FramePtr)
Definition: CoroSplit.cpp:311
static void updateAsyncFuncPointerContextSize(coro::Shape &Shape)
Definition: CoroSplit.cpp:1107
static void replaceCoroEnd(AnyCoroEndInst *End, const coro::Shape &Shape, Value *FramePtr, bool InResume, CallGraph *CG)
Definition: CoroSplit.cpp:383
static void lowerAwaitSuspend(IRBuilder<> &Builder, CoroAwaitSuspendInst *CB, coro::Shape &Shape)
Definition: CoroSplit.cpp:84
static void lowerAwaitSuspends(Function &F, coro::Shape &Shape)
Definition: CoroSplit.cpp:150
static void handleNoSuspendCoroutine(coro::Shape &Shape)
Definition: CoroSplit.cpp:1168
static void postSplitCleanup(Function &F)
Definition: CoroSplit.cpp:1154
static TypeSize getFrameSizeForShape(coro::Shape &Shape)
Definition: CoroSplit.cpp:1122
Coerce the arguments in p FnArgs according to p FnTy in p static CallArgs void coerceArguments(IRBuilder<> &Builder, FunctionType *FnTy, ArrayRef< Value * > FnArgs, SmallVectorImpl< Value * > &CallArgs)
Definition: CoroSplit.cpp:1649
static void replaceAsyncResumeFunction(CoroSuspendAsyncInst *Suspend, Value *Continuation)
Definition: CoroSplit.cpp:1634
return RetTy
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
#define LLVM_DEBUG(...)
Definition: Debug.h:106
This file defines the DenseMap class.
This file contains constants used for implementing Dwarf debug support.
std::string Name
uint32_t Index
uint64_t Size
bool End
Definition: ELF_riscv.cpp:480
@ InlineInfo
#define DEBUG_TYPE
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.
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
#define P(N)
FunctionAnalysisManager FAM
This file provides a priority worklist.
const SmallVectorImpl< MachineOperand > & Cond
Remove Loads Into Fake Uses
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some templates that are useful if you are working with the STL at all.
raw_pwrite_stream & OS
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file contains some functions that are useful when dealing with strings.
static SymbolRef::Type getType(const Symbol *Sym)
Definition: TapiFile.cpp:39
This pass exposes codegen information to IR-level passes.
static const unsigned FramePtr
void setSwiftError(bool V)
Specify whether this alloca is used to represent a swifterror.
Definition: Instructions.h:151
void setAlignment(Align Align)
Definition: Instructions.h:128
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:253
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:410
CoroAllocInst * getCoroAlloc()
Definition: CoroInstr.h:117
Align getStorageAlignment() const
Definition: CoroInstr.h:246
uint64_t getStorageSize() const
Definition: CoroInstr.h:242
This class represents an incoming formal argument to a Function.
Definition: Argument.h:31
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
ArrayRef< T > drop_front(size_t N=1) const
Drop the first N elements of the array.
Definition: ArrayRef.h:207
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:168
iterator begin() const
Definition: ArrayRef.h:156
AttrBuilder & addAlignmentAttr(MaybeAlign Align)
This turns an alignment into the form used internally in Attribute.
AttrBuilder & addAttribute(Attribute::AttrKind Val)
Add an attribute to the builder.
AttrBuilder & addDereferenceableAttr(uint64_t Bytes)
This turns the number of dereferenceable bytes into the form used internally in Attribute.
AttributeList removeParamAttributes(LLVMContext &C, unsigned ArgNo, const AttributeMask &AttrsToRemove) const
Remove the specified attribute at the specified arg index from this attribute list.
Definition: Attributes.h:743
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:212
BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="", bool Before=false)
Split the basic block into two basic blocks at the specified instruction.
Definition: BasicBlock.cpp:577
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:219
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...
Definition: BasicBlock.h:239
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Definition: InstrTypes.h:1120
void setCallingConv(CallingConv::ID CC)
Definition: InstrTypes.h:1411
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
Definition: InstrTypes.h:1349
Value * getCalledOperand() const
Definition: InstrTypes.h:1342
void setAttributes(AttributeList A)
Set the attributes for this call.
Definition: InstrTypes.h:1428
Value * getArgOperand(unsigned i) const
Definition: InstrTypes.h:1294
AttributeList getAttributes() const
Return the attributes for this call.
Definition: InstrTypes.h:1425
The basic data container for the call graph of a Module of IR.
Definition: CallGraph.h:71
This class represents a function call, abstracting a target machine's calling convention.
static Constant * get(ArrayType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1312
static Constant * getPointerCast(Constant *C, Type *Ty)
Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant expression.
Definition: Constants.cpp:2253
This is the shared class of boolean and integer constants.
Definition: Constants.h:83
static ConstantInt * getTrue(LLVMContext &Context)
Definition: Constants.cpp:866
static ConstantInt * getFalse(LLVMContext &Context)
Definition: Constants.cpp:873
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
Definition: Constants.cpp:1826
static Constant * get(StructType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1378
static ConstantTokenNone * get(LLVMContext &Context)
Return the ConstantTokenNone.
Definition: Constants.cpp:1522
This represents the llvm.coro.align instruction.
Definition: CoroInstr.h:640
This represents the llvm.coro.alloc instruction.
Definition: CoroInstr.h:70
This represents the llvm.coro.await.suspend.{void,bool,handle} instructions.
Definition: CoroInstr.h:85
Value * getFrame() const
Definition: CoroInstr.h:91
Value * getAwaiter() const
Definition: CoroInstr.h:89
Function * getWrapperFunction() const
Definition: CoroInstr.h:93
This class represents the llvm.coro.begin or llvm.coro.begin.custom.abi instructions.
Definition: CoroInstr.h:448
AnyCoroIdInst * getId() const
Definition: CoroInstr.h:452
bool hasCustomABI() const
Definition: CoroInstr.h:456
int getCustomABI() const
Definition: CoroInstr.h:460
This represents the llvm.coro.id instruction.
Definition: CoroInstr.h:147
void setInfo(Constant *C)
Definition: CoroInstr.h:214
This represents the llvm.coro.size instruction.
Definition: CoroInstr.h:628
This represents the llvm.coro.suspend.async instruction.
Definition: CoroInstr.h:562
CoroAsyncResumeInst * getResumeFunction() const
Definition: CoroInstr.h:583
This represents the llvm.coro.suspend instruction.
Definition: CoroInstr.h:530
CoroSaveInst * getCoroSave() const
Definition: CoroInstr.h:534
DISubprogram * getSubprogram() const
Get the subprogram for this scope.
DIFile * getFile() const
Subprogram description.
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:63
This is the common base class for debug info intrinsics for variables.
Record of a variable value-assignment, aka a non instruction representation of the dbg....
A debug info location.
Definition: DebugLoc.h:33
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:162
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
Definition: Dominators.cpp:321
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.
Definition: DerivedTypes.h:105
Type * getReturnType() const
Definition: DerivedTypes.h:126
static 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)
Definition: Function.h:173
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition: Function.h:216
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
Definition: Function.h:251
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition: Function.h:277
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition: Function.h:353
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
Definition: Function.h:356
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition: Function.cpp:369
bool isCoroOnlyDestroyWhenComplete() const
Definition: Function.h:546
size_t arg_size() const
Definition: Function.h:901
Argument * getArg(unsigned i) const
Definition: Function.h:886
void setLinkage(LinkageTypes LT)
Definition: GlobalValue.h:537
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:656
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:294
@ InternalLinkage
Rename collisions when linking (static functions).
Definition: GlobalValue.h:59
@ ExternalLinkage
Externally visible function.
Definition: GlobalValue.h:52
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
Definition: Globals.cpp:492
AllocaInst * CreateAlloca(Type *Ty, unsigned AddrSpace, Value *ArraySize=nullptr, const Twine &Name="")
Definition: IRBuilder.h:1796
Value * CreateInsertValue(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition: IRBuilder.h:2554
InvokeInst * CreateInvoke(FunctionType *Ty, Value *Callee, BasicBlock *NormalDest, BasicBlock *UnwindDest, ArrayRef< Value * > Args, ArrayRef< OperandBundleDef > OpBundles, const Twine &Name="")
Create an invoke instruction.
Definition: IRBuilder.h:1182
BasicBlock::iterator GetInsertPoint() const
Definition: IRBuilder.h:172
Value * CreateStructGEP(Type *Ty, Value *Ptr, unsigned Idx, const Twine &Name="")
Definition: IRBuilder.h:1995
Value * CreateConstInBoundsGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0, const Twine &Name="")
Definition: IRBuilder.h:1912
CleanupReturnInst * CreateCleanupRet(CleanupPadInst *CleanupPad, BasicBlock *UnwindBB=nullptr)
Definition: IRBuilder.h:1259
ReturnInst * CreateRet(Value *V)
Create a 'ret <val>' instruction.
Definition: IRBuilder.h:1119
ConstantInt * getInt64(uint64_t C)
Get a constant 64-bit value.
Definition: IRBuilder.h:488
Value * CreateBitOrPointerCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2236
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Definition: IRBuilder.h:2429
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2155
BranchInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
Definition: IRBuilder.h:1144
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
Definition: IRBuilder.h:1813
LLVMContext & getContext() const
Definition: IRBuilder.h:173
ReturnInst * CreateRetVoid()
Create a 'ret void' instruction.
Definition: IRBuilder.h:1114
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition: IRBuilder.h:1826
ConstantInt * getFalse()
Get the constant value for i1 false.
Definition: IRBuilder.h:468
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args={}, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2444
BranchInst * CreateBr(BasicBlock *Dest)
Create an unconditional 'br label X' instruction.
Definition: IRBuilder.h:1138
Value * CreateIsNull(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg == 0.
Definition: IRBuilder.h:2575
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition: IRBuilder.h:177
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2697
This class captures the data input to the InlineFunction call, and records the auxiliary results prod...
Definition: Cloning.h:255
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:475
InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Definition: Instruction.cpp:94
const Instruction * getNextNonDebugInstruction(bool SkipPseudoOp=false) const
Return a pointer to the next non-debug instruction in the same basic block as 'this',...
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
A node in the call graph.
An SCC of the call graph.
A lazily constructed view of the call graph of a module.
void addSplitFunction(Function &OriginalFunction, Function &NewFunction)
Add a new function split/outlined from an existing function.
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 MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1543
static MDString * get(LLVMContext &Context, StringRef Str)
Definition: Metadata.cpp:606
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
FunctionListType::iterator iterator
The Function iterators.
Definition: Module.h:90
Diagnostic information for applied optimization remarks.
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(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
Definition: DerivedTypes.h:686
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Definition: Constants.cpp:1878
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:111
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: Analysis.h:114
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:117
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.
Definition: SmallPtrSet.h:519
bool empty() const
Definition: SmallVector.h:81
size_t size() const
Definition: SmallVector.h:78
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:573
void reserve(size_type N)
Definition: SmallVector.h:663
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:683
void push_back(const T &Elt)
Definition: SmallVector.h:413
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
Type * getTypeAtIndex(const Value *V) const
Given an index value into the type, return the type of the element.
Definition: Type.cpp:711
Analysis pass providing the TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
bool supportsTailCallFor(const CallBase *CB) const
If target supports tail call on CB.
Value handle that tracks a Value across RAUW.
Definition: ValueHandle.h:331
ValueTy * getValPtr() const
Definition: ValueHandle.h:335
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
bool isArch64Bit() const
Test whether the architecture is 64-bit.
Definition: Triple.cpp:1681
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
static Type * getVoidTy(LLVMContext &C)
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:128
static IntegerType * getInt8Ty(LLVMContext &C)
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
void setOperand(unsigned i, Value *Val)
Definition: User.h:233
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:534
iterator_range< user_iterator > users()
Definition: Value.h:421
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition: Value.cpp:694
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:1075
iterator_range< use_iterator > uses()
Definition: Value.h:376
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
void takeName(Value *V)
Transfer the name from V to this value.
Definition: Value.cpp:383
void splitCoroutine(Function &F, coro::Shape &Shape, SmallVectorImpl< Function * > &Clones, TargetTransformInfo &TTI) override
Definition: CoroSplit.cpp:1780
void splitCoroutine(Function &F, coro::Shape &Shape, SmallVectorImpl< Function * > &Clones, TargetTransformInfo &TTI) override
Definition: CoroSplit.cpp:1684
Value * deriveNewFramePointer()
Derive the value of the new frame pointer.
Definition: CoroSplit.cpp:742
static Function * createClone(Function &OrigF, const Twine &Suffix, coro::Shape &Shape, Function *NewF, AnyCoroSuspendInst *ActiveSuspend, TargetTransformInfo &TTI)
Create a clone for a continuation lowering.
Definition: CoroCloner.h:84
ValueToValueMapTy VMap
Definition: CoroCloner.h:52
bool isSwitchDestroyFunction()
Definition: CoroCloner.h:105
void replaceRetconOrAsyncSuspendUses()
Replace uses of the active llvm.coro.suspend.retcon/async call with the arguments to the continuation...
Definition: CoroSplit.cpp:469
virtual void create()
Clone the body of the original function into a resume function of some sort.
Definition: CoroSplit.cpp:866
void splitCoroutine(Function &F, coro::Shape &Shape, SmallVectorImpl< Function * > &Clones, TargetTransformInfo &TTI) override
Definition: CoroSplit.cpp:1952
static Function * createClone(Function &OrigF, const Twine &Suffix, coro::Shape &Shape, CloneKind FKind, TargetTransformInfo &TTI)
Create a clone for a switch lowering.
Definition: CoroCloner.h:139
void create() override
Clone the body of the original function into a resume function of some sort.
Definition: CoroSplit.cpp:1093
const ParentTy * getParent() const
Definition: ilist_node.h:32
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition: ilist_node.h:353
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
@ Fast
Attempts to make calls as fast as possible (e.g.
Definition: CallingConv.h:41
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
void salvageDebugInfo(SmallDenseMap< Argument *, AllocaInst *, 4 > &ArgToAllocaMap, DbgVariableIntrinsic &DVI, bool IsEntryPoint)
Attempts to rewrite the location operand of debug intrinsics in terms of the coroutine frame pointer,...
Definition: CoroFrame.cpp:1927
@ 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....
Definition: Coroutines.cpp:155
void normalizeCoroutine(Function &F, coro::Shape &Shape, TargetTransformInfo &TTI)
Definition: CoroFrame.cpp:2013
CallInst * createMustTailCall(DebugLoc Loc, Function *MustTailCallFn, TargetTransformInfo &TTI, ArrayRef< Value * > Arguments, IRBuilder<> &)
Definition: CoroSplit.cpp:1664
void replaceCoroFree(CoroIdInst *CoroId, bool Elide)
Definition: Coroutines.cpp:135
bool isTriviallyMaterializable(Instruction &I)
@ SwitchCleanup
The shared cleanup function for a switch lowering.
@ Continuation
An individual continuation function.
DiagnosticInfoOptimizationBase::Argument NV
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
UnaryFunction for_each(R &&Range, UnaryFunction F)
Provide wrappers to std::for_each which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1732
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.
Definition: STLExtras.h:864
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition: STLExtras.h:2448
bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
Definition: Verifier.cpp:7297
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.
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...
Definition: STLExtras.h:657
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:167
unsigned changeToUnreachable(Instruction *I, bool PreserveLCSSA=false, DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Insert an unreachable instruction before the specified instruction, making it and the rest of the cod...
Definition: Local.cpp:2909
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
DWARFExpression::Operation Op
InlineResult InlineFunction(CallBase &CB, InlineFunctionInfo &IFI, bool MergeAttributes=false, AAResults *CalleeAAR=nullptr, bool InsertLifetime=true, Function *ForwardVarArgsTo=nullptr)
This function inlines the called function into the basic block of the caller.
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.
auto predecessors(const MachineBasicBlock *BB)
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
bool removeUnreachableBlocks(Function &F, DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Remove all blocks that can not be reached from the function's entry.
Definition: Local.cpp:3274
bool isPotentiallyReachable(const Instruction *From, const Instruction *To, const SmallPtrSetImpl< BasicBlock * > *ExclusionSet=nullptr, const DominatorTree *DT=nullptr, const LoopInfo *LI=nullptr)
Determine whether instruction 'To' is reachable from 'From', without passing through any blocks in Ex...
Definition: CFG.cpp:281
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:860
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
uint64_t value() const
This is a hole in the type system and should not be abused.
Definition: Alignment.h:85
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.
PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &AM, LazyCallGraph &CG, CGSCCUpdateResult &UR)
Definition: CoroSplit.cpp:2172
CoroSplitPass(bool OptimizeFrame=false)
Definition: CoroSplit.cpp:2128
BaseABITy CreateAndInitABI
Definition: CoroSplit.h:52
CallInst * makeSubFnCall(Value *Arg, int Index, Instruction *InsertPt)
Definition: Coroutines.cpp:52
SmallVector< CallInst *, 2 > SymmetricTransfers
Definition: CoroShape.h:59
SmallVector< CoroAwaitSuspendInst *, 4 > CoroAwaitSuspends
Definition: CoroShape.h:58
AsyncLoweringStorage AsyncLowering
Definition: CoroShape.h:150
FunctionType * getResumeFunctionType() const
Definition: CoroShape.h:188
IntegerType * getIndexType() const
Definition: CoroShape.h:173
StructType * FrameTy
Definition: CoroShape.h:109
AnyCoroIdRetconInst * getRetconCoroId() const
Definition: CoroShape.h:158
PointerType * getSwitchResumePointerType() const
Definition: CoroShape.h:182
CoroIdInst * getSwitchCoroId() const
Definition: CoroShape.h:153
SmallVector< CoroSizeInst *, 2 > CoroSizes
Definition: CoroShape.h:55
CallingConv::ID getResumeFunctionCC() const
Definition: CoroShape.h:225
coro::ABI ABI
Definition: CoroShape.h:107
Value * FramePtr
Definition: CoroShape.h:112
SmallVector< AnyCoroSuspendInst *, 4 > CoroSuspends
Definition: CoroShape.h:57
uint64_t FrameSize
Definition: CoroShape.h:111
Value * emitAlloc(IRBuilder<> &Builder, Value *Size, CallGraph *CG) const
Allocate memory according to the rules of the active lowering.
Definition: Coroutines.cpp:505
ConstantInt * getIndex(uint64_t Value) const
Definition: CoroShape.h:178
SwitchLoweringStorage SwitchLowering
Definition: CoroShape.h:148
CoroBeginInst * CoroBegin
Definition: CoroShape.h:53
BasicBlock::iterator getInsertPtAfterFramePtr() const
Definition: CoroShape.h:245
ArrayRef< Type * > getRetconResultTypes() const
Definition: CoroShape.h:205
void emitDealloc(IRBuilder<> &Builder, Value *Ptr, CallGraph *CG) const
Deallocate memory according to the rules of the active lowering.
Definition: Coroutines.cpp:528
RetconLoweringStorage RetconLowering
Definition: CoroShape.h:149
SmallVector< CoroAlignInst *, 2 > CoroAligns
Definition: CoroShape.h:56
CoroIdAsyncInst * getAsyncCoroId() const
Definition: CoroShape.h:163
SmallVector< AnyCoroEndInst *, 4 > CoroEnds
Definition: CoroShape.h:54
SmallVector< CallInst *, 2 > SwiftErrorOps
Definition: CoroShape.h:62
BasicBlock * AllocaSpillBlock
Definition: CoroShape.h:113
unsigned getSwitchIndexField() const
Definition: CoroShape.h:168