LLVM  9.0.0svn
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 
21 #include "CoroInstr.h"
22 #include "CoroInternal.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/Twine.h"
31 #include "llvm/IR/Argument.h"
32 #include "llvm/IR/Attributes.h"
33 #include "llvm/IR/BasicBlock.h"
34 #include "llvm/IR/CFG.h"
35 #include "llvm/IR/CallSite.h"
36 #include "llvm/IR/CallingConv.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/DataLayout.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GlobalValue.h"
42 #include "llvm/IR/GlobalVariable.h"
43 #include "llvm/IR/IRBuilder.h"
44 #include "llvm/IR/InstIterator.h"
45 #include "llvm/IR/InstrTypes.h"
46 #include "llvm/IR/Instruction.h"
47 #include "llvm/IR/Instructions.h"
48 #include "llvm/IR/IntrinsicInst.h"
49 #include "llvm/IR/LLVMContext.h"
51 #include "llvm/IR/Module.h"
52 #include "llvm/IR/Type.h"
53 #include "llvm/IR/Value.h"
54 #include "llvm/IR/Verifier.h"
55 #include "llvm/Pass.h"
56 #include "llvm/Support/Casting.h"
57 #include "llvm/Support/Debug.h"
59 #include "llvm/Transforms/Scalar.h"
63 #include <cassert>
64 #include <cstddef>
65 #include <cstdint>
66 #include <initializer_list>
67 #include <iterator>
68 
69 using namespace llvm;
70 
71 #define DEBUG_TYPE "coro-split"
72 
73 // Create an entry block for a resume function with a switch that will jump to
74 // suspend points.
76  LLVMContext &C = F.getContext();
77 
78  // resume.entry:
79  // %index.addr = getelementptr inbounds %f.Frame, %f.Frame* %FramePtr, i32 0,
80  // i32 2
81  // % index = load i32, i32* %index.addr
82  // switch i32 %index, label %unreachable [
83  // i32 0, label %resume.0
84  // i32 1, label %resume.1
85  // ...
86  // ]
87 
88  auto *NewEntry = BasicBlock::Create(C, "resume.entry", &F);
89  auto *UnreachBB = BasicBlock::Create(C, "unreachable", &F);
90 
91  IRBuilder<> Builder(NewEntry);
92  auto *FramePtr = Shape.FramePtr;
93  auto *FrameTy = Shape.FrameTy;
94  auto *GepIndex = Builder.CreateConstInBoundsGEP2_32(
95  FrameTy, FramePtr, 0, coro::Shape::IndexField, "index.addr");
96  auto *Index = Builder.CreateLoad(GepIndex, "index");
97  auto *Switch =
98  Builder.CreateSwitch(Index, UnreachBB, Shape.CoroSuspends.size());
99  Shape.ResumeSwitch = Switch;
100 
101  size_t SuspendIndex = 0;
102  for (CoroSuspendInst *S : Shape.CoroSuspends) {
103  ConstantInt *IndexVal = Shape.getIndex(SuspendIndex);
104 
105  // Replace CoroSave with a store to Index:
106  // %index.addr = getelementptr %f.frame... (index field number)
107  // store i32 0, i32* %index.addr1
108  auto *Save = S->getCoroSave();
109  Builder.SetInsertPoint(Save);
110  if (S->isFinal()) {
111  // Final suspend point is represented by storing zero in ResumeFnAddr.
112  auto *GepIndex = Builder.CreateConstInBoundsGEP2_32(FrameTy, FramePtr, 0,
113  0, "ResumeFn.addr");
114  auto *NullPtr = ConstantPointerNull::get(cast<PointerType>(
115  cast<PointerType>(GepIndex->getType())->getElementType()));
116  Builder.CreateStore(NullPtr, GepIndex);
117  } else {
118  auto *GepIndex = Builder.CreateConstInBoundsGEP2_32(
119  FrameTy, FramePtr, 0, coro::Shape::IndexField, "index.addr");
120  Builder.CreateStore(IndexVal, GepIndex);
121  }
123  Save->eraseFromParent();
124 
125  // Split block before and after coro.suspend and add a jump from an entry
126  // switch:
127  //
128  // whateverBB:
129  // whatever
130  // %0 = call i8 @llvm.coro.suspend(token none, i1 false)
131  // switch i8 %0, label %suspend[i8 0, label %resume
132  // i8 1, label %cleanup]
133  // becomes:
134  //
135  // whateverBB:
136  // whatever
137  // br label %resume.0.landing
138  //
139  // resume.0: ; <--- jump from the switch in the resume.entry
140  // %0 = tail call i8 @llvm.coro.suspend(token none, i1 false)
141  // br label %resume.0.landing
142  //
143  // resume.0.landing:
144  // %1 = phi i8[-1, %whateverBB], [%0, %resume.0]
145  // switch i8 % 1, label %suspend [i8 0, label %resume
146  // i8 1, label %cleanup]
147 
148  auto *SuspendBB = S->getParent();
149  auto *ResumeBB =
150  SuspendBB->splitBasicBlock(S, "resume." + Twine(SuspendIndex));
151  auto *LandingBB = ResumeBB->splitBasicBlock(
152  S->getNextNode(), ResumeBB->getName() + Twine(".landing"));
153  Switch->addCase(IndexVal, ResumeBB);
154 
155  cast<BranchInst>(SuspendBB->getTerminator())->setSuccessor(0, LandingBB);
156  auto *PN = PHINode::Create(Builder.getInt8Ty(), 2, "", &LandingBB->front());
157  S->replaceAllUsesWith(PN);
158  PN->addIncoming(Builder.getInt8(-1), SuspendBB);
159  PN->addIncoming(S, ResumeBB);
160 
161  ++SuspendIndex;
162  }
163 
164  Builder.SetInsertPoint(UnreachBB);
165  Builder.CreateUnreachable();
166 
167  return NewEntry;
168 }
169 
170 // In Resumers, we replace fallthrough coro.end with ret void and delete the
171 // rest of the block.
173  ValueToValueMapTy &VMap) {
174  auto *NewE = cast<IntrinsicInst>(VMap[End]);
175  ReturnInst::Create(NewE->getContext(), nullptr, NewE);
176 
177  // Remove the rest of the block, by splitting it into an unreachable block.
178  auto *BB = NewE->getParent();
179  BB->splitBasicBlock(NewE);
181 }
182 
183 // In Resumers, we replace unwind coro.end with True to force the immediate
184 // unwind to caller.
186  if (Shape.CoroEnds.empty())
187  return;
188 
189  LLVMContext &Context = Shape.CoroEnds.front()->getContext();
190  auto *True = ConstantInt::getTrue(Context);
191  for (CoroEndInst *CE : Shape.CoroEnds) {
192  if (!CE->isUnwind())
193  continue;
194 
195  auto *NewCE = cast<IntrinsicInst>(VMap[CE]);
196 
197  // If coro.end has an associated bundle, add cleanupret instruction.
198  if (auto Bundle = NewCE->getOperandBundle(LLVMContext::OB_funclet)) {
199  Value *FromPad = Bundle->Inputs[0];
200  auto *CleanupRet = CleanupReturnInst::Create(FromPad, nullptr, NewCE);
201  NewCE->getParent()->splitBasicBlock(NewCE);
202  CleanupRet->getParent()->getTerminator()->eraseFromParent();
203  }
204 
205  NewCE->replaceAllUsesWith(True);
206  NewCE->eraseFromParent();
207  }
208 }
209 
210 // Rewrite final suspend point handling. We do not use suspend index to
211 // represent the final suspend point. Instead we zero-out ResumeFnAddr in the
212 // coroutine frame, since it is undefined behavior to resume a coroutine
213 // suspended at the final suspend point. Thus, in the resume function, we can
214 // simply remove the last case (when coro::Shape is built, the final suspend
215 // point (if present) is always the last element of CoroSuspends array).
216 // In the destroy function, we add a code sequence to check if ResumeFnAddress
217 // is Null, and if so, jump to the appropriate label to handle cleanup from the
218 // final suspend point.
219 static void handleFinalSuspend(IRBuilder<> &Builder, Value *FramePtr,
220  coro::Shape &Shape, SwitchInst *Switch,
221  bool IsDestroy) {
222  assert(Shape.HasFinalSuspend);
223  auto FinalCaseIt = std::prev(Switch->case_end());
224  BasicBlock *ResumeBB = FinalCaseIt->getCaseSuccessor();
225  Switch->removeCase(FinalCaseIt);
226  if (IsDestroy) {
227  BasicBlock *OldSwitchBB = Switch->getParent();
228  auto *NewSwitchBB = OldSwitchBB->splitBasicBlock(Switch, "Switch");
229  Builder.SetInsertPoint(OldSwitchBB->getTerminator());
230  auto *GepIndex = Builder.CreateConstInBoundsGEP2_32(Shape.FrameTy, FramePtr,
231  0, 0, "ResumeFn.addr");
232  auto *Load = Builder.CreateLoad(GepIndex);
233  auto *NullPtr =
234  ConstantPointerNull::get(cast<PointerType>(Load->getType()));
235  auto *Cond = Builder.CreateICmpEQ(Load, NullPtr);
236  Builder.CreateCondBr(Cond, ResumeBB, NewSwitchBB);
237  OldSwitchBB->getTerminator()->eraseFromParent();
238  }
239 }
240 
241 // Create a resume clone by cloning the body of the original function, setting
242 // new entry block and replacing coro.suspend an appropriate value to force
243 // resume or cleanup pass for every suspend point.
244 static Function *createClone(Function &F, Twine Suffix, coro::Shape &Shape,
245  BasicBlock *ResumeEntry, int8_t FnIndex) {
246  Module *M = F.getParent();
247  auto *FrameTy = Shape.FrameTy;
248  auto *FnPtrTy = cast<PointerType>(FrameTy->getElementType(0));
249  auto *FnTy = cast<FunctionType>(FnPtrTy->getElementType());
250 
251  Function *NewF =
252  Function::Create(FnTy, GlobalValue::LinkageTypes::ExternalLinkage,
253  F.getName() + Suffix, M);
254  NewF->addParamAttr(0, Attribute::NonNull);
255  NewF->addParamAttr(0, Attribute::NoAlias);
256 
257  ValueToValueMapTy VMap;
258  // Replace all args with undefs. The buildCoroutineFrame algorithm already
259  // rewritten access to the args that occurs after suspend points with loads
260  // and stores to/from the coroutine frame.
261  for (Argument &A : F.args())
262  VMap[&A] = UndefValue::get(A.getType());
263 
265 
266  CloneFunctionInto(NewF, &F, VMap, /*ModuleLevelChanges=*/true, Returns);
267  NewF->setLinkage(GlobalValue::LinkageTypes::InternalLinkage);
268 
269  // Remove old returns.
270  for (ReturnInst *Return : Returns)
271  changeToUnreachable(Return, /*UseLLVMTrap=*/false);
272 
273  // Remove old return attributes.
274  NewF->removeAttributes(
276  AttributeFuncs::typeIncompatible(NewF->getReturnType()));
277 
278  // Make AllocaSpillBlock the new entry block.
279  auto *SwitchBB = cast<BasicBlock>(VMap[ResumeEntry]);
280  auto *Entry = cast<BasicBlock>(VMap[Shape.AllocaSpillBlock]);
281  Entry->moveBefore(&NewF->getEntryBlock());
282  Entry->getTerminator()->eraseFromParent();
283  BranchInst::Create(SwitchBB, Entry);
284  Entry->setName("entry" + Suffix);
285 
286  // Clear all predecessors of the new entry block.
287  auto *Switch = cast<SwitchInst>(VMap[Shape.ResumeSwitch]);
288  Entry->replaceAllUsesWith(Switch->getDefaultDest());
289 
290  IRBuilder<> Builder(&NewF->getEntryBlock().front());
291 
292  // Remap frame pointer.
293  Argument *NewFramePtr = &*NewF->arg_begin();
294  Value *OldFramePtr = cast<Value>(VMap[Shape.FramePtr]);
295  NewFramePtr->takeName(OldFramePtr);
296  OldFramePtr->replaceAllUsesWith(NewFramePtr);
297 
298  // Remap vFrame pointer.
299  auto *NewVFrame = Builder.CreateBitCast(
300  NewFramePtr, Type::getInt8PtrTy(Builder.getContext()), "vFrame");
301  Value *OldVFrame = cast<Value>(VMap[Shape.CoroBegin]);
302  OldVFrame->replaceAllUsesWith(NewVFrame);
303 
304  // Rewrite final suspend handling as it is not done via switch (allows to
305  // remove final case from the switch, since it is undefined behavior to resume
306  // the coroutine suspended at the final suspend point.
307  if (Shape.HasFinalSuspend) {
308  auto *Switch = cast<SwitchInst>(VMap[Shape.ResumeSwitch]);
309  bool IsDestroy = FnIndex != 0;
310  handleFinalSuspend(Builder, NewFramePtr, Shape, Switch, IsDestroy);
311  }
312 
313  // Replace coro suspend with the appropriate resume index.
314  // Replacing coro.suspend with (0) will result in control flow proceeding to
315  // a resume label associated with a suspend point, replacing it with (1) will
316  // result in control flow proceeding to a cleanup label associated with this
317  // suspend point.
318  auto *NewValue = Builder.getInt8(FnIndex ? 1 : 0);
319  for (CoroSuspendInst *CS : Shape.CoroSuspends) {
320  auto *MappedCS = cast<CoroSuspendInst>(VMap[CS]);
321  MappedCS->replaceAllUsesWith(NewValue);
322  MappedCS->eraseFromParent();
323  }
324 
325  // Remove coro.end intrinsics.
326  replaceFallthroughCoroEnd(Shape.CoroEnds.front(), VMap);
327  replaceUnwindCoroEnds(Shape, VMap);
328  // Eliminate coro.free from the clones, replacing it with 'null' in cleanup,
329  // to suppress deallocation code.
330  coro::replaceCoroFree(cast<CoroIdInst>(VMap[Shape.CoroBegin->getId()]),
331  /*Elide=*/FnIndex == 2);
332 
333  NewF->setCallingConv(CallingConv::Fast);
334 
335  return NewF;
336 }
337 
338 static void removeCoroEnds(coro::Shape &Shape) {
339  if (Shape.CoroEnds.empty())
340  return;
341 
342  LLVMContext &Context = Shape.CoroEnds.front()->getContext();
343  auto *False = ConstantInt::getFalse(Context);
344 
345  for (CoroEndInst *CE : Shape.CoroEnds) {
346  CE->replaceAllUsesWith(False);
347  CE->eraseFromParent();
348  }
349 }
350 
351 static void replaceFrameSize(coro::Shape &Shape) {
352  if (Shape.CoroSizes.empty())
353  return;
354 
355  // In the same function all coro.sizes should have the same result type.
356  auto *SizeIntrin = Shape.CoroSizes.back();
357  Module *M = SizeIntrin->getModule();
358  const DataLayout &DL = M->getDataLayout();
359  auto Size = DL.getTypeAllocSize(Shape.FrameTy);
360  auto *SizeConstant = ConstantInt::get(SizeIntrin->getType(), Size);
361 
362  for (CoroSizeInst *CS : Shape.CoroSizes) {
363  CS->replaceAllUsesWith(SizeConstant);
364  CS->eraseFromParent();
365  }
366 }
367 
368 // Create a global constant array containing pointers to functions provided and
369 // set Info parameter of CoroBegin to point at this constant. Example:
370 //
371 // @f.resumers = internal constant [2 x void(%f.frame*)*]
372 // [void(%f.frame*)* @f.resume, void(%f.frame*)* @f.destroy]
373 // define void @f() {
374 // ...
375 // call i8* @llvm.coro.begin(i8* null, i32 0, i8* null,
376 // i8* bitcast([2 x void(%f.frame*)*] * @f.resumers to i8*))
377 //
378 // Assumes that all the functions have the same signature.
379 static void setCoroInfo(Function &F, CoroBeginInst *CoroBegin,
380  std::initializer_list<Function *> Fns) {
381  SmallVector<Constant *, 4> Args(Fns.begin(), Fns.end());
382  assert(!Args.empty());
383  Function *Part = *Fns.begin();
384  Module *M = Part->getParent();
385  auto *ArrTy = ArrayType::get(Part->getType(), Args.size());
386 
387  auto *ConstVal = ConstantArray::get(ArrTy, Args);
388  auto *GV = new GlobalVariable(*M, ConstVal->getType(), /*isConstant=*/true,
390  F.getName() + Twine(".resumers"));
391 
392  // Update coro.begin instruction to refer to this constant.
393  LLVMContext &C = F.getContext();
395  CoroBegin->getId()->setInfo(BC);
396 }
397 
398 // Store addresses of Resume/Destroy/Cleanup functions in the coroutine frame.
399 static void updateCoroFrame(coro::Shape &Shape, Function *ResumeFn,
400  Function *DestroyFn, Function *CleanupFn) {
401  IRBuilder<> Builder(Shape.FramePtr->getNextNode());
402  auto *ResumeAddr = Builder.CreateConstInBoundsGEP2_32(
403  Shape.FrameTy, Shape.FramePtr, 0, coro::Shape::ResumeField,
404  "resume.addr");
405  Builder.CreateStore(ResumeFn, ResumeAddr);
406 
407  Value *DestroyOrCleanupFn = DestroyFn;
408 
409  CoroIdInst *CoroId = Shape.CoroBegin->getId();
410  if (CoroAllocInst *CA = CoroId->getCoroAlloc()) {
411  // If there is a CoroAlloc and it returns false (meaning we elide the
412  // allocation, use CleanupFn instead of DestroyFn).
413  DestroyOrCleanupFn = Builder.CreateSelect(CA, DestroyFn, CleanupFn);
414  }
415 
416  auto *DestroyAddr = Builder.CreateConstInBoundsGEP2_32(
417  Shape.FrameTy, Shape.FramePtr, 0, coro::Shape::DestroyField,
418  "destroy.addr");
419  Builder.CreateStore(DestroyOrCleanupFn, DestroyAddr);
420 }
421 
422 static void postSplitCleanup(Function &F) {
425 
426  FPM.add(createVerifierPass());
427  FPM.add(createSCCPPass());
428  FPM.add(createCFGSimplificationPass());
429  FPM.add(createEarlyCSEPass());
430  FPM.add(createCFGSimplificationPass());
431 
432  FPM.doInitialization();
433  FPM.run(F);
434  FPM.doFinalization();
435 }
436 
437 // Assuming we arrived at the block NewBlock from Prev instruction, store
438 // PHI's incoming values in the ResolvedValues map.
439 static void
441  DenseMap<Value *, Value *> &ResolvedValues) {
442  auto *PrevBB = Prev->getParent();
443  for (PHINode &PN : NewBlock->phis()) {
444  auto V = PN.getIncomingValueForBlock(PrevBB);
445  // See if we already resolved it.
446  auto VI = ResolvedValues.find(V);
447  if (VI != ResolvedValues.end())
448  V = VI->second;
449  // Remember the value.
450  ResolvedValues[&PN] = V;
451  }
452 }
453 
454 // Replace a sequence of branches leading to a ret, with a clone of a ret
455 // instruction. Suspend instruction represented by a switch, track the PHI
456 // values and select the correct case successor when possible.
457 static bool simplifyTerminatorLeadingToRet(Instruction *InitialInst) {
458  DenseMap<Value *, Value *> ResolvedValues;
459 
460  Instruction *I = InitialInst;
461  while (I->isTerminator()) {
462  if (isa<ReturnInst>(I)) {
463  if (I != InitialInst)
464  ReplaceInstWithInst(InitialInst, I->clone());
465  return true;
466  }
467  if (auto *BR = dyn_cast<BranchInst>(I)) {
468  if (BR->isUnconditional()) {
469  BasicBlock *BB = BR->getSuccessor(0);
470  scanPHIsAndUpdateValueMap(I, BB, ResolvedValues);
472  continue;
473  }
474  } else if (auto *SI = dyn_cast<SwitchInst>(I)) {
475  Value *V = SI->getCondition();
476  auto it = ResolvedValues.find(V);
477  if (it != ResolvedValues.end())
478  V = it->second;
479  if (ConstantInt *Cond = dyn_cast<ConstantInt>(V)) {
480  BasicBlock *BB = SI->findCaseValue(Cond)->getCaseSuccessor();
481  scanPHIsAndUpdateValueMap(I, BB, ResolvedValues);
483  continue;
484  }
485  }
486  return false;
487  }
488  return false;
489 }
490 
491 // Add musttail to any resume instructions that is immediately followed by a
492 // suspend (i.e. ret). We do this even in -O0 to support guaranteed tail call
493 // for symmetrical coroutine control transfer (C++ Coroutines TS extension).
494 // This transformation is done only in the resume part of the coroutine that has
495 // identical signature and calling convention as the coro.resume call.
497  bool changed = false;
498 
499  // Collect potential resume instructions.
501  for (auto &I : instructions(F))
502  if (auto *Call = dyn_cast<CallInst>(&I))
503  if (auto *CalledValue = Call->getCalledValue())
504  // CoroEarly pass replaced coro resumes with indirect calls to an
505  // address return by CoroSubFnInst intrinsic. See if it is one of those.
506  if (isa<CoroSubFnInst>(CalledValue->stripPointerCasts()))
507  Resumes.push_back(Call);
508 
509  // Set musttail on those that are followed by a ret instruction.
510  for (CallInst *Call : Resumes)
511  if (simplifyTerminatorLeadingToRet(Call->getNextNode())) {
512  Call->setTailCallKind(CallInst::TCK_MustTail);
513  changed = true;
514  }
515 
516  if (changed)
518 }
519 
520 // Coroutine has no suspend points. Remove heap allocation for the coroutine
521 // frame if possible.
522 static void handleNoSuspendCoroutine(CoroBeginInst *CoroBegin, Type *FrameTy) {
523  auto *CoroId = CoroBegin->getId();
524  auto *AllocInst = CoroId->getCoroAlloc();
525  coro::replaceCoroFree(CoroId, /*Elide=*/AllocInst != nullptr);
526  if (AllocInst) {
527  IRBuilder<> Builder(AllocInst);
528  // FIXME: Need to handle overaligned members.
529  auto *Frame = Builder.CreateAlloca(FrameTy);
530  auto *VFrame = Builder.CreateBitCast(Frame, Builder.getInt8PtrTy());
531  AllocInst->replaceAllUsesWith(Builder.getFalse());
532  AllocInst->eraseFromParent();
533  CoroBegin->replaceAllUsesWith(VFrame);
534  } else {
535  CoroBegin->replaceAllUsesWith(CoroBegin->getMem());
536  }
537  CoroBegin->eraseFromParent();
538 }
539 
540 // SimplifySuspendPoint needs to check that there is no calls between
541 // coro_save and coro_suspend, since any of the calls may potentially resume
542 // the coroutine and if that is the case we cannot eliminate the suspend point.
544  for (Instruction *I = From; I != To; I = I->getNextNode()) {
545  // Assume that no intrinsic can resume the coroutine.
546  if (isa<IntrinsicInst>(I))
547  continue;
548 
549  if (CallSite(I))
550  return true;
551  }
552  return false;
553 }
554 
555 static bool hasCallsInBlocksBetween(BasicBlock *SaveBB, BasicBlock *ResDesBB) {
558 
559  Set.insert(SaveBB);
560  Worklist.push_back(ResDesBB);
561 
562  // Accumulate all blocks between SaveBB and ResDesBB. Because CoroSaveIntr
563  // returns a token consumed by suspend instruction, all blocks in between
564  // will have to eventually hit SaveBB when going backwards from ResDesBB.
565  while (!Worklist.empty()) {
566  auto *BB = Worklist.pop_back_val();
567  Set.insert(BB);
568  for (auto *Pred : predecessors(BB))
569  if (Set.count(Pred) == 0)
570  Worklist.push_back(Pred);
571  }
572 
573  // SaveBB and ResDesBB are checked separately in hasCallsBetween.
574  Set.erase(SaveBB);
575  Set.erase(ResDesBB);
576 
577  for (auto *BB : Set)
578  if (hasCallsInBlockBetween(BB->getFirstNonPHI(), nullptr))
579  return true;
580 
581  return false;
582 }
583 
584 static bool hasCallsBetween(Instruction *Save, Instruction *ResumeOrDestroy) {
585  auto *SaveBB = Save->getParent();
586  auto *ResumeOrDestroyBB = ResumeOrDestroy->getParent();
587 
588  if (SaveBB == ResumeOrDestroyBB)
589  return hasCallsInBlockBetween(Save->getNextNode(), ResumeOrDestroy);
590 
591  // Any calls from Save to the end of the block?
592  if (hasCallsInBlockBetween(Save->getNextNode(), nullptr))
593  return true;
594 
595  // Any calls from begging of the block up to ResumeOrDestroy?
596  if (hasCallsInBlockBetween(ResumeOrDestroyBB->getFirstNonPHI(),
597  ResumeOrDestroy))
598  return true;
599 
600  // Any calls in all of the blocks between SaveBB and ResumeOrDestroyBB?
601  if (hasCallsInBlocksBetween(SaveBB, ResumeOrDestroyBB))
602  return true;
603 
604  return false;
605 }
606 
607 // If a SuspendIntrin is preceded by Resume or Destroy, we can eliminate the
608 // suspend point and replace it with nornal control flow.
610  CoroBeginInst *CoroBegin) {
611  Instruction *Prev = Suspend->getPrevNode();
612  if (!Prev) {
613  auto *Pred = Suspend->getParent()->getSinglePredecessor();
614  if (!Pred)
615  return false;
616  Prev = Pred->getTerminator();
617  }
618 
619  CallSite CS{Prev};
620  if (!CS)
621  return false;
622 
623  auto *CallInstr = CS.getInstruction();
624 
625  auto *Callee = CS.getCalledValue()->stripPointerCasts();
626 
627  // See if the callsite is for resumption or destruction of the coroutine.
628  auto *SubFn = dyn_cast<CoroSubFnInst>(Callee);
629  if (!SubFn)
630  return false;
631 
632  // Does not refer to the current coroutine, we cannot do anything with it.
633  if (SubFn->getFrame() != CoroBegin)
634  return false;
635 
636  // See if the transformation is safe. Specifically, see if there are any
637  // calls in between Save and CallInstr. They can potenitally resume the
638  // coroutine rendering this optimization unsafe.
639  auto *Save = Suspend->getCoroSave();
640  if (hasCallsBetween(Save, CallInstr))
641  return false;
642 
643  // Replace llvm.coro.suspend with the value that results in resumption over
644  // the resume or cleanup path.
645  Suspend->replaceAllUsesWith(SubFn->getRawIndex());
646  Suspend->eraseFromParent();
647  Save->eraseFromParent();
648 
649  // No longer need a call to coro.resume or coro.destroy.
650  if (auto *Invoke = dyn_cast<InvokeInst>(CallInstr)) {
651  BranchInst::Create(Invoke->getNormalDest(), Invoke);
652  }
653 
654  // Grab the CalledValue from CS before erasing the CallInstr.
655  auto *CalledValue = CS.getCalledValue();
656  CallInstr->eraseFromParent();
657 
658  // If no more users remove it. Usually it is a bitcast of SubFn.
659  if (CalledValue != SubFn && CalledValue->user_empty())
660  if (auto *I = dyn_cast<Instruction>(CalledValue))
661  I->eraseFromParent();
662 
663  // Now we are good to remove SubFn.
664  if (SubFn->user_empty())
665  SubFn->eraseFromParent();
666 
667  return true;
668 }
669 
670 // Remove suspend points that are simplified.
671 static void simplifySuspendPoints(coro::Shape &Shape) {
672  auto &S = Shape.CoroSuspends;
673  size_t I = 0, N = S.size();
674  if (N == 0)
675  return;
676  while (true) {
677  if (simplifySuspendPoint(S[I], Shape.CoroBegin)) {
678  if (--N == I)
679  break;
680  std::swap(S[I], S[N]);
681  continue;
682  }
683  if (++I == N)
684  break;
685  }
686  S.resize(N);
687 }
688 
690  // Collect all blocks that we need to look for instructions to relocate.
691  SmallPtrSet<BasicBlock *, 4> RelocBlocks;
693  Work.push_back(CB->getParent());
694 
695  do {
696  BasicBlock *Current = Work.pop_back_val();
697  for (BasicBlock *BB : predecessors(Current))
698  if (RelocBlocks.count(BB) == 0) {
699  RelocBlocks.insert(BB);
700  Work.push_back(BB);
701  }
702  } while (!Work.empty());
703  return RelocBlocks;
704 }
705 
708  SmallPtrSetImpl<BasicBlock *> &RelocBlocks) {
709  SmallPtrSet<Instruction *, 8> DoNotRelocate;
710  // Collect all instructions that we should not relocate
712 
713  // Start with CoroBegin and terminators of all preceding blocks.
714  Work.push_back(CoroBegin);
715  BasicBlock *CoroBeginBB = CoroBegin->getParent();
716  for (BasicBlock *BB : RelocBlocks)
717  if (BB != CoroBeginBB)
718  Work.push_back(BB->getTerminator());
719 
720  // For every instruction in the Work list, place its operands in DoNotRelocate
721  // set.
722  do {
723  Instruction *Current = Work.pop_back_val();
724  LLVM_DEBUG(dbgs() << "CoroSplit: Will not relocate: " << *Current << "\n");
725  DoNotRelocate.insert(Current);
726  for (Value *U : Current->operands()) {
727  auto *I = dyn_cast<Instruction>(U);
728  if (!I)
729  continue;
730 
731  if (auto *A = dyn_cast<AllocaInst>(I)) {
732  // Stores to alloca instructions that occur before the coroutine frame
733  // is allocated should not be moved; the stored values may be used by
734  // the coroutine frame allocator. The operands to those stores must also
735  // remain in place.
736  for (const auto &User : A->users())
737  if (auto *SI = dyn_cast<llvm::StoreInst>(User))
738  if (RelocBlocks.count(SI->getParent()) != 0 &&
739  DoNotRelocate.count(SI) == 0) {
740  Work.push_back(SI);
741  DoNotRelocate.insert(SI);
742  }
743  continue;
744  }
745 
746  if (DoNotRelocate.count(I) == 0) {
747  Work.push_back(I);
748  DoNotRelocate.insert(I);
749  }
750  }
751  } while (!Work.empty());
752  return DoNotRelocate;
753 }
754 
756  // Analyze which non-alloca instructions are needed for allocation and
757  // relocate the rest to after coro.begin. We need to do it, since some of the
758  // targets of those instructions may be placed into coroutine frame memory
759  // for which becomes available after coro.begin intrinsic.
760 
761  auto BlockSet = getCoroBeginPredBlocks(CoroBegin);
762  auto DoNotRelocateSet = getNotRelocatableInstructions(CoroBegin, BlockSet);
763 
764  Instruction *InsertPt = CoroBegin->getNextNode();
765  BasicBlock &BB = F.getEntryBlock(); // TODO: Look at other blocks as well.
766  for (auto B = BB.begin(), E = BB.end(); B != E;) {
767  Instruction &I = *B++;
768  if (isa<AllocaInst>(&I))
769  continue;
770  if (&I == CoroBegin)
771  break;
772  if (DoNotRelocateSet.count(&I))
773  continue;
774  I.moveBefore(InsertPt);
775  }
776 }
777 
778 static void splitCoroutine(Function &F, CallGraph &CG, CallGraphSCC &SCC) {
779  coro::Shape Shape(F);
780  if (!Shape.CoroBegin)
781  return;
782 
783  simplifySuspendPoints(Shape);
785  buildCoroutineFrame(F, Shape);
786  replaceFrameSize(Shape);
787 
788  // If there are no suspend points, no split required, just remove
789  // the allocation and deallocation blocks, they are not needed.
790  if (Shape.CoroSuspends.empty()) {
792  removeCoroEnds(Shape);
793  postSplitCleanup(F);
794  coro::updateCallGraph(F, {}, CG, SCC);
795  return;
796  }
797 
798  auto *ResumeEntry = createResumeEntryBlock(F, Shape);
799  auto ResumeClone = createClone(F, ".resume", Shape, ResumeEntry, 0);
800  auto DestroyClone = createClone(F, ".destroy", Shape, ResumeEntry, 1);
801  auto CleanupClone = createClone(F, ".cleanup", Shape, ResumeEntry, 2);
802 
803  // We no longer need coro.end in F.
804  removeCoroEnds(Shape);
805 
806  postSplitCleanup(F);
807  postSplitCleanup(*ResumeClone);
808  postSplitCleanup(*DestroyClone);
809  postSplitCleanup(*CleanupClone);
810 
811  addMustTailToCoroResumes(*ResumeClone);
812 
813  // Store addresses resume/destroy/cleanup functions in the coroutine frame.
814  updateCoroFrame(Shape, ResumeClone, DestroyClone, CleanupClone);
815 
816  // Create a constant array referring to resume/destroy/clone functions pointed
817  // by the last argument of @llvm.coro.info, so that CoroElide pass can
818  // determined correct function to call.
819  setCoroInfo(F, Shape.CoroBegin, {ResumeClone, DestroyClone, CleanupClone});
820 
821  // Update call graph and add the functions we created to the SCC.
822  coro::updateCallGraph(F, {ResumeClone, DestroyClone, CleanupClone}, CG, SCC);
823 }
824 
825 // When we see the coroutine the first time, we insert an indirect call to a
826 // devirt trigger function and mark the coroutine that it is now ready for
827 // split.
828 static void prepareForSplit(Function &F, CallGraph &CG) {
829  Module &M = *F.getParent();
830 #ifndef NDEBUG
832  assert(DevirtFn && "coro.devirt.trigger function not found");
833 #endif
834 
836 
837  // Insert an indirect call sequence that will be devirtualized by CoroElide
838  // pass:
839  // %0 = call i8* @llvm.coro.subfn.addr(i8* null, i8 -1)
840  // %1 = bitcast i8* %0 to void(i8*)*
841  // call void %1(i8* null)
842  coro::LowererBase Lowerer(M);
843  Instruction *InsertPt = F.getEntryBlock().getTerminator();
845  auto *DevirtFnAddr =
846  Lowerer.makeSubFnCall(Null, CoroSubFnInst::RestartTrigger, InsertPt);
847  auto *IndirectCall = CallInst::Create(DevirtFnAddr, Null, "", InsertPt);
848 
849  // Update CG graph with an indirect call we just added.
850  CG[&F]->addCalledFunction(IndirectCall, CG.getCallsExternalNode());
851 }
852 
853 // Make sure that there is a devirtualization trigger function that CoroSplit
854 // pass uses the force restart CGSCC pipeline. If devirt trigger function is not
855 // found, we will create one and add it to the current SCC.
857  Module &M = CG.getModule();
859  return;
860 
861  LLVMContext &C = M.getContext();
863  /*IsVarArgs=*/false);
864  Function *DevirtFn =
865  Function::Create(FnTy, GlobalValue::LinkageTypes::PrivateLinkage,
867  DevirtFn->addFnAttr(Attribute::AlwaysInline);
868  auto *Entry = BasicBlock::Create(C, "entry", DevirtFn);
869  ReturnInst::Create(C, Entry);
870 
871  auto *Node = CG.getOrInsertFunction(DevirtFn);
872 
873  SmallVector<CallGraphNode *, 8> Nodes(SCC.begin(), SCC.end());
874  Nodes.push_back(Node);
875  SCC.initialize(Nodes);
876 }
877 
878 //===----------------------------------------------------------------------===//
879 // Top Level Driver
880 //===----------------------------------------------------------------------===//
881 
882 namespace {
883 
884 struct CoroSplit : public CallGraphSCCPass {
885  static char ID; // Pass identification, replacement for typeid
886 
887  CoroSplit() : CallGraphSCCPass(ID) {
889  }
890 
891  bool Run = false;
892 
893  // A coroutine is identified by the presence of coro.begin intrinsic, if
894  // we don't have any, this pass has nothing to do.
895  bool doInitialization(CallGraph &CG) override {
896  Run = coro::declaresIntrinsics(CG.getModule(), {"llvm.coro.begin"});
898  }
899 
900  bool runOnSCC(CallGraphSCC &SCC) override {
901  if (!Run)
902  return false;
903 
904  // Find coroutines for processing.
905  SmallVector<Function *, 4> Coroutines;
906  for (CallGraphNode *CGN : SCC)
907  if (auto *F = CGN->getFunction())
908  if (F->hasFnAttribute(CORO_PRESPLIT_ATTR))
909  Coroutines.push_back(F);
910 
911  if (Coroutines.empty())
912  return false;
913 
914  CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
915  createDevirtTriggerFunc(CG, SCC);
916 
917  for (Function *F : Coroutines) {
918  Attribute Attr = F->getFnAttribute(CORO_PRESPLIT_ATTR);
920  LLVM_DEBUG(dbgs() << "CoroSplit: Processing coroutine '" << F->getName()
921  << "' state: " << Value << "\n");
922  if (Value == UNPREPARED_FOR_SPLIT) {
923  prepareForSplit(*F, CG);
924  continue;
925  }
926  F->removeFnAttr(CORO_PRESPLIT_ATTR);
927  splitCoroutine(*F, CG, SCC);
928  }
929  return true;
930  }
931 
932  void getAnalysisUsage(AnalysisUsage &AU) const override {
934  }
935 
936  StringRef getPassName() const override { return "Coroutine Splitting"; }
937 };
938 
939 } // end anonymous namespace
940 
941 char CoroSplit::ID = 0;
942 
944  CoroSplit, "coro-split",
945  "Split coroutine into a set of functions driving its state machine", false,
946  false)
947 
948 Pass *llvm::createCoroSplitPass() { return new CoroSplit(); }
Pass interface - Implemented by all &#39;passes&#39;.
Definition: Pass.h:80
uint64_t CallInst * C
Return a value (possibly void), from a function.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks &#39;this&#39; from the containing basic block and deletes it.
Definition: Instruction.cpp:67
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:110
static ConstantInt * getFalse(LLVMContext &Context)
Definition: Constants.cpp:584
static void createDevirtTriggerFunc(CallGraph &CG, CallGraphSCC &SCC)
Definition: CoroSplit.cpp:856
BranchInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional &#39;br Cond, TrueDest, FalseDest&#39; instruction.
Definition: IRBuilder.h:853
CaseIt case_end()
Returns a read/write iterator that points one past the last in the SwitchInst.
void ReplaceInstWithInst(BasicBlock::InstListType &BIL, BasicBlock::iterator &BI, Instruction *I)
Replace the instruction specified by BI with the instruction specified by I.
Instruction * FramePtr
Definition: CoroInternal.h:81
static void setCoroInfo(Function &F, CoroBeginInst *CoroBegin, std::initializer_list< Function *> Fns)
Definition: CoroSplit.cpp:379
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
This class represents an incoming formal argument to a Function.
Definition: Argument.h:29
LLVMContext & Context
AllocaInst * CreateAlloca(Type *Ty, unsigned AddrSpace, Value *ArraySize=nullptr, const Twine &Name="")
Definition: IRBuilder.h:1343
CoroBeginInst * CoroBegin
Definition: CoroInternal.h:67
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition: ilist_node.h:288
This represents the llvm.coro.alloc instruction.
Definition: CoroInstr.h:81
This class represents lattice values for constants.
Definition: AllocatorList.h:23
static void addMustTailToCoroResumes(Function &F)
Definition: CoroSplit.cpp:496
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
adds the attribute to the list of attributes for the given arg.
Definition: Function.cpp:385
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve &#39;CreateLoad(Ty, Ptr, "...")&#39; correctly, instead of converting the string to &#39;bool...
Definition: IRBuilder.h:1356
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:64
static void splitCoroutine(Function &F, CallGraph &CG, CallGraphSCC &SCC)
Definition: CoroSplit.cpp:778
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
iterator end() const
bool removeUnreachableBlocks(Function &F, LazyValueInfo *LVI=nullptr, DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Remove all blocks that can not be reached from the function&#39;s entry.
Definition: Local.cpp:2200
Pass * createCoroSplitPass()
Split up coroutines into multiple functions driving their state machines.
static void relocateInstructionBefore(CoroBeginInst *CoroBegin, Function &F)
Definition: CoroSplit.cpp:755
This class represents a function call, abstracting a target machine&#39;s calling convention.
virtual bool doInitialization(CallGraph &CG)
doInitialization - This method is called before the SCC&#39;s of the program has been processed...
FunctionPass * createVerifierPass(bool FatalErrors=true)
Definition: Verifier.cpp:5242
The two locations do not alias at all.
Definition: AliasAnalysis.h:83
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:56
bool isTerminator() const
Definition: Instruction.h:128
F(f)
static void replaceFrameSize(coro::Shape &Shape)
Definition: CoroSplit.cpp:351
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.cpp:137
A node in the call graph for a module.
Definition: CallGraph.h:164
void getAnalysisUsage(AnalysisUsage &Info) const override
getAnalysisUsage - For this class, we declare that we require and preserve the call graph...
Module & getModule() const
Returns the module the call graph corresponds to.
Definition: CallGraph.h:113
static Constant * get(ArrayType *T, ArrayRef< Constant *> V)
Definition: Constants.cpp:982
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Definition: SmallPtrSet.h:343
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:268
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, Instruction *InsertBefore=nullptr)
FunctionPass * createCFGSimplificationPass(unsigned Threshold=1, bool ForwardSwitchCond=false, bool ConvertSwitch=false, bool KeepLoops=true, bool SinkCommon=false, std::function< bool(const Function &)> Ftor=nullptr)
static bool simplifySuspendPoint(CoroSuspendInst *Suspend, CoroBeginInst *CoroBegin)
Definition: CoroSplit.cpp:609
void CloneFunctionInto(Function *NewFunc, const Function *OldFunc, ValueToValueMapTy &VMap, bool ModuleLevelChanges, SmallVectorImpl< ReturnInst *> &Returns, const char *NameSuffix="", ClonedCodeInfo *CodeInfo=nullptr, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Clone OldFunc into NewFunc, transforming the old arguments into references to VMap values...
unsigned changeToUnreachable(Instruction *I, bool UseLLVMTrap, bool PreserveLCSSA=false, DomTreeUpdater *DTU=nullptr)
Insert an unreachable instruction before the specified instruction, making it and the rest of the cod...
Definition: Local.cpp:1895
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:370
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:80
static void handleNoSuspendCoroutine(CoroBeginInst *CoroBegin, Type *FrameTy)
Definition: CoroSplit.cpp:522
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:243
This represents the llvm.coro.suspend instruction.
Definition: CoroInstr.h:265
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:742
This file contains the simple types necessary to represent the attributes associated with functions a...
static void scanPHIsAndUpdateValueMap(Instruction *Prev, BasicBlock *NewBlock, DenseMap< Value *, Value *> &ResolvedValues)
Definition: CoroSplit.cpp:440
FunctionPass * createSCCPPass()
Definition: SCCP.cpp:1869
This class represents the llvm.coro.subfn.addr instruction.
Definition: CoroInstr.h:34
#define PREPARED_FOR_SPLIT
Definition: CoroInternal.h:39
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition: IRBuilder.h:1385
Instruction * clone() const
Create a copy of &#39;this&#39; instruction that is identical in all ways except the following: ...
const Instruction * getFirstNonPHIOrDbgOrLifetime() const
Returns a pointer to the first instruction in this block that is not a PHINode, a debug intrinsic...
Definition: BasicBlock.cpp:203
This file provides interfaces used to build and manipulate a call graph, which is a very useful tool ...
Fast - This calling convention attempts to make calls as fast as possible (e.g.
Definition: CallingConv.h:42
ConstantInt * getIndex(uint64_t Value) const
Definition: CoroInternal.h:91
void initializeCoroSplitPass(PassRegistry &)
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1731
static void replaceFallthroughCoroEnd(IntrinsicInst *End, ValueToValueMapTy &VMap)
Definition: CoroSplit.cpp:172
This represents the llvm.coro.alloc instruction.
Definition: CoroInstr.h:69
SmallVector< CoroSizeInst *, 2 > CoroSizes
Definition: CoroInternal.h:69
void add(Pass *P) override
Add a pass to the queue of passes to run.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:428
static void simplifySuspendPoints(coro::Shape &Shape)
Definition: CoroSplit.cpp:671
SmallVector< CoroSuspendInst *, 4 > CoroSuspends
Definition: CoroInternal.h:70
iterator begin()
Definition: Function.h:655
amdgpu Simplify well known AMD library false Value * Callee
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
Definition: IRBuilder.h:126
const BasicBlock & getEntryBlock() const
Definition: Function.h:639
iterator begin() const
This represents the llvm.coro.size instruction.
Definition: CoroInstr.h:290
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition: Function.h:135
static void postSplitCleanup(Function &F)
Definition: CoroSplit.cpp:422
Control flow instructions. These all have token chains.
Definition: ISDOpcodes.h:628
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
Definition: Constants.cpp:1400
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
Definition: BasicBlock.cpp:233
CallGraphNode * getCallsExternalNode() const
Definition: CallGraph.h:138
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
#define CORO_PRESPLIT_ATTR
Definition: CoroInternal.h:37
bool isFinal() const
Definition: CoroInstr.h:276
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
UnreachableInst * CreateUnreachable()
Definition: IRBuilder.h:977
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:370
Value * getMem() const
Definition: CoroInstr.h:220
static void prepareForSplit(Function &F, CallGraph &CG)
Definition: CoroSplit.cpp:828
Represent the analysis usage information of a pass.
static Type * getVoidTy(LLVMContext &C)
Definition: Type.cpp:160
This represents the llvm.coro.end instruction.
Definition: CoroInstr.h:302
static bool hasCallsBetween(Instruction *Save, Instruction *ResumeOrDestroy)
Definition: CoroSplit.cpp:584
static FunctionType * get(Type *Result, ArrayRef< Type *> Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
Definition: Type.cpp:296
op_range operands()
Definition: User.h:237
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:99
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1838
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:381
void initialize(ArrayRef< CallGraphNode *> NewNodes)
static bool hasCallsInBlocksBetween(BasicBlock *SaveBB, BasicBlock *ResDesBB)
Definition: CoroSplit.cpp:555
CaseIt removeCase(CaseIt I)
This method removes the specified case and its successor from the switch instruction.
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
Definition: Function.cpp:192
static void replaceUnwindCoroEnds(coro::Shape &Shape, ValueToValueMapTy &VMap)
Definition: CoroSplit.cpp:185
FunctionPassManager manages FunctionPasses and BasicBlockPassManagers.
static Function * createClone(Function &F, Twine Suffix, coro::Shape &Shape, BasicBlock *ResumeEntry, int8_t FnIndex)
Definition: CoroSplit.cpp:244
static UndefValue * get(Type *T)
Static factory methods - Return an &#39;undef&#39; object of the specified type.
Definition: Constants.cpp:1414
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs, and aliases.
Definition: Value.cpp:528
PointerType * getInt8PtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer to an 8-bit integer value.
Definition: IRBuilder.h:384
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
Definition: Type.cpp:219
static SmallPtrSet< BasicBlock *, 4 > getCoroBeginPredBlocks(CoroBeginInst *CB)
Definition: CoroSplit.cpp:689
static bool hasCallsInBlockBetween(Instruction *From, Instruction *To)
Definition: CoroSplit.cpp:543
static Constant * getPointerCast(Constant *C, Type *Ty)
Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant expression.
Definition: Constants.cpp:1586
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:417
StructType * FrameTy
Definition: CoroInternal.h:80
This is the shared class of boolean and integer constants.
Definition: Constants.h:83
BlockVerifier::State From
bool erase(PtrType Ptr)
erase - If the set contains the specified pointer, remove it and return true, otherwise return false...
Definition: SmallPtrSet.h:377
iterator end()
Definition: BasicBlock.h:270
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:845
Module.h This file contains the declarations for the Module class.
LLVM_NODISCARD T pop_back_val()
Definition: SmallVector.h:379
void buildCoroutineFrame(Function &F, Shape &Shape)
Definition: CoroFrame.cpp:865
#define UNPREPARED_FOR_SPLIT
Definition: CoroInternal.h:38
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:621
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
pred_range predecessors(BasicBlock *BB)
Definition: CFG.h:124
static ConstantInt * getTrue(LLVMContext &Context)
Definition: Constants.cpp:577
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
Definition: Module.cpp:175
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:940
This class represents the llvm.coro.begin instruction.
Definition: CoroInstr.h:214
Value * makeSubFnCall(Value *Arg, int Index, Instruction *InsertPt)
Definition: Coroutines.cpp:107
bool isUnwind() const
Definition: CoroInstr.h:307
IntegerType * getInt8Ty()
Fetch the type representing an 8-bit integer.
Definition: IRBuilder.h:336
static void updateCoroFrame(coro::Shape &Shape, Function *ResumeFn, Function *DestroyFn, Function *CleanupFn)
Definition: CoroSplit.cpp:399
static BasicBlock * createResumeEntryBlock(Function &F, coro::Shape &Shape)
Definition: CoroSplit.cpp:75
ConstantInt * getFalse()
Get the constant value for i1 false.
Definition: IRBuilder.h:291
SwitchInst * CreateSwitch(Value *V, BasicBlock *Dest, unsigned NumCases=10, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a switch instruction with the specified value, default dest, and with a hint for the number of...
Definition: IRBuilder.h:876
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Definition: DataLayout.h:435
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
The basic data container for the call graph of a Module of IR.
Definition: CallGraph.h:73
INITIALIZE_PASS(CoroSplit, "coro-split", "Split coroutine into a set of functions driving its state machine", false, false) Pass *llvm
Definition: CoroSplit.cpp:943
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
StringRef getValueAsString() const
Return the attribute&#39;s value as a string.
Definition: Attributes.cpp:194
SwitchInst * ResumeSwitch
Definition: CoroInternal.h:83
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:213
static void handleFinalSuspend(IRBuilder<> &Builder, Value *FramePtr, coro::Shape &Shape, SwitchInst *Switch, bool IsDestroy)
Definition: CoroSplit.cpp:219
#define I(x, y, z)
Definition: MD5.cpp:58
#define N
Value * CreateConstInBoundsGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0, unsigned Idx1, const Twine &Name="")
Definition: IRBuilder.h:1552
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
Definition: Type.cpp:580
#define CORO_DEVIRT_TRIGGER_FN
Definition: CoroInternal.h:41
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:322
uint32_t Size
Definition: Profile.cpp:46
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition: BasicBlock.h:324
static ConstantTokenNone * get(LLVMContext &Context)
Return the ConstantTokenNone.
Definition: Constants.cpp:1129
BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
Definition: BasicBlock.cpp:407
CoroIdInst * getId() const
Definition: CoroInstr.h:218
void replaceCoroFree(CoroIdInst *CoroId, bool Elide)
Definition: Coroutines.cpp:152
static SmallPtrSet< Instruction *, 8 > getNotRelocatableInstructions(CoroBeginInst *CoroBegin, SmallPtrSetImpl< BasicBlock *> &RelocBlocks)
Definition: CoroSplit.cpp:707
Multiway switch.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
SmallVector< CoroEndInst *, 4 > CoroEnds
Definition: CoroInternal.h:68
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:565
LLVM Value Representation.
Definition: Value.h:72
void setInfo(Constant *C)
Definition: CoroInstr.h:163
CallGraphSCC - This is a single SCC that a CallGraphSCCPass is run on.
CallGraphNode * getOrInsertFunction(const Function *F)
Similar to operator[], but this will insert a new CallGraphNode for F if one does not already exist...
Definition: CallGraph.cpp:148
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB=nullptr, Instruction *InsertBefore=nullptr)
AttrBuilder typeIncompatible(Type *Ty)
Which attributes cannot be applied to a type.
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
Definition: Instruction.cpp:86
static bool simplifyTerminatorLeadingToRet(Instruction *InitialInst)
Definition: CoroSplit.cpp:457
bool declaresIntrinsics(Module &M, std::initializer_list< StringRef >)
Definition: Coroutines.cpp:139
void addFnAttr(Attribute::AttrKind Kind)
Add function attributes to this function.
Definition: Function.h:229
FunctionPass * createEarlyCSEPass(bool UseMemorySSA=false)
Definition: EarlyCSE.cpp:1319
ConstantInt * getInt8(uint8_t C)
Get a constant 8-bit value.
Definition: IRBuilder.h:296
static void removeCoroEnds(coro::Shape &Shape)
Definition: CoroSplit.cpp:338
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
inst_range instructions(Function *F)
Definition: InstIterator.h:133
CoroAllocInst * getCoroAlloc()
Definition: CoroInstr.h:85
BasicBlock * AllocaSpillBlock
Definition: CoroInternal.h:82
#define LLVM_DEBUG(X)
Definition: Debug.h:122
CoroSaveInst * getCoroSave() const
Definition: CoroInstr.h:269
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
void updateCallGraph(Function &Caller, ArrayRef< Function *> Funcs, CallGraph &CG, CallGraphSCC &SCC)
Definition: Coroutines.cpp:193
iterator_range< arg_iterator > args()
Definition: Function.h:688
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:43
const BasicBlock * getParent() const
Definition: Instruction.h:66