LLVM 22.0.0git
CoroFrame.cpp
Go to the documentation of this file.
1//===- CoroFrame.cpp - Builds and manipulates coroutine frame -------------===//
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 file contains classes used to discover if for a particular value
9// its definition precedes and its uses follow a suspend block. This is
10// referred to as a suspend crossing value.
11//
12// Using the information discovered we form a Coroutine Frame structure to
13// contain those values. All uses of those values are replaced with appropriate
14// GEP + load from the coroutine frame. At the point of the definition we spill
15// the value into the coroutine frame.
16//===----------------------------------------------------------------------===//
17
18#include "CoroInternal.h"
19#include "llvm/ADT/ScopeExit.h"
22#include "llvm/IR/DIBuilder.h"
23#include "llvm/IR/DebugInfo.h"
24#include "llvm/IR/Dominators.h"
25#include "llvm/IR/IRBuilder.h"
28#include "llvm/IR/Module.h"
30#include "llvm/Support/Debug.h"
40#include <algorithm>
41#include <optional>
42
43using namespace llvm;
44
45#define DEBUG_TYPE "coro-frame"
46
47namespace {
48class FrameTypeBuilder;
49// Mapping from the to-be-spilled value to all the users that need reload.
50struct FrameDataInfo {
51 // All the values (that are not allocas) that needs to be spilled to the
52 // frame.
53 coro::SpillInfo &Spills;
54 // Allocas contains all values defined as allocas that need to live in the
55 // frame.
57
58 FrameDataInfo(coro::SpillInfo &Spills,
60 : Spills(Spills), Allocas(Allocas) {}
61
62 SmallVector<Value *, 8> getAllDefs() const {
64 for (const auto &P : Spills)
65 Defs.push_back(P.first);
66 for (const auto &A : Allocas)
67 Defs.push_back(A.Alloca);
68 return Defs;
69 }
70
71 uint32_t getFieldIndex(Value *V) const {
72 auto Itr = FieldIndexMap.find(V);
73 assert(Itr != FieldIndexMap.end() &&
74 "Value does not have a frame field index");
75 return Itr->second;
76 }
77
78 void setFieldIndex(Value *V, uint32_t Index) {
79 assert((LayoutIndexUpdateStarted || FieldIndexMap.count(V) == 0) &&
80 "Cannot set the index for the same field twice.");
81 FieldIndexMap[V] = Index;
82 }
83
84 Align getAlign(Value *V) const {
85 auto Iter = FieldAlignMap.find(V);
86 assert(Iter != FieldAlignMap.end());
87 return Iter->second;
88 }
89
90 void setAlign(Value *V, Align AL) {
91 assert(FieldAlignMap.count(V) == 0);
92 FieldAlignMap.insert({V, AL});
93 }
94
95 uint64_t getDynamicAlign(Value *V) const {
96 auto Iter = FieldDynamicAlignMap.find(V);
97 assert(Iter != FieldDynamicAlignMap.end());
98 return Iter->second;
99 }
100
101 void setDynamicAlign(Value *V, uint64_t Align) {
102 assert(FieldDynamicAlignMap.count(V) == 0);
103 FieldDynamicAlignMap.insert({V, Align});
104 }
105
106 uint64_t getOffset(Value *V) const {
107 auto Iter = FieldOffsetMap.find(V);
108 assert(Iter != FieldOffsetMap.end());
109 return Iter->second;
110 }
111
112 void setOffset(Value *V, uint64_t Offset) {
113 assert(FieldOffsetMap.count(V) == 0);
114 FieldOffsetMap.insert({V, Offset});
115 }
116
117 // Remap the index of every field in the frame, using the final layout index.
118 void updateLayoutIndex(FrameTypeBuilder &B);
119
120private:
121 // LayoutIndexUpdateStarted is used to avoid updating the index of any field
122 // twice by mistake.
123 bool LayoutIndexUpdateStarted = false;
124 // Map from values to their slot indexes on the frame. They will be first set
125 // with their original insertion field index. After the frame is built, their
126 // indexes will be updated into the final layout index.
127 DenseMap<Value *, uint32_t> FieldIndexMap;
128 // Map from values to their alignment on the frame. They would be set after
129 // the frame is built.
130 DenseMap<Value *, Align> FieldAlignMap;
131 DenseMap<Value *, uint64_t> FieldDynamicAlignMap;
132 // Map from values to their offset on the frame. They would be set after
133 // the frame is built.
134 DenseMap<Value *, uint64_t> FieldOffsetMap;
135};
136} // namespace
137
138#ifndef NDEBUG
139static void dumpSpills(StringRef Title, const coro::SpillInfo &Spills) {
140 dbgs() << "------------- " << Title << " --------------\n";
141 for (const auto &E : Spills) {
142 E.first->dump();
143 dbgs() << " user: ";
144 for (auto *I : E.second)
145 I->dump();
146 }
147}
148
150 dbgs() << "------------- Allocas --------------\n";
151 for (const auto &A : Allocas) {
152 A.Alloca->dump();
153 }
154}
155#endif
156
157namespace {
158using FieldIDType = size_t;
159// We cannot rely solely on natural alignment of a type when building a
160// coroutine frame and if the alignment specified on the Alloca instruction
161// differs from the natural alignment of the alloca type we will need to insert
162// padding.
163class FrameTypeBuilder {
164private:
165 struct Field {
168 Type *Ty;
169 FieldIDType LayoutFieldIndex;
170 Align Alignment;
171 Align TyAlignment;
172 uint64_t DynamicAlignBuffer;
173 };
174
175 const DataLayout &DL;
177 uint64_t StructSize = 0;
178 Align StructAlign;
179 bool IsFinished = false;
180
181 std::optional<Align> MaxFrameAlignment;
182
184 DenseMap<Value*, unsigned> FieldIndexByKey;
185
186public:
187 FrameTypeBuilder(LLVMContext &Context, const DataLayout &DL,
188 std::optional<Align> MaxFrameAlignment)
189 : DL(DL), Context(Context), MaxFrameAlignment(MaxFrameAlignment) {}
190
191 /// Add a field to this structure for the storage of an `alloca`
192 /// instruction.
193 [[nodiscard]] FieldIDType addFieldForAlloca(AllocaInst *AI,
194 bool IsHeader = false) {
195 Type *Ty = AI->getAllocatedType();
196
197 // Make an array type if this is a static array allocation.
198 if (AI->isArrayAllocation()) {
199 if (auto *CI = dyn_cast<ConstantInt>(AI->getArraySize()))
200 Ty = ArrayType::get(Ty, CI->getValue().getZExtValue());
201 else
202 report_fatal_error("Coroutines cannot handle non static allocas yet");
203 }
204
205 return addField(Ty, AI->getAlign(), IsHeader);
206 }
207
208 /// We want to put the allocas whose lifetime-ranges are not overlapped
209 /// into one slot of coroutine frame.
210 /// Consider the example at:https://bugs.llvm.org/show_bug.cgi?id=45566
211 ///
212 /// cppcoro::task<void> alternative_paths(bool cond) {
213 /// if (cond) {
214 /// big_structure a;
215 /// process(a);
216 /// co_await something();
217 /// } else {
218 /// big_structure b;
219 /// process2(b);
220 /// co_await something();
221 /// }
222 /// }
223 ///
224 /// We want to put variable a and variable b in the same slot to
225 /// reduce the size of coroutine frame.
226 ///
227 /// This function use StackLifetime algorithm to partition the AllocaInsts in
228 /// Spills to non-overlapped sets in order to put Alloca in the same
229 /// non-overlapped set into the same slot in the Coroutine Frame. Then add
230 /// field for the allocas in the same non-overlapped set by using the largest
231 /// type as the field type.
232 ///
233 /// Side Effects: Because We sort the allocas, the order of allocas in the
234 /// frame may be different with the order in the source code.
235 void addFieldForAllocas(const Function &F, FrameDataInfo &FrameData,
236 coro::Shape &Shape, bool OptimizeFrame);
237
238 /// Add a field to this structure.
239 [[nodiscard]] FieldIDType addField(Type *Ty, MaybeAlign MaybeFieldAlignment,
240 bool IsHeader = false,
241 bool IsSpillOfValue = false) {
242 assert(!IsFinished && "adding fields to a finished builder");
243 assert(Ty && "must provide a type for a field");
244
245 // The field size is always the alloc size of the type.
246 uint64_t FieldSize = DL.getTypeAllocSize(Ty);
247
248 // For an alloca with size=0, we don't need to add a field and they
249 // can just point to any index in the frame. Use index 0.
250 if (FieldSize == 0) {
251 return 0;
252 }
253
254 // The field alignment might not be the type alignment, but we need
255 // to remember the type alignment anyway to build the type.
256 // If we are spilling values we don't need to worry about ABI alignment
257 // concerns.
258 Align ABIAlign = DL.getABITypeAlign(Ty);
259 Align TyAlignment = ABIAlign;
260 if (IsSpillOfValue && MaxFrameAlignment && *MaxFrameAlignment < ABIAlign)
261 TyAlignment = *MaxFrameAlignment;
262 Align FieldAlignment = MaybeFieldAlignment.value_or(TyAlignment);
263
264 // The field alignment could be bigger than the max frame case, in that case
265 // we request additional storage to be able to dynamically align the
266 // pointer.
267 uint64_t DynamicAlignBuffer = 0;
268 if (MaxFrameAlignment && (FieldAlignment > *MaxFrameAlignment)) {
269 DynamicAlignBuffer =
270 offsetToAlignment(MaxFrameAlignment->value(), FieldAlignment);
271 FieldAlignment = *MaxFrameAlignment;
272 FieldSize = FieldSize + DynamicAlignBuffer;
273 }
274
275 // Lay out header fields immediately.
277 if (IsHeader) {
278 Offset = alignTo(StructSize, FieldAlignment);
279 StructSize = Offset + FieldSize;
280
281 // Everything else has a flexible offset.
282 } else {
284 }
285
286 Fields.push_back({FieldSize, Offset, Ty, 0, FieldAlignment, TyAlignment,
287 DynamicAlignBuffer});
288 return Fields.size() - 1;
289 }
290
291 /// Finish the layout and create the struct type with the given name.
292 StructType *finish(StringRef Name);
293
294 uint64_t getStructSize() const {
295 assert(IsFinished && "not yet finished!");
296 return StructSize;
297 }
298
299 Align getStructAlign() const {
300 assert(IsFinished && "not yet finished!");
301 return StructAlign;
302 }
303
304 FieldIDType getLayoutFieldIndex(FieldIDType Id) const {
305 assert(IsFinished && "not yet finished!");
306 return Fields[Id].LayoutFieldIndex;
307 }
308
309 Field getLayoutField(FieldIDType Id) const {
310 assert(IsFinished && "not yet finished!");
311 return Fields[Id];
312 }
313};
314} // namespace
315
316void FrameDataInfo::updateLayoutIndex(FrameTypeBuilder &B) {
317 auto Updater = [&](Value *I) {
318 auto Field = B.getLayoutField(getFieldIndex(I));
319 setFieldIndex(I, Field.LayoutFieldIndex);
320 setAlign(I, Field.Alignment);
321 uint64_t dynamicAlign =
322 Field.DynamicAlignBuffer
323 ? Field.DynamicAlignBuffer + Field.Alignment.value()
324 : 0;
325 setDynamicAlign(I, dynamicAlign);
326 setOffset(I, Field.Offset);
327 };
328 LayoutIndexUpdateStarted = true;
329 for (auto &S : Spills)
330 Updater(S.first);
331 for (const auto &A : Allocas)
332 Updater(A.Alloca);
333 LayoutIndexUpdateStarted = false;
334}
335
336void FrameTypeBuilder::addFieldForAllocas(const Function &F,
337 FrameDataInfo &FrameData,
338 coro::Shape &Shape,
339 bool OptimizeFrame) {
340 using AllocaSetType = SmallVector<AllocaInst *, 4>;
341 SmallVector<AllocaSetType, 4> NonOverlapedAllocas;
342
343 // We need to add field for allocas at the end of this function.
344 auto AddFieldForAllocasAtExit = make_scope_exit([&]() {
345 for (auto AllocaList : NonOverlapedAllocas) {
346 auto *LargestAI = *AllocaList.begin();
347 FieldIDType Id = addFieldForAlloca(LargestAI);
348 for (auto *Alloca : AllocaList)
349 FrameData.setFieldIndex(Alloca, Id);
350 }
351 });
352
353 if (!OptimizeFrame) {
354 for (const auto &A : FrameData.Allocas) {
355 AllocaInst *Alloca = A.Alloca;
356 NonOverlapedAllocas.emplace_back(AllocaSetType(1, Alloca));
357 }
358 return;
359 }
360
361 // Because there are paths from the lifetime.start to coro.end
362 // for each alloca, the liferanges for every alloca is overlaped
363 // in the blocks who contain coro.end and the successor blocks.
364 // So we choose to skip there blocks when we calculate the liferange
365 // for each alloca. It should be reasonable since there shouldn't be uses
366 // in these blocks and the coroutine frame shouldn't be used outside the
367 // coroutine body.
368 //
369 // Note that the user of coro.suspend may not be SwitchInst. However, this
370 // case seems too complex to handle. And it is harmless to skip these
371 // patterns since it just prevend putting the allocas to live in the same
372 // slot.
373 DenseMap<SwitchInst *, BasicBlock *> DefaultSuspendDest;
374 for (auto *CoroSuspendInst : Shape.CoroSuspends) {
375 for (auto *U : CoroSuspendInst->users()) {
376 if (auto *ConstSWI = dyn_cast<SwitchInst>(U)) {
377 auto *SWI = const_cast<SwitchInst *>(ConstSWI);
378 DefaultSuspendDest[SWI] = SWI->getDefaultDest();
379 SWI->setDefaultDest(SWI->getSuccessor(1));
380 }
381 }
382 }
383
384 auto ExtractAllocas = [&]() {
385 AllocaSetType Allocas;
386 Allocas.reserve(FrameData.Allocas.size());
387 for (const auto &A : FrameData.Allocas)
388 Allocas.push_back(A.Alloca);
389 return Allocas;
390 };
391 StackLifetime StackLifetimeAnalyzer(F, ExtractAllocas(),
392 StackLifetime::LivenessType::May);
393 StackLifetimeAnalyzer.run();
394 auto DoAllocasInterfere = [&](const AllocaInst *AI1, const AllocaInst *AI2) {
395 return StackLifetimeAnalyzer.getLiveRange(AI1).overlaps(
396 StackLifetimeAnalyzer.getLiveRange(AI2));
397 };
398 auto GetAllocaSize = [&](const coro::AllocaInfo &A) {
399 std::optional<TypeSize> RetSize = A.Alloca->getAllocationSize(DL);
400 assert(RetSize && "Variable Length Arrays (VLA) are not supported.\n");
401 assert(!RetSize->isScalable() && "Scalable vectors are not yet supported");
402 return RetSize->getFixedValue();
403 };
404 // Put larger allocas in the front. So the larger allocas have higher
405 // priority to merge, which can save more space potentially. Also each
406 // AllocaSet would be ordered. So we can get the largest Alloca in one
407 // AllocaSet easily.
408 sort(FrameData.Allocas, [&](const auto &Iter1, const auto &Iter2) {
409 return GetAllocaSize(Iter1) > GetAllocaSize(Iter2);
410 });
411 for (const auto &A : FrameData.Allocas) {
412 AllocaInst *Alloca = A.Alloca;
413 bool Merged = false;
414 // Try to find if the Alloca does not interfere with any existing
415 // NonOverlappedAllocaSet. If it is true, insert the alloca to that
416 // NonOverlappedAllocaSet.
417 for (auto &AllocaSet : NonOverlapedAllocas) {
418 assert(!AllocaSet.empty() && "Processing Alloca Set is not empty.\n");
419 bool NoInterference = none_of(AllocaSet, [&](auto Iter) {
420 return DoAllocasInterfere(Alloca, Iter);
421 });
422 // If the alignment of A is multiple of the alignment of B, the address
423 // of A should satisfy the requirement for aligning for B.
424 //
425 // There may be other more fine-grained strategies to handle the alignment
426 // infomation during the merging process. But it seems hard to handle
427 // these strategies and benefit little.
428 bool Alignable = [&]() -> bool {
429 auto *LargestAlloca = *AllocaSet.begin();
430 return LargestAlloca->getAlign().value() % Alloca->getAlign().value() ==
431 0;
432 }();
433 bool CouldMerge = NoInterference && Alignable;
434 if (!CouldMerge)
435 continue;
436 AllocaSet.push_back(Alloca);
437 Merged = true;
438 break;
439 }
440 if (!Merged) {
441 NonOverlapedAllocas.emplace_back(AllocaSetType(1, Alloca));
442 }
443 }
444 // Recover the default target destination for each Switch statement
445 // reserved.
446 for (auto SwitchAndDefaultDest : DefaultSuspendDest) {
447 SwitchInst *SWI = SwitchAndDefaultDest.first;
448 BasicBlock *DestBB = SwitchAndDefaultDest.second;
449 SWI->setDefaultDest(DestBB);
450 }
451 // This Debug Info could tell us which allocas are merged into one slot.
452 LLVM_DEBUG(for (auto &AllocaSet
453 : NonOverlapedAllocas) {
454 if (AllocaSet.size() > 1) {
455 dbgs() << "In Function:" << F.getName() << "\n";
456 dbgs() << "Find Union Set "
457 << "\n";
458 dbgs() << "\tAllocas are \n";
459 for (auto Alloca : AllocaSet)
460 dbgs() << "\t\t" << *Alloca << "\n";
461 }
462 });
463}
464
465StructType *FrameTypeBuilder::finish(StringRef Name) {
466 assert(!IsFinished && "already finished!");
467
468 // Prepare the optimal-layout field array.
469 // The Id in the layout field is a pointer to our Field for it.
471 LayoutFields.reserve(Fields.size());
472 for (auto &Field : Fields) {
473 LayoutFields.emplace_back(&Field, Field.Size, Field.Alignment,
474 Field.Offset);
475 }
476
477 // Perform layout.
478 auto SizeAndAlign = performOptimizedStructLayout(LayoutFields);
479 StructSize = SizeAndAlign.first;
480 StructAlign = SizeAndAlign.second;
481
482 auto getField = [](const OptimizedStructLayoutField &LayoutField) -> Field & {
483 return *static_cast<Field *>(const_cast<void*>(LayoutField.Id));
484 };
485
486 // We need to produce a packed struct type if there's a field whose
487 // assigned offset isn't a multiple of its natural type alignment.
488 bool Packed = [&] {
489 for (auto &LayoutField : LayoutFields) {
490 auto &F = getField(LayoutField);
491 if (!isAligned(F.TyAlignment, LayoutField.Offset))
492 return true;
493 }
494 return false;
495 }();
496
497 // Build the struct body.
498 SmallVector<Type*, 16> FieldTypes;
499 FieldTypes.reserve(LayoutFields.size() * 3 / 2);
500 uint64_t LastOffset = 0;
501 for (auto &LayoutField : LayoutFields) {
502 auto &F = getField(LayoutField);
503
504 auto Offset = LayoutField.Offset;
505
506 // Add a padding field if there's a padding gap and we're either
507 // building a packed struct or the padding gap is more than we'd
508 // get from aligning to the field type's natural alignment.
509 assert(Offset >= LastOffset);
510 if (Offset != LastOffset) {
511 if (Packed || alignTo(LastOffset, F.TyAlignment) != Offset)
512 FieldTypes.push_back(ArrayType::get(Type::getInt8Ty(Context),
513 Offset - LastOffset));
514 }
515
516 F.Offset = Offset;
517 F.LayoutFieldIndex = FieldTypes.size();
518
519 FieldTypes.push_back(F.Ty);
520 if (F.DynamicAlignBuffer) {
521 FieldTypes.push_back(
522 ArrayType::get(Type::getInt8Ty(Context), F.DynamicAlignBuffer));
523 }
524 LastOffset = Offset + F.Size;
525 }
526
527 StructType *Ty = StructType::create(Context, FieldTypes, Name, Packed);
528
529#ifndef NDEBUG
530 // Check that the IR layout matches the offsets we expect.
531 auto Layout = DL.getStructLayout(Ty);
532 for (auto &F : Fields) {
533 assert(Ty->getElementType(F.LayoutFieldIndex) == F.Ty);
534 assert(Layout->getElementOffset(F.LayoutFieldIndex) == F.Offset);
535 }
536#endif
537
538 IsFinished = true;
539
540 return Ty;
541}
542
543static void cacheDIVar(FrameDataInfo &FrameData,
545 for (auto *V : FrameData.getAllDefs()) {
546 if (DIVarCache.contains(V))
547 continue;
548
549 auto CacheIt = [&DIVarCache, V](const auto &Container) {
550 auto *I = llvm::find_if(Container, [](auto *DDI) {
551 return DDI->getExpression()->getNumElements() == 0;
552 });
553 if (I != Container.end())
554 DIVarCache.insert({V, (*I)->getVariable()});
555 };
556 CacheIt(findDVRDeclares(V));
557 }
558}
559
560/// Create name for Type. It uses MDString to store new created string to
561/// avoid memory leak.
563 if (Ty->isIntegerTy()) {
564 // The longest name in common may be '__int_128', which has 9 bits.
565 SmallString<16> Buffer;
566 raw_svector_ostream OS(Buffer);
567 OS << "__int_" << cast<IntegerType>(Ty)->getBitWidth();
568 auto *MDName = MDString::get(Ty->getContext(), OS.str());
569 return MDName->getString();
570 }
571
572 if (Ty->isFloatingPointTy()) {
573 if (Ty->isFloatTy())
574 return "__float_";
575 if (Ty->isDoubleTy())
576 return "__double_";
577 return "__floating_type_";
578 }
579
580 if (Ty->isPointerTy())
581 return "PointerType";
582
583 if (Ty->isStructTy()) {
584 if (!cast<StructType>(Ty)->hasName())
585 return "__LiteralStructType_";
586
587 auto Name = Ty->getStructName();
588
589 SmallString<16> Buffer(Name);
590 for (auto &Iter : Buffer)
591 if (Iter == '.' || Iter == ':')
592 Iter = '_';
593 auto *MDName = MDString::get(Ty->getContext(), Buffer.str());
594 return MDName->getString();
595 }
596
597 return "UnknownType";
598}
599
600static DIType *solveDIType(DIBuilder &Builder, Type *Ty,
601 const DataLayout &Layout, DIScope *Scope,
602 unsigned LineNum,
603 DenseMap<Type *, DIType *> &DITypeCache) {
604 if (DIType *DT = DITypeCache.lookup(Ty))
605 return DT;
606
608
609 DIType *RetType = nullptr;
610
611 if (Ty->isIntegerTy()) {
612 auto BitWidth = cast<IntegerType>(Ty)->getBitWidth();
613 RetType = Builder.createBasicType(Name, BitWidth, dwarf::DW_ATE_signed,
614 llvm::DINode::FlagArtificial);
615 } else if (Ty->isFloatingPointTy()) {
616 RetType = Builder.createBasicType(Name, Layout.getTypeSizeInBits(Ty),
617 dwarf::DW_ATE_float,
618 llvm::DINode::FlagArtificial);
619 } else if (Ty->isPointerTy()) {
620 // Construct PointerType points to null (aka void *) instead of exploring
621 // pointee type to avoid infinite search problem. For example, we would be
622 // in trouble if we traverse recursively:
623 //
624 // struct Node {
625 // Node* ptr;
626 // };
627 RetType =
628 Builder.createPointerType(nullptr, Layout.getTypeSizeInBits(Ty),
629 Layout.getABITypeAlign(Ty).value() * CHAR_BIT,
630 /*DWARFAddressSpace=*/std::nullopt, Name);
631 } else if (Ty->isStructTy()) {
632 auto *DIStruct = Builder.createStructType(
633 Scope, Name, Scope->getFile(), LineNum, Layout.getTypeSizeInBits(Ty),
634 Layout.getPrefTypeAlign(Ty).value() * CHAR_BIT,
635 llvm::DINode::FlagArtificial, nullptr, llvm::DINodeArray());
636
637 auto *StructTy = cast<StructType>(Ty);
639 for (unsigned I = 0; I < StructTy->getNumElements(); I++) {
640 DIType *DITy = solveDIType(Builder, StructTy->getElementType(I), Layout,
641 DIStruct, LineNum, DITypeCache);
642 assert(DITy);
643 Elements.push_back(Builder.createMemberType(
644 DIStruct, DITy->getName(), DIStruct->getFile(), LineNum,
645 DITy->getSizeInBits(), DITy->getAlignInBits(),
646 Layout.getStructLayout(StructTy)->getElementOffsetInBits(I),
647 llvm::DINode::FlagArtificial, DITy));
648 }
649
650 Builder.replaceArrays(DIStruct, Builder.getOrCreateArray(Elements));
651
652 RetType = DIStruct;
653 } else {
654 LLVM_DEBUG(dbgs() << "Unresolved Type: " << *Ty << "\n");
655 TypeSize Size = Layout.getTypeSizeInBits(Ty);
656 auto *CharSizeType = Builder.createBasicType(
657 Name, 8, dwarf::DW_ATE_unsigned_char, llvm::DINode::FlagArtificial);
658
659 if (Size <= 8)
660 RetType = CharSizeType;
661 else {
662 if (Size % 8 != 0)
663 Size = TypeSize::getFixed(Size + 8 - (Size % 8));
664
665 RetType = Builder.createArrayType(
666 Size, Layout.getPrefTypeAlign(Ty).value(), CharSizeType,
667 Builder.getOrCreateArray(Builder.getOrCreateSubrange(0, Size / 8)));
668 }
669 }
670
671 DITypeCache.insert({Ty, RetType});
672 return RetType;
673}
674
675/// Build artificial debug info for C++ coroutine frames to allow users to
676/// inspect the contents of the frame directly
677///
678/// Create Debug information for coroutine frame with debug name "__coro_frame".
679/// The debug information for the fields of coroutine frame is constructed from
680/// the following way:
681/// 1. For all the value in the Frame, we search the use of dbg.declare to find
682/// the corresponding debug variables for the value. If we can find the
683/// debug variable, we can get full and accurate debug information.
684/// 2. If we can't get debug information in step 1 and 2, we could only try to
685/// build the DIType by Type. We did this in solveDIType. We only handle
686/// integer, float, double, integer type and struct type for now.
688 FrameDataInfo &FrameData) {
689 DISubprogram *DIS = F.getSubprogram();
690 // If there is no DISubprogram for F, it implies the function is compiled
691 // without debug info. So we also don't generate debug info for the frame.
692 if (!DIS || !DIS->getUnit() ||
694 (dwarf::SourceLanguage)DIS->getUnit()->getSourceLanguage()) ||
695 DIS->getUnit()->getEmissionKind() != DICompileUnit::DebugEmissionKind::FullDebug)
696 return;
697
698 assert(Shape.ABI == coro::ABI::Switch &&
699 "We could only build debug infomation for C++ coroutine now.\n");
700
701 DIBuilder DBuilder(*F.getParent(), /*AllowUnresolved*/ false);
702
703 assert(Shape.getPromiseAlloca() &&
704 "Coroutine with switch ABI should own Promise alloca");
705
706 DIFile *DFile = DIS->getFile();
707 unsigned LineNum = DIS->getLine();
708
709 DICompositeType *FrameDITy = DBuilder.createStructType(
710 DIS->getUnit(), Twine(F.getName() + ".coro_frame_ty").str(),
711 DFile, LineNum, Shape.FrameSize * 8,
712 Shape.FrameAlign.value() * 8, llvm::DINode::FlagArtificial, nullptr,
713 llvm::DINodeArray());
714 StructType *FrameTy = Shape.FrameTy;
716 DataLayout Layout = F.getDataLayout();
717
719 cacheDIVar(FrameData, DIVarCache);
720
721 unsigned ResumeIndex = coro::Shape::SwitchFieldIndex::Resume;
722 unsigned DestroyIndex = coro::Shape::SwitchFieldIndex::Destroy;
723 unsigned IndexIndex = Shape.SwitchLowering.IndexField;
724
726 NameCache.insert({ResumeIndex, "__resume_fn"});
727 NameCache.insert({DestroyIndex, "__destroy_fn"});
728 NameCache.insert({IndexIndex, "__coro_index"});
729
730 Type *ResumeFnTy = FrameTy->getElementType(ResumeIndex),
731 *DestroyFnTy = FrameTy->getElementType(DestroyIndex),
732 *IndexTy = FrameTy->getElementType(IndexIndex);
733
735 TyCache.insert(
736 {ResumeIndex, DBuilder.createPointerType(
737 nullptr, Layout.getTypeSizeInBits(ResumeFnTy))});
738 TyCache.insert(
739 {DestroyIndex, DBuilder.createPointerType(
740 nullptr, Layout.getTypeSizeInBits(DestroyFnTy))});
741
742 /// FIXME: If we fill the field `SizeInBits` with the actual size of
743 /// __coro_index in bits, then __coro_index wouldn't show in the debugger.
744 TyCache.insert({IndexIndex, DBuilder.createBasicType(
745 "__coro_index",
746 (Layout.getTypeSizeInBits(IndexTy) < 8)
747 ? 8
748 : Layout.getTypeSizeInBits(IndexTy),
749 dwarf::DW_ATE_unsigned_char)});
750
751 for (auto *V : FrameData.getAllDefs()) {
752 auto It = DIVarCache.find(V);
753 if (It == DIVarCache.end())
754 continue;
755
756 auto Index = FrameData.getFieldIndex(V);
757
758 NameCache.insert({Index, It->second->getName()});
759 TyCache.insert({Index, It->second->getType()});
760 }
761
762 // Cache from index to (Align, Offset Pair)
764 // The Align and Offset of Resume function and Destroy function are fixed.
765 OffsetCache.insert({ResumeIndex, {8, 0}});
766 OffsetCache.insert({DestroyIndex, {8, 8}});
767 OffsetCache.insert(
768 {IndexIndex,
770
771 for (auto *V : FrameData.getAllDefs()) {
772 auto Index = FrameData.getFieldIndex(V);
773
774 OffsetCache.insert(
775 {Index, {FrameData.getAlign(V).value(), FrameData.getOffset(V)}});
776 }
777
778 DenseMap<Type *, DIType *> DITypeCache;
779 // This counter is used to avoid same type names. e.g., there would be
780 // many i32 and i64 types in one coroutine. And we would use i32_0 and
781 // i32_1 to avoid the same type. Since it makes no sense the name of the
782 // fields confilicts with each other.
783 unsigned UnknownTypeNum = 0;
784 for (unsigned Index = 0; Index < FrameTy->getNumElements(); Index++) {
785 auto OCIt = OffsetCache.find(Index);
786 if (OCIt == OffsetCache.end())
787 continue;
788
789 std::string Name;
790 uint64_t SizeInBits;
791 uint32_t AlignInBits;
792 uint64_t OffsetInBits;
793 DIType *DITy = nullptr;
794
795 Type *Ty = FrameTy->getElementType(Index);
796 assert(Ty->isSized() && "We can't handle type which is not sized.\n");
797 SizeInBits = Layout.getTypeSizeInBits(Ty).getFixedValue();
798 AlignInBits = OCIt->second.first * 8;
799 OffsetInBits = OCIt->second.second * 8;
800
801 if (auto It = NameCache.find(Index); It != NameCache.end()) {
802 Name = It->second.str();
803 DITy = TyCache[Index];
804 } else {
805 DITy = solveDIType(DBuilder, Ty, Layout, FrameDITy, LineNum, DITypeCache);
806 assert(DITy && "SolveDIType shouldn't return nullptr.\n");
807 Name = DITy->getName().str();
808 Name += "_" + std::to_string(UnknownTypeNum);
809 UnknownTypeNum++;
810 }
811
812 Elements.push_back(DBuilder.createMemberType(
813 FrameDITy, Name, DFile, LineNum, SizeInBits, AlignInBits, OffsetInBits,
814 llvm::DINode::FlagArtificial, DITy));
815 }
816
817 DBuilder.replaceArrays(FrameDITy, DBuilder.getOrCreateArray(Elements));
818
819 auto *FrameDIVar =
820 DBuilder.createAutoVariable(DIS, "__coro_frame", DFile, LineNum,
821 FrameDITy, true, DINode::FlagArtificial);
822
823 // Subprogram would have ContainedNodes field which records the debug
824 // variables it contained. So we need to add __coro_frame to the
825 // ContainedNodes of it.
826 //
827 // If we don't add __coro_frame to the RetainedNodes, user may get
828 // `no symbol __coro_frame in context` rather than `__coro_frame`
829 // is optimized out, which is more precise.
830 auto RetainedNodes = DIS->getRetainedNodes();
831 SmallVector<Metadata *, 32> RetainedNodesVec(RetainedNodes.begin(),
832 RetainedNodes.end());
833 RetainedNodesVec.push_back(FrameDIVar);
834 DIS->replaceOperandWith(7, (MDTuple::get(F.getContext(), RetainedNodesVec)));
835
836 // Construct the location for the frame debug variable. The column number
837 // is fake but it should be fine.
838 DILocation *DILoc =
839 DILocation::get(DIS->getContext(), LineNum, /*Column=*/1, DIS);
840 assert(FrameDIVar->isValidLocationForIntrinsic(DILoc));
841
842 DbgVariableRecord *NewDVR =
843 new DbgVariableRecord(ValueAsMetadata::get(Shape.FramePtr), FrameDIVar,
844 DBuilder.createExpression(), DILoc,
845 DbgVariableRecord::LocationType::Declare);
847 It->getParent()->insertDbgRecordBefore(NewDVR, It);
848}
849
850// Build a struct that will keep state for an active coroutine.
851// struct f.frame {
852// ResumeFnTy ResumeFnAddr;
853// ResumeFnTy DestroyFnAddr;
854// ... promise (if present) ...
855// int ResumeIndex;
856// ... spills ...
857// };
859 FrameDataInfo &FrameData,
860 bool OptimizeFrame) {
861 LLVMContext &C = F.getContext();
862 const DataLayout &DL = F.getDataLayout();
863
864 // We will use this value to cap the alignment of spilled values.
865 std::optional<Align> MaxFrameAlignment;
866 if (Shape.ABI == coro::ABI::Async)
867 MaxFrameAlignment = Shape.AsyncLowering.getContextAlignment();
868 FrameTypeBuilder B(C, DL, MaxFrameAlignment);
869
870 AllocaInst *PromiseAlloca = Shape.getPromiseAlloca();
871 std::optional<FieldIDType> SwitchIndexFieldId;
872
873 if (Shape.ABI == coro::ABI::Switch) {
874 auto *FnPtrTy = PointerType::getUnqual(C);
875
876 // Add header fields for the resume and destroy functions.
877 // We can rely on these being perfectly packed.
878 (void)B.addField(FnPtrTy, std::nullopt, /*header*/ true);
879 (void)B.addField(FnPtrTy, std::nullopt, /*header*/ true);
880
881 // PromiseAlloca field needs to be explicitly added here because it's
882 // a header field with a fixed offset based on its alignment. Hence it
883 // needs special handling and cannot be added to FrameData.Allocas.
884 if (PromiseAlloca)
885 FrameData.setFieldIndex(
886 PromiseAlloca, B.addFieldForAlloca(PromiseAlloca, /*header*/ true));
887
888 // Add a field to store the suspend index. This doesn't need to
889 // be in the header.
890 unsigned IndexBits = std::max(1U, Log2_64_Ceil(Shape.CoroSuspends.size()));
891 Type *IndexType = Type::getIntNTy(C, IndexBits);
892
893 SwitchIndexFieldId = B.addField(IndexType, std::nullopt);
894 } else {
895 assert(PromiseAlloca == nullptr && "lowering doesn't support promises");
896 }
897
898 // Because multiple allocas may own the same field slot,
899 // we add allocas to field here.
900 B.addFieldForAllocas(F, FrameData, Shape, OptimizeFrame);
901 // Add PromiseAlloca to Allocas list so that
902 // 1. updateLayoutIndex could update its index after
903 // `performOptimizedStructLayout`
904 // 2. it is processed in insertSpills.
905 if (Shape.ABI == coro::ABI::Switch && PromiseAlloca)
906 // We assume that the promise alloca won't be modified before
907 // CoroBegin and no alias will be create before CoroBegin.
908 FrameData.Allocas.emplace_back(
909 PromiseAlloca, DenseMap<Instruction *, std::optional<APInt>>{}, false);
910 // Create an entry for every spilled value.
911 for (auto &S : FrameData.Spills) {
912 Type *FieldType = S.first->getType();
913 // For byval arguments, we need to store the pointed value in the frame,
914 // instead of the pointer itself.
915 if (const Argument *A = dyn_cast<Argument>(S.first))
916 if (A->hasByValAttr())
917 FieldType = A->getParamByValType();
918 FieldIDType Id = B.addField(FieldType, std::nullopt, false /*header*/,
919 true /*IsSpillOfValue*/);
920 FrameData.setFieldIndex(S.first, Id);
921 }
922
923 StructType *FrameTy = [&] {
924 SmallString<32> Name(F.getName());
925 Name.append(".Frame");
926 return B.finish(Name);
927 }();
928
929 FrameData.updateLayoutIndex(B);
930 Shape.FrameAlign = B.getStructAlign();
931 Shape.FrameSize = B.getStructSize();
932
933 switch (Shape.ABI) {
934 case coro::ABI::Switch: {
935 // In the switch ABI, remember the switch-index field.
936 auto IndexField = B.getLayoutField(*SwitchIndexFieldId);
937 Shape.SwitchLowering.IndexField = IndexField.LayoutFieldIndex;
938 Shape.SwitchLowering.IndexAlign = IndexField.Alignment.value();
939 Shape.SwitchLowering.IndexOffset = IndexField.Offset;
940
941 // Also round the frame size up to a multiple of its alignment, as is
942 // generally expected in C/C++.
943 Shape.FrameSize = alignTo(Shape.FrameSize, Shape.FrameAlign);
944 break;
945 }
946
947 // In the retcon ABI, remember whether the frame is inline in the storage.
948 case coro::ABI::Retcon:
949 case coro::ABI::RetconOnce: {
950 auto Id = Shape.getRetconCoroId();
952 = (B.getStructSize() <= Id->getStorageSize() &&
953 B.getStructAlign() <= Id->getStorageAlignment());
954 break;
955 }
956 case coro::ABI::Async: {
959 // Also make the final context size a multiple of the context alignment to
960 // make allocation easier for allocators.
964 if (Shape.AsyncLowering.getContextAlignment() < Shape.FrameAlign) {
966 "The alignment requirment of frame variables cannot be higher than "
967 "the alignment of the async function context");
968 }
969 break;
970 }
971 }
972
973 return FrameTy;
974}
975
976// Replace all alloca and SSA values that are accessed across suspend points
977// with GetElementPointer from coroutine frame + loads and stores. Create an
978// AllocaSpillBB that will become the new entry block for the resume parts of
979// the coroutine:
980//
981// %hdl = coro.begin(...)
982// whatever
983//
984// becomes:
985//
986// %hdl = coro.begin(...)
987// br label %AllocaSpillBB
988//
989// AllocaSpillBB:
990// ; geps corresponding to allocas that were moved to coroutine frame
991// br label PostSpill
992//
993// PostSpill:
994// whatever
995//
996//
997static void insertSpills(const FrameDataInfo &FrameData, coro::Shape &Shape) {
998 LLVMContext &C = Shape.CoroBegin->getContext();
999 Function *F = Shape.CoroBegin->getFunction();
1000 IRBuilder<> Builder(C);
1001 StructType *FrameTy = Shape.FrameTy;
1002 Value *FramePtr = Shape.FramePtr;
1003 DominatorTree DT(*F);
1005
1006 // Create a GEP with the given index into the coroutine frame for the original
1007 // value Orig. Appends an extra 0 index for array-allocas, preserving the
1008 // original type.
1009 auto GetFramePointer = [&](Value *Orig) -> Value * {
1010 FieldIDType Index = FrameData.getFieldIndex(Orig);
1011 SmallVector<Value *, 3> Indices = {
1012 ConstantInt::get(Type::getInt32Ty(C), 0),
1013 ConstantInt::get(Type::getInt32Ty(C), Index),
1014 };
1015
1016 if (auto *AI = dyn_cast<AllocaInst>(Orig)) {
1017 if (auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
1018 auto Count = CI->getValue().getZExtValue();
1019 if (Count > 1) {
1020 Indices.push_back(ConstantInt::get(Type::getInt32Ty(C), 0));
1021 }
1022 } else {
1023 report_fatal_error("Coroutines cannot handle non static allocas yet");
1024 }
1025 }
1026
1027 auto GEP = cast<GetElementPtrInst>(
1028 Builder.CreateInBoundsGEP(FrameTy, FramePtr, Indices));
1029 if (auto *AI = dyn_cast<AllocaInst>(Orig)) {
1030 if (FrameData.getDynamicAlign(Orig) != 0) {
1031 assert(FrameData.getDynamicAlign(Orig) == AI->getAlign().value());
1032 auto *M = AI->getModule();
1033 auto *IntPtrTy = M->getDataLayout().getIntPtrType(AI->getType());
1034 auto *PtrValue = Builder.CreatePtrToInt(GEP, IntPtrTy);
1035 auto *AlignMask =
1036 ConstantInt::get(IntPtrTy, AI->getAlign().value() - 1);
1037 PtrValue = Builder.CreateAdd(PtrValue, AlignMask);
1038 PtrValue = Builder.CreateAnd(PtrValue, Builder.CreateNot(AlignMask));
1039 return Builder.CreateIntToPtr(PtrValue, AI->getType());
1040 }
1041 // If the type of GEP is not equal to the type of AllocaInst, it implies
1042 // that the AllocaInst may be reused in the Frame slot of other
1043 // AllocaInst. So We cast GEP to the AllocaInst here to re-use
1044 // the Frame storage.
1045 //
1046 // Note: If we change the strategy dealing with alignment, we need to refine
1047 // this casting.
1048 if (GEP->getType() != Orig->getType())
1049 return Builder.CreateAddrSpaceCast(GEP, Orig->getType(),
1050 Orig->getName() + Twine(".cast"));
1051 }
1052 return GEP;
1053 };
1054
1055 for (auto const &E : FrameData.Spills) {
1056 Value *Def = E.first;
1057 auto SpillAlignment = Align(FrameData.getAlign(Def));
1058 // Create a store instruction storing the value into the
1059 // coroutine frame.
1060 BasicBlock::iterator InsertPt = coro::getSpillInsertionPt(Shape, Def, DT);
1061
1062 Type *ByValTy = nullptr;
1063 if (auto *Arg = dyn_cast<Argument>(Def)) {
1064 // If we're spilling an Argument, make sure we clear 'captures'
1065 // from the coroutine function.
1066 Arg->getParent()->removeParamAttr(Arg->getArgNo(), Attribute::Captures);
1067
1068 if (Arg->hasByValAttr())
1069 ByValTy = Arg->getParamByValType();
1070 }
1071
1072 auto Index = FrameData.getFieldIndex(Def);
1073 Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
1074 auto *G = Builder.CreateConstInBoundsGEP2_32(
1075 FrameTy, FramePtr, 0, Index, Def->getName() + Twine(".spill.addr"));
1076 if (ByValTy) {
1077 // For byval arguments, we need to store the pointed value in the frame,
1078 // instead of the pointer itself.
1079 auto *Value = Builder.CreateLoad(ByValTy, Def);
1080 Builder.CreateAlignedStore(Value, G, SpillAlignment);
1081 } else {
1082 Builder.CreateAlignedStore(Def, G, SpillAlignment);
1083 }
1084
1085 BasicBlock *CurrentBlock = nullptr;
1086 Value *CurrentReload = nullptr;
1087 for (auto *U : E.second) {
1088 // If we have not seen the use block, create a load instruction to reload
1089 // the spilled value from the coroutine frame. Populates the Value pointer
1090 // reference provided with the frame GEP.
1091 if (CurrentBlock != U->getParent()) {
1092 CurrentBlock = U->getParent();
1093 Builder.SetInsertPoint(CurrentBlock,
1094 CurrentBlock->getFirstInsertionPt());
1095
1096 auto *GEP = GetFramePointer(E.first);
1097 GEP->setName(E.first->getName() + Twine(".reload.addr"));
1098 if (ByValTy)
1099 CurrentReload = GEP;
1100 else
1101 CurrentReload = Builder.CreateAlignedLoad(
1102 FrameTy->getElementType(FrameData.getFieldIndex(E.first)), GEP,
1103 SpillAlignment, E.first->getName() + Twine(".reload"));
1104
1106 // Try best to find dbg.declare. If the spill is a temp, there may not
1107 // be a direct dbg.declare. Walk up the load chain to find one from an
1108 // alias.
1109 if (F->getSubprogram()) {
1110 auto *CurDef = Def;
1111 while (DVRs.empty() && isa<LoadInst>(CurDef)) {
1112 auto *LdInst = cast<LoadInst>(CurDef);
1113 // Only consider ptr to ptr same type load.
1114 if (LdInst->getPointerOperandType() != LdInst->getType())
1115 break;
1116 CurDef = LdInst->getPointerOperand();
1117 if (!isa<AllocaInst, LoadInst>(CurDef))
1118 break;
1119 DVRs = findDVRDeclares(CurDef);
1120 }
1121 }
1122
1123 auto SalvageOne = [&](DbgVariableRecord *DDI) {
1124 // This dbg.declare is preserved for all coro-split function
1125 // fragments. It will be unreachable in the main function, and
1126 // processed by coro::salvageDebugInfo() by the Cloner.
1128 ValueAsMetadata::get(CurrentReload), DDI->getVariable(),
1129 DDI->getExpression(), DDI->getDebugLoc(),
1130 DbgVariableRecord::LocationType::Declare);
1131 Builder.GetInsertPoint()->getParent()->insertDbgRecordBefore(
1132 NewDVR, Builder.GetInsertPoint());
1133 // This dbg.declare is for the main function entry point. It
1134 // will be deleted in all coro-split functions.
1135 coro::salvageDebugInfo(ArgToAllocaMap, *DDI, false /*UseEntryValue*/);
1136 };
1137 for_each(DVRs, SalvageOne);
1138 }
1139
1140 // If we have a single edge PHINode, remove it and replace it with a
1141 // reload from the coroutine frame. (We already took care of multi edge
1142 // PHINodes by normalizing them in the rewritePHIs function).
1143 if (auto *PN = dyn_cast<PHINode>(U)) {
1144 assert(PN->getNumIncomingValues() == 1 &&
1145 "unexpected number of incoming "
1146 "values in the PHINode");
1147 PN->replaceAllUsesWith(CurrentReload);
1148 PN->eraseFromParent();
1149 continue;
1150 }
1151
1152 // Replace all uses of CurrentValue in the current instruction with
1153 // reload.
1154 U->replaceUsesOfWith(Def, CurrentReload);
1155 // Instructions are added to Def's user list if the attached
1156 // debug records use Def. Update those now.
1157 for (DbgVariableRecord &DVR : filterDbgVars(U->getDbgRecordRange()))
1158 DVR.replaceVariableLocationOp(Def, CurrentReload, true);
1159 }
1160 }
1161
1162 BasicBlock *FramePtrBB = Shape.getInsertPtAfterFramePtr()->getParent();
1163
1164 auto SpillBlock = FramePtrBB->splitBasicBlock(
1165 Shape.getInsertPtAfterFramePtr(), "AllocaSpillBB");
1166 SpillBlock->splitBasicBlock(&SpillBlock->front(), "PostSpill");
1167 Shape.AllocaSpillBlock = SpillBlock;
1168
1169 // retcon and retcon.once lowering assumes all uses have been sunk.
1170 if (Shape.ABI == coro::ABI::Retcon || Shape.ABI == coro::ABI::RetconOnce ||
1171 Shape.ABI == coro::ABI::Async) {
1172 // If we found any allocas, replace all of their remaining uses with Geps.
1173 Builder.SetInsertPoint(SpillBlock, SpillBlock->begin());
1174 for (const auto &P : FrameData.Allocas) {
1175 AllocaInst *Alloca = P.Alloca;
1176 auto *G = GetFramePointer(Alloca);
1177
1178 // Remove any lifetime intrinsics, now that these are no longer allocas.
1179 for (User *U : make_early_inc_range(Alloca->users())) {
1180 auto *I = cast<Instruction>(U);
1181 if (I->isLifetimeStartOrEnd())
1182 I->eraseFromParent();
1183 }
1184
1185 // We are not using ReplaceInstWithInst(P.first, cast<Instruction>(G))
1186 // here, as we are changing location of the instruction.
1187 G->takeName(Alloca);
1188 Alloca->replaceAllUsesWith(G);
1189 Alloca->eraseFromParent();
1190 }
1191 return;
1192 }
1193
1194 // If we found any alloca, replace all of their remaining uses with GEP
1195 // instructions. To remain debugbility, we replace the uses of allocas for
1196 // dbg.declares and dbg.values with the reload from the frame.
1197 // Note: We cannot replace the alloca with GEP instructions indiscriminately,
1198 // as some of the uses may not be dominated by CoroBegin.
1199 Builder.SetInsertPoint(Shape.AllocaSpillBlock,
1200 Shape.AllocaSpillBlock->begin());
1201 SmallVector<Instruction *, 4> UsersToUpdate;
1202 for (const auto &A : FrameData.Allocas) {
1203 AllocaInst *Alloca = A.Alloca;
1204 UsersToUpdate.clear();
1205 for (User *U : make_early_inc_range(Alloca->users())) {
1206 auto *I = cast<Instruction>(U);
1207 // It is meaningless to retain the lifetime intrinsics refer for the
1208 // member of coroutine frames and the meaningless lifetime intrinsics
1209 // are possible to block further optimizations.
1210 if (I->isLifetimeStartOrEnd())
1211 I->eraseFromParent();
1212 else if (DT.dominates(Shape.CoroBegin, I))
1213 UsersToUpdate.push_back(I);
1214 }
1215
1216 if (UsersToUpdate.empty())
1217 continue;
1218 auto *G = GetFramePointer(Alloca);
1219 G->setName(Alloca->getName() + Twine(".reload.addr"));
1220
1221 SmallVector<DbgVariableRecord *> DbgVariableRecords;
1222 findDbgUsers(Alloca, DbgVariableRecords);
1223 for (auto *DVR : DbgVariableRecords)
1224 DVR->replaceVariableLocationOp(Alloca, G);
1225
1226 for (Instruction *I : UsersToUpdate)
1227 I->replaceUsesOfWith(Alloca, G);
1228 }
1229 Builder.SetInsertPoint(&*Shape.getInsertPtAfterFramePtr());
1230 for (const auto &A : FrameData.Allocas) {
1231 AllocaInst *Alloca = A.Alloca;
1232 if (A.MayWriteBeforeCoroBegin) {
1233 // isEscaped really means potentially modified before CoroBegin.
1234 if (Alloca->isArrayAllocation())
1236 "Coroutines cannot handle copying of array allocas yet");
1237
1238 auto *G = GetFramePointer(Alloca);
1239 auto *Value = Builder.CreateLoad(Alloca->getAllocatedType(), Alloca);
1240 Builder.CreateStore(Value, G);
1241 }
1242 // For each alias to Alloca created before CoroBegin but used after
1243 // CoroBegin, we recreate them after CoroBegin by applying the offset
1244 // to the pointer in the frame.
1245 for (const auto &Alias : A.Aliases) {
1246 auto *FramePtr = GetFramePointer(Alloca);
1247 auto &Value = *Alias.second;
1248 auto ITy = IntegerType::get(C, Value.getBitWidth());
1249 auto *AliasPtr =
1250 Builder.CreatePtrAdd(FramePtr, ConstantInt::get(ITy, Value));
1251 Alias.first->replaceUsesWithIf(
1252 AliasPtr, [&](Use &U) { return DT.dominates(Shape.CoroBegin, U); });
1253 }
1254 }
1255
1256 // PromiseAlloca is not collected in FrameData.Allocas. So we don't handle
1257 // the case that the PromiseAlloca may have writes before CoroBegin in the
1258 // above codes. And it may be problematic in edge cases. See
1259 // https://github.com/llvm/llvm-project/issues/57861 for an example.
1260 if (Shape.ABI == coro::ABI::Switch && Shape.SwitchLowering.PromiseAlloca) {
1262 // If there is memory accessing to promise alloca before CoroBegin;
1263 bool HasAccessingPromiseBeforeCB = llvm::any_of(PA->uses(), [&](Use &U) {
1264 auto *Inst = dyn_cast<Instruction>(U.getUser());
1265 if (!Inst || DT.dominates(Shape.CoroBegin, Inst))
1266 return false;
1267
1268 if (auto *CI = dyn_cast<CallInst>(Inst)) {
1269 // It is fine if the call wouldn't write to the Promise.
1270 // This is possible for @llvm.coro.id intrinsics, which
1271 // would take the promise as the second argument as a
1272 // marker.
1273 if (CI->onlyReadsMemory() ||
1274 CI->onlyReadsMemory(CI->getArgOperandNo(&U)))
1275 return false;
1276 return true;
1277 }
1278
1279 return isa<StoreInst>(Inst) ||
1280 // It may take too much time to track the uses.
1281 // Be conservative about the case the use may escape.
1282 isa<GetElementPtrInst>(Inst) ||
1283 // There would always be a bitcast for the promise alloca
1284 // before we enabled Opaque pointers. And now given
1285 // opaque pointers are enabled by default. This should be
1286 // fine.
1287 isa<BitCastInst>(Inst);
1288 });
1289 if (HasAccessingPromiseBeforeCB) {
1290 Builder.SetInsertPoint(&*Shape.getInsertPtAfterFramePtr());
1291 auto *G = GetFramePointer(PA);
1292 auto *Value = Builder.CreateLoad(PA->getAllocatedType(), PA);
1293 Builder.CreateStore(Value, G);
1294 }
1295 }
1296}
1297
1298// Moves the values in the PHIs in SuccBB that correspong to PredBB into a new
1299// PHI in InsertedBB.
1301 BasicBlock *InsertedBB,
1302 BasicBlock *PredBB,
1303 PHINode *UntilPHI = nullptr) {
1304 auto *PN = cast<PHINode>(&SuccBB->front());
1305 do {
1306 int Index = PN->getBasicBlockIndex(InsertedBB);
1307 Value *V = PN->getIncomingValue(Index);
1308 PHINode *InputV = PHINode::Create(
1309 V->getType(), 1, V->getName() + Twine(".") + SuccBB->getName());
1310 InputV->insertBefore(InsertedBB->begin());
1311 InputV->addIncoming(V, PredBB);
1312 PN->setIncomingValue(Index, InputV);
1313 PN = dyn_cast<PHINode>(PN->getNextNode());
1314 } while (PN != UntilPHI);
1315}
1316
1317// Rewrites the PHI Nodes in a cleanuppad.
1318static void rewritePHIsForCleanupPad(BasicBlock *CleanupPadBB,
1319 CleanupPadInst *CleanupPad) {
1320 // For every incoming edge to a CleanupPad we will create a new block holding
1321 // all incoming values in single-value PHI nodes. We will then create another
1322 // block to act as a dispather (as all unwind edges for related EH blocks
1323 // must be the same).
1324 //
1325 // cleanuppad:
1326 // %2 = phi i32[%0, %catchswitch], [%1, %catch.1]
1327 // %3 = cleanuppad within none []
1328 //
1329 // It will create:
1330 //
1331 // cleanuppad.corodispatch
1332 // %2 = phi i8[0, %catchswitch], [1, %catch.1]
1333 // %3 = cleanuppad within none []
1334 // switch i8 % 2, label %unreachable
1335 // [i8 0, label %cleanuppad.from.catchswitch
1336 // i8 1, label %cleanuppad.from.catch.1]
1337 // cleanuppad.from.catchswitch:
1338 // %4 = phi i32 [%0, %catchswitch]
1339 // br %label cleanuppad
1340 // cleanuppad.from.catch.1:
1341 // %6 = phi i32 [%1, %catch.1]
1342 // br %label cleanuppad
1343 // cleanuppad:
1344 // %8 = phi i32 [%4, %cleanuppad.from.catchswitch],
1345 // [%6, %cleanuppad.from.catch.1]
1346
1347 // Unreachable BB, in case switching on an invalid value in the dispatcher.
1348 auto *UnreachBB = BasicBlock::Create(
1349 CleanupPadBB->getContext(), "unreachable", CleanupPadBB->getParent());
1350 IRBuilder<> Builder(UnreachBB);
1351 Builder.CreateUnreachable();
1352
1353 // Create a new cleanuppad which will be the dispatcher.
1354 auto *NewCleanupPadBB =
1355 BasicBlock::Create(CleanupPadBB->getContext(),
1356 CleanupPadBB->getName() + Twine(".corodispatch"),
1357 CleanupPadBB->getParent(), CleanupPadBB);
1358 Builder.SetInsertPoint(NewCleanupPadBB);
1359 auto *SwitchType = Builder.getInt8Ty();
1360 auto *SetDispatchValuePN =
1361 Builder.CreatePHI(SwitchType, pred_size(CleanupPadBB));
1362 CleanupPad->removeFromParent();
1363 CleanupPad->insertAfter(SetDispatchValuePN->getIterator());
1364 auto *SwitchOnDispatch = Builder.CreateSwitch(SetDispatchValuePN, UnreachBB,
1365 pred_size(CleanupPadBB));
1366
1367 int SwitchIndex = 0;
1368 SmallVector<BasicBlock *, 8> Preds(predecessors(CleanupPadBB));
1369 for (BasicBlock *Pred : Preds) {
1370 // Create a new cleanuppad and move the PHI values to there.
1371 auto *CaseBB = BasicBlock::Create(CleanupPadBB->getContext(),
1372 CleanupPadBB->getName() +
1373 Twine(".from.") + Pred->getName(),
1374 CleanupPadBB->getParent(), CleanupPadBB);
1375 updatePhiNodes(CleanupPadBB, Pred, CaseBB);
1376 CaseBB->setName(CleanupPadBB->getName() + Twine(".from.") +
1377 Pred->getName());
1378 Builder.SetInsertPoint(CaseBB);
1379 Builder.CreateBr(CleanupPadBB);
1380 movePHIValuesToInsertedBlock(CleanupPadBB, CaseBB, NewCleanupPadBB);
1381
1382 // Update this Pred to the new unwind point.
1383 setUnwindEdgeTo(Pred->getTerminator(), NewCleanupPadBB);
1384
1385 // Setup the switch in the dispatcher.
1386 auto *SwitchConstant = ConstantInt::get(SwitchType, SwitchIndex);
1387 SetDispatchValuePN->addIncoming(SwitchConstant, Pred);
1388 SwitchOnDispatch->addCase(SwitchConstant, CaseBB);
1389 SwitchIndex++;
1390 }
1391}
1392
1395 for (auto &BB : F) {
1396 for (auto &Phi : BB.phis()) {
1397 if (Phi.getNumIncomingValues() == 1) {
1398 Worklist.push_back(&Phi);
1399 } else
1400 break;
1401 }
1402 }
1403 while (!Worklist.empty()) {
1404 auto *Phi = Worklist.pop_back_val();
1405 auto *OriginalValue = Phi->getIncomingValue(0);
1406 Phi->replaceAllUsesWith(OriginalValue);
1407 }
1408}
1409
1410static void rewritePHIs(BasicBlock &BB) {
1411 // For every incoming edge we will create a block holding all
1412 // incoming values in a single PHI nodes.
1413 //
1414 // loop:
1415 // %n.val = phi i32[%n, %entry], [%inc, %loop]
1416 //
1417 // It will create:
1418 //
1419 // loop.from.entry:
1420 // %n.loop.pre = phi i32 [%n, %entry]
1421 // br %label loop
1422 // loop.from.loop:
1423 // %inc.loop.pre = phi i32 [%inc, %loop]
1424 // br %label loop
1425 //
1426 // After this rewrite, further analysis will ignore any phi nodes with more
1427 // than one incoming edge.
1428
1429 // TODO: Simplify PHINodes in the basic block to remove duplicate
1430 // predecessors.
1431
1432 // Special case for CleanupPad: all EH blocks must have the same unwind edge
1433 // so we need to create an additional "dispatcher" block.
1434 if (!BB.empty()) {
1435 if (auto *CleanupPad =
1436 dyn_cast_or_null<CleanupPadInst>(BB.getFirstNonPHIIt())) {
1438 for (BasicBlock *Pred : Preds) {
1439 if (CatchSwitchInst *CS =
1440 dyn_cast<CatchSwitchInst>(Pred->getTerminator())) {
1441 // CleanupPad with a CatchSwitch predecessor: therefore this is an
1442 // unwind destination that needs to be handle specially.
1443 assert(CS->getUnwindDest() == &BB);
1444 (void)CS;
1445 rewritePHIsForCleanupPad(&BB, CleanupPad);
1446 return;
1447 }
1448 }
1449 }
1450 }
1451
1452 LandingPadInst *LandingPad = nullptr;
1453 PHINode *ReplPHI = nullptr;
1454 if (!BB.empty()) {
1455 if ((LandingPad =
1456 dyn_cast_or_null<LandingPadInst>(BB.getFirstNonPHIIt()))) {
1457 // ehAwareSplitEdge will clone the LandingPad in all the edge blocks.
1458 // We replace the original landing pad with a PHINode that will collect the
1459 // results from all of them.
1460 ReplPHI = PHINode::Create(LandingPad->getType(), 1, "");
1461 ReplPHI->insertBefore(LandingPad->getIterator());
1462 ReplPHI->takeName(LandingPad);
1463 LandingPad->replaceAllUsesWith(ReplPHI);
1464 // We will erase the original landing pad at the end of this function after
1465 // ehAwareSplitEdge cloned it in the transition blocks.
1466 }
1467 }
1468
1470 for (BasicBlock *Pred : Preds) {
1471 auto *IncomingBB = ehAwareSplitEdge(Pred, &BB, LandingPad, ReplPHI);
1472 IncomingBB->setName(BB.getName() + Twine(".from.") + Pred->getName());
1473
1474 // Stop the moving of values at ReplPHI, as this is either null or the PHI
1475 // that replaced the landing pad.
1476 movePHIValuesToInsertedBlock(&BB, IncomingBB, Pred, ReplPHI);
1477 }
1478
1479 if (LandingPad) {
1480 // Calls to ehAwareSplitEdge function cloned the original lading pad.
1481 // No longer need it.
1482 LandingPad->eraseFromParent();
1483 }
1484}
1485
1486static void rewritePHIs(Function &F) {
1488
1489 for (BasicBlock &BB : F)
1490 if (auto *PN = dyn_cast<PHINode>(&BB.front()))
1491 if (PN->getNumIncomingValues() > 1)
1492 WorkList.push_back(&BB);
1493
1494 for (BasicBlock *BB : WorkList)
1495 rewritePHIs(*BB);
1496}
1497
1498// Splits the block at a particular instruction unless it is the first
1499// instruction in the block with a single predecessor.
1501 auto *BB = I->getParent();
1502 if (&BB->front() == I) {
1503 if (BB->getSinglePredecessor()) {
1504 BB->setName(Name);
1505 return BB;
1506 }
1507 }
1508 return BB->splitBasicBlock(I, Name);
1509}
1510
1511// Split above and below a particular instruction so that it
1512// will be all alone by itself in a block.
1513static void splitAround(Instruction *I, const Twine &Name) {
1515 splitBlockIfNotFirst(I->getNextNode(), "After" + Name);
1516}
1517
1518/// After we split the coroutine, will the given basic block be along
1519/// an obvious exit path for the resumption function?
1521 unsigned depth = 3) {
1522 // If we've bottomed out our depth count, stop searching and assume
1523 // that the path might loop back.
1524 if (depth == 0) return false;
1525
1526 // If this is a suspend block, we're about to exit the resumption function.
1527 if (coro::isSuspendBlock(BB))
1528 return true;
1529
1530 // Recurse into the successors.
1531 for (auto *Succ : successors(BB)) {
1532 if (!willLeaveFunctionImmediatelyAfter(Succ, depth - 1))
1533 return false;
1534 }
1535
1536 // If none of the successors leads back in a loop, we're on an exit/abort.
1537 return true;
1538}
1539
1541 // Look for a free that isn't sufficiently obviously followed by
1542 // either a suspend or a termination, i.e. something that will leave
1543 // the coro resumption frame.
1544 for (auto *U : AI->users()) {
1545 auto FI = dyn_cast<CoroAllocaFreeInst>(U);
1546 if (!FI) continue;
1547
1548 if (!willLeaveFunctionImmediatelyAfter(FI->getParent()))
1549 return true;
1550 }
1551
1552 // If we never found one, we don't need a stack save.
1553 return false;
1554}
1555
1556/// Turn each of the given local allocas into a normal (dynamic) alloca
1557/// instruction.
1559 SmallVectorImpl<Instruction*> &DeadInsts) {
1560 for (auto *AI : LocalAllocas) {
1561 IRBuilder<> Builder(AI);
1562
1563 // Save the stack depth. Try to avoid doing this if the stackrestore
1564 // is going to immediately precede a return or something.
1565 Value *StackSave = nullptr;
1567 StackSave = Builder.CreateStackSave();
1568
1569 // Allocate memory.
1570 auto Alloca = Builder.CreateAlloca(Builder.getInt8Ty(), AI->getSize());
1571 Alloca->setAlignment(AI->getAlignment());
1572
1573 for (auto *U : AI->users()) {
1574 // Replace gets with the allocation.
1575 if (isa<CoroAllocaGetInst>(U)) {
1576 U->replaceAllUsesWith(Alloca);
1577
1578 // Replace frees with stackrestores. This is safe because
1579 // alloca.alloc is required to obey a stack discipline, although we
1580 // don't enforce that structurally.
1581 } else {
1582 auto FI = cast<CoroAllocaFreeInst>(U);
1583 if (StackSave) {
1584 Builder.SetInsertPoint(FI);
1585 Builder.CreateStackRestore(StackSave);
1586 }
1587 }
1588 DeadInsts.push_back(cast<Instruction>(U));
1589 }
1590
1591 DeadInsts.push_back(AI);
1592 }
1593}
1594
1595/// Get the current swifterror value.
1597 coro::Shape &Shape) {
1598 // Make a fake function pointer as a sort of intrinsic.
1599 auto FnTy = FunctionType::get(ValueTy, {}, false);
1600 auto Fn = ConstantPointerNull::get(Builder.getPtrTy());
1601
1602 auto Call = Builder.CreateCall(FnTy, Fn, {});
1603 Shape.SwiftErrorOps.push_back(Call);
1604
1605 return Call;
1606}
1607
1608/// Set the given value as the current swifterror value.
1609///
1610/// Returns a slot that can be used as a swifterror slot.
1612 coro::Shape &Shape) {
1613 // Make a fake function pointer as a sort of intrinsic.
1614 auto FnTy = FunctionType::get(Builder.getPtrTy(),
1615 {V->getType()}, false);
1616 auto Fn = ConstantPointerNull::get(Builder.getPtrTy());
1617
1618 auto Call = Builder.CreateCall(FnTy, Fn, { V });
1619 Shape.SwiftErrorOps.push_back(Call);
1620
1621 return Call;
1622}
1623
1624/// Set the swifterror value from the given alloca before a call,
1625/// then put in back in the alloca afterwards.
1626///
1627/// Returns an address that will stand in for the swifterror slot
1628/// until splitting.
1630 AllocaInst *Alloca,
1631 coro::Shape &Shape) {
1632 auto ValueTy = Alloca->getAllocatedType();
1633 IRBuilder<> Builder(Call);
1634
1635 // Load the current value from the alloca and set it as the
1636 // swifterror value.
1637 auto ValueBeforeCall = Builder.CreateLoad(ValueTy, Alloca);
1638 auto Addr = emitSetSwiftErrorValue(Builder, ValueBeforeCall, Shape);
1639
1640 // Move to after the call. Since swifterror only has a guaranteed
1641 // value on normal exits, we can ignore implicit and explicit unwind
1642 // edges.
1643 if (isa<CallInst>(Call)) {
1644 Builder.SetInsertPoint(Call->getNextNode());
1645 } else {
1646 auto Invoke = cast<InvokeInst>(Call);
1647 Builder.SetInsertPoint(Invoke->getNormalDest()->getFirstNonPHIOrDbg());
1648 }
1649
1650 // Get the current swifterror value and store it to the alloca.
1651 auto ValueAfterCall = emitGetSwiftErrorValue(Builder, ValueTy, Shape);
1652 Builder.CreateStore(ValueAfterCall, Alloca);
1653
1654 return Addr;
1655}
1656
1657/// Eliminate a formerly-swifterror alloca by inserting the get/set
1658/// intrinsics and attempting to MemToReg the alloca away.
1660 coro::Shape &Shape) {
1661 for (Use &Use : llvm::make_early_inc_range(Alloca->uses())) {
1662 // swifterror values can only be used in very specific ways.
1663 // We take advantage of that here.
1664 auto User = Use.getUser();
1665 if (isa<LoadInst>(User) || isa<StoreInst>(User))
1666 continue;
1667
1668 assert(isa<CallInst>(User) || isa<InvokeInst>(User));
1669 auto Call = cast<Instruction>(User);
1670
1671 auto Addr = emitSetAndGetSwiftErrorValueAround(Call, Alloca, Shape);
1672
1673 // Use the returned slot address as the call argument.
1674 Use.set(Addr);
1675 }
1676
1677 // All the uses should be loads and stores now.
1678 assert(isAllocaPromotable(Alloca));
1679}
1680
1681/// "Eliminate" a swifterror argument by reducing it to the alloca case
1682/// and then loading and storing in the prologue and epilog.
1683///
1684/// The argument keeps the swifterror flag.
1686 coro::Shape &Shape,
1687 SmallVectorImpl<AllocaInst*> &AllocasToPromote) {
1688 IRBuilder<> Builder(&F.getEntryBlock(),
1689 F.getEntryBlock().getFirstNonPHIOrDbg());
1690
1691 auto ArgTy = cast<PointerType>(Arg.getType());
1692 auto ValueTy = PointerType::getUnqual(F.getContext());
1693
1694 // Reduce to the alloca case:
1695
1696 // Create an alloca and replace all uses of the arg with it.
1697 auto Alloca = Builder.CreateAlloca(ValueTy, ArgTy->getAddressSpace());
1698 Arg.replaceAllUsesWith(Alloca);
1699
1700 // Set an initial value in the alloca. swifterror is always null on entry.
1701 auto InitialValue = Constant::getNullValue(ValueTy);
1702 Builder.CreateStore(InitialValue, Alloca);
1703
1704 // Find all the suspends in the function and save and restore around them.
1705 for (auto *Suspend : Shape.CoroSuspends) {
1706 (void) emitSetAndGetSwiftErrorValueAround(Suspend, Alloca, Shape);
1707 }
1708
1709 // Find all the coro.ends in the function and restore the error value.
1710 for (auto *End : Shape.CoroEnds) {
1711 Builder.SetInsertPoint(End);
1712 auto FinalValue = Builder.CreateLoad(ValueTy, Alloca);
1713 (void) emitSetSwiftErrorValue(Builder, FinalValue, Shape);
1714 }
1715
1716 // Now we can use the alloca logic.
1717 AllocasToPromote.push_back(Alloca);
1718 eliminateSwiftErrorAlloca(F, Alloca, Shape);
1719}
1720
1721/// Eliminate all problematic uses of swifterror arguments and allocas
1722/// from the function. We'll fix them up later when splitting the function.
1724 SmallVector<AllocaInst*, 4> AllocasToPromote;
1725
1726 // Look for a swifterror argument.
1727 for (auto &Arg : F.args()) {
1728 if (!Arg.hasSwiftErrorAttr()) continue;
1729
1730 eliminateSwiftErrorArgument(F, Arg, Shape, AllocasToPromote);
1731 break;
1732 }
1733
1734 // Look for swifterror allocas.
1735 for (auto &Inst : F.getEntryBlock()) {
1736 auto Alloca = dyn_cast<AllocaInst>(&Inst);
1737 if (!Alloca || !Alloca->isSwiftError()) continue;
1738
1739 // Clear the swifterror flag.
1740 Alloca->setSwiftError(false);
1741
1742 AllocasToPromote.push_back(Alloca);
1743 eliminateSwiftErrorAlloca(F, Alloca, Shape);
1744 }
1745
1746 // If we have any allocas to promote, compute a dominator tree and
1747 // promote them en masse.
1748 if (!AllocasToPromote.empty()) {
1749 DominatorTree DT(F);
1750 PromoteMemToReg(AllocasToPromote, DT);
1751 }
1752}
1753
1754/// For each local variable that all of its user are only used inside one of
1755/// suspended region, we sink their lifetime.start markers to the place where
1756/// after the suspend block. Doing so minimizes the lifetime of each variable,
1757/// hence minimizing the amount of data we end up putting on the frame.
1759 SuspendCrossingInfo &Checker,
1760 const DominatorTree &DT) {
1761 if (F.hasOptNone())
1762 return;
1763
1764 // Collect all possible basic blocks which may dominate all uses of allocas.
1766 DomSet.insert(&F.getEntryBlock());
1767 for (auto *CSI : Shape.CoroSuspends) {
1768 BasicBlock *SuspendBlock = CSI->getParent();
1769 assert(coro::isSuspendBlock(SuspendBlock) &&
1770 SuspendBlock->getSingleSuccessor() &&
1771 "should have split coro.suspend into its own block");
1772 DomSet.insert(SuspendBlock->getSingleSuccessor());
1773 }
1774
1775 for (Instruction &I : instructions(F)) {
1776 AllocaInst* AI = dyn_cast<AllocaInst>(&I);
1777 if (!AI)
1778 continue;
1779
1780 for (BasicBlock *DomBB : DomSet) {
1781 bool Valid = true;
1783
1784 auto isLifetimeStart = [](Instruction* I) {
1785 if (auto* II = dyn_cast<IntrinsicInst>(I))
1786 return II->getIntrinsicID() == Intrinsic::lifetime_start;
1787 return false;
1788 };
1789
1790 auto collectLifetimeStart = [&](Instruction *U, AllocaInst *AI) {
1791 if (isLifetimeStart(U)) {
1792 Lifetimes.push_back(U);
1793 return true;
1794 }
1795 if (!U->hasOneUse() || U->stripPointerCasts() != AI)
1796 return false;
1797 if (isLifetimeStart(U->user_back())) {
1798 Lifetimes.push_back(U->user_back());
1799 return true;
1800 }
1801 return false;
1802 };
1803
1804 for (User *U : AI->users()) {
1805 Instruction *UI = cast<Instruction>(U);
1806 // For all users except lifetime.start markers, if they are all
1807 // dominated by one of the basic blocks and do not cross
1808 // suspend points as well, then there is no need to spill the
1809 // instruction.
1810 if (!DT.dominates(DomBB, UI->getParent()) ||
1811 Checker.isDefinitionAcrossSuspend(DomBB, UI)) {
1812 // Skip lifetime.start, GEP and bitcast used by lifetime.start
1813 // markers.
1814 if (collectLifetimeStart(UI, AI))
1815 continue;
1816 Valid = false;
1817 break;
1818 }
1819 }
1820 // Sink lifetime.start markers to dominate block when they are
1821 // only used outside the region.
1822 if (Valid && Lifetimes.size() != 0) {
1823 auto *NewLifetime = Lifetimes[0]->clone();
1824 NewLifetime->replaceUsesOfWith(NewLifetime->getOperand(0), AI);
1825 NewLifetime->insertBefore(DomBB->getTerminator()->getIterator());
1826
1827 // All the outsided lifetime.start markers are no longer necessary.
1828 for (Instruction *S : Lifetimes)
1829 S->eraseFromParent();
1830
1831 break;
1832 }
1833 }
1834 }
1835}
1836
1837static std::optional<std::pair<Value &, DIExpression &>>
1839 bool UseEntryValue, Function *F, Value *Storage,
1840 DIExpression *Expr, bool SkipOutermostLoad) {
1841 IRBuilder<> Builder(F->getContext());
1842 auto InsertPt = F->getEntryBlock().getFirstInsertionPt();
1843 while (isa<IntrinsicInst>(InsertPt))
1844 ++InsertPt;
1845 Builder.SetInsertPoint(&F->getEntryBlock(), InsertPt);
1846
1847 while (auto *Inst = dyn_cast_or_null<Instruction>(Storage)) {
1848 if (auto *LdInst = dyn_cast<LoadInst>(Inst)) {
1849 Storage = LdInst->getPointerOperand();
1850 // FIXME: This is a heuristic that works around the fact that
1851 // LLVM IR debug intrinsics cannot yet distinguish between
1852 // memory and value locations: Because a dbg.declare(alloca) is
1853 // implicitly a memory location no DW_OP_deref operation for the
1854 // last direct load from an alloca is necessary. This condition
1855 // effectively drops the *last* DW_OP_deref in the expression.
1856 if (!SkipOutermostLoad)
1858 } else if (auto *StInst = dyn_cast<StoreInst>(Inst)) {
1859 Storage = StInst->getValueOperand();
1860 } else {
1862 SmallVector<Value *, 0> AdditionalValues;
1864 *Inst, Expr ? Expr->getNumLocationOperands() : 0, Ops,
1865 AdditionalValues);
1866 if (!Op || !AdditionalValues.empty()) {
1867 // If salvaging failed or salvaging produced more than one location
1868 // operand, give up.
1869 break;
1870 }
1871 Storage = Op;
1872 Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, /*StackValue*/ false);
1873 }
1874 SkipOutermostLoad = false;
1875 }
1876 if (!Storage)
1877 return std::nullopt;
1878
1879 auto *StorageAsArg = dyn_cast<Argument>(Storage);
1880 const bool IsSwiftAsyncArg =
1881 StorageAsArg && StorageAsArg->hasAttribute(Attribute::SwiftAsync);
1882
1883 // Swift async arguments are described by an entry value of the ABI-defined
1884 // register containing the coroutine context.
1885 // Entry values in variadic expressions are not supported.
1886 if (IsSwiftAsyncArg && UseEntryValue && !Expr->isEntryValue() &&
1889
1890 // If the coroutine frame is an Argument, store it in an alloca to improve
1891 // its availability (e.g. registers may be clobbered).
1892 // Avoid this if the value is guaranteed to be available through other means
1893 // (e.g. swift ABI guarantees).
1894 if (StorageAsArg && !IsSwiftAsyncArg) {
1895 auto &Cached = ArgToAllocaMap[StorageAsArg];
1896 if (!Cached) {
1897 Cached = Builder.CreateAlloca(Storage->getType(), 0, nullptr,
1898 Storage->getName() + ".debug");
1899 Builder.CreateStore(Storage, Cached);
1900 }
1901 Storage = Cached;
1902 // FIXME: LLVM lacks nuanced semantics to differentiate between
1903 // memory and direct locations at the IR level. The backend will
1904 // turn a dbg.declare(alloca, ..., DIExpression()) into a memory
1905 // location. Thus, if there are deref and offset operations in the
1906 // expression, we need to add a DW_OP_deref at the *start* of the
1907 // expression to first load the contents of the alloca before
1908 // adjusting it with the expression.
1910 }
1911
1912 Expr = Expr->foldConstantMath();
1913 return {{*Storage, *Expr}};
1914}
1915
1918 DbgVariableRecord &DVR, bool UseEntryValue) {
1919
1920 Function *F = DVR.getFunction();
1921 // Follow the pointer arithmetic all the way to the incoming
1922 // function argument and convert into a DIExpression.
1923 bool SkipOutermostLoad = DVR.isDbgDeclare();
1924 Value *OriginalStorage = DVR.getVariableLocationOp(0);
1925
1926 auto SalvagedInfo =
1927 ::salvageDebugInfoImpl(ArgToAllocaMap, UseEntryValue, F, OriginalStorage,
1928 DVR.getExpression(), SkipOutermostLoad);
1929 if (!SalvagedInfo)
1930 return;
1931
1932 Value *Storage = &SalvagedInfo->first;
1933 DIExpression *Expr = &SalvagedInfo->second;
1934
1935 DVR.replaceVariableLocationOp(OriginalStorage, Storage);
1936 DVR.setExpression(Expr);
1937 // We only hoist dbg.declare today since it doesn't make sense to hoist
1938 // dbg.value since it does not have the same function wide guarantees that
1939 // dbg.declare does.
1940 if (DVR.getType() == DbgVariableRecord::LocationType::Declare) {
1941 std::optional<BasicBlock::iterator> InsertPt;
1942 if (auto *I = dyn_cast<Instruction>(Storage)) {
1943 InsertPt = I->getInsertionPointAfterDef();
1944 // Update DILocation only if variable was not inlined.
1945 DebugLoc ILoc = I->getDebugLoc();
1946 DebugLoc DVRLoc = DVR.getDebugLoc();
1947 if (ILoc && DVRLoc &&
1948 DVRLoc->getScope()->getSubprogram() ==
1949 ILoc->getScope()->getSubprogram())
1950 DVR.setDebugLoc(ILoc);
1951 } else if (isa<Argument>(Storage))
1952 InsertPt = F->getEntryBlock().begin();
1953 if (InsertPt) {
1954 DVR.removeFromParent();
1955 (*InsertPt)->getParent()->insertDbgRecordBefore(&DVR, *InsertPt);
1956 }
1957 }
1958}
1959
1962 // Don't eliminate swifterror in async functions that won't be split.
1963 if (Shape.ABI != coro::ABI::Async || !Shape.CoroSuspends.empty())
1965
1966 if (Shape.ABI == coro::ABI::Switch &&
1969 }
1970
1971 // Make sure that all coro.save, coro.suspend and the fallthrough coro.end
1972 // intrinsics are in their own blocks to simplify the logic of building up
1973 // SuspendCrossing data.
1974 for (auto *CSI : Shape.CoroSuspends) {
1975 if (auto *Save = CSI->getCoroSave())
1976 splitAround(Save, "CoroSave");
1977 splitAround(CSI, "CoroSuspend");
1978 }
1979
1980 // Put CoroEnds into their own blocks.
1981 for (AnyCoroEndInst *CE : Shape.CoroEnds) {
1982 splitAround(CE, "CoroEnd");
1983
1984 // Emit the musttail call function in a new block before the CoroEnd.
1985 // We do this here so that the right suspend crossing info is computed for
1986 // the uses of the musttail call function call. (Arguments to the coro.end
1987 // instructions would be ignored)
1988 if (auto *AsyncEnd = dyn_cast<CoroAsyncEndInst>(CE)) {
1989 auto *MustTailCallFn = AsyncEnd->getMustTailCallFunction();
1990 if (!MustTailCallFn)
1991 continue;
1992 IRBuilder<> Builder(AsyncEnd);
1993 SmallVector<Value *, 8> Args(AsyncEnd->args());
1994 auto Arguments = ArrayRef<Value *>(Args).drop_front(3);
1995 auto *Call = coro::createMustTailCall(
1996 AsyncEnd->getDebugLoc(), MustTailCallFn, TTI, Arguments, Builder);
1997 splitAround(Call, "MustTailCall.Before.CoroEnd");
1998 }
1999 }
2000
2001 // Later code makes structural assumptions about single predecessors phis e.g
2002 // that they are not live across a suspend point.
2004
2005 // Transforms multi-edge PHI Nodes, so that any value feeding into a PHI will
2006 // never have its definition separated from the PHI by the suspend point.
2007 rewritePHIs(F);
2008}
2009
2010void coro::BaseABI::buildCoroutineFrame(bool OptimizeFrame) {
2013
2014 const DominatorTree DT(F);
2017 sinkLifetimeStartMarkers(F, Shape, Checker, DT);
2018
2019 // All values (that are not allocas) that needs to be spilled to the frame.
2020 coro::SpillInfo Spills;
2021 // All values defined as allocas that need to live in the frame.
2023
2024 // Collect the spills for arguments and other not-materializable values.
2025 coro::collectSpillsFromArgs(Spills, F, Checker);
2026 SmallVector<Instruction *, 4> DeadInstructions;
2028 coro::collectSpillsAndAllocasFromInsts(Spills, Allocas, DeadInstructions,
2029 LocalAllocas, F, Checker, DT, Shape);
2030 coro::collectSpillsFromDbgInfo(Spills, F, Checker);
2031
2032 LLVM_DEBUG(dumpAllocas(Allocas));
2033 LLVM_DEBUG(dumpSpills("Spills", Spills));
2034
2037 sinkSpillUsesAfterCoroBegin(DT, Shape.CoroBegin, Spills, Allocas);
2038
2039 // Build frame
2040 FrameDataInfo FrameData(Spills, Allocas);
2041 Shape.FrameTy = buildFrameType(F, Shape, FrameData, OptimizeFrame);
2043 // For now, this works for C++ programs only.
2044 buildFrameDebugInfo(F, Shape, FrameData);
2045 // Insert spills and reloads
2046 insertSpills(FrameData, Shape);
2047 lowerLocalAllocas(LocalAllocas, DeadInstructions);
2048
2049 for (auto *I : DeadInstructions)
2050 I->eraseFromParent();
2051}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AMDGPU Lower Kernel Arguments
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static void cleanupSinglePredPHIs(Function &F)
Definition: CoroFrame.cpp:1393
static std::optional< std::pair< Value &, DIExpression & > > salvageDebugInfoImpl(SmallDenseMap< Argument *, AllocaInst *, 4 > &ArgToAllocaMap, bool UseEntryValue, Function *F, Value *Storage, DIExpression *Expr, bool SkipOutermostLoad)
Definition: CoroFrame.cpp:1838
static void eliminateSwiftError(Function &F, coro::Shape &Shape)
Eliminate all problematic uses of swifterror arguments and allocas from the function.
Definition: CoroFrame.cpp:1723
static void lowerLocalAllocas(ArrayRef< CoroAllocaAllocInst * > LocalAllocas, SmallVectorImpl< Instruction * > &DeadInsts)
Turn each of the given local allocas into a normal (dynamic) alloca instruction.
Definition: CoroFrame.cpp:1558
static Value * emitSetSwiftErrorValue(IRBuilder<> &Builder, Value *V, coro::Shape &Shape)
Set the given value as the current swifterror value.
Definition: CoroFrame.cpp:1611
static Value * emitSetAndGetSwiftErrorValueAround(Instruction *Call, AllocaInst *Alloca, coro::Shape &Shape)
Set the swifterror value from the given alloca before a call, then put in back in the alloca afterwar...
Definition: CoroFrame.cpp:1629
static void cacheDIVar(FrameDataInfo &FrameData, DenseMap< Value *, DILocalVariable * > &DIVarCache)
Definition: CoroFrame.cpp:543
static bool localAllocaNeedsStackSave(CoroAllocaAllocInst *AI)
Definition: CoroFrame.cpp:1540
static void dumpAllocas(const SmallVectorImpl< coro::AllocaInfo > &Allocas)
Definition: CoroFrame.cpp:149
static void splitAround(Instruction *I, const Twine &Name)
Definition: CoroFrame.cpp:1513
static void eliminateSwiftErrorAlloca(Function &F, AllocaInst *Alloca, coro::Shape &Shape)
Eliminate a formerly-swifterror alloca by inserting the get/set intrinsics and attempting to MemToReg...
Definition: CoroFrame.cpp:1659
static void rewritePHIs(BasicBlock &BB)
Definition: CoroFrame.cpp:1410
static void movePHIValuesToInsertedBlock(BasicBlock *SuccBB, BasicBlock *InsertedBB, BasicBlock *PredBB, PHINode *UntilPHI=nullptr)
Definition: CoroFrame.cpp:1300
static void dumpSpills(StringRef Title, const coro::SpillInfo &Spills)
Definition: CoroFrame.cpp:139
static DIType * solveDIType(DIBuilder &Builder, Type *Ty, const DataLayout &Layout, DIScope *Scope, unsigned LineNum, DenseMap< Type *, DIType * > &DITypeCache)
Definition: CoroFrame.cpp:600
static bool willLeaveFunctionImmediatelyAfter(BasicBlock *BB, unsigned depth=3)
After we split the coroutine, will the given basic block be along an obvious exit path for the resump...
Definition: CoroFrame.cpp:1520
static StructType * buildFrameType(Function &F, coro::Shape &Shape, FrameDataInfo &FrameData, bool OptimizeFrame)
Definition: CoroFrame.cpp:858
static void eliminateSwiftErrorArgument(Function &F, Argument &Arg, coro::Shape &Shape, SmallVectorImpl< AllocaInst * > &AllocasToPromote)
"Eliminate" a swifterror argument by reducing it to the alloca case and then loading and storing in t...
Definition: CoroFrame.cpp:1685
static void buildFrameDebugInfo(Function &F, coro::Shape &Shape, FrameDataInfo &FrameData)
Build artificial debug info for C++ coroutine frames to allow users to inspect the contents of the fr...
Definition: CoroFrame.cpp:687
static BasicBlock * splitBlockIfNotFirst(Instruction *I, const Twine &Name)
Definition: CoroFrame.cpp:1500
static void rewritePHIsForCleanupPad(BasicBlock *CleanupPadBB, CleanupPadInst *CleanupPad)
Definition: CoroFrame.cpp:1318
static void sinkLifetimeStartMarkers(Function &F, coro::Shape &Shape, SuspendCrossingInfo &Checker, const DominatorTree &DT)
For each local variable that all of its user are only used inside one of suspended region,...
Definition: CoroFrame.cpp:1758
static StringRef solveTypeName(Type *Ty)
Create name for Type.
Definition: CoroFrame.cpp:562
static Value * emitGetSwiftErrorValue(IRBuilder<> &Builder, Type *ValueTy, coro::Shape &Shape)
Get the current swifterror value.
Definition: CoroFrame.cpp:1596
static void insertSpills(const FrameDataInfo &FrameData, coro::Shape &Shape)
Definition: CoroFrame.cpp:997
Given that RA is a live value
uint64_t Addr
std::string Name
uint64_t Size
bool End
Definition: ELF_riscv.cpp:480
static bool isLifetimeStart(const Instruction *Inst)
Definition: GVN.cpp:1213
Hexagon Common GEP
static MaybeAlign getAlign(Value *Ptr)
Definition: IRBuilder.cpp:442
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
#define G(x, y, z)
Definition: MD5.cpp:56
uint64_t IntrinsicInst * II
This file provides an interface for laying out a sequence of fields as a struct in a way that attempt...
#define P(N)
static unsigned getNumElements(Type *Ty)
raw_pwrite_stream & OS
This file defines the make_scope_exit function, which executes user-defined cleanup logic at scope ex...
This file defines the SmallString class.
#define LLVM_DEBUG(...)
Definition: Debug.h:119
static const unsigned FramePtr
an instruction to allocate memory on the stack
Definition: Instructions.h:64
bool isSwiftError() const
Return true if this alloca is used as a swifterror argument to a call.
Definition: Instructions.h:153
void setSwiftError(bool V)
Specify whether this alloca is used to represent a swifterror.
Definition: Instructions.h:155
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
Definition: Instructions.h:128
PointerType * getType() const
Overload to return most specific pointer type.
Definition: Instructions.h:101
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
Definition: Instructions.h:121
LLVM_ABI bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1.
void setAlignment(Align Align)
Definition: Instructions.h:132
const Value * getArraySize() const
Get the number of elements allocated.
Definition: Instructions.h:97
This class represents an incoming formal argument to a Function.
Definition: Argument.h:32
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:200
LLVM Basic Block Representation.
Definition: BasicBlock.h:62
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:459
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
Definition: BasicBlock.cpp:393
bool empty() const
Definition: BasicBlock.h:481
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
Definition: BasicBlock.cpp:337
const Instruction & front() const
Definition: BasicBlock.h:482
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:206
LLVM_ABI 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:555
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
Definition: BasicBlock.cpp:467
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:213
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:170
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
Definition: BasicBlock.cpp:131
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
Definition: Constants.cpp:1833
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:373
This represents the llvm.coro.alloca.alloc instruction.
Definition: CoroInstr.h:746
void clearPromise()
Definition: CoroInstr.h:159
This represents the llvm.coro.suspend instruction.
Definition: CoroInstr.h:531
LLVM_ABI DIDerivedType * createMemberType(DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNo, Metadata *SizeInBits, uint32_t AlignInBits, Metadata *OffsetInBits, DINode::DIFlags Flags, DIType *Ty, DINodeArray Annotations=nullptr)
Create debugging information entry for a member.
Definition: DIBuilder.cpp:431
LLVM_ABI DIDerivedType * createPointerType(DIType *PointeeTy, uint64_t SizeInBits, uint32_t AlignInBits=0, std::optional< unsigned > DWARFAddressSpace=std::nullopt, StringRef Name="", DINodeArray Annotations=nullptr)
Create debugging information entry for a pointer.
Definition: DIBuilder.cpp:347
LLVM_ABI DIBasicType * createBasicType(StringRef Name, uint64_t SizeInBits, unsigned Encoding, DINode::DIFlags Flags=DINode::FlagZero, uint32_t NumExtraInhabitants=0)
Create debugging information entry for a basic type.
Definition: DIBuilder.cpp:265
LLVM_ABI DISubrange * getOrCreateSubrange(int64_t Lo, int64_t Count)
Create a descriptor for a value range.
Definition: DIBuilder.cpp:821
LLVM_ABI DICompositeType * createArrayType(uint64_t Size, uint32_t AlignInBits, DIType *Ty, DINodeArray Subscripts, PointerUnion< DIExpression *, DIVariable * > DataLocation=nullptr, PointerUnion< DIExpression *, DIVariable * > Associated=nullptr, PointerUnion< DIExpression *, DIVariable * > Allocated=nullptr, PointerUnion< DIExpression *, DIVariable * > Rank=nullptr)
Create debugging information entry for an array.
Definition: DIBuilder.cpp:686
LLVM_ABI DICompositeType * createStructType(DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber, Metadata *SizeInBits, uint32_t AlignInBits, DINode::DIFlags Flags, DIType *DerivedFrom, DINodeArray Elements, unsigned RunTimeLang=0, DIType *VTableHolder=nullptr, StringRef UniqueIdentifier="", DIType *Specification=nullptr, uint32_t NumExtraInhabitants=0)
Create debugging information entry for a struct.
Definition: DIBuilder.cpp:592
LLVM_ABI DINodeArray getOrCreateArray(ArrayRef< Metadata * > Elements)
Get a DINodeArray, create one if required.
Definition: DIBuilder.cpp:801
LLVM_ABI DIExpression * createExpression(ArrayRef< uint64_t > Addr={})
Create a new descriptor for the specified variable which has a complex address expression for its add...
Definition: DIBuilder.cpp:966
LLVM_ABI DILocalVariable * createAutoVariable(DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNo, DIType *Ty, bool AlwaysPreserve=false, DINode::DIFlags Flags=DINode::FlagZero, uint32_t AlignInBits=0)
Create a new descriptor for an auto variable.
Definition: DIBuilder.cpp:924
LLVM_ABI void replaceArrays(DICompositeType *&T, DINodeArray Elements, DINodeArray TParams=DINodeArray())
Replace arrays on a composite type.
Definition: DIBuilder.cpp:1216
DWARF expression.
LLVM_ABI bool isEntryValue() const
Check if the expression consists of exactly one entry value operand.
static LLVM_ABI DIExpression * appendOpsToArg(const DIExpression *Expr, ArrayRef< uint64_t > Ops, unsigned ArgNo, bool StackValue=false)
Create a copy of Expr by appending the given list of Ops to each instance of the operand DW_OP_LLVM_a...
LLVM_ABI DIExpression * foldConstantMath()
Try to shorten an expression with constant math operations that can be evaluated at compile time.
LLVM_ABI uint64_t getNumLocationOperands() const
Return the number of unique location operands referred to (via DW_OP_LLVM_arg) in this expression; th...
static LLVM_ABI DIExpression * prepend(const DIExpression *Expr, uint8_t Flags, int64_t Offset=0)
Prepend DIExpr with a deref and offset operation and optionally turn it into a stack value or/and an ...
LLVM_ABI bool isSingleLocationExpression() const
Return whether the evaluated expression makes use of a single location at the start of the expression...
Debug location.
Base class for scope-like contexts.
DIFile * getFile() const
Subprogram description. Uses SubclassData1.
Base class for types.
StringRef getName() const
uint64_t getSizeInBits() const
LLVM_ABI uint32_t getAlignInBits() const
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
LLVM_ABI const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
Definition: DataLayout.cpp:708
LLVM_ABI Align getABITypeAlign(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
Definition: DataLayout.cpp:842
TypeSize getTypeSizeInBits(Type *Ty) const
Size examples:
Definition: DataLayout.h:674
LLVM_ABI Align getPrefTypeAlign(Type *Ty) const
Returns the preferred stack/global alignment for the specified type.
Definition: DataLayout.cpp:846
LLVM_ABI void removeFromParent()
LLVM_ABI Function * getFunction()
DebugLoc getDebugLoc() const
void setDebugLoc(DebugLoc Loc)
Record of a variable value-assignment, aka a non instruction representation of the dbg....
void setExpression(DIExpression *NewExpr)
DIExpression * getExpression() const
LLVM_ABI Value * getVariableLocationOp(unsigned OpIdx) const
LLVM_ABI void replaceVariableLocationOp(Value *OldValue, Value *NewValue, bool AllowEmpty=false)
A debug info location.
Definition: DebugLoc.h:124
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: DenseMap.h:203
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:177
iterator end()
Definition: DenseMap.h:87
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition: DenseMap.h:168
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:230
void reserve(size_type NumEntries)
Grow the densemap so that it can contain at least NumEntries items before resizing again.
Definition: DenseMap.h:124
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:165
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
Definition: Dominators.cpp:135
AllocaInst * CreateAlloca(Type *Ty, unsigned AddrSpace, Value *ArraySize=nullptr, const Twine &Name="")
Definition: IRBuilder.h:1830
CallInst * CreateStackSave(const Twine &Name="")
Create a call to llvm.stacksave.
Definition: IRBuilder.h:1121
LoadInst * CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align, const char *Name)
Definition: IRBuilder.h:1864
UnreachableInst * CreateUnreachable()
Definition: IRBuilder.h:1339
BasicBlock::iterator GetInsertPoint() const
Definition: IRBuilder.h:202
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2199
Value * CreatePtrAdd(Value *Ptr, Value *Offset, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Definition: IRBuilder.h:2036
Value * CreateInBoundsGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="")
Definition: IRBuilder.h:1931
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Definition: IRBuilder.h:2494
Value * CreateNot(Value *V, const Twine &Name="")
Definition: IRBuilder.h:1805
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:1220
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:1847
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1551
Value * CreateConstInBoundsGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0, unsigned Idx1, const Twine &Name="")
Definition: IRBuilder.h:1970
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition: IRBuilder.h:1860
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1403
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2194
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args={}, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2508
PointerType * getPtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer.
Definition: IRBuilder.h:605
BranchInst * CreateBr(BasicBlock *Dest)
Create an unconditional 'br label X' instruction.
Definition: IRBuilder.h:1191
CallInst * CreateStackRestore(Value *Ptr, const Twine &Name="")
Create a call to llvm.stackrestore.
Definition: IRBuilder.h:1128
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition: IRBuilder.h:207
StoreInst * CreateAlignedStore(Value *Val, Value *Ptr, MaybeAlign Align, bool isVolatile=false)
Definition: IRBuilder.h:1883
IntegerType * getInt8Ty()
Fetch the type representing an 8-bit integer.
Definition: IRBuilder.h:552
Value * CreateAddrSpaceCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2209
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2780
LLVM_ABI void removeFromParent()
This method unlinks 'this' from the containing basic block, but does not delete it.
Definition: Instruction.cpp:90
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:78
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
Definition: Instruction.cpp:82
LLVM_ABI void insertAfter(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately after the specified instruction.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition: Type.cpp:319
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
The landingpad instruction holds all of the information necessary to generate correct exception handl...
LLVM_ABI void replaceOperandWith(unsigned I, Metadata *New)
Replace a specific operand.
Definition: Metadata.cpp:1078
LLVMContext & getContext() const
Definition: Metadata.h:1241
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition: Metadata.cpp:607
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1522
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...
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:401
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:541
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
StringRef str() const
Explicit conversion to StringRef.
Definition: SmallString.h:254
bool empty() const
Definition: SmallVector.h:82
size_t size() const
Definition: SmallVector.h:79
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:574
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:938
void reserve(size_type N)
Definition: SmallVector.h:664
void push_back(const T &Elt)
Definition: SmallVector.h:414
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1197
Compute live ranges of allocas.
Definition: StackLifetime.h:37
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:55
std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:233
TypeSize getElementOffsetInBits(unsigned Idx) const
Definition: DataLayout.h:662
Class to represent struct types.
Definition: DerivedTypes.h:218
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition: Type.cpp:620
unsigned getNumElements() const
Random access to the elements.
Definition: DerivedTypes.h:368
Type * getElementType(unsigned N) const
Definition: DerivedTypes.h:369
bool isDefinitionAcrossSuspend(BasicBlock *DefBB, User *U) const
Multiway switch.
void setDefaultDest(BasicBlock *DefaultCase)
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
TinyPtrVector - This class is specialized for cases where there are normally 0 or 1 element in a vect...
Definition: TinyPtrVector.h:29
bool empty() const
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:82
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
Definition: Twine.cpp:17
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition: TypeSize.h:346
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
bool isPointerTy() const
True if this is an instance of PointerType.
Definition: Type.h:267
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition: Type.h:153
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
LLVM_ABI StringRef getStructName() const
bool isStructTy() const
True if this is an instance of StructType.
Definition: Type.h:261
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition: Type.h:311
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:128
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Definition: Type.h:156
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition: Type.h:184
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:240
A Use represents the edge between a Value definition and its users.
Definition: Use.h:35
LLVM_ABI void set(Value *Val)
Definition: Value.h:905
User * getUser() const
Returns the User that contains this Use.
Definition: Use.h:61
static LLVM_ABI ValueAsMetadata * get(Value *V)
Definition: Metadata.cpp:502
LLVM Value Representation.
Definition: Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:256
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:546
iterator_range< user_iterator > users()
Definition: Value.h:426
LLVM_ABI void replaceUsesWithIf(Value *New, llvm::function_ref< bool(Use &U)> ShouldReplace)
Go through the uses list for this definition and make each use point to "V" if the callback ShouldRep...
Definition: Value.cpp:554
LLVM_ABI LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:1098
iterator_range< use_iterator > uses()
Definition: Value.h:380
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:322
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition: Value.cpp:396
std::function< bool(Instruction &I)> IsMaterializable
Definition: ABI.h:64
Function & F
Definition: ABI.h:59
virtual void buildCoroutineFrame(bool OptimizeFrame)
Definition: CoroFrame.cpp:2010
constexpr ScalarTy getFixedValue() const
Definition: TypeSize.h:203
const ParentTy * getParent() const
Definition: ilist_node.h:34
self_iterator getIterator()
Definition: ilist_node.h:134
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:692
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
@ 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...
BasicBlock::iterator getSpillInsertionPt(const coro::Shape &, Value *Def, const DominatorTree &DT)
Definition: SpillUtils.cpp:575
bool isSuspendBlock(BasicBlock *BB)
Definition: Coroutines.cpp:98
void normalizeCoroutine(Function &F, coro::Shape &Shape, TargetTransformInfo &TTI)
Definition: CoroFrame.cpp:1960
CallInst * createMustTailCall(DebugLoc Loc, Function *MustTailCallFn, TargetTransformInfo &TTI, ArrayRef< Value * > Arguments, IRBuilder<> &)
Definition: CoroSplit.cpp:1684
void sinkSpillUsesAfterCoroBegin(const DominatorTree &DT, CoroBeginInst *CoroBegin, coro::SpillInfo &Spills, SmallVectorImpl< coro::AllocaInfo > &Allocas)
Async and Retcon{Once} conventions assume that all spill uses can be sunk after the coro....
Definition: SpillUtils.cpp:528
LLVM_ABI void doRematerializations(Function &F, SuspendCrossingInfo &Checker, std::function< bool(Instruction &)> IsMaterializable)
void collectSpillsFromArgs(SpillInfo &Spills, Function &F, const SuspendCrossingInfo &Checker)
Definition: SpillUtils.cpp:445
void collectSpillsFromDbgInfo(SpillInfo &Spills, Function &F, const SuspendCrossingInfo &Checker)
Definition: SpillUtils.cpp:509
void salvageDebugInfo(SmallDenseMap< Argument *, AllocaInst *, 4 > &ArgToAllocaMap, DbgVariableRecord &DVR, bool UseEntryValue)
Attempts to rewrite the location operand of debug records in terms of the coroutine frame pointer,...
Definition: CoroFrame.cpp:1916
void collectSpillsAndAllocasFromInsts(SpillInfo &Spills, SmallVector< AllocaInfo, 8 > &Allocas, SmallVector< Instruction *, 4 > &DeadInstructions, SmallVector< CoroAllocaAllocInst *, 4 > &LocalAllocas, Function &F, const SuspendCrossingInfo &Checker, const DominatorTree &DT, const coro::Shape &Shape)
Definition: SpillUtils.cpp:454
SourceLanguage
Definition: Dwarf.h:214
bool isCPlusPlus(SourceLanguage S)
Definition: Dwarf.h:504
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:477
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:1737
LLVM_ABI void PromoteMemToReg(ArrayRef< AllocaInst * > Allocas, DominatorTree &DT, AssumptionCache *AC=nullptr)
Promote the specified list of alloca instructions into scalar registers, inserting PHI nodes as appro...
detail::scope_exit< std::decay_t< Callable > > make_scope_exit(Callable &&F)
Definition: ScopeExit.h:59
unsigned Log2_64_Ceil(uint64_t Value)
Return the ceil log base 2 of the specified value, 64 if the value is zero.
Definition: MathExtras.h:355
bool isAligned(Align Lhs, uint64_t SizeInBytes)
Checks that SizeInBytes is a multiple of the alignment.
Definition: Alignment.h:145
auto successors(const MachineBasicBlock *BB)
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:663
auto pred_size(const MachineBasicBlock *BB)
LLVM_ABI bool isAllocaPromotable(const AllocaInst *AI)
Return true if this alloca is legal for promotion.
static Error getOffset(const SymbolRef &Sym, SectionRef Sec, uint64_t &Result)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1751
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1669
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:207
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1758
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition: Error.cpp:167
LLVM_ABI BasicBlock * ehAwareSplitEdge(BasicBlock *BB, BasicBlock *Succ, LandingPadInst *OriginalPad=nullptr, PHINode *LandingPadReplacement=nullptr, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions(), const Twine &BBName="")
Split the edge connect the specficed blocks in the case that Succ is an Exception Handling Block.
LLVM_ABI Value * salvageDebugInfoImpl(Instruction &I, uint64_t CurrentLocOps, SmallVectorImpl< uint64_t > &Ops, SmallVectorImpl< Value * > &AdditionalValues)
Definition: Local.cpp:2274
uint64_t offsetToAlignment(uint64_t Value, Align Alignment)
Returns the offset to the next integer (mod 2**64) that is greater than or equal to Value and is a mu...
Definition: Alignment.h:197
LLVM_ABI std::pair< uint64_t, Align > performOptimizedStructLayout(MutableArrayRef< OptimizedStructLayoutField > Fields)
Compute a layout for a struct containing the given fields, making a best-effort attempt to minimize t...
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition: Alignment.h:155
DWARFExpression::Operation Op
constexpr unsigned BitWidth
Definition: BitmaskEnum.h:223
LLVM_ABI void updatePhiNodes(BasicBlock *DestBB, BasicBlock *OldPred, BasicBlock *NewPred, PHINode *Until=nullptr)
Replaces all uses of OldPred with the NewPred block in all PHINodes in a block.
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1777
LLVM_ABI TinyPtrVector< DbgVariableRecord * > findDVRDeclares(Value *V)
Finds dbg.declare records declaring local variables as living in the memory that 'V' points to.
Definition: DebugInfo.cpp:48
auto predecessors(const MachineBasicBlock *BB)
LLVM_ABI void setUnwindEdgeTo(Instruction *TI, BasicBlock *Succ)
Sets the unwind edge of an instruction to a particular successor.
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
LLVM_ABI void findDbgUsers(Value *V, SmallVectorImpl< DbgVariableRecord * > &DbgVariableRecords)
Finds the debug info records describing a value.
Definition: DebugInfo.cpp:129
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
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition: Alignment.h:117
Align Alignment
The required alignment of this field.
uint64_t Offset
The offset of this field in the final layout.
uint64_t Size
The required size of this field in bytes.
static constexpr uint64_t FlexibleOffset
A special value for Offset indicating that the field can be moved anywhere.
A MapVector that performs no allocations if smaller than a certain size.
Definition: MapVector.h:249
AsyncLoweringStorage AsyncLowering
Definition: CoroShape.h:155
StructType * FrameTy
Definition: CoroShape.h:114
AnyCoroIdRetconInst * getRetconCoroId() const
Definition: CoroShape.h:163
CoroIdInst * getSwitchCoroId() const
Definition: CoroShape.h:158
coro::ABI ABI
Definition: CoroShape.h:112
Value * FramePtr
Definition: CoroShape.h:117
SmallVector< AnyCoroSuspendInst *, 4 > CoroSuspends
Definition: CoroShape.h:58
uint64_t FrameSize
Definition: CoroShape.h:116
AllocaInst * getPromiseAlloca() const
Definition: CoroShape.h:244
SwitchLoweringStorage SwitchLowering
Definition: CoroShape.h:153
CoroBeginInst * CoroBegin
Definition: CoroShape.h:54
BasicBlock::iterator getInsertPtAfterFramePtr() const
Definition: CoroShape.h:250
RetconLoweringStorage RetconLowering
Definition: CoroShape.h:154
SmallVector< AnyCoroEndInst *, 4 > CoroEnds
Definition: CoroShape.h:55
SmallVector< CallInst *, 2 > SwiftErrorOps
Definition: CoroShape.h:63
BasicBlock * AllocaSpillBlock
Definition: CoroShape.h:118