clang 24.0.0git
CGStmt.cpp
Go to the documentation of this file.
1//===--- CGStmt.cpp - Emit LLVM Code from Statements ----------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This contains code to emit Stmt nodes as LLVM code.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CGDebugInfo.h"
14#include "CGOpenMPRuntime.h"
15#include "CodeGenFunction.h"
16#include "CodeGenModule.h"
17#include "CodeGenPGO.h"
18#include "TargetInfo.h"
19#include "clang/AST/Attr.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/Stmt.h"
22#include "clang/AST/StmtSYCL.h"
31#include "llvm/ADT/ArrayRef.h"
32#include "llvm/ADT/DenseMap.h"
33#include "llvm/ADT/SmallSet.h"
34#include "llvm/ADT/StringExtras.h"
35#include "llvm/IR/Assumptions.h"
36#include "llvm/IR/DataLayout.h"
37#include "llvm/IR/InlineAsm.h"
38#include "llvm/IR/Intrinsics.h"
39#include "llvm/IR/MDBuilder.h"
40#include "llvm/Support/SaveAndRestore.h"
41#include <optional>
42
43using namespace clang;
44using namespace CodeGen;
45
46//===----------------------------------------------------------------------===//
47// Statement Emission
48//===----------------------------------------------------------------------===//
49
51 if (CGDebugInfo *DI = getDebugInfo()) {
53 Loc = S->getBeginLoc();
54 DI->EmitLocation(Builder, Loc);
55
56 LastStopPoint = Loc;
57 }
58}
59
61 assert(S && "Null statement?");
62 PGO->setCurrentStmt(S);
63
64 // These statements have their own debug info handling.
65 if (EmitSimpleStmt(S, Attrs))
66 return;
67
68 // Check if we are generating unreachable code.
69 if (!HaveInsertPoint()) {
70 // If so, and the statement doesn't contain a label, then we do not need to
71 // generate actual code. This is safe because (1) the current point is
72 // unreachable, so we don't need to execute the code, and (2) we've already
73 // handled the statements which update internal data structures (like the
74 // local variable map) which could be used by subsequent statements.
75 if (!ContainsLabel(S)) {
76 // Verify that any decl statements were handled as simple, they may be in
77 // scope of subsequent reachable statements.
78 assert(!isa<DeclStmt>(*S) && "Unexpected DeclStmt!");
79 PGO->markStmtMaybeUsed(S);
80 return;
81 }
82
83 // Otherwise, make a new block to hold the code.
85 }
86
87 // Generate a stoppoint if we are emitting debug info.
89
90 // Ignore all OpenMP directives except for simd if OpenMP with Simd is
91 // enabled.
92 if (getLangOpts().OpenMP && getLangOpts().OpenMPSimd) {
93 if (const auto *D = dyn_cast<OMPExecutableDirective>(S)) {
95 return;
96 }
97 }
98
99 switch (S->getStmtClass()) {
101 case Stmt::CXXCatchStmtClass:
102 case Stmt::SEHExceptStmtClass:
103 case Stmt::SEHFinallyStmtClass:
104 case Stmt::MSDependentExistsStmtClass:
105 case Stmt::UnresolvedSYCLKernelCallStmtClass:
106 llvm_unreachable("invalid statement class to emit generically");
107 case Stmt::NullStmtClass:
108 case Stmt::CompoundStmtClass:
109 case Stmt::DeclStmtClass:
110 case Stmt::LabelStmtClass:
111 case Stmt::AttributedStmtClass:
112 case Stmt::GotoStmtClass:
113 case Stmt::BreakStmtClass:
114 case Stmt::ContinueStmtClass:
115 case Stmt::DefaultStmtClass:
116 case Stmt::CaseStmtClass:
117 case Stmt::DeferStmtClass:
118 case Stmt::SEHLeaveStmtClass:
119 case Stmt::SYCLKernelCallStmtClass:
120 llvm_unreachable("should have emitted these statements as simple");
121
122#define STMT(Type, Base)
123#define ABSTRACT_STMT(Op)
124#define EXPR(Type, Base) \
125 case Stmt::Type##Class:
126#include "clang/AST/StmtNodes.inc"
127 {
128 // Remember the block we came in on.
129 llvm::BasicBlock *incoming = Builder.GetInsertBlock();
130 assert(incoming && "expression emission must have an insertion point");
131
133
134 llvm::BasicBlock *outgoing = Builder.GetInsertBlock();
135 assert(outgoing && "expression emission cleared block!");
136
137 // The expression emitters assume (reasonably!) that the insertion
138 // point is always set. To maintain that, the call-emission code
139 // for noreturn functions has to enter a new block with no
140 // predecessors. We want to kill that block and mark the current
141 // insertion point unreachable in the common case of a call like
142 // "exit();". Since expression emission doesn't otherwise create
143 // blocks with no predecessors, we can just test for that.
144 // However, we must be careful not to do this to our incoming
145 // block, because *statement* emission does sometimes create
146 // reachable blocks which will have no predecessors until later in
147 // the function. This occurs with, e.g., labels that are not
148 // reachable by fallthrough.
149 if (incoming != outgoing && outgoing->use_empty()) {
150 outgoing->eraseFromParent();
151 Builder.ClearInsertionPoint();
152 }
153 break;
154 }
155
156 case Stmt::IndirectGotoStmtClass:
158
159 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
160 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S), Attrs); break;
161 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S), Attrs); break;
162 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S), Attrs); break;
163
164 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
165
166 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
167 case Stmt::GCCAsmStmtClass: // Intentional fall-through.
168 case Stmt::MSAsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
169 case Stmt::CoroutineBodyStmtClass:
171 break;
172 case Stmt::CoreturnStmtClass:
174 break;
175 case Stmt::CapturedStmtClass: {
176 const CapturedStmt *CS = cast<CapturedStmt>(S);
178 }
179 break;
180 case Stmt::ObjCAtTryStmtClass:
182 break;
183 case Stmt::ObjCAtCatchStmtClass:
184 llvm_unreachable(
185 "@catch statements should be handled by EmitObjCAtTryStmt");
186 case Stmt::ObjCAtFinallyStmtClass:
187 llvm_unreachable(
188 "@finally statements should be handled by EmitObjCAtTryStmt");
189 case Stmt::ObjCAtThrowStmtClass:
191 break;
192 case Stmt::ObjCAtSynchronizedStmtClass:
194 break;
195 case Stmt::ObjCForCollectionStmtClass:
197 break;
198 case Stmt::ObjCAutoreleasePoolStmtClass:
200 break;
201
202 case Stmt::CXXTryStmtClass:
204 break;
205 case Stmt::CXXForRangeStmtClass:
207 break;
208 case Stmt::CXXExpansionStmtPatternClass:
209 llvm_unreachable("unexpanded expansion statements should not be emitted");
210 case Stmt::CXXExpansionStmtInstantiationClass:
212 break;
213 case Stmt::SEHTryStmtClass:
215 break;
216 case Stmt::OMPMetaDirectiveClass:
218 break;
219 case Stmt::OMPCanonicalLoopClass:
221 break;
222 case Stmt::OMPParallelDirectiveClass:
224 break;
225 case Stmt::OMPSimdDirectiveClass:
227 break;
228 case Stmt::OMPTileDirectiveClass:
230 break;
231 case Stmt::OMPStripeDirectiveClass:
233 break;
234 case Stmt::OMPUnrollDirectiveClass:
236 break;
237 case Stmt::OMPReverseDirectiveClass:
239 break;
240 case Stmt::OMPSplitDirectiveClass:
242 break;
243 case Stmt::OMPInterchangeDirectiveClass:
245 break;
246 case Stmt::OMPFlattenDirectiveClass:
248 break;
249 case Stmt::OMPFuseDirectiveClass:
251 break;
252 case Stmt::OMPForDirectiveClass:
254 break;
255 case Stmt::OMPForSimdDirectiveClass:
257 break;
258 case Stmt::OMPSectionsDirectiveClass:
260 break;
261 case Stmt::OMPSectionDirectiveClass:
263 break;
264 case Stmt::OMPSingleDirectiveClass:
266 break;
267 case Stmt::OMPMasterDirectiveClass:
269 break;
270 case Stmt::OMPCriticalDirectiveClass:
272 break;
273 case Stmt::OMPParallelForDirectiveClass:
275 break;
276 case Stmt::OMPParallelForSimdDirectiveClass:
278 break;
279 case Stmt::OMPParallelMasterDirectiveClass:
281 break;
282 case Stmt::OMPParallelSectionsDirectiveClass:
284 break;
285 case Stmt::OMPTaskDirectiveClass:
287 break;
288 case Stmt::OMPTaskyieldDirectiveClass:
290 break;
291 case Stmt::OMPErrorDirectiveClass:
293 break;
294 case Stmt::OMPBarrierDirectiveClass:
296 break;
297 case Stmt::OMPTaskwaitDirectiveClass:
299 break;
300 case Stmt::OMPTaskgroupDirectiveClass:
302 break;
303 case Stmt::OMPFlushDirectiveClass:
305 break;
306 case Stmt::OMPDepobjDirectiveClass:
308 break;
309 case Stmt::OMPScanDirectiveClass:
311 break;
312 case Stmt::OMPOrderedStandaloneDirectiveClass:
314 break;
315 case Stmt::OMPOrderedBlockAssocDirectiveClass:
317 break;
318 case Stmt::OMPAtomicDirectiveClass:
320 break;
321 case Stmt::OMPTargetDirectiveClass:
323 break;
324 case Stmt::OMPTeamsDirectiveClass:
326 break;
327 case Stmt::OMPCancellationPointDirectiveClass:
329 break;
330 case Stmt::OMPCancelDirectiveClass:
332 break;
333 case Stmt::OMPTargetDataDirectiveClass:
335 break;
336 case Stmt::OMPTargetEnterDataDirectiveClass:
338 break;
339 case Stmt::OMPTargetExitDataDirectiveClass:
341 break;
342 case Stmt::OMPTargetParallelDirectiveClass:
344 break;
345 case Stmt::OMPTargetParallelForDirectiveClass:
347 break;
348 case Stmt::OMPTaskLoopDirectiveClass:
350 break;
351 case Stmt::OMPTaskLoopSimdDirectiveClass:
353 break;
354 case Stmt::OMPMasterTaskLoopDirectiveClass:
356 break;
357 case Stmt::OMPMaskedTaskLoopDirectiveClass:
359 break;
360 case Stmt::OMPMasterTaskLoopSimdDirectiveClass:
363 break;
364 case Stmt::OMPMaskedTaskLoopSimdDirectiveClass:
367 break;
368 case Stmt::OMPParallelMasterTaskLoopDirectiveClass:
371 break;
372 case Stmt::OMPParallelMaskedTaskLoopDirectiveClass:
375 break;
376 case Stmt::OMPParallelMasterTaskLoopSimdDirectiveClass:
379 break;
380 case Stmt::OMPParallelMaskedTaskLoopSimdDirectiveClass:
383 break;
384 case Stmt::OMPDistributeDirectiveClass:
386 break;
387 case Stmt::OMPTargetUpdateDirectiveClass:
389 break;
390 case Stmt::OMPDistributeParallelForDirectiveClass:
393 break;
394 case Stmt::OMPDistributeParallelForSimdDirectiveClass:
397 break;
398 case Stmt::OMPDistributeSimdDirectiveClass:
400 break;
401 case Stmt::OMPTargetParallelForSimdDirectiveClass:
404 break;
405 case Stmt::OMPTargetSimdDirectiveClass:
407 break;
408 case Stmt::OMPTeamsDistributeDirectiveClass:
410 break;
411 case Stmt::OMPTeamsDistributeSimdDirectiveClass:
414 break;
415 case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass:
418 break;
419 case Stmt::OMPTeamsDistributeParallelForDirectiveClass:
422 break;
423 case Stmt::OMPTargetTeamsDirectiveClass:
425 break;
426 case Stmt::OMPTargetTeamsDistributeDirectiveClass:
429 break;
430 case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass:
433 break;
434 case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass:
437 break;
438 case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass:
441 break;
442 case Stmt::OMPInteropDirectiveClass:
444 break;
445 case Stmt::OMPDispatchDirectiveClass:
446 CGM.ErrorUnsupported(S, "OpenMP dispatch directive");
447 break;
448 case Stmt::OMPScopeDirectiveClass:
450 break;
451 case Stmt::OMPMaskedDirectiveClass:
453 break;
454 case Stmt::OMPGenericLoopDirectiveClass:
456 break;
457 case Stmt::OMPTeamsGenericLoopDirectiveClass:
459 break;
460 case Stmt::OMPTargetTeamsGenericLoopDirectiveClass:
463 break;
464 case Stmt::OMPParallelGenericLoopDirectiveClass:
467 break;
468 case Stmt::OMPTargetParallelGenericLoopDirectiveClass:
471 break;
472 case Stmt::OMPTargetGenericLoopDirectiveClass:
474 break;
475 case Stmt::OMPParallelMaskedDirectiveClass:
477 break;
478 case Stmt::OMPAssumeDirectiveClass:
480 break;
481 case Stmt::OpenACCComputeConstructClass:
483 break;
484 case Stmt::OpenACCLoopConstructClass:
486 break;
487 case Stmt::OpenACCCombinedConstructClass:
489 break;
490 case Stmt::OpenACCDataConstructClass:
492 break;
493 case Stmt::OpenACCEnterDataConstructClass:
495 break;
496 case Stmt::OpenACCExitDataConstructClass:
498 break;
499 case Stmt::OpenACCHostDataConstructClass:
501 break;
502 case Stmt::OpenACCWaitConstructClass:
504 break;
505 case Stmt::OpenACCInitConstructClass:
507 break;
508 case Stmt::OpenACCShutdownConstructClass:
510 break;
511 case Stmt::OpenACCSetConstructClass:
513 break;
514 case Stmt::OpenACCUpdateConstructClass:
516 break;
517 case Stmt::OpenACCAtomicConstructClass:
519 break;
520 case Stmt::OpenACCCacheConstructClass:
522 break;
523 }
524}
525
528 switch (S->getStmtClass()) {
529 default:
530 return false;
531 case Stmt::NullStmtClass:
532 break;
533 case Stmt::CompoundStmtClass:
535 break;
536 case Stmt::DeclStmtClass:
538 break;
539 case Stmt::LabelStmtClass:
541 break;
542 case Stmt::AttributedStmtClass:
544 break;
545 case Stmt::GotoStmtClass:
547 break;
548 case Stmt::BreakStmtClass:
550 break;
551 case Stmt::ContinueStmtClass:
553 break;
554 case Stmt::DefaultStmtClass:
556 break;
557 case Stmt::CaseStmtClass:
558 EmitCaseStmt(cast<CaseStmt>(*S), Attrs);
559 break;
560 case Stmt::DeferStmtClass:
562 break;
563 case Stmt::SEHLeaveStmtClass:
565 break;
566 case Stmt::SYCLKernelCallStmtClass:
568 break;
569 }
570 return true;
571}
572
573/// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
574/// this captures the expression result of the last sub-statement and returns it
575/// (for use by the statement expression extension).
577 AggValueSlot AggSlot) {
578 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(),
579 "LLVM IR generation of compound statement ('{}')");
580
581 // Keep track of the current cleanup stack depth, including debug scopes.
583
584 return EmitCompoundStmtWithoutScope(S, GetLast, AggSlot);
585}
586
589 bool GetLast,
590 AggValueSlot AggSlot) {
591
593 E = S.body_end() - GetLast;
594 I != E; ++I)
595 EmitStmt(*I);
596
597 Address RetAlloca = Address::invalid();
598 if (GetLast) {
599 // We have to special case labels here. They are statements, but when put
600 // at the end of a statement expression, they yield the value of their
601 // subexpression. Handle this by walking through all labels we encounter,
602 // emitting them before we evaluate the subexpr.
603 // Similar issues arise for attributed statements.
604 const Stmt *LastStmt = S.body_back();
605 while (!isa<Expr>(LastStmt)) {
606 if (const auto *LS = dyn_cast<LabelStmt>(LastStmt)) {
607 EmitLabel(LS->getDecl());
608 LastStmt = LS->getSubStmt();
609 } else if (const auto *AS = dyn_cast<AttributedStmt>(LastStmt)) {
610 // FIXME: Update this if we ever have attributes that affect the
611 // semantics of an expression.
612 LastStmt = AS->getSubStmt();
613 } else {
614 llvm_unreachable("unknown value statement");
615 }
616 }
617
619
620 const Expr *E = cast<Expr>(LastStmt);
621 QualType ExprTy = E->getType();
622 if (hasAggregateEvaluationKind(ExprTy)) {
623 EmitAggExpr(E, AggSlot);
624 } else {
625 // We can't return an RValue here because there might be cleanups at
626 // the end of the StmtExpr. Because of that, we have to emit the result
627 // here into a temporary alloca.
628 RetAlloca = CreateMemTempWithoutCast(ExprTy);
629 EmitAnyExprToMem(E, RetAlloca, Qualifiers(),
630 /*IsInit*/ false);
631 }
632 }
633
634 return RetAlloca;
635}
636
638 llvm::UncondBrInst *BI = dyn_cast<llvm::UncondBrInst>(BB->getTerminator());
639
640 // If there is a cleanup stack, then we it isn't worth trying to
641 // simplify this block (we would need to remove it from the scope map
642 // and cleanup entry).
643 if (!EHStack.empty())
644 return;
645
646 // Can only simplify direct branches.
647 if (!BI)
648 return;
649
650 // Can only simplify empty blocks.
651 if (BI->getIterator() != BB->begin())
652 return;
653
654 BB->replaceAllUsesWith(BI->getSuccessor());
655 BI->eraseFromParent();
656 BB->eraseFromParent();
657}
658
659void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
660 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
661
662 // Fall out of the current block (if necessary).
663 EmitBranch(BB);
664
665 if (IsFinished && BB->use_empty()) {
666 delete BB;
667 return;
668 }
669
670 // Place the block after the current block, if possible, or else at
671 // the end of the function.
672 if (CurBB && CurBB->getParent())
673 CurFn->insert(std::next(CurBB->getIterator()), BB);
674 else
675 CurFn->insert(CurFn->end(), BB);
676 Builder.SetInsertPoint(BB);
677}
678
679void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
680 // Emit a branch from the current block to the target one if this
681 // was a real block. If this was just a fall-through block after a
682 // terminator, don't emit it.
683 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
684
685 if (!CurBB || CurBB->hasTerminator()) {
686 // If there is no insert point or the previous block is already
687 // terminated, don't touch it.
688 } else {
689 // Otherwise, create a fall-through branch.
690 Builder.CreateBr(Target);
691 }
692
693 Builder.ClearInsertionPoint();
694}
695
696void CodeGenFunction::EmitBlockAfterUses(llvm::BasicBlock *block) {
697 bool inserted = false;
698 for (llvm::User *u : block->users()) {
699 if (llvm::Instruction *insn = dyn_cast<llvm::Instruction>(u)) {
700 CurFn->insert(std::next(insn->getParent()->getIterator()), block);
701 inserted = true;
702 break;
703 }
704 }
705
706 if (!inserted)
707 CurFn->insert(CurFn->end(), block);
708
709 Builder.SetInsertPoint(block);
710}
711
714 JumpDest &Dest = LabelMap[D];
715 if (Dest.isValid()) return Dest;
716
717 // Create, but don't insert, the new block.
718 Dest = JumpDest(createBasicBlock(D->getName()),
721 return Dest;
722}
723
725 // Add this label to the current lexical scope if we're within any
726 // normal cleanups. Jumps "in" to this label --- when permitted by
727 // the language --- may need to be routed around such cleanups.
728 if (EHStack.hasNormalCleanups() && CurLexicalScope)
729 CurLexicalScope->addLabel(D);
730
731 JumpDest &Dest = LabelMap[D];
732
733 // If we didn't need a forward reference to this label, just go
734 // ahead and create a destination at the current scope.
735 if (!Dest.isValid()) {
737
738 // Otherwise, we need to give this label a target depth and remove
739 // it from the branch-fixups list.
740 } else {
741 assert(!Dest.getScopeDepth().isValid() && "already emitted label!");
742 Dest.setScopeDepth(EHStack.stable_begin());
744 }
745
746 EmitBlock(Dest.getBlock());
747
748 // Emit debug info for labels.
749 if (CGDebugInfo *DI = getDebugInfo()) {
750 if (CGM.getCodeGenOpts().hasReducedDebugInfo()) {
751 DI->setLocation(D->getLocation());
752 DI->EmitLabel(D, Builder);
753 }
754 }
755
757}
758
759/// Change the cleanup scope of the labels in this lexical scope to
760/// match the scope of the enclosing context.
762 assert(!Labels.empty());
763 EHScopeStack::stable_iterator innermostScope
764 = CGF.EHStack.getInnermostNormalCleanup();
765
766 // Change the scope depth of all the labels.
767 for (const LabelDecl *Label : Labels) {
768 assert(CGF.LabelMap.count(Label));
769 JumpDest &dest = CGF.LabelMap.find(Label)->second;
770 assert(dest.getScopeDepth().isValid());
771 assert(innermostScope.encloses(dest.getScopeDepth()));
772 dest.setScopeDepth(innermostScope);
773 }
774
775 // Reparent the labels if the new scope also has cleanups.
776 if (innermostScope != EHScopeStack::stable_end() && ParentScope) {
777 ParentScope->Labels.append(Labels.begin(), Labels.end());
778 }
779}
780
781
783 EmitLabel(S.getDecl());
784
785 // IsEHa - emit eha.scope.begin if it's a side entry of a scope
786 if (getLangOpts().EHAsynch && S.isSideEntry())
788
789 EmitStmt(S.getSubStmt());
790}
791
793 bool nomerge = InNoMergeAttributedStmt;
794 bool noinline = InNoInlineAttributedStmt;
795 bool alwaysinline = InAlwaysInlineAttributedStmt;
796 bool noconvergent = InNoConvergentAttributedStmt;
797 StringRef amdgpuAVMode = AMDGPUAvailableVisibleMode;
798 HLSLControlFlowHintAttr::Spelling flattenOrBranch = HLSLControlFlowAttr;
799 const CallExpr *musttail = MustTailCall;
800 const AtomicAttr *AA = nullptr;
801
802 for (const auto *A : S.getAttrs()) {
803 switch (A->getKind()) {
804 default:
805 break;
806 case attr::NoMerge:
807 nomerge = true;
808 break;
809 case attr::NoInline:
810 noinline = true;
811 alwaysinline = false;
812 break;
813 case attr::AlwaysInline:
814 alwaysinline = true;
815 noinline = false;
816 break;
817 case attr::NoConvergent:
818 noconvergent = true;
819 break;
820 case attr::MustTail: {
821 const Stmt *Sub = S.getSubStmt();
822 const ReturnStmt *R = cast<ReturnStmt>(Sub);
823 musttail = cast<CallExpr>(R->getRetValue()->IgnoreParens());
824 } break;
825 case attr::CXXAssume: {
826 const Expr *Assumption = cast<CXXAssumeAttr>(A)->getAssumption();
827 if (getLangOpts().CXXAssumptions && Builder.GetInsertBlock() &&
828 !Assumption->HasSideEffects(getContext())) {
829 llvm::Value *AssumptionVal = EmitCheckedArgForAssume(Assumption);
830 Builder.CreateAssumption(AssumptionVal);
831 }
832 } break;
833 case attr::Atomic:
834 AA = cast<AtomicAttr>(A);
835 break;
836 case attr::AMDGPUAvailableVisible:
837 amdgpuAVMode = cast<AMDGPUAvailableVisibleAttr>(A)->getMode();
838 break;
839 case attr::HLSLControlFlowHint: {
840 flattenOrBranch = cast<HLSLControlFlowHintAttr>(A)->getSemanticSpelling();
841 } break;
842 }
843 }
844
845 assert(!(alwaysinline && noinline) &&
846 "alwaysinline and noinline are mutually exclusive");
847
848 SaveAndRestore save_nomerge(InNoMergeAttributedStmt, nomerge);
849 SaveAndRestore save_noinline(InNoInlineAttributedStmt, noinline);
850 SaveAndRestore save_alwaysinline(InAlwaysInlineAttributedStmt, alwaysinline);
851 SaveAndRestore save_noconvergent(InNoConvergentAttributedStmt, noconvergent);
852 SaveAndRestore save_amdgpuav(AMDGPUAvailableVisibleMode, amdgpuAVMode);
853 SaveAndRestore save_musttail(MustTailCall, musttail);
854 SaveAndRestore save_flattenOrBranch(HLSLControlFlowAttr, flattenOrBranch);
855 CGAtomicOptionsRAII AORAII(CGM, AA);
856 EmitStmt(S.getSubStmt(), S.getAttrs());
857}
858
860 // If this code is reachable then emit a stop point (if generating
861 // debug info). We have to do this ourselves because we are on the
862 // "simple" statement path.
863 if (HaveInsertPoint())
864 EmitStopPoint(&S);
865
866 // Reinitialize the variables this goto bypasses, whose scope it re-enters.
867 // Backward gotos reinit here while forward gotos are recorded for
868 // EmitAutoVarAlloca to patch once the alloca exists. Skip when jump sources
869 // are unknown (computed goto); EmitAutoVarAlloca then uses function-scope
870 // init.
871 if (HaveInsertPoint() && !Bypasses.isAlwaysBypassed()) {
873 BypassingForwardJumps.push_back({Builder.GetInsertBlock(), &S});
874 }
875
878}
879
880
883 if (const LabelDecl *Target = S.getConstantTarget()) {
885 return;
886 }
887
888 // Ensure that we have an i8* for our PHI node.
889 llvm::Value *V = Builder.CreateBitCast(EmitScalarExpr(S.getTarget()),
890 Int8PtrTy, "addr");
891 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
892
893 // Get the basic block for the indirect goto.
894 llvm::BasicBlock *IndGotoBB = GetIndirectGotoBlock();
895
896 // The first instruction in the block has to be the PHI for the switch dest,
897 // add an entry for this branch.
898 cast<llvm::PHINode>(IndGotoBB->begin())->addIncoming(V, CurBB);
899
900 EmitBranch(IndGotoBB);
901 if (CurBB && CurBB->hasTerminator())
902 addInstToCurrentSourceAtom(CurBB->getTerminator(), nullptr);
903}
904
906 const Stmt *Else = S.getElse();
907
908 // The else branch of a consteval if statement is always the only branch that
909 // can be runtime evaluated.
910 if (S.isConsteval()) {
911 const Stmt *Executed = S.isNegatedConsteval() ? S.getThen() : Else;
912 if (Executed) {
913 RunCleanupsScope ExecutedScope(*this);
914 EmitStmt(Executed);
915 }
916 return;
917 }
918
919 // C99 6.8.4.1: The first substatement is executed if the expression compares
920 // unequal to 0. The condition must be a scalar type.
921 LexicalScope ConditionScope(*this, S.getCond()->getSourceRange());
922 ApplyDebugLocation DL(*this, S.getCond());
923
924 if (S.getInit()) {
925 EmitStmt(S.getInit());
926
927 // The init statement may have cleared the insertion point (e.g. it ended in
928 // a 'noreturn' call); the condition emitted below needs a valid one.
930 }
931
932 if (S.getConditionVariable())
934
935 // If the condition constant folds and can be elided, try to avoid emitting
936 // the condition and the dead arm of the if/else.
937 bool CondConstant;
938 if (ConstantFoldsToSimpleInteger(S.getCond(), CondConstant,
939 S.isConstexpr())) {
940 // Figure out which block (then or else) is executed.
941 const Stmt *Executed = S.getThen();
942 const Stmt *Skipped = Else;
943 if (!CondConstant) // Condition false?
944 std::swap(Executed, Skipped);
945
946 // If the skipped block has no labels in it, just emit the executed block.
947 // This avoids emitting dead code and simplifies the CFG substantially.
948 if (S.isConstexpr() || !ContainsLabel(Skipped)) {
950 /*UseBoth=*/true);
951 if (Executed) {
953 RunCleanupsScope ExecutedScope(*this);
954 EmitStmt(Executed);
955 }
956 PGO->markStmtMaybeUsed(Skipped);
957 return;
958 }
959 }
960
961 auto HasSkip = hasSkipCounter(&S);
962
963 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
964 // the conditional branch.
965 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
966 llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
967 llvm::BasicBlock *ElseBlock =
968 (Else || HasSkip ? createBasicBlock("if.else") : ContBlock);
969 // Prefer the PGO based weights over the likelihood attribute.
970 // When the build isn't optimized the metadata isn't used, so don't generate
971 // it.
972 // Also, differentiate between disabled PGO and a never executed branch with
973 // PGO. Assuming PGO is in use:
974 // - we want to ignore the [[likely]] attribute if the branch is never
975 // executed,
976 // - assuming the profile is poor, preserving the attribute may still be
977 // beneficial.
978 // As an approximation, preserve the attribute only if both the branch and the
979 // parent context were not executed.
981 uint64_t ThenCount = getProfileCount(S.getThen());
982 if (!ThenCount && !getCurrentProfileCount() &&
983 CGM.getCodeGenOpts().OptimizationLevel)
984 LH = Stmt::getLikelihood(S.getThen(), Else);
985
986 // When measuring MC/DC, always fully evaluate the condition up front using
987 // EvaluateExprAsBool() so that the test vector bitmap can be updated prior to
988 // executing the body of the if.then or if.else. This is useful for when
989 // there is a 'return' within the body, but this is particularly beneficial
990 // when one if-stmt is nested within another if-stmt so that all of the MC/DC
991 // updates are kept linear and consistent.
992 if (!CGM.getCodeGenOpts().MCDCCoverage) {
993 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock, ThenCount, LH,
994 /*ConditionalOp=*/nullptr,
995 /*ConditionalDecl=*/S.getConditionVariable());
996 } else {
997 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
999 Builder.CreateCondBr(BoolCondVal, ThenBlock, ElseBlock);
1000 }
1001
1002 // Emit the 'then' code.
1003 EmitBlock(ThenBlock);
1005 {
1006 RunCleanupsScope ThenScope(*this);
1007 EmitStmt(S.getThen());
1008 }
1009 EmitBranch(ContBlock);
1010
1011 // Emit the 'else' code if present.
1012 if (Else) {
1013 {
1014 // There is no need to emit line number for an unconditional branch.
1015 auto NL = ApplyDebugLocation::CreateEmpty(*this);
1016 EmitBlock(ElseBlock);
1017 }
1018 // Add a counter to else block unless it has CounterExpr.
1019 if (HasSkip)
1021 {
1022 RunCleanupsScope ElseScope(*this);
1023 EmitStmt(Else);
1024 }
1025 {
1026 // There is no need to emit line number for an unconditional branch.
1027 auto NL = ApplyDebugLocation::CreateEmpty(*this);
1028 EmitBranch(ContBlock);
1029 }
1030 } else if (HasSkip) {
1031 EmitBlock(ElseBlock);
1033 EmitBranch(ContBlock);
1034 }
1035
1036 // Emit the continuation block for code after the if.
1037 EmitBlock(ContBlock, true);
1038}
1039
1040bool CodeGenFunction::checkIfLoopMustProgress(const Expr *ControllingExpression,
1041 bool HasEmptyBody) {
1043 getLangOpts(), CGM.getCodeGenOpts(), getContext(), ControllingExpression,
1044 HasEmptyBody,
1045 [this] { CurFn->removeFnAttr(llvm::Attribute::MustProgress); });
1046}
1047
1049 ArrayRef<const Attr *> WhileAttrs) {
1050 // Emit the header for the loop, which will also become
1051 // the continue target.
1052 JumpDest LoopHeader = getJumpDestInCurrentScope("while.cond");
1053 EmitBlock(LoopHeader.getBlock());
1054
1055 if (CGM.shouldEmitConvergenceTokens())
1056 ConvergenceTokenStack.push_back(
1057 emitConvergenceLoopToken(LoopHeader.getBlock()));
1058
1059 // Create an exit block for when the condition fails, which will
1060 // also become the break target.
1062
1063 // Store the blocks to use for break and continue.
1064 BreakContinueStack.push_back(BreakContinue(S, LoopExit, LoopHeader));
1065
1066 // C++ [stmt.while]p2:
1067 // When the condition of a while statement is a declaration, the
1068 // scope of the variable that is declared extends from its point
1069 // of declaration (3.3.2) to the end of the while statement.
1070 // [...]
1071 // The object created in a condition is destroyed and created
1072 // with each iteration of the loop.
1073 RunCleanupsScope ConditionScope(*this);
1074
1075 if (S.getConditionVariable())
1077
1078 // Evaluate the conditional in the while header. C99 6.8.5.1: The
1079 // evaluation of the controlling expression takes place before each
1080 // execution of the loop body.
1081 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
1082
1084
1085 // while(1) is common, avoid extra exit blocks. Be sure
1086 // to correctly handle break/continue though.
1087 llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal);
1088 bool EmitBoolCondBranch = !C || !C->isOne();
1089 const SourceRange &R = S.getSourceRange();
1090 LoopStack.push(
1091 LoopHeader.getBlock(), CGM.getContext(), CGM.getCodeGenOpts(), WhileAttrs,
1092 SourceLocToDebugLoc(R.getBegin()), SourceLocToDebugLoc(R.getEnd()),
1094
1095 // As long as the condition is true, go to the loop body.
1096 llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
1097 if (EmitBoolCondBranch) {
1098 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
1099 if (hasSkipCounter(&S) || ConditionScope.requiresCleanups())
1100 ExitBlock = createBasicBlock("while.exit");
1101 llvm::MDNode *Weights =
1102 createProfileWeightsForLoop(S.getCond(), getProfileCount(S.getBody()));
1103 if (!Weights && CGM.getCodeGenOpts().OptimizationLevel)
1104 BoolCondVal = emitCondLikelihoodViaExpectIntrinsic(
1105 BoolCondVal, Stmt::getLikelihood(S.getBody()));
1106 auto *I = Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock, Weights);
1107 // Key Instructions: Emit the condition and branch as separate source
1108 // location atoms otherwise we may omit a step onto the loop condition in
1109 // favour of the `while` keyword.
1110 // FIXME: We could have the branch as the backup location for the condition,
1111 // which would probably be a better experience. Explore this later.
1112 if (auto *CondI = dyn_cast<llvm::Instruction>(BoolCondVal))
1113 addInstToNewSourceAtom(CondI, nullptr);
1114 addInstToNewSourceAtom(I, nullptr);
1115
1116 if (ExitBlock != LoopExit.getBlock()) {
1117 EmitBlock(ExitBlock);
1120 }
1121 } else if (const Attr *A = Stmt::getLikelihoodAttr(S.getBody())) {
1122 CGM.getDiags().Report(A->getLocation(),
1123 diag::warn_attribute_has_no_effect_on_infinite_loop)
1124 << A << A->getRange();
1125 CGM.getDiags().Report(
1126 S.getWhileLoc(),
1127 diag::note_attribute_has_no_effect_on_infinite_loop_here)
1129 }
1130
1131 // Emit the loop body. We have to emit this in a cleanup scope
1132 // because it might be a singleton DeclStmt.
1133 {
1134 RunCleanupsScope BodyScope(*this);
1135 EmitBlock(LoopBody);
1137 EmitStmt(S.getBody());
1138 }
1139
1140 BreakContinueStack.pop_back();
1141
1142 // Immediately force cleanup.
1143 ConditionScope.ForceCleanup();
1144
1145 EmitStopPoint(&S);
1146 // Branch to the loop header again.
1147 EmitBranch(LoopHeader.getBlock());
1148
1149 LoopStack.pop();
1150
1151 // Emit the exit block.
1152 EmitBlock(LoopExit.getBlock(), true);
1153
1154 // The LoopHeader typically is just a branch if we skipped emitting
1155 // a branch, try to erase it.
1156 if (!EmitBoolCondBranch) {
1157 SimplifyForwardingBlocks(LoopHeader.getBlock());
1158 PGO->markStmtAsUsed(true, &S);
1159 }
1160
1161 if (CGM.shouldEmitConvergenceTokens())
1162 ConvergenceTokenStack.pop_back();
1163}
1164
1166 ArrayRef<const Attr *> DoAttrs) {
1168 JumpDest LoopCond = getJumpDestInCurrentScope("do.cond");
1169
1170 uint64_t ParentCount = getCurrentProfileCount();
1171
1172 // Store the blocks to use for break and continue.
1173 BreakContinueStack.push_back(BreakContinue(S, LoopExit, LoopCond));
1174
1175 // Emit the body of the loop.
1176 llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
1177
1178 EmitBlockWithFallThrough(LoopBody, &S);
1179
1180 if (CGM.shouldEmitConvergenceTokens())
1182
1183 {
1184 RunCleanupsScope BodyScope(*this);
1185 EmitStmt(S.getBody());
1186 }
1187
1188 EmitBlock(LoopCond.getBlock());
1189
1190 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
1191 // after each execution of the loop body."
1192
1193 // Evaluate the conditional in the while header.
1194 // C99 6.8.5p2/p4: The first substatement is executed if the expression
1195 // compares unequal to 0. The condition must be a scalar type.
1196 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
1197
1198 BreakContinueStack.pop_back();
1199
1200 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
1201 // to correctly handle break/continue though.
1202 llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal);
1203 bool EmitBoolCondBranch = !C || !C->isZero();
1204
1205 const SourceRange &R = S.getSourceRange();
1206 LoopStack.push(
1207 LoopBody, CGM.getContext(), CGM.getCodeGenOpts(), DoAttrs,
1208 SourceLocToDebugLoc(R.getBegin()), SourceLocToDebugLoc(R.getEnd()),
1210
1211 auto *LoopFalse = (hasSkipCounter(&S) ? createBasicBlock("do.loopfalse")
1212 : LoopExit.getBlock());
1213
1214 // As long as the condition is true, iterate the loop.
1215 if (EmitBoolCondBranch) {
1216 uint64_t BackedgeCount = getProfileCount(S.getBody()) - ParentCount;
1217 auto *I = Builder.CreateCondBr(
1218 BoolCondVal, LoopBody, LoopFalse,
1219 createProfileWeightsForLoop(S.getCond(), BackedgeCount));
1220
1221 // Key Instructions: Emit the condition and branch as separate source
1222 // location atoms otherwise we may omit a step onto the loop condition in
1223 // favour of the closing brace.
1224 // FIXME: We could have the branch as the backup location for the condition,
1225 // which would probably be a better experience (no jumping to the brace).
1226 if (auto *CondI = dyn_cast<llvm::Instruction>(BoolCondVal))
1227 addInstToNewSourceAtom(CondI, nullptr);
1228 addInstToNewSourceAtom(I, nullptr);
1229 }
1230
1231 LoopStack.pop();
1232
1233 if (LoopFalse != LoopExit.getBlock()) {
1234 EmitBlock(LoopFalse);
1235 incrementProfileCounter(UseSkipPath, &S, /*UseBoth=*/true);
1236 }
1237
1238 // Emit the exit block.
1239 EmitBlock(LoopExit.getBlock());
1240
1241 // The DoCond block typically is just a branch if we skipped
1242 // emitting a branch, try to erase it.
1243 if (!EmitBoolCondBranch)
1245
1246 if (CGM.shouldEmitConvergenceTokens())
1247 ConvergenceTokenStack.pop_back();
1248}
1249
1251 ArrayRef<const Attr *> ForAttrs) {
1252 std::optional<LexicalScope> ForScope;
1254 if (getLangOpts().C99 || getLangOpts().CPlusPlus) {
1256 ForScope.emplace(*this, S.getSourceRange());
1257
1258 // Evaluate the first part before the loop.
1259 if (S.getInit())
1260 EmitStmt(S.getInit());
1261 } else {
1262 // Before C99 the init variable belongs to the enclosing scope, so create
1263 // the loop exit after its cleanups: leaving the loop must not run them.
1264 if (S.getInit())
1265 EmitStmt(S.getInit());
1267 }
1268
1269 // Start the loop with a block that tests the condition.
1270 // If there's an increment, the continue scope will be overwritten
1271 // later.
1272 JumpDest CondDest = getJumpDestInCurrentScope("for.cond");
1273 llvm::BasicBlock *CondBlock = CondDest.getBlock();
1274 EmitBlock(CondBlock);
1275
1276 if (CGM.shouldEmitConvergenceTokens())
1277 ConvergenceTokenStack.push_back(emitConvergenceLoopToken(CondBlock));
1278
1279 const SourceRange &R = S.getSourceRange();
1280 LoopStack.push(
1281 CondBlock, CGM.getContext(), CGM.getCodeGenOpts(), ForAttrs,
1282 SourceLocToDebugLoc(R.getBegin()), SourceLocToDebugLoc(R.getEnd()),
1284
1285 // Create a cleanup scope for the condition variable cleanups.
1286 LexicalScope ConditionScope(*this, S.getSourceRange());
1287
1288 // If the for loop doesn't have an increment we can just use the condition as
1289 // the continue block. Otherwise, if there is no condition variable, we can
1290 // form the continue block now. If there is a condition variable, we can't
1291 // form the continue block until after we've emitted the condition, because
1292 // the condition is in scope in the increment, but Sema's jump diagnostics
1293 // ensure that there are no continues from the condition variable that jump
1294 // to the loop increment.
1295 JumpDest Continue;
1296 if (!S.getInc())
1297 Continue = CondDest;
1298 else if (!S.getConditionVariable())
1299 Continue = getJumpDestInCurrentScope("for.inc");
1300 BreakContinueStack.push_back(BreakContinue(S, LoopExit, Continue));
1301
1302 if (S.getCond()) {
1303 // If the for statement has a condition scope, emit the local variable
1304 // declaration.
1305 if (S.getConditionVariable()) {
1307
1308 // We have entered the condition variable's scope, so we're now able to
1309 // jump to the continue block.
1310 Continue = S.getInc() ? getJumpDestInCurrentScope("for.inc") : CondDest;
1311 BreakContinueStack.back().ContinueBlock = Continue;
1312 }
1313
1314 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
1315 // If there are any cleanups between here and the loop-exit scope,
1316 // create a block to stage a loop exit along.
1317 if (hasSkipCounter(&S) || (ForScope && ForScope->requiresCleanups()))
1318 ExitBlock = createBasicBlock("for.cond.cleanup");
1319
1320 // As long as the condition is true, iterate the loop.
1321 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1322
1323 // C99 6.8.5p2/p4: The first substatement is executed if the expression
1324 // compares unequal to 0. The condition must be a scalar type.
1325 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
1326
1328
1329 llvm::MDNode *Weights =
1330 createProfileWeightsForLoop(S.getCond(), getProfileCount(S.getBody()));
1331 if (!Weights && CGM.getCodeGenOpts().OptimizationLevel)
1332 BoolCondVal = emitCondLikelihoodViaExpectIntrinsic(
1333 BoolCondVal, Stmt::getLikelihood(S.getBody()));
1334
1335 auto *I = Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock, Weights);
1336 // Key Instructions: Emit the condition and branch as separate atoms to
1337 // match existing loop stepping behaviour. FIXME: We could have the branch
1338 // as the backup location for the condition, which would probably be a
1339 // better experience (no jumping to the brace).
1340 if (auto *CondI = dyn_cast<llvm::Instruction>(BoolCondVal))
1341 addInstToNewSourceAtom(CondI, nullptr);
1342 addInstToNewSourceAtom(I, nullptr);
1343
1344 if (ExitBlock != LoopExit.getBlock()) {
1345 EmitBlock(ExitBlock);
1348 }
1349
1350 EmitBlock(ForBody);
1351 } else {
1352 // Treat it as a non-zero constant. Don't even create a new block for the
1353 // body, just fall into it.
1354 PGO->markStmtAsUsed(true, &S);
1355 }
1356
1358
1359 {
1360 // Create a separate cleanup scope for the body, in case it is not
1361 // a compound statement.
1362 RunCleanupsScope BodyScope(*this);
1363 EmitStmt(S.getBody());
1364 }
1365
1366 // The last block in the loop's body (which unconditionally branches to the
1367 // `inc` block if there is one).
1368 auto *FinalBodyBB = Builder.GetInsertBlock();
1369
1370 // If there is an increment, emit it next.
1371 if (S.getInc()) {
1372 EmitBlock(Continue.getBlock());
1373 EmitStmt(S.getInc());
1374 }
1375
1376 BreakContinueStack.pop_back();
1377
1378 ConditionScope.ForceCleanup();
1379
1380 EmitStopPoint(&S);
1381 EmitBranch(CondBlock);
1382
1383 if (ForScope)
1384 ForScope->ForceCleanup();
1385
1386 LoopStack.pop();
1387
1388 // Emit the fall-through block.
1389 EmitBlock(LoopExit.getBlock(), true);
1390
1391 if (CGM.shouldEmitConvergenceTokens())
1392 ConvergenceTokenStack.pop_back();
1393
1394 if (FinalBodyBB) {
1395 // Key Instructions: We want the for closing brace to be step-able on to
1396 // match existing behaviour.
1397 addInstToNewSourceAtom(FinalBodyBB->getTerminator(), nullptr);
1398 }
1399}
1400
1401void
1403 ArrayRef<const Attr *> ForAttrs) {
1405
1406 LexicalScope ForScope(*this, S.getSourceRange());
1407
1408 // Evaluate the first pieces before the loop.
1409 if (S.getInit())
1410 EmitStmt(S.getInit());
1413 EmitStmt(S.getEndStmt());
1414
1415 // Start the loop with a block that tests the condition.
1416 // If there's an increment, the continue scope will be overwritten
1417 // later.
1418 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1419 EmitBlock(CondBlock);
1420
1421 if (CGM.shouldEmitConvergenceTokens())
1422 ConvergenceTokenStack.push_back(emitConvergenceLoopToken(CondBlock));
1423
1424 const SourceRange &R = S.getSourceRange();
1425 LoopStack.push(CondBlock, CGM.getContext(), CGM.getCodeGenOpts(), ForAttrs,
1426 SourceLocToDebugLoc(R.getBegin()),
1427 SourceLocToDebugLoc(R.getEnd()));
1428
1429 // If there are any cleanups between here and the loop-exit scope,
1430 // create a block to stage a loop exit along.
1431 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
1432 if (hasSkipCounter(&S) || ForScope.requiresCleanups())
1433 ExitBlock = createBasicBlock("for.cond.cleanup");
1434
1435 // The loop body, consisting of the specified body and the loop variable.
1436 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1437
1438 // The body is executed if the expression, contextually converted
1439 // to bool, is true.
1440 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
1441 llvm::MDNode *Weights =
1442 createProfileWeightsForLoop(S.getCond(), getProfileCount(S.getBody()));
1443 if (!Weights && CGM.getCodeGenOpts().OptimizationLevel)
1444 BoolCondVal = emitCondLikelihoodViaExpectIntrinsic(
1445 BoolCondVal, Stmt::getLikelihood(S.getBody()));
1446 auto *I = Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock, Weights);
1447 // Key Instructions: Emit the condition and branch as separate atoms to
1448 // match existing loop stepping behaviour. FIXME: We could have the branch as
1449 // the backup location for the condition, which would probably be a better
1450 // experience.
1451 if (auto *CondI = dyn_cast<llvm::Instruction>(BoolCondVal))
1452 addInstToNewSourceAtom(CondI, nullptr);
1453 addInstToNewSourceAtom(I, nullptr);
1454
1455 if (ExitBlock != LoopExit.getBlock()) {
1456 EmitBlock(ExitBlock);
1459 }
1460
1461 EmitBlock(ForBody);
1463
1464 // Create a block for the increment. In case of a 'continue', we jump there.
1465 JumpDest Continue = getJumpDestInCurrentScope("for.inc");
1466
1467 // Store the blocks to use for break and continue.
1468 BreakContinueStack.push_back(BreakContinue(S, LoopExit, Continue));
1469
1470 {
1471 // Create a separate cleanup scope for the loop variable and body.
1472 LexicalScope BodyScope(*this, S.getSourceRange());
1474 EmitStmt(S.getBody());
1475 }
1476 // The last block in the loop's body (which unconditionally branches to the
1477 // `inc` block if there is one).
1478 auto *FinalBodyBB = Builder.GetInsertBlock();
1479
1480 EmitStopPoint(&S);
1481 // If there is an increment, emit it next.
1482 EmitBlock(Continue.getBlock());
1483 EmitStmt(S.getInc());
1484
1485 BreakContinueStack.pop_back();
1486
1487 EmitBranch(CondBlock);
1488
1489 ForScope.ForceCleanup();
1490
1491 LoopStack.pop();
1492
1493 // Emit the fall-through block.
1494 EmitBlock(LoopExit.getBlock(), true);
1495
1496 if (CGM.shouldEmitConvergenceTokens())
1497 ConvergenceTokenStack.pop_back();
1498
1499 if (FinalBodyBB) {
1500 // We want the for closing brace to be step-able on to match existing
1501 // behaviour.
1502 addInstToNewSourceAtom(FinalBodyBB->getTerminator(), nullptr);
1503 }
1504}
1505
1508 LexicalScope Scope(*this, S.getSourceRange());
1509
1510 for (const Stmt *DS : S.getPreambleStmts())
1511 EmitStmt(DS);
1512
1513 if (S.getInstantiations().empty())
1514 return;
1515
1516 JumpDest ExpandExit = getJumpDestInCurrentScope("expand.end");
1517 JumpDest ContinueDest;
1518 for (auto [N, Inst] : enumerate(S.getInstantiations())) {
1519 if (N == S.getInstantiations().size() - 1)
1520 ContinueDest = ExpandExit;
1521 else
1522 ContinueDest = getJumpDestInCurrentScope("expand.next");
1523
1524 LexicalScope ExpansionScope(*this, Inst->getSourceRange());
1525 BreakContinueStack.push_back(BreakContinue(S, ExpandExit, ContinueDest));
1526 EmitStmt(Inst);
1527 BreakContinueStack.pop_back();
1528 EmitBlock(ContinueDest.getBlock(), true);
1529 }
1530}
1531
1532void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
1533 if (RV.isScalar()) {
1534 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
1535 } else if (RV.isAggregate()) {
1536 LValue Dest = MakeAddrLValue(ReturnValue, Ty);
1539 } else {
1541 /*init*/ true);
1542 }
1544}
1545
1546namespace {
1547// RAII struct used to save and restore a return statment's result expression.
1548struct SaveRetExprRAII {
1549 SaveRetExprRAII(const Expr *RetExpr, CodeGenFunction &CGF)
1550 : OldRetExpr(CGF.RetExpr), CGF(CGF) {
1551 CGF.RetExpr = RetExpr;
1552 }
1553 ~SaveRetExprRAII() { CGF.RetExpr = OldRetExpr; }
1554 const Expr *OldRetExpr;
1555 CodeGenFunction &CGF;
1556};
1557} // namespace
1558
1559/// Determine if the given call uses the swiftasync calling convention.
1560static bool isSwiftAsyncCallee(const CallExpr *CE) {
1561 auto calleeQualType = CE->getCallee()->getType();
1562 const FunctionType *calleeType = nullptr;
1563 if (calleeQualType->isFunctionPointerType() ||
1564 calleeQualType->isFunctionReferenceType() ||
1565 calleeQualType->isBlockPointerType() ||
1566 calleeQualType->isMemberFunctionPointerType()) {
1567 calleeType = calleeQualType->getPointeeType()->castAs<FunctionType>();
1568 } else if (auto *ty = dyn_cast<FunctionType>(calleeQualType)) {
1569 calleeType = ty;
1570 } else if (auto CMCE = dyn_cast<CXXMemberCallExpr>(CE)) {
1571 if (auto methodDecl = CMCE->getMethodDecl()) {
1572 // getMethodDecl() doesn't handle member pointers at the moment.
1573 calleeType = methodDecl->getType()->castAs<FunctionType>();
1574 } else {
1575 return false;
1576 }
1577 } else {
1578 return false;
1579 }
1580 return calleeType->getCallConv() == CallingConv::CC_SwiftAsync;
1581}
1582
1583/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
1584/// if the function returns void, or may be missing one if the function returns
1585/// non-void. Fun stuff :).
1588 if (requiresReturnValueCheck()) {
1589 llvm::Constant *SLoc = EmitCheckSourceLocation(S.getBeginLoc());
1590 auto *SLocPtr =
1591 new llvm::GlobalVariable(CGM.getModule(), SLoc->getType(), false,
1592 llvm::GlobalVariable::PrivateLinkage, SLoc);
1593 SLocPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1594 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(SLocPtr);
1595 assert(ReturnLocation.isValid() && "No valid return location");
1596 Builder.CreateStore(SLocPtr, ReturnLocation);
1597 }
1598
1599 // Returning from an outlined SEH helper is UB, and we already warn on it.
1600 if (IsOutlinedSEHHelper) {
1601 Builder.CreateUnreachable();
1602 Builder.ClearInsertionPoint();
1603 }
1604
1605 // Emit the result value, even if unused, to evaluate the side effects.
1606 const Expr *RV = S.getRetValue();
1607
1608 // Record the result expression of the return statement. The recorded
1609 // expression is used to determine whether a block capture's lifetime should
1610 // end at the end of the full expression as opposed to the end of the scope
1611 // enclosing the block expression.
1612 //
1613 // This permits a small, easily-implemented exception to our over-conservative
1614 // rules about not jumping to statements following block literals with
1615 // non-trivial cleanups.
1616 SaveRetExprRAII SaveRetExpr(RV, *this);
1617
1618 RunCleanupsScope cleanupScope(*this);
1619 if (const auto *EWC = dyn_cast_or_null<ExprWithCleanups>(RV))
1620 RV = EWC->getSubExpr();
1621
1622 // If we're in a swiftasynccall function, and the return expression is a
1623 // call to a swiftasynccall function, mark the call as the musttail call.
1624 std::optional<llvm::SaveAndRestore<const CallExpr *>> SaveMustTail;
1625 if (RV && CurFnInfo &&
1626 CurFnInfo->getASTCallingConvention() == CallingConv::CC_SwiftAsync) {
1627 if (auto CE = dyn_cast<CallExpr>(RV)) {
1628 if (isSwiftAsyncCallee(CE)) {
1629 SaveMustTail.emplace(MustTailCall, CE);
1630 }
1631 }
1632 }
1633
1634 // FIXME: Clean this up by using an LValue for ReturnTemp,
1635 // EmitStoreThroughLValue, and EmitAnyExpr.
1636 // Check if the NRVO candidate was not globalized in OpenMP mode.
1637 if (getLangOpts().ElideConstructors && S.getNRVOCandidate() &&
1639 (!getLangOpts().OpenMP ||
1640 !CGM.getOpenMPRuntime()
1641 .getAddressOfLocalVariable(*this, S.getNRVOCandidate())
1642 .isValid())) {
1643 // Apply the named return value optimization for this return statement,
1644 // which means doing nothing: the appropriate result has already been
1645 // constructed into the NRVO variable.
1646
1647 // If there is an NRVO flag for this variable, set it to 1 into indicate
1648 // that the cleanup code should not destroy the variable.
1649 if (llvm::Value *NRVOFlag = NRVOFlags[S.getNRVOCandidate()])
1650 Builder.CreateFlagStore(Builder.getTrue(), NRVOFlag);
1651 } else if (!ReturnValue.isValid() || (RV && RV->getType()->isVoidType())) {
1652 // Make sure not to return anything, but evaluate the expression
1653 // for side effects.
1654 if (RV) {
1655 EmitAnyExpr(RV);
1656 }
1657 } else if (!RV) {
1658 // Do nothing (return value is left uninitialized)
1659 } else if (FnRetTy->isReferenceType()) {
1660 // If this function returns a reference, take the address of the expression
1661 // rather than the value.
1663 auto *I = Builder.CreateStore(Result.getScalarVal(), ReturnValue);
1664 addInstToCurrentSourceAtom(I, I->getValueOperand());
1665 } else {
1666 switch (getEvaluationKind(RV->getType())) {
1667 case TEK_Scalar: {
1668 llvm::Value *Ret = EmitScalarExpr(RV);
1669 if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect) {
1671 /*isInit*/ true);
1672 } else {
1673 auto *I = Builder.CreateStore(Ret, ReturnValue);
1674 addInstToCurrentSourceAtom(I, I->getValueOperand());
1675 }
1676 break;
1677 }
1678 case TEK_Complex:
1680 /*isInit*/ true);
1681 break;
1682 case TEK_Aggregate:
1689 break;
1690 }
1691 }
1692
1693 ++NumReturnExprs;
1694 if (!RV || RV->isEvaluatable(getContext()))
1695 ++NumSimpleReturnExprs;
1696
1697 cleanupScope.ForceCleanup();
1699}
1700
1702 // As long as debug info is modeled with instructions, we have to ensure we
1703 // have a place to insert here and write the stop point here.
1704 if (HaveInsertPoint())
1705 EmitStopPoint(&S);
1706
1707 for (const auto *I : S.decls())
1708 EmitDecl(*I, /*EvaluateConditionDecl=*/true);
1709}
1710
1712 -> const BreakContinue * {
1713 if (!S.isNamed())
1714 return &BreakContinueStack.back();
1715
1716 const Stmt *LoopOrSwitch = S.getNamedLoopOrSwitch();
1717 assert(LoopOrSwitch && "break/continue target label not available?");
1718 for (const BreakContinue &BC : llvm::reverse(BreakContinueStack))
1719 if (BC.LoopOrSwitch == LoopOrSwitch)
1720 return &BC;
1721
1722 llvm_unreachable("break/continue target not found");
1723}
1724
1726 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
1727
1728 // If this code is reachable then emit a stop point (if generating
1729 // debug info). We have to do this ourselves because we are on the
1730 // "simple" statement path.
1731 if (HaveInsertPoint())
1732 EmitStopPoint(&S);
1733
1736}
1737
1739 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
1740
1741 // If this code is reachable then emit a stop point (if generating
1742 // debug info). We have to do this ourselves because we are on the
1743 // "simple" statement path.
1744 if (HaveInsertPoint())
1745 EmitStopPoint(&S);
1746
1749}
1750
1751/// Return whether S has an enumerator of a BPF preserve_access_index enum,
1752/// which Sema keeps as a pseudo-object for __builtin_preserve_enum_value(), or
1753/// an explicit __builtin_preserve_enum_value() call, not in an operand of
1754/// sizeof or alignof.
1755static bool hasBPFEnumeratorRef(const Stmt *S) {
1756 if (!S || isa<UnaryExprOrTypeTraitExpr>(S))
1757 return false;
1758 if (const auto *POE = dyn_cast<PseudoObjectExpr>(S))
1759 if (const auto *DRE = dyn_cast<DeclRefExpr>(POE->getSyntacticForm());
1760 DRE && isa<EnumConstantDecl>(DRE->getDecl()))
1761 return true;
1762 if (const auto *Call = dyn_cast<CallExpr>(S);
1763 Call && Call->getBuiltinCallee() == BPF::BI__builtin_preserve_enum_value)
1764 return true;
1765 return llvm::any_of(S->children(), hasBPFEnumeratorRef);
1766}
1767
1768/// If the case value E has a relocated enumerator or an explicit
1769/// __builtin_preserve_enum_value() call, see
1770/// SemaBPF::verifyCaseExpr(), return E without its ConstantExpr and casts.
1771/// Sema does not check it for duplicates, so it is not added to the switch even
1772/// without debug info, where its local value is used.
1774 const Expr *E) {
1775 if (!E || !CGF.getTarget().getTriple().isBPF())
1776 return nullptr;
1777 while (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
1778 E = ICE->getSubExpr();
1779 const auto *CE = dyn_cast<ConstantExpr>(E);
1780 if (!CE || !hasBPFEnumeratorRef(CE->getSubExpr()))
1781 return nullptr;
1782 return CE->getSubExpr();
1783}
1784
1785static bool isBPFRelocatedCase(CodeGenFunction &CGF, const CaseStmt &S) {
1786 return getBPFRelocatedCaseValue(CGF, S.getLHS()) ||
1788}
1789
1790/// Emit a case statement whose value is relocated: move the switch to a new
1791/// block, and in its old block, branch to the case if the condition matches the
1792/// relocated value, otherwise to the switch. So the relocated cases are checked
1793/// in source order, before the other cases. E.g., with relocated A, B and C,
1794///
1795/// switch (x) { case 1: ... case A: ... case B ... C: ... }
1796///
1797/// is emitted like:
1798///
1799/// if (x == A) goto case_A;
1800/// if (x >= B && x <= C) goto case_BC;
1801/// switch (x) { case 1: ... }
1803 ArrayRef<const Attr *> Attrs) {
1804 llvm::BasicBlock *CaseDest = createBasicBlock("sw.bb");
1805 EmitBlockWithFallThrough(CaseDest, &S);
1806
1807 llvm::BasicBlock *CheckBB = SwitchInsn->getParent();
1808 llvm::BasicBlock *SwitchBB = createBasicBlock("sw.dispatch");
1809 CurFn->insert(std::next(CheckBB->getIterator()), SwitchBB);
1810 SwitchInsn->removeFromParent();
1811 SwitchInsn->insertInto(SwitchBB, SwitchBB->end());
1812
1813 // Emit the check at the end of CheckBB, then come back to the case body.
1814 {
1815 llvm::IRBuilderBase::InsertPointGuard IPG(Builder);
1816 Builder.SetInsertPoint(CheckBB);
1817 ApplyDebugLocation DL(*this, S.getLHS());
1818 llvm::Value *CondV = SwitchInsn->getCondition();
1819 auto EmitCaseValue = [&](const Expr *E) -> llvm::Value * {
1820 if (const Expr *Reloc = getBPFRelocatedCaseValue(*this, E))
1821 return Builder.CreateIntCast(
1822 EmitScalarExpr(Reloc), CondV->getType(),
1823 Reloc->getType()->isSignedIntegerOrEnumerationType());
1824 return Builder.getInt(E->EvaluateKnownConstInt(getContext()));
1825 };
1826
1827 llvm::Value *Cond;
1828 if (!S.getRHS()) {
1829 Cond = Builder.CreateICmpEQ(CondV, EmitCaseValue(S.getLHS()));
1830 } else {
1831 // The relocated range may be empty.
1832 bool IsSigned = S.getLHS()->getType()->isSignedIntegerOrEnumerationType();
1833 llvm::Value *Lo = Builder.CreateICmp(IsSigned ? llvm::CmpInst::ICMP_SGE
1834 : llvm::CmpInst::ICMP_UGE,
1835 CondV, EmitCaseValue(S.getLHS()));
1836 llvm::Value *Hi = Builder.CreateICmp(IsSigned ? llvm::CmpInst::ICMP_SLE
1837 : llvm::CmpInst::ICMP_ULE,
1838 CondV, EmitCaseValue(S.getRHS()));
1839 Cond = Builder.CreateAnd(Lo, Hi);
1840 }
1841 if (SwitchLikelihood)
1842 Cond = emitCondLikelihoodViaExpectIntrinsic(Cond,
1843 Stmt::getLikelihood(Attrs));
1844 Builder.CreateCondBr(Cond, CaseDest, SwitchBB);
1845 }
1846
1847 EmitStmt(S.getSubStmt());
1848}
1849
1850/// EmitCaseStmtRange - If case statement range is not too big then
1851/// add multiple cases to switch instruction, one for each value within
1852/// the range. If range is too big then emit "if" condition check.
1854 ArrayRef<const Attr *> Attrs) {
1855 assert(S.getRHS() && "Expected RHS value in CaseStmt");
1856
1857 llvm::APSInt LHS = S.getLHS()->EvaluateKnownConstInt(getContext());
1858 llvm::APSInt RHS = S.getRHS()->EvaluateKnownConstInt(getContext());
1859
1860 // Emit the code for this case. We do this first to make sure it is
1861 // properly chained from our predecessor before generating the
1862 // switch machinery to enter this block.
1863 llvm::BasicBlock *CaseDest = createBasicBlock("sw.bb");
1864 EmitBlockWithFallThrough(CaseDest, &S);
1865 EmitStmt(S.getSubStmt());
1866
1867 // If range is empty, do nothing.
1868 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
1869 return;
1870
1872 llvm::APInt Range = RHS - LHS;
1873 // FIXME: parameters such as this should not be hardcoded.
1874 if (Range.getBitWidth() < 7 ||
1875 Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
1876 // Range is small enough to add multiple switch instruction cases.
1877 uint64_t Total = getProfileCount(&S);
1878 unsigned NCases = Range.getZExtValue() + 1;
1879 // We only have one region counter for the entire set of cases here, so we
1880 // need to divide the weights evenly between the generated cases, ensuring
1881 // that the total weight is preserved. E.g., a weight of 5 over three cases
1882 // will be distributed as weights of 2, 2, and 1.
1883 uint64_t Weight = Total / NCases, Rem = Total % NCases;
1884 for (unsigned I = 0; I != NCases; ++I) {
1885 if (SwitchWeights)
1886 SwitchWeights->push_back(Weight + (Rem ? 1 : 0));
1887 else if (SwitchLikelihood)
1888 SwitchLikelihood->push_back(LH);
1889
1890 if (Rem)
1891 Rem--;
1892 SwitchInsn->addCase(Builder.getInt(LHS), CaseDest);
1893 ++LHS;
1894 }
1895 return;
1896 }
1897
1898 // The range is too big. Emit "if" condition into a new block,
1899 // making sure to save and restore the current insertion point.
1900 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
1901
1902 // Push this test onto the chain of range checks (which terminates
1903 // in the default basic block). The switch's default will be changed
1904 // to the top of this chain after switch emission is complete.
1905 llvm::BasicBlock *FalseDest = CaseRangeBlock;
1906 CaseRangeBlock = createBasicBlock("sw.caserange");
1907
1908 CurFn->insert(CurFn->end(), CaseRangeBlock);
1909 Builder.SetInsertPoint(CaseRangeBlock);
1910
1911 // Emit range check.
1912 llvm::Value *Diff =
1913 Builder.CreateSub(SwitchInsn->getCondition(), Builder.getInt(LHS));
1914 llvm::Value *Cond =
1915 Builder.CreateICmpULE(Diff, Builder.getInt(Range), "inbounds");
1916
1917 llvm::MDNode *Weights = nullptr;
1918 if (SwitchWeights) {
1919 uint64_t ThisCount = getProfileCount(&S);
1920 uint64_t DefaultCount = (*SwitchWeights)[0];
1921 Weights = createProfileWeights(ThisCount, DefaultCount);
1922
1923 // Since we're chaining the switch default through each large case range, we
1924 // need to update the weight for the default, ie, the first case, to include
1925 // this case.
1926 (*SwitchWeights)[0] += ThisCount;
1927 } else if (SwitchLikelihood)
1928 Cond = emitCondLikelihoodViaExpectIntrinsic(Cond, LH);
1929
1930 Builder.CreateCondBr(Cond, CaseDest, FalseDest, Weights);
1931
1932 // Restore the appropriate insertion point.
1933 if (RestoreBB)
1934 Builder.SetInsertPoint(RestoreBB);
1935 else
1936 Builder.ClearInsertionPoint();
1937}
1938
1940 ArrayRef<const Attr *> Attrs) {
1941 // If there is no enclosing switch instance that we're aware of, then this
1942 // case statement and its block can be elided. This situation only happens
1943 // when we've constant-folded the switch, are emitting the constant case,
1944 // and part of the constant case includes another case statement. For
1945 // instance: switch (4) { case 4: do { case 5: } while (1); }
1946 if (!SwitchInsn) {
1947 EmitStmt(S.getSubStmt());
1948 return;
1949 }
1950
1951 if (isBPFRelocatedCase(*this, S)) {
1952 EmitBPFRelocatedCaseStmt(S, Attrs);
1953 return;
1954 }
1955
1956 // Handle case ranges.
1957 if (S.getRHS()) {
1958 EmitCaseStmtRange(S, Attrs);
1959 return;
1960 }
1961
1962 llvm::ConstantInt *CaseVal =
1964
1965 // Emit debuginfo for the case value if it is an enum value.
1966 // Look through implicit casts and check the subexpression of ConstantExpr.
1967 const auto *CE = dyn_cast<ConstantExpr>(S.getLHS()->IgnoreImpCasts());
1968 const Expr *SubExpr = CE ? CE->getSubExpr() : S.getLHS()->IgnoreImpCasts();
1969 if (const auto *DRE = dyn_cast<DeclRefExpr>(SubExpr))
1970 if (CGDebugInfo *Dbg = getDebugInfo())
1971 if (CGM.getCodeGenOpts().hasReducedDebugInfo())
1972 Dbg->EmitGlobalVariable(DRE->getDecl(),
1973 APValue(llvm::APSInt(CaseVal->getValue())));
1974
1975 if (SwitchLikelihood)
1976 SwitchLikelihood->push_back(Stmt::getLikelihood(Attrs));
1977
1978 // If the body of the case is just a 'break', try to not emit an empty block.
1979 // If we're profiling or we're not optimizing, leave the block in for better
1980 // debug and coverage analysis.
1981 if (!CGM.getCodeGenOpts().hasProfileClangInstr() &&
1982 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1984 JumpDest Block = BreakContinueStack.back().BreakBlock;
1985
1986 // Only do this optimization if there are no cleanups that need emitting.
1988 if (SwitchWeights)
1989 SwitchWeights->push_back(getProfileCount(&S));
1990 SwitchInsn->addCase(CaseVal, Block.getBlock());
1991
1992 // If there was a fallthrough into this case, make sure to redirect it to
1993 // the end of the switch as well.
1994 if (Builder.GetInsertBlock()) {
1995 Builder.CreateBr(Block.getBlock());
1996 Builder.ClearInsertionPoint();
1997 }
1998 return;
1999 }
2000 }
2001
2002 llvm::BasicBlock *CaseDest = createBasicBlock("sw.bb");
2003 EmitBlockWithFallThrough(CaseDest, &S);
2004 if (SwitchWeights)
2005 SwitchWeights->push_back(getProfileCount(&S));
2006 SwitchInsn->addCase(CaseVal, CaseDest);
2007
2008 // Recursively emitting the statement is acceptable, but is not wonderful for
2009 // code where we have many case statements nested together, i.e.:
2010 // case 1:
2011 // case 2:
2012 // case 3: etc.
2013 // Handling this recursively will create a new block for each case statement
2014 // that falls through to the next case which is IR intensive. It also causes
2015 // deep recursion which can run into stack depth limitations. Handle
2016 // sequential non-range case statements specially.
2017 //
2018 // TODO When the next case has a likelihood attribute the code returns to the
2019 // recursive algorithm. Maybe improve this case if it becomes common practice
2020 // to use a lot of attributes.
2021 const CaseStmt *CurCase = &S;
2022 const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
2023
2024 // Otherwise, iteratively add consecutive cases to this switch stmt.
2025 while (NextCase && NextCase->getRHS() == nullptr &&
2026 !isBPFRelocatedCase(*this, *NextCase)) {
2027 CurCase = NextCase;
2028 llvm::ConstantInt *CaseVal =
2029 Builder.getInt(CurCase->getLHS()->EvaluateKnownConstInt(getContext()));
2030
2031 if (SwitchWeights)
2032 SwitchWeights->push_back(getProfileCount(NextCase));
2033 if (CGM.getCodeGenOpts().hasProfileClangInstr()) {
2034 CaseDest = createBasicBlock("sw.bb");
2035 EmitBlockWithFallThrough(CaseDest, CurCase);
2036 }
2037 // Since this loop is only executed when the CaseStmt has no attributes
2038 // use a hard-coded value.
2039 if (SwitchLikelihood)
2040 SwitchLikelihood->push_back(Stmt::LH_None);
2041
2042 SwitchInsn->addCase(CaseVal, CaseDest);
2043 NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt());
2044 }
2045
2046 // Generate a stop point for debug info if the case statement is
2047 // followed by a default statement. A fallthrough case before a
2048 // default case gets its own branch target.
2049 if (CurCase->getSubStmt()->getStmtClass() == Stmt::DefaultStmtClass)
2050 EmitStopPoint(CurCase);
2051
2052 // Normal default recursion for non-cases.
2053 EmitStmt(CurCase->getSubStmt());
2054}
2055
2057 ArrayRef<const Attr *> Attrs) {
2058 // If there is no enclosing switch instance that we're aware of, then this
2059 // default statement can be elided. This situation only happens when we've
2060 // constant-folded the switch.
2061 if (!SwitchInsn) {
2062 EmitStmt(S.getSubStmt());
2063 return;
2064 }
2065
2066 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
2067 assert(DefaultBlock->empty() &&
2068 "EmitDefaultStmt: Default block already defined?");
2069
2070 if (SwitchLikelihood)
2071 SwitchLikelihood->front() = Stmt::getLikelihood(Attrs);
2072
2073 EmitBlockWithFallThrough(DefaultBlock, &S);
2074
2075 EmitStmt(S.getSubStmt());
2076}
2077
2078namespace {
2079struct EmitDeferredStatement final : EHScopeStack::Cleanup {
2080 const DeferStmt &Stmt;
2081 EmitDeferredStatement(const DeferStmt *Stmt) : Stmt(*Stmt) {}
2082
2083 void Emit(CodeGenFunction &CGF, Flags) override {
2084 // Take care that any cleanups pushed by the body of a '_Defer' statement
2085 // don't clobber the current cleanup slot value.
2086 //
2087 // Assume we have a scope that pushes a cleanup; when that scope is exited,
2088 // we need to run that cleanup; this is accomplished by emitting the cleanup
2089 // into a separate block and then branching to that block at scope exit.
2090 //
2091 // Where this gets complicated is if we exit the scope in multiple different
2092 // ways; e.g. in a 'for' loop, we may exit the scope of its body by falling
2093 // off the end (in which case we need to run the cleanup and then branch to
2094 // the increment), or by 'break'ing out of the loop (in which case we need
2095 // to run the cleanup and then branch to the loop exit block); in both cases
2096 // we first branch to the cleanup block to run the cleanup, but the block we
2097 // need to jump to *after* running the cleanup is different.
2098 //
2099 // This is accomplished using a local integer variable called the 'cleanup
2100 // slot': before branching to the cleanup block, we store a value into that
2101 // slot. Then, in the cleanup block, after running the cleanup, we load the
2102 // value of that variable and 'switch' on it to branch to the appropriate
2103 // continuation block.
2104 //
2105 // The problem that arises once '_Defer' statements are involved is that the
2106 // body of a '_Defer' is an arbitrary statement which itself can create more
2107 // cleanups. This means we may end up overwriting the cleanup slot before we
2108 // ever have a chance to 'switch' on it, which means that once we *do* get
2109 // to the 'switch', we end up in whatever block the cleanup code happened to
2110 // pick as the default 'switch' exit label!
2111 //
2112 // That is, what is normally supposed to happen is something like:
2113 //
2114 // 1. Store 'X' to cleanup slot.
2115 // 2. Branch to cleanup block.
2116 // 3. Execute cleanup.
2117 // 4. Read value from cleanup slot.
2118 // 5. Branch to the block associated with 'X'.
2119 //
2120 // But if we encounter a _Defer' statement that contains a cleanup, then
2121 // what might instead happen is:
2122 //
2123 // 1. Store 'X' to cleanup slot.
2124 // 2. Branch to cleanup block.
2125 // 3. Execute cleanup; this ends up pushing another cleanup, so:
2126 // 3a. Store 'Y' to cleanup slot.
2127 // 3b. Run steps 2–5 recursively.
2128 // 4. Read value from cleanup slot, which is now 'Y' instead of 'X'.
2129 // 5. Branch to the block associated with 'Y'... which doesn't even
2130 // exist because the value 'Y' is only meaningful for the inner
2131 // cleanup. The result is we just branch 'somewhere random'.
2132 //
2133 // The rest of the cleanup code simply isn't prepared to handle this case
2134 // because most other cleanups can't push more cleanups, and thus, emitting
2135 // other cleanups generally cannot clobber the cleanup slot.
2136 //
2137 // To prevent this from happening, save the current cleanup slot value and
2138 // restore it after emitting the '_Defer' statement.
2139 llvm::Value *SavedCleanupDest = nullptr;
2140 if (CGF.NormalCleanupDest.isValid())
2141 SavedCleanupDest =
2142 CGF.Builder.CreateLoad(CGF.NormalCleanupDest, "cleanup.dest.saved");
2143
2144 CGF.EmitStmt(Stmt.getBody());
2145
2146 if (SavedCleanupDest && CGF.HaveInsertPoint())
2147 CGF.Builder.CreateStore(SavedCleanupDest, CGF.NormalCleanupDest);
2148
2149 // Cleanups must end with an insert point.
2150 CGF.EnsureInsertPoint();
2151 }
2152};
2153} // namespace
2154
2156 EHStack.pushCleanup<EmitDeferredStatement>(NormalAndEHCleanup, &S);
2157}
2158
2159/// CollectStatementsForCase - Given the body of a 'switch' statement and a
2160/// constant value that is being switched on, see if we can dead code eliminate
2161/// the body of the switch to a simple series of statements to emit. Basically,
2162/// on a switch (5) we want to find these statements:
2163/// case 5:
2164/// printf(...); <--
2165/// ++i; <--
2166/// break;
2167///
2168/// and add them to the ResultStmts vector. If it is unsafe to do this
2169/// transformation (for example, one of the elided statements contains a label
2170/// that might be jumped to), return CSFC_Failure. If we handled it and 'S'
2171/// should include statements after it (e.g. the printf() line is a substmt of
2172/// the case) then return CSFC_FallThrough. If we handled it and found a break
2173/// statement, then return CSFC_Success.
2174///
2175/// If Case is non-null, then we are looking for the specified case, checking
2176/// that nothing we jump over contains labels. If Case is null, then we found
2177/// the case and are looking for the break.
2178///
2179/// If the recursive walk actually finds our Case, then we set FoundCase to
2180/// true.
2181///
2184 const SwitchCase *Case,
2185 bool &FoundCase,
2186 SmallVectorImpl<const Stmt*> &ResultStmts) {
2187 // If this is a null statement, just succeed.
2188 if (!S)
2189 return Case ? CSFC_Success : CSFC_FallThrough;
2190
2191 // If this is the switchcase (case 4: or default) that we're looking for, then
2192 // we're in business. Just add the substatement.
2193 if (const SwitchCase *SC = dyn_cast<SwitchCase>(S)) {
2194 if (S == Case) {
2195 FoundCase = true;
2196 return CollectStatementsForCase(SC->getSubStmt(), nullptr, FoundCase,
2197 ResultStmts);
2198 }
2199
2200 // Otherwise, this is some other case or default statement, just ignore it.
2201 return CollectStatementsForCase(SC->getSubStmt(), Case, FoundCase,
2202 ResultStmts);
2203 }
2204
2205 // If we are in the live part of the code and we found our break statement,
2206 // return a success!
2207 if (!Case && isa<BreakStmt>(S))
2208 return CSFC_Success;
2209
2210 // If this is a switch statement, then it might contain the SwitchCase, the
2211 // break, or neither.
2212 if (const CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
2213 // Handle this as two cases: we might be looking for the SwitchCase (if so
2214 // the skipped statements must be skippable) or we might already have it.
2215 CompoundStmt::const_body_iterator I = CS->body_begin(), E = CS->body_end();
2216 bool StartedInLiveCode = FoundCase;
2217 unsigned StartSize = ResultStmts.size();
2218
2219 // If we've not found the case yet, scan through looking for it.
2220 if (Case) {
2221 // Keep track of whether we see a skipped declaration. The code could be
2222 // using the declaration even if it is skipped, so we can't optimize out
2223 // the decl if the kept statements might refer to it.
2224 bool HadSkippedDecl = false;
2225
2226 // If we're looking for the case, just see if we can skip each of the
2227 // substatements.
2228 for (; Case && I != E; ++I) {
2229 HadSkippedDecl |= CodeGenFunction::mightAddDeclToScope(*I);
2230
2231 switch (CollectStatementsForCase(*I, Case, FoundCase, ResultStmts)) {
2232 case CSFC_Failure: return CSFC_Failure;
2233 case CSFC_Success:
2234 // A successful result means that either 1) that the statement doesn't
2235 // have the case and is skippable, or 2) does contain the case value
2236 // and also contains the break to exit the switch. In the later case,
2237 // we just verify the rest of the statements are elidable.
2238 if (FoundCase) {
2239 // If we found the case and skipped declarations, we can't do the
2240 // optimization.
2241 if (HadSkippedDecl)
2242 return CSFC_Failure;
2243
2244 for (++I; I != E; ++I)
2245 if (CodeGenFunction::ContainsLabel(*I, true))
2246 return CSFC_Failure;
2247 return CSFC_Success;
2248 }
2249 break;
2250 case CSFC_FallThrough:
2251 // If we have a fallthrough condition, then we must have found the
2252 // case started to include statements. Consider the rest of the
2253 // statements in the compound statement as candidates for inclusion.
2254 assert(FoundCase && "Didn't find case but returned fallthrough?");
2255 // We recursively found Case, so we're not looking for it anymore.
2256 Case = nullptr;
2257
2258 // If we found the case and skipped declarations, we can't do the
2259 // optimization.
2260 if (HadSkippedDecl)
2261 return CSFC_Failure;
2262 break;
2263 }
2264 }
2265
2266 if (!FoundCase)
2267 return CSFC_Success;
2268
2269 assert(!HadSkippedDecl && "fallthrough after skipping decl");
2270 }
2271
2272 // If we have statements in our range, then we know that the statements are
2273 // live and need to be added to the set of statements we're tracking.
2274 bool AnyDecls = false;
2275 for (; I != E; ++I) {
2277
2278 switch (CollectStatementsForCase(*I, nullptr, FoundCase, ResultStmts)) {
2279 case CSFC_Failure: return CSFC_Failure;
2280 case CSFC_FallThrough:
2281 // A fallthrough result means that the statement was simple and just
2282 // included in ResultStmt, keep adding them afterwards.
2283 break;
2284 case CSFC_Success:
2285 // A successful result means that we found the break statement and
2286 // stopped statement inclusion. We just ensure that any leftover stmts
2287 // are skippable and return success ourselves.
2288 for (++I; I != E; ++I)
2289 if (CodeGenFunction::ContainsLabel(*I, true))
2290 return CSFC_Failure;
2291 return CSFC_Success;
2292 }
2293 }
2294
2295 // If we're about to fall out of a scope without hitting a 'break;', we
2296 // can't perform the optimization if there were any decls in that scope
2297 // (we'd lose their end-of-lifetime).
2298 if (AnyDecls) {
2299 // If the entire compound statement was live, there's one more thing we
2300 // can try before giving up: emit the whole thing as a single statement.
2301 // We can do that unless the statement contains a 'break;'.
2302 // FIXME: Such a break must be at the end of a construct within this one.
2303 // We could emit this by just ignoring the BreakStmts entirely.
2304 if (StartedInLiveCode && !CodeGenFunction::containsBreak(S)) {
2305 ResultStmts.resize(StartSize);
2306 ResultStmts.push_back(S);
2307 } else {
2308 return CSFC_Failure;
2309 }
2310 }
2311
2312 return CSFC_FallThrough;
2313 }
2314
2315 // Okay, this is some other statement that we don't handle explicitly, like a
2316 // for statement or increment etc. If we are skipping over this statement,
2317 // just verify it doesn't have labels, which would make it invalid to elide.
2318 if (Case) {
2319 if (CodeGenFunction::ContainsLabel(S, true))
2320 return CSFC_Failure;
2321 return CSFC_Success;
2322 }
2323
2324 // Otherwise, we want to include this statement. Everything is cool with that
2325 // so long as it doesn't contain a break out of the switch we're in.
2327
2328 // Otherwise, everything is great. Include the statement and tell the caller
2329 // that we fall through and include the next statement as well.
2330 ResultStmts.push_back(S);
2331 return CSFC_FallThrough;
2332}
2333
2334/// FindCaseStatementsForValue - Find the case statement being jumped to and
2335/// then invoke CollectStatementsForCase to find the list of statements to emit
2336/// for a switch on constant. See the comment above CollectStatementsForCase
2337/// for more details.
2339 const llvm::APSInt &ConstantCondValue,
2340 SmallVectorImpl<const Stmt*> &ResultStmts,
2341 ASTContext &C,
2342 const SwitchCase *&ResultCase) {
2343 // First step, find the switch case that is being branched to. We can do this
2344 // efficiently by scanning the SwitchCase list.
2345 const SwitchCase *Case = S.getSwitchCaseList();
2346 const DefaultStmt *DefaultCase = nullptr;
2347
2348 for (; Case; Case = Case->getNextSwitchCase()) {
2349 // It's either a default or case. Just remember the default statement in
2350 // case we're not jumping to any numbered cases.
2351 if (const DefaultStmt *DS = dyn_cast<DefaultStmt>(Case)) {
2352 DefaultCase = DS;
2353 continue;
2354 }
2355
2356 // Check to see if this case is the one we're looking for.
2357 const CaseStmt *CS = cast<CaseStmt>(Case);
2358 // Don't handle case ranges yet.
2359 if (CS->getRHS()) return false;
2360
2361 // If we found our case, remember it as 'case'.
2362 if (CS->getLHS()->EvaluateKnownConstInt(C) == ConstantCondValue)
2363 break;
2364 }
2365
2366 // If we didn't find a matching case, we use a default if it exists, or we
2367 // elide the whole switch body!
2368 if (!Case) {
2369 // It is safe to elide the body of the switch if it doesn't contain labels
2370 // etc. If it is safe, return successfully with an empty ResultStmts list.
2371 if (!DefaultCase)
2373 Case = DefaultCase;
2374 }
2375
2376 // Ok, we know which case is being jumped to, try to collect all the
2377 // statements that follow it. This can fail for a variety of reasons. Also,
2378 // check to see that the recursive walk actually found our case statement.
2379 // Insane cases like this can fail to find it in the recursive walk since we
2380 // don't handle every stmt kind:
2381 // switch (4) {
2382 // while (1) {
2383 // case 4: ...
2384 bool FoundCase = false;
2385 ResultCase = Case;
2386 return CollectStatementsForCase(S.getBody(), Case, FoundCase,
2387 ResultStmts) != CSFC_Failure &&
2388 FoundCase;
2389}
2390
2391static std::optional<SmallVector<uint64_t, 16>>
2393 // Are there enough branches to weight them?
2394 if (Likelihoods.size() <= 1)
2395 return std::nullopt;
2396
2397 uint64_t NumUnlikely = 0;
2398 uint64_t NumNone = 0;
2399 uint64_t NumLikely = 0;
2400 for (const auto LH : Likelihoods) {
2401 switch (LH) {
2402 case Stmt::LH_Unlikely:
2403 ++NumUnlikely;
2404 break;
2405 case Stmt::LH_None:
2406 ++NumNone;
2407 break;
2408 case Stmt::LH_Likely:
2409 ++NumLikely;
2410 break;
2411 }
2412 }
2413
2414 // Is there a likelihood attribute used?
2415 if (NumUnlikely == 0 && NumLikely == 0)
2416 return std::nullopt;
2417
2418 // When multiple cases share the same code they can be combined during
2419 // optimization. In that case the weights of the branch will be the sum of
2420 // the individual weights. Make sure the combined sum of all neutral cases
2421 // doesn't exceed the value of a single likely attribute.
2422 // The additions both avoid divisions by 0 and make sure the weights of None
2423 // don't exceed the weight of Likely.
2424 const uint64_t Likely = INT32_MAX / (NumLikely + 2);
2425 const uint64_t None = Likely / (NumNone + 1);
2426 const uint64_t Unlikely = 0;
2427
2429 Result.reserve(Likelihoods.size());
2430 for (const auto LH : Likelihoods) {
2431 switch (LH) {
2432 case Stmt::LH_Unlikely:
2433 Result.push_back(Unlikely);
2434 break;
2435 case Stmt::LH_None:
2436 Result.push_back(None);
2437 break;
2438 case Stmt::LH_Likely:
2439 Result.push_back(Likely);
2440 break;
2441 }
2442 }
2443
2444 return Result;
2445}
2446
2448 for (const SwitchCase *SC = S.getSwitchCaseList(); SC;
2449 SC = SC->getNextSwitchCase())
2450 if (const auto *CS = dyn_cast<CaseStmt>(SC);
2451 CS && isBPFRelocatedCase(CGF, *CS))
2452 return true;
2453 return false;
2454}
2455
2457 // Handle nested switch statements.
2458 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
2459 SmallVector<uint64_t, 16> *SavedSwitchWeights = SwitchWeights;
2460 SmallVector<Stmt::Likelihood, 16> *SavedSwitchLikelihood = SwitchLikelihood;
2461 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
2462
2463 // See if we can constant fold the condition of the switch and therefore only
2464 // emit the live case statement (if any) of the switch. A relocated case value
2465 // is not known until load time.
2466 llvm::APSInt ConstantCondValue;
2467 if (!hasBPFRelocatedCase(*this, S) &&
2468 ConstantFoldsToSimpleInteger(S.getCond(), ConstantCondValue)) {
2470 const SwitchCase *Case = nullptr;
2471 if (FindCaseStatementsForValue(S, ConstantCondValue, CaseStmts,
2472 getContext(), Case)) {
2473 if (Case)
2475 RunCleanupsScope ExecutedScope(*this);
2476
2477 if (S.getInit())
2478 EmitStmt(S.getInit());
2479
2480 // Emit the condition variable if needed inside the entire cleanup scope
2481 // used by this special case for constant folded switches.
2482 if (S.getConditionVariable())
2483 EmitDecl(*S.getConditionVariable(), /*EvaluateConditionDecl=*/true);
2484
2485 // At this point, we are no longer "within" a switch instance, so
2486 // we can temporarily enforce this to ensure that any embedded case
2487 // statements are not emitted.
2488 SwitchInsn = nullptr;
2489
2490 // Okay, we can dead code eliminate everything except this case. Emit the
2491 // specified series of statements and we're good.
2492 for (const Stmt *CaseStmt : CaseStmts)
2495 PGO->markStmtMaybeUsed(S.getBody());
2496
2497 // Now we want to restore the saved switch instance so that nested
2498 // switches continue to function properly
2499 SwitchInsn = SavedSwitchInsn;
2500
2501 return;
2502 }
2503 }
2504
2505 JumpDest SwitchExit = getJumpDestInCurrentScope("sw.epilog");
2506
2507 RunCleanupsScope ConditionScope(*this);
2508
2509 if (S.getInit()) {
2510 EmitStmt(S.getInit());
2511
2512 // The init statement may have cleared the insertion point (e.g. it ended in
2513 // a 'noreturn' call); the condition emitted below needs a valid one.
2515 }
2516
2517 if (S.getConditionVariable())
2519 llvm::Value *CondV = EmitScalarExpr(S.getCond());
2521
2522 // Create basic block to hold stuff that comes after switch
2523 // statement. We also need to create a default block now so that
2524 // explicit case ranges tests can have a place to jump to on
2525 // failure.
2526 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
2527
2528 // The dispatch is the jump that bypasses any declarations sitting between the
2529 // switch and its case labels, so the initialization goes here, ahead of the
2530 // switch instruction -- not at the case labels. A case label is also reached
2531 // by falling through from the case above it, and that edge bypasses nothing;
2532 // initializing there would clobber a variable the previous case had written.
2533 // The declarations are inside the body and so have no alloca yet, hence the
2534 // patch-it-in-later handling in EmitAutoVarAlloca.
2535 if (!Bypasses.isAlwaysBypassed())
2536 BypassingForwardJumps.push_back({Builder.GetInsertBlock(), &S});
2537
2538 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
2539 addInstToNewSourceAtom(SwitchInsn, CondV);
2540
2541 if (HLSLControlFlowAttr != HLSLControlFlowHintAttr::SpellingNotCalculated) {
2542 llvm::MDBuilder MDHelper(CGM.getLLVMContext());
2543 llvm::ConstantInt *BranchHintConstant =
2545 HLSLControlFlowHintAttr::Spelling::Microsoft_branch
2546 ? llvm::ConstantInt::get(CGM.Int32Ty, 1)
2547 : llvm::ConstantInt::get(CGM.Int32Ty, 2);
2548 llvm::Metadata *Vals[] = {MDHelper.createString("hlsl.controlflow.hint"),
2549 MDHelper.createConstant(BranchHintConstant)};
2550 SwitchInsn->setMetadata("hlsl.controlflow.hint",
2551 llvm::MDNode::get(CGM.getLLVMContext(), Vals));
2552 }
2553
2554 if (PGO->haveRegionCounts()) {
2555 // Walk the SwitchCase list to find how many there are.
2556 uint64_t DefaultCount = 0;
2557 unsigned NumCases = 0;
2558 for (const SwitchCase *Case = S.getSwitchCaseList();
2559 Case;
2560 Case = Case->getNextSwitchCase()) {
2561 if (isa<DefaultStmt>(Case))
2562 DefaultCount = getProfileCount(Case);
2563 NumCases += 1;
2564 }
2565 SwitchWeights = new SmallVector<uint64_t, 16>();
2566 SwitchWeights->reserve(NumCases);
2567 // The default needs to be first. We store the edge count, so we already
2568 // know the right weight.
2569 SwitchWeights->push_back(DefaultCount);
2570 } else if (CGM.getCodeGenOpts().OptimizationLevel) {
2571 SwitchLikelihood = new SmallVector<Stmt::Likelihood, 16>();
2572 // Initialize the default case.
2573 SwitchLikelihood->push_back(Stmt::LH_None);
2574 }
2575
2576 CaseRangeBlock = DefaultBlock;
2577
2578 // Clear the insertion point to indicate we are in unreachable code.
2579 Builder.ClearInsertionPoint();
2580
2581 // All break statements jump to NextBlock. If BreakContinueStack is non-empty
2582 // then reuse last ContinueBlock.
2583 JumpDest OuterContinue;
2584 if (!BreakContinueStack.empty())
2585 OuterContinue = BreakContinueStack.back().ContinueBlock;
2586
2587 BreakContinueStack.push_back(BreakContinue(S, SwitchExit, OuterContinue));
2588
2589 // Emit switch body.
2590 EmitStmt(S.getBody());
2591
2592 BreakContinueStack.pop_back();
2593
2594 // Update the default block in case explicit case range tests have
2595 // been chained on top.
2596 SwitchInsn->setDefaultDest(CaseRangeBlock);
2597
2598 // If a default was never emitted:
2599 if (!DefaultBlock->getParent()) {
2600 // If we have cleanups, emit the default block so that there's a
2601 // place to jump through the cleanups from.
2602 if (ConditionScope.requiresCleanups()) {
2603 EmitBlock(DefaultBlock);
2604
2605 // Otherwise, just forward the default block to the switch end.
2606 } else {
2607 DefaultBlock->replaceAllUsesWith(SwitchExit.getBlock());
2608 delete DefaultBlock;
2609 }
2610 }
2611
2612 ConditionScope.ForceCleanup();
2613
2614 // Close the last case (or DefaultBlock).
2615 EmitBranch(SwitchExit.getBlock());
2616
2617 // Insert a False Counter if SwitchStmt doesn't have DefaultStmt.
2618 if (hasSkipCounter(S.getCond())) {
2619 auto *ImplicitDefaultBlock = createBasicBlock("sw.false");
2620 EmitBlock(ImplicitDefaultBlock);
2622 Builder.CreateBr(SwitchInsn->getDefaultDest());
2623 SwitchInsn->setDefaultDest(ImplicitDefaultBlock);
2624 }
2625
2626 // Emit continuation.
2627 EmitBlock(SwitchExit.getBlock(), true);
2629
2630 // If the switch has a condition wrapped by __builtin_unpredictable,
2631 // create metadata that specifies that the switch is unpredictable.
2632 // Don't bother if not optimizing because that metadata would not be used.
2633 auto *Call = dyn_cast<CallExpr>(S.getCond());
2634 if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
2635 auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
2636 if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
2637 llvm::MDBuilder MDHelper(getLLVMContext());
2638 SwitchInsn->setMetadata(llvm::LLVMContext::MD_unpredictable,
2639 MDHelper.createUnpredictable());
2640 }
2641 }
2642
2643 if (SwitchWeights) {
2644 assert(SwitchWeights->size() == 1 + SwitchInsn->getNumCases() &&
2645 "switch weights do not match switch cases");
2646 // If there's only one jump destination there's no sense weighting it.
2647 if (SwitchWeights->size() > 1)
2648 SwitchInsn->setMetadata(llvm::LLVMContext::MD_prof,
2649 createProfileWeights(*SwitchWeights));
2650 delete SwitchWeights;
2651 } else if (SwitchLikelihood) {
2652 assert(SwitchLikelihood->size() == 1 + SwitchInsn->getNumCases() &&
2653 "switch likelihoods do not match switch cases");
2654 std::optional<SmallVector<uint64_t, 16>> LHW =
2655 getLikelihoodWeights(*SwitchLikelihood);
2656 if (LHW) {
2657 llvm::MDBuilder MDHelper(CGM.getLLVMContext());
2658 SwitchInsn->setMetadata(llvm::LLVMContext::MD_prof,
2659 createProfileWeights(*LHW));
2660 }
2661 delete SwitchLikelihood;
2662 }
2663 SwitchInsn = SavedSwitchInsn;
2664 SwitchWeights = SavedSwitchWeights;
2665 SwitchLikelihood = SavedSwitchLikelihood;
2666 CaseRangeBlock = SavedCRBlock;
2667}
2668
2669std::pair<llvm::Value*, llvm::Type *> CodeGenFunction::EmitAsmInputLValue(
2670 const TargetInfo::ConstraintInfo &Info, LValue InputValue,
2671 QualType InputType, std::string &ConstraintStr, SourceLocation Loc) {
2672 if (Info.allowsRegister() || !Info.allowsMemory()) {
2674 return {EmitLoadOfLValue(InputValue, Loc).getScalarVal(), nullptr};
2675
2676 llvm::Type *Ty = ConvertType(InputType);
2677 uint64_t Size = CGM.getDataLayout().getTypeSizeInBits(Ty);
2678 if ((Size <= 64 && llvm::isPowerOf2_64(Size)) ||
2679 getTargetHooks().isScalarizableAsmOperand(*this, Ty)) {
2680 Ty = llvm::IntegerType::get(getLLVMContext(), Size);
2681
2682 return {Builder.CreateLoad(InputValue.getAddress().withElementType(Ty)),
2683 nullptr};
2684 }
2685 }
2686
2687 Address Addr = InputValue.getAddress();
2688 ConstraintStr += '*';
2689 return {InputValue.getPointer(*this), Addr.getElementType()};
2690}
2691std::pair<llvm::Value *, llvm::Type *>
2692CodeGenFunction::EmitAsmInput(const TargetInfo::ConstraintInfo &Info,
2693 const Expr *InputExpr,
2694 std::string &ConstraintStr) {
2695 // If this can't be a register or memory, i.e., has to be a constant
2696 // (immediate or symbolic), try to emit it as such.
2697 if (!Info.allowsRegister() && !Info.allowsMemory()) {
2698 if (Info.requiresImmediateConstant()) {
2699 Expr::EvalResult EVResult;
2700 InputExpr->EvaluateAsRValue(EVResult, getContext(), true);
2701
2702 llvm::APSInt IntResult;
2703 if (EVResult.Val.toIntegralConstant(IntResult, InputExpr->getType(),
2704 getContext()))
2705 return {llvm::ConstantInt::get(getLLVMContext(), IntResult), nullptr};
2706 }
2707
2708 Expr::EvalResult Result;
2709 if (InputExpr->EvaluateAsInt(Result, getContext()))
2710 return {llvm::ConstantInt::get(getLLVMContext(), Result.Val.getInt()),
2711 nullptr};
2712 }
2713
2714 if (Info.allowsRegister() || !Info.allowsMemory())
2716 return {EmitScalarExpr(InputExpr), nullptr};
2717 if (InputExpr->getStmtClass() == Expr::CXXThisExprClass)
2718 return {EmitScalarExpr(InputExpr), nullptr};
2719 InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
2720 LValue Dest = EmitLValue(InputExpr);
2721 return EmitAsmInputLValue(Info, Dest, InputExpr->getType(), ConstraintStr,
2722 InputExpr->getExprLoc());
2723}
2724
2725/// getAsmSrcLocInfo - Return the !srcloc metadata node to attach to an inline
2726/// asm call instruction. The !srcloc MDNode contains a list of constant
2727/// integers which are the source locations of the start of each line in the
2728/// asm.
2729static llvm::MDNode *getAsmSrcLocInfo(const StringLiteral *Str,
2730 CodeGenFunction &CGF) {
2732 // Add the location of the first line to the MDNode.
2733 Locs.push_back(llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
2734 CGF.Int64Ty, Str->getBeginLoc().getRawEncoding())));
2735 StringRef StrVal = Str->getString();
2736 if (!StrVal.empty()) {
2737 const SourceManager &SM = CGF.CGM.getContext().getSourceManager();
2738 const LangOptions &LangOpts = CGF.CGM.getLangOpts();
2739 unsigned StartToken = 0;
2740 unsigned ByteOffset = 0;
2741
2742 // Add the location of the start of each subsequent line of the asm to the
2743 // MDNode.
2744 for (unsigned i = 0, e = StrVal.size() - 1; i != e; ++i) {
2745 if (StrVal[i] != '\n') continue;
2746 SourceLocation LineLoc = Str->getLocationOfByte(
2747 i + 1, SM, LangOpts, CGF.getTarget(), &StartToken, &ByteOffset);
2748 Locs.push_back(llvm::ConstantAsMetadata::get(
2749 llvm::ConstantInt::get(CGF.Int64Ty, LineLoc.getRawEncoding())));
2750 }
2751 }
2752
2753 return llvm::MDNode::get(CGF.getLLVMContext(), Locs);
2754}
2755
2756namespace clang {
2757
2758/// This structure holds the information gathered about the constraints for an
2759/// inline assembly statement. It helps in separating the constraint processing
2760/// from the code generation.
2762 CodeGenFunction &CGF;
2763 CodeGenModule &CGM; // Per-module state.
2764 const AsmStmt &S;
2765 CGBuilderTy &Builder;
2766
2767 // The final asm string.
2768 std::string AsmString;
2769
2770 // The output and input constraints.
2771 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
2772 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
2773
2774 // Constraint strings.
2775 std::string Constraints;
2776 std::string InOutConstraints;
2777
2778 // Keep track of out constraints for tied input operand.
2779 std::vector<std::string> OutputConstraints;
2780
2781 // Keep track of argument types.
2782 std::vector<llvm::Value *> Args;
2783 std::vector<llvm::Type *> ArgTypes;
2784 std::vector<llvm::Type *> ArgElemTypes;
2785
2786 // Keep track of result register constraints.
2787 std::vector<LValue> ResultRegDests;
2788 std::vector<QualType> ResultRegQualTys;
2789 std::vector<llvm::Type *> ResultRegTypes;
2790 std::vector<llvm::Type *> ResultTruncRegTypes;
2791
2792 llvm::BitVector ResultTypeRequiresCast;
2793
2794 // Keep track of in/out constraints.
2795 std::vector<llvm::Value *> InOutArgs;
2796 std::vector<llvm::Type *> InOutArgTypes;
2797 std::vector<llvm::Type *> InOutArgElemTypes;
2798
2799 // Destination blocks for 'asm gotos'.
2800 llvm::BasicBlock *DefaultDest = nullptr;
2802
2803 std::vector<std::optional<std::pair<unsigned, unsigned>>> ResultBounds;
2804
2805 // An inline asm can be marked readonly if it meets the following
2806 // conditions:
2807 //
2808 // - it doesn't have any sideeffects
2809 // - it doesn't clobber memory
2810 // - it doesn't return a value by-reference
2811 //
2812 // It can be marked readnone if it doesn't have any input memory
2813 // constraints in addition to meeting the conditions listed above.
2814 bool ReadOnly = true;
2815 bool ReadNone = true;
2816
2817 bool GetOutputAndInputConstraints();
2818 void HandleOutputConstraints();
2819 void HandleMSStyleAsmBlob();
2820 void HandleInputConstraints();
2821 bool HandleLabels();
2822 bool HandleClobbers();
2823 void UpdateAsmCallInst(llvm::CallBase &Result, bool HasSideEffect,
2824 bool HasUnwindClobber, bool NoMerge, bool NoConvergent,
2825 std::vector<llvm::Value *> &RegResults);
2826 void EmitAsmStores(const llvm::ArrayRef<llvm::Value *> RegResults);
2827
2828 void EmitHipStdParUnsupportedAsm() {
2829 constexpr auto Name = "__ASM__hipstdpar_unsupported";
2830
2831 std::string Asm;
2832 if (auto GCCAsm = dyn_cast<GCCAsmStmt>(&S))
2833 Asm = GCCAsm->getAsmString();
2834
2835 auto &Ctx = getLLVMContext();
2836 auto StrTy = llvm::ConstantDataArray::getString(Ctx, Asm);
2837 auto FnTy = llvm::FunctionType::get(llvm::Type::getVoidTy(Ctx),
2838 {StrTy->getType()}, false);
2839 auto UBF = CGM.getModule().getOrInsertFunction(Name, FnTy);
2840
2841 Builder.CreateCall(UBF, {StrTy});
2842 }
2843
2844 ASTContext &getContext() { return CGF.getContext(); }
2845 llvm::LLVMContext &getLLVMContext() { return CGF.getLLVMContext(); }
2846 const TargetInfo &getTarget() const { return CGF.getTarget(); }
2847 const LangOptions &getLangOpts() const { return CGF.getLangOpts(); }
2848 const TargetCodeGenInfo &getTargetHooks() const {
2849 return CGM.getTargetCodeGenInfo();
2850 }
2851
2852public:
2854 : CGF(CGF), CGM(CGF.CGM), S(S), Builder(CGF.Builder),
2855 AsmString(S.generateAsmString(CGF.getContext())) {}
2856
2857 void EmitAsmStmt();
2858};
2859
2860} // namespace clang
2861
2863 // Pop all cleanup blocks at the end of the asm statement.
2864 CodeGenFunction::RunCleanupsScope Cleanups(*this);
2865
2866 // Get all the output and input constraints together.
2867 AsmConstraintsInfo AsmInfo(*this, S);
2868 AsmInfo.EmitAsmStmt();
2869}
2870
2872 if (!GetOutputAndInputConstraints())
2873 return EmitHipStdParUnsupportedAsm();
2874
2875 // Handle output constraints.
2876 HandleOutputConstraints();
2877
2878 // If this is a Microsoft-style asm blob, store the return registers (EAX:EDX)
2879 // to the return value slot. Only do this when returning in registers.
2880 HandleMSStyleAsmBlob();
2881
2882 // Handle input constraints.
2883 HandleInputConstraints();
2884
2885 // Handle 'asm goto' labels.
2886 bool IsGCCAsmGoto = HandleLabels();
2887
2888 // Handle any clobbers.
2889 bool HasUnwindClobber = HandleClobbers();
2890 assert(!(HasUnwindClobber && IsGCCAsmGoto) &&
2891 "unwind clobber can't be used with asm goto");
2892
2893 // Add machine specific clobbers
2894 std::string_view MachineClobbers = getTarget().getClobbers();
2895 if (!MachineClobbers.empty()) {
2896 if (!Constraints.empty())
2897 Constraints += ',';
2898 Constraints += MachineClobbers;
2899 }
2900
2901 llvm::Type *ResultType;
2902 if (ResultRegTypes.empty())
2903 ResultType = CGF.VoidTy;
2904 else if (ResultRegTypes.size() == 1)
2905 ResultType = ResultRegTypes[0];
2906 else
2907 ResultType = llvm::StructType::get(getLLVMContext(), ResultRegTypes);
2908
2909 llvm::FunctionType *FTy =
2910 llvm::FunctionType::get(ResultType, ArgTypes, false);
2911
2912 bool HasSideEffect = S.isVolatile() || S.getNumOutputs() == 0;
2913
2914 llvm::InlineAsm::AsmDialect GnuAsmDialect =
2915 CGM.getCodeGenOpts().getInlineAsmDialect() == CodeGenOptions::IAD_ATT
2916 ? llvm::InlineAsm::AD_ATT
2917 : llvm::InlineAsm::AD_Intel;
2918 llvm::InlineAsm::AsmDialect AsmDialect =
2919 isa<MSAsmStmt>(&S) ? llvm::InlineAsm::AD_Intel : GnuAsmDialect;
2920
2921 llvm::InlineAsm *IA = llvm::InlineAsm::get(
2922 FTy, AsmString, Constraints, HasSideEffect,
2923 /* IsAlignStack */ false, AsmDialect, HasUnwindClobber);
2924 std::vector<llvm::Value *> RegResults;
2925 llvm::CallBrInst *CBR;
2926 llvm::DenseMap<llvm::BasicBlock *, SmallVector<llvm::Value *, 4>>
2927 CBRRegResults;
2928
2929 if (IsGCCAsmGoto) {
2930 if (CGF.HaveInsertPoint() && !CGF.Bypasses.isAlwaysBypassed()) {
2931 CGF.emitBypassedVarInitsForSource(&S);
2932 CGF.BypassingForwardJumps.push_back({Builder.GetInsertBlock(), &S});
2933 }
2934 CBR = Builder.CreateCallBr(IA, DefaultDest, IndirectDests, Args);
2935 CGF.EmitBlock(DefaultDest);
2936 UpdateAsmCallInst(*CBR, HasSideEffect,
2937 /*HasUnwindClobber=*/false, CGF.InNoMergeAttributedStmt,
2938 CGF.InNoConvergentAttributedStmt, RegResults);
2939
2940 // Because we are emitting code top to bottom, we don't have enough
2941 // information at this point to know precisely whether we have a critical
2942 // edge. If we have outputs, split all indirect destinations.
2943 if (!RegResults.empty()) {
2944 unsigned I = 0;
2945 for (llvm::BasicBlock *Dest : CBR->getIndirectDests()) {
2946 llvm::Twine SynthName = Dest->getName() + ".split";
2947 llvm::BasicBlock *SynthBB = CGF.createBasicBlock(SynthName);
2948 llvm::IRBuilderBase::InsertPointGuard IPG(Builder);
2949 Builder.SetInsertPoint(SynthBB);
2950
2951 if (ResultRegTypes.size() == 1) {
2952 CBRRegResults[SynthBB].push_back(CBR);
2953 } else {
2954 for (unsigned J = 0, E = ResultRegTypes.size(); J != E; ++J) {
2955 llvm::Value *Tmp = Builder.CreateExtractValue(CBR, J, "asmresult");
2956 CBRRegResults[SynthBB].push_back(Tmp);
2957 }
2958 }
2959
2960 CGF.EmitBranch(Dest);
2961 CGF.EmitBlock(SynthBB);
2962 CBR->setIndirectDest(I++, SynthBB);
2963 }
2964 }
2965 } else if (HasUnwindClobber) {
2966 llvm::CallBase *Result = CGF.EmitCallOrInvoke(IA, Args, "");
2967 UpdateAsmCallInst(*Result, HasSideEffect,
2968 /*HasUnwindClobber=*/true, CGF.InNoMergeAttributedStmt,
2969 CGF.InNoConvergentAttributedStmt, RegResults);
2970 } else {
2971 llvm::CallInst *Result =
2972 Builder.CreateCall(IA, Args, CGF.getBundlesForFunclet(IA));
2973 UpdateAsmCallInst(*Result, HasSideEffect,
2974 /*HasUnwindClobber=*/false, CGF.InNoMergeAttributedStmt,
2975 CGF.InNoConvergentAttributedStmt, RegResults);
2976 }
2977
2978 EmitAsmStores(RegResults);
2979
2980 // If this is an asm goto with outputs, repeat EmitAsmStores, but with a
2981 // different insertion point; one for each indirect destination and with
2982 // CBRRegResults rather than RegResults.
2983 if (IsGCCAsmGoto && !CBRRegResults.empty()) {
2984 for (llvm::BasicBlock *Succ : CBR->getIndirectDests()) {
2985 llvm::IRBuilderBase::InsertPointGuard IPG(Builder);
2986 Builder.SetInsertPoint(--(Succ->end()));
2987 EmitAsmStores(CBRRegResults[Succ]);
2988 }
2989 }
2990}
2991
2992/// Gather and validate the output and input constraints for the given inline
2993/// assembly statement. This ensures that the constraints are valid for the
2994/// target and prepares them for further processing.
2995bool AsmConstraintsInfo::GetOutputAndInputConstraints() {
2996 bool IsValidTargetAsm = true;
2997 bool IsHipStdPar = getLangOpts().HIPStdPar && getLangOpts().CUDAIsDevice;
2998 for (unsigned I = 0, E = S.getNumOutputs(); I != E && IsValidTargetAsm; I++) {
2999 StringRef Name;
3000 if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
3001 Name = GAS->getOutputName(I);
3002
3003 TargetInfo::ConstraintInfo Info(S.getOutputConstraint(I), Name);
3004
3005 bool IsValid = getTarget().validateOutputConstraint(Info);
3006 if (IsHipStdPar && !IsValid)
3007 IsValidTargetAsm = false;
3008 else
3009 assert(IsValid && "Failed to parse output constraint");
3010
3011 OutputConstraintInfos.push_back(Info);
3012 }
3013
3014 for (unsigned I = 0, E = S.getNumInputs(); I != E && IsValidTargetAsm; I++) {
3015 StringRef Name;
3016 if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
3017 Name = GAS->getInputName(I);
3018
3019 TargetInfo::ConstraintInfo Info(S.getInputConstraint(I), Name);
3020
3021 bool IsValid =
3022 getTarget().validateInputConstraint(OutputConstraintInfos, Info);
3023 if (IsHipStdPar && !IsValid)
3024 IsValidTargetAsm = false;
3025 else
3026 assert(IsValid && "Failed to parse input constraint");
3027
3028 InputConstraintInfos.push_back(Info);
3029 }
3030
3031 return IsValidTargetAsm;
3032}
3033
3034/// Process the output constraints of an inline assembly statement. This method
3035/// handles the complexity of determining whether an output should be a
3036/// register or memory operand, manages tied operands, and prepares the
3037/// necessary arguments for the LLVM inline asm call.
3038void AsmConstraintsInfo::HandleOutputConstraints() {
3039 // Keep track of defined physregs.
3040 llvm::SmallSet<std::string, 8> PhysRegOutputs;
3041
3042 for (unsigned I = 0, E = S.getNumOutputs(); I != E; I++) {
3043 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[I];
3044
3045 // Simplify the output constraint.
3046 std::string OutputConstraint(S.getOutputConstraint(I));
3047 OutputConstraint = getTarget().simplifyConstraint(
3048 StringRef(OutputConstraint).substr(1), &OutputConstraintInfos);
3049
3050 const Expr *OutExpr = S.getOutputExpr(I);
3051 OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
3052
3053 std::string GCCReg;
3054 OutputConstraint = S.addVariableConstraints(
3055 OutputConstraint, *OutExpr, getTarget(), Info.earlyClobber(),
3056 [&](const Stmt *UnspStmt, StringRef Msg) {
3057 CGM.ErrorUnsupported(UnspStmt, Msg);
3058 },
3059 &GCCReg);
3060
3061 // Give an error on multiple outputs to same physreg.
3062 if (!GCCReg.empty() && !PhysRegOutputs.insert(GCCReg).second)
3063 CGM.Error(S.getAsmLoc(), "multiple outputs to hard register: " + GCCReg);
3064
3065 OutputConstraints.push_back(OutputConstraint);
3066 LValue Dest = CGF.EmitLValue(OutExpr);
3067 if (!Constraints.empty())
3068 Constraints += ',';
3069
3070 // If this is a register output, then make the inline asm return it
3071 // by-value. If this is a memory result, return the value by-reference.
3072 QualType QTy = OutExpr->getType();
3073 const bool IsScalarOrAggregate =
3076
3077 if (!Info.allowsMemory() && IsScalarOrAggregate) {
3078 Constraints += "=" + OutputConstraint;
3079 ResultRegQualTys.push_back(QTy);
3080 ResultRegDests.push_back(Dest);
3081
3082 ResultBounds.emplace_back(Info.getOutputOperandBounds());
3083
3084 llvm::Type *Ty = CGF.ConvertTypeForMem(QTy);
3085 const bool RequiresCast =
3086 Info.allowsRegister() &&
3087 (getTargetHooks().isScalarizableAsmOperand(CGF, Ty) ||
3088 Ty->isAggregateType());
3089
3090 ResultTruncRegTypes.push_back(Ty);
3091 ResultTypeRequiresCast.push_back(RequiresCast);
3092
3093 if (RequiresCast) {
3094 if (unsigned Size = getContext().getTypeSize(QTy))
3095 Ty = llvm::IntegerType::get(getLLVMContext(), Size);
3096 else
3097 CGM.Error(OutExpr->getExprLoc(), "output size should not be zero");
3098 }
3099
3100 ResultRegTypes.push_back(Ty);
3101
3102 // If this output is tied to an input, and if the input is larger, then
3103 // we need to set the actual result type of the inline asm node to be the
3104 // same as the input type.
3105 if (Info.hasMatchingInput()) {
3106 unsigned InputNo;
3107 for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) {
3108 TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo];
3109 if (Input.hasTiedOperand() && Input.getTiedOperand() == I)
3110 break;
3111 }
3112 assert(InputNo != S.getNumInputs() && "Didn't find matching input!");
3113
3114 QualType InputTy = S.getInputExpr(InputNo)->getType();
3115 QualType OutputType = OutExpr->getType();
3116
3117 uint64_t InputSize = getContext().getTypeSize(InputTy);
3118 if (getContext().getTypeSize(OutputType) < InputSize)
3119 // Form the asm to return the value as a larger integer or fp type.
3120 ResultRegTypes.back() = CGF.ConvertType(InputTy);
3121 }
3122
3123 if (llvm::Type *AdjTy = getTargetHooks().adjustInlineAsmType(
3124 CGF, OutputConstraint, ResultRegTypes.back()))
3125 ResultRegTypes.back() = AdjTy;
3126 else
3127 CGM.getDiags().Report(S.getAsmLoc(),
3128 diag::err_asm_invalid_type_in_input)
3129 << OutExpr->getType() << OutputConstraint;
3130
3131 // Update largest vector width for any vector types.
3132 if (auto *VT = dyn_cast<llvm::VectorType>(ResultRegTypes.back()))
3133 CGF.LargestVectorWidth =
3134 std::max((uint64_t)CGF.LargestVectorWidth,
3135 VT->getPrimitiveSizeInBits().getKnownMinValue());
3136 } else {
3137 Address DestAddr = Dest.getAddress();
3138
3139 // Matrix types in memory are represented by arrays, but accessed through
3140 // vector pointers, with the alignment specified on the access operation.
3141 // For inline assembly, update pointer arguments to use vector pointers.
3142 // Otherwise there will be a mis-match if the matrix is also an
3143 // input-argument which is represented as vector.
3144 if (isa<MatrixType>(OutExpr->getType().getCanonicalType()))
3145 DestAddr =
3146 DestAddr.withElementType(CGF.ConvertType(OutExpr->getType()));
3147
3148 ArgTypes.push_back(DestAddr.getType());
3149 ArgElemTypes.push_back(DestAddr.getElementType());
3150 Args.push_back(DestAddr.emitRawPointer(CGF));
3151
3152 Constraints += "=*" + OutputConstraint;
3153 ReadOnly = false;
3154 ReadNone = false;
3155 }
3156
3157 if (!Info.isReadWrite())
3158 continue;
3159
3160 InOutConstraints += ',';
3161
3162 const Expr *InputExpr = S.getOutputExpr(I);
3163 llvm::Value *Arg;
3164 llvm::Type *ArgElemType;
3165 std::tie(Arg, ArgElemType) =
3166 CGF.EmitAsmInputLValue(Info, Dest, InputExpr->getType(),
3167 InOutConstraints, InputExpr->getExprLoc());
3168
3169 if (llvm::Type *AdjTy = getTargetHooks().adjustInlineAsmType(
3170 CGF, OutputConstraint, Arg->getType()))
3171 Arg = Builder.CreateBitCast(Arg, AdjTy);
3172
3173 // Update largest vector width for any vector types.
3174 if (auto *VT = dyn_cast<llvm::VectorType>(Arg->getType()))
3175 CGF.LargestVectorWidth =
3176 std::max((uint64_t)CGF.LargestVectorWidth,
3177 VT->getPrimitiveSizeInBits().getKnownMinValue());
3178
3179 // Only tie earlyclobber physregs.
3180 if (Info.allowsRegister() && (GCCReg.empty() || Info.earlyClobber()))
3181 InOutConstraints += llvm::utostr(I);
3182 else
3183 InOutConstraints += OutputConstraint;
3184
3185 InOutArgTypes.push_back(Arg->getType());
3186 InOutArgElemTypes.push_back(ArgElemType);
3187 InOutArgs.push_back(Arg);
3188 }
3189}
3190
3191/// Special handling for Microsoft-style inline assembly blocks. This ensures
3192/// that return registers (like EAX:EDX) are correctly mapped to the function's
3193/// return value slot when necessary.
3194void AsmConstraintsInfo::HandleMSStyleAsmBlob() {
3195 if (!isa<MSAsmStmt>(&S))
3196 return;
3197
3198 const ABIArgInfo &RetAI = CGF.CurFnInfo->getReturnInfo();
3199 if (!RetAI.isDirect() && !RetAI.isExtend())
3200 return;
3201
3202 // Make a fake lvalue for the return value slot.
3203 LValue ReturnSlot =
3205 CGM.getTargetCodeGenInfo().addReturnRegisterOutputs(
3206 CGF, ReturnSlot, Constraints, ResultRegTypes, ResultTruncRegTypes,
3207 ResultRegDests, AsmString, S.getNumOutputs());
3208 CGF.SawAsmBlock = true;
3209}
3210
3211/// Process the input constraints of an inline assembly statement. It handles
3212/// type conversions, extensions for tied operands, and collects the necessary
3213/// LLVM values to be passed to the inline assembly call.
3214void AsmConstraintsInfo::HandleInputConstraints() {
3215 ASTContext &Ctx = getContext();
3216
3217 for (unsigned I = 0, E = S.getNumInputs(); I != E; I++) {
3218 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[I];
3219 const Expr *InputExpr = S.getInputExpr(I);
3220
3221 if (Info.allowsMemory())
3222 ReadNone = false;
3223
3224 if (!Constraints.empty())
3225 Constraints += ',';
3226
3227 // Simplify the input constraint.
3228 std::string InputConstraint(S.getInputConstraint(I));
3229 InputConstraint =
3230 getTarget().simplifyConstraint(InputConstraint, &OutputConstraintInfos);
3231
3232 InputConstraint = S.addVariableConstraints(
3233 InputConstraint, *InputExpr->IgnoreParenNoopCasts(Ctx), getTarget(),
3234 false /* No EarlyClobber */,
3235 [&](const Stmt *UnspStmt, std::string_view Msg) {
3236 CGM.ErrorUnsupported(UnspStmt, Msg);
3237 });
3238
3239 std::string ReplaceConstraint(InputConstraint);
3240 llvm::Value *Arg;
3241 llvm::Type *ArgElemType;
3242 std::tie(Arg, ArgElemType) = CGF.EmitAsmInput(Info, InputExpr, Constraints);
3243
3244 // If this input argument is tied to a larger output result, extend the
3245 // input to be the same size as the output. The LLVM backend wants to see
3246 // the input and output of a matching constraint be the same size. Note
3247 // that GCC does not define what the top bits are here. We use zext because
3248 // that is usually cheaper, but LLVM IR should really get an anyext someday.
3249 if (Info.hasTiedOperand()) {
3250 unsigned Output = Info.getTiedOperand();
3251 QualType OutputType = S.getOutputExpr(Output)->getType();
3252 QualType InputTy = InputExpr->getType();
3253
3254 if (Ctx.getTypeSize(OutputType) > Ctx.getTypeSize(InputTy)) {
3255 // Use ptrtoint as appropriate so that we can do our extension.
3256 if (isa<llvm::PointerType>(Arg->getType()))
3257 Arg = Builder.CreatePtrToInt(Arg, CGF.IntPtrTy);
3258
3259 llvm::Type *OutputTy = CGF.ConvertType(OutputType);
3260 if (isa<llvm::IntegerType>(OutputTy))
3261 Arg = Builder.CreateZExt(Arg, OutputTy);
3262 else if (isa<llvm::PointerType>(OutputTy))
3263 Arg = Builder.CreateZExt(Arg, CGF.IntPtrTy);
3264 else if (OutputTy->isFloatingPointTy())
3265 Arg = Builder.CreateFPExt(Arg, OutputTy);
3266 }
3267
3268 // Deal with the tied operands' constraint code in adjustInlineAsmType.
3269 ReplaceConstraint = OutputConstraints[Output];
3270 }
3271
3272 if (llvm::Type *AdjTy = getTargetHooks().adjustInlineAsmType(
3273 CGF, ReplaceConstraint, Arg->getType()))
3274 Arg = Builder.CreateBitCast(Arg, AdjTy);
3275 else
3276 CGM.getDiags().Report(S.getAsmLoc(), diag::err_asm_invalid_type_in_input)
3277 << InputExpr->getType() << InputConstraint;
3278
3279 // Update largest vector width for any vector types.
3280 if (auto *VT = dyn_cast<llvm::VectorType>(Arg->getType()))
3281 CGF.LargestVectorWidth =
3282 std::max((uint64_t)CGF.LargestVectorWidth,
3283 VT->getPrimitiveSizeInBits().getKnownMinValue());
3284
3285 ArgTypes.push_back(Arg->getType());
3286 ArgElemTypes.push_back(ArgElemType);
3287 Args.push_back(Arg);
3288
3289 Constraints += InputConstraint;
3290 }
3291
3292 // Append the "input" part of in/out constraints.
3293 for (unsigned I = 0, E = InOutArgs.size(); I != E; I++) {
3294 ArgTypes.push_back(InOutArgTypes[I]);
3295 ArgElemTypes.push_back(InOutArgElemTypes[I]);
3296 Args.push_back(InOutArgs[I]);
3297 }
3298
3299 Constraints += InOutConstraints;
3300}
3301
3302/// Handle labels in an 'asm goto' statement. This method resolves the symbolic
3303/// labels to LLVM basic blocks and updates the constraint string to reflect
3304/// the indirect jump targets.
3305bool AsmConstraintsInfo::HandleLabels() {
3306 if (const auto *GS = dyn_cast<GCCAsmStmt>(&S); GS && GS->isAsmGoto()) {
3307 for (const auto *E : GS->labels()) {
3308 CodeGenFunction::JumpDest Dest = CGF.getJumpDestForLabel(E->getLabel());
3309 IndirectDests.push_back(Dest.getBlock());
3310
3311 if (!Constraints.empty())
3312 Constraints += ',';
3313
3314 Constraints += "!i";
3315 }
3316
3317 DefaultDest = CGF.createBasicBlock("asm.fallthrough");
3318 return true;
3319 }
3320
3321 return false;
3322}
3323
3324/// Process clobber constraints for an inline assembly statement. This
3325/// identifies which registers or system state (like "memory" or "cc") are
3326/// modified by the assembly block, which is crucial for correct optimization
3327/// and side-effect modeling.
3328bool AsmConstraintsInfo::HandleClobbers() {
3329 bool HasUnwindClobber = false;
3330 for (unsigned I = 0, E = S.getNumClobbers(); I != E; I++) {
3331 std::string Clobber = S.getClobber(I);
3332
3333 if (Clobber == "unwind") {
3334 HasUnwindClobber = true;
3335 continue;
3336 }
3337
3338 if (Clobber == "memory") {
3339 ReadOnly = false;
3340 ReadNone = false;
3341 } else if (Clobber != "cc") {
3342 Clobber = getTarget().getNormalizedGCCRegisterName(Clobber);
3343 if (CGM.getCodeGenOpts().StackClashProtector &&
3344 getTarget().isSPRegName(Clobber)) {
3345 CGM.getDiags().Report(S.getAsmLoc(),
3346 diag::warn_stack_clash_protection_inline_asm);
3347 }
3348 }
3349
3350 if (isa<MSAsmStmt>(&S)) {
3351 if (Clobber == "eax" || Clobber == "edx") {
3352 if (Constraints.find("=&A") != std::string::npos)
3353 continue;
3354
3355 std::string::size_type position1 =
3356 Constraints.find("={" + Clobber + "}");
3357 if (position1 != std::string::npos) {
3358 Constraints.insert(position1 + 1, "&");
3359 continue;
3360 }
3361
3362 std::string::size_type position2 = Constraints.find("=A");
3363 if (position2 != std::string::npos) {
3364 Constraints.insert(position2 + 1, "&");
3365 continue;
3366 }
3367 }
3368 }
3369
3370 if (!Constraints.empty())
3371 Constraints += ',';
3372
3373 Constraints += "~{" + Clobber + '}';
3374 }
3375
3376 return HasUnwindClobber;
3377}
3378
3379void AsmConstraintsInfo::UpdateAsmCallInst(
3380 llvm::CallBase &Result, bool HasSideEffect, bool HasUnwindClobber,
3381 bool NoMerge, bool NoConvergent, std::vector<llvm::Value *> &RegResults) {
3382 if (!HasUnwindClobber)
3383 Result.addFnAttr(llvm::Attribute::NoUnwind);
3384
3385 if (NoMerge)
3386 Result.addFnAttr(llvm::Attribute::NoMerge);
3387
3388 // Attach readnone and readonly attributes.
3389 if (!HasSideEffect) {
3390 if (ReadNone)
3391 Result.setDoesNotAccessMemory();
3392 else if (ReadOnly)
3393 Result.setOnlyReadsMemory();
3394 }
3395
3396 // Add elementtype attribute for indirect constraints.
3397 for (auto Pair : llvm::enumerate(ArgElemTypes)) {
3398 if (Pair.value()) {
3399 auto Attr = llvm::Attribute::get(
3400 getLLVMContext(), llvm::Attribute::ElementType, Pair.value());
3401 Result.addParamAttr(Pair.index(), Attr);
3402 }
3403 }
3404
3405 // Slap the source location of the inline asm into a !srcloc metadata on the
3406 // call.
3407 const StringLiteral *SL;
3408 if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(&S);
3409 gccAsmStmt &&
3410 (SL = dyn_cast<StringLiteral>(gccAsmStmt->getAsmStringExpr()))) {
3411 Result.setMetadata("srcloc", getAsmSrcLocInfo(SL, CGF));
3412 } else {
3413 // At least put the line number on MS inline asm blobs and GCC asm constexpr
3414 // strings.
3415 llvm::Constant *Loc =
3416 llvm::ConstantInt::get(CGF.Int64Ty, S.getAsmLoc().getRawEncoding());
3417 Result.setMetadata("srcloc",
3418 llvm::MDNode::get(getLLVMContext(),
3419 llvm::ConstantAsMetadata::get(Loc)));
3420 }
3421
3422 // Make inline-asm calls Key for the debug info feature Key Instructions.
3423 CGF.addInstToNewSourceAtom(&Result, nullptr);
3424
3425 if (!NoConvergent && getLangOpts().assumeFunctionsAreConvergent())
3426 // Conservatively, mark all inline asm blocks in CUDA or OpenCL as
3427 // convergent (meaning, they may call an intrinsically convergent op, such
3428 // as bar.sync, and so can't have certain optimizations applied around
3429 // them) unless it's explicitly marked 'noconvergent'.
3430 Result.addFnAttr(llvm::Attribute::Convergent);
3431
3432 // Extract all of the register value results from the asm.
3433 if (ResultRegTypes.size() == 1) {
3434 RegResults.push_back(&Result);
3435 } else {
3436 for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) {
3437 llvm::Value *Tmp = Builder.CreateExtractValue(&Result, i, "asmresult");
3438 RegResults.push_back(Tmp);
3439 }
3440 }
3441}
3442
3443void AsmConstraintsInfo::EmitAsmStores(
3444 const llvm::ArrayRef<llvm::Value *> RegResults) {
3445 llvm::LLVMContext &CTX = getLLVMContext();
3446
3447 assert(RegResults.size() == ResultRegTypes.size());
3448 assert(RegResults.size() == ResultTruncRegTypes.size());
3449 assert(RegResults.size() == ResultRegDests.size());
3450
3451 // ResultRegDests can also be populated by addReturnRegisterOutputs() above,
3452 // in which case its size may grow.
3453 assert(ResultTypeRequiresCast.size() <= ResultRegDests.size());
3454 assert(ResultBounds.size() <= ResultRegDests.size());
3455
3456 for (unsigned i = 0, e = RegResults.size(); i != e; ++i) {
3457 llvm::Value *Tmp = RegResults[i];
3458 llvm::Type *TruncTy = ResultTruncRegTypes[i];
3459
3460 if (i < ResultBounds.size() && ResultBounds[i].has_value()) {
3461 const auto [LowerBound, UpperBound] = ResultBounds[i].value();
3462
3463 // FIXME: Support for nonzero lower bounds not yet implemented.
3464 assert(LowerBound == 0 && "Output operand lower bound is not zero.");
3465
3466 llvm::Constant *UpperBoundConst =
3467 llvm::ConstantInt::get(Tmp->getType(), UpperBound);
3468 llvm::Value *IsBooleanValue =
3469 Builder.CreateCmp(llvm::CmpInst::ICMP_ULT, Tmp, UpperBoundConst);
3470 llvm::Function *FnAssume = CGM.getIntrinsic(llvm::Intrinsic::assume);
3471
3472 Builder.CreateCall(FnAssume, IsBooleanValue);
3473 }
3474
3475 // ResultTypeRequiresCast elements correspond to the first
3476 // ResultTypeRequiresCast.size() elements of RegResults.
3477 const bool RequiresCast =
3478 i < ResultTypeRequiresCast.size() && ResultTypeRequiresCast[i];
3479
3480 // If the result type of the LLVM IR asm doesn't match the result type of
3481 // the expression, do the conversion. An output returned as an integer is
3482 // converted where it's stored below.
3483 if (ResultRegTypes[i] != TruncTy && !RequiresCast) {
3484 // Truncate the integer result to the right size, note that TruncTy can be
3485 // a pointer.
3486 if (TruncTy->isFloatingPointTy())
3487 Tmp = Builder.CreateFPTrunc(Tmp, TruncTy);
3488 else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) {
3489 uint64_t ResSize = CGM.getDataLayout().getTypeSizeInBits(TruncTy);
3490 Tmp = Builder.CreateTrunc(
3491 Tmp, llvm::IntegerType::get(CTX, (unsigned)ResSize));
3492 Tmp = Builder.CreateIntToPtr(Tmp, TruncTy);
3493 } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) {
3494 uint64_t TmpSize =
3495 CGM.getDataLayout().getTypeSizeInBits(Tmp->getType());
3496 Tmp = Builder.CreatePtrToInt(
3497 Tmp, llvm::IntegerType::get(CTX, (unsigned)TmpSize));
3498 Tmp = Builder.CreateTrunc(Tmp, TruncTy);
3499 } else if (Tmp->getType()->isIntegerTy() && TruncTy->isIntegerTy()) {
3500 Tmp = Builder.CreateZExtOrTrunc(Tmp, TruncTy);
3501 } else if (Tmp->getType()->isVectorTy() || TruncTy->isVectorTy()) {
3502 Tmp = Builder.CreateBitCast(Tmp, TruncTy);
3503 }
3504 }
3505
3506 ApplyAtomGroup Grp(CGF.getDebugInfo());
3507 LValue Dest = ResultRegDests[i];
3508
3509 if (RequiresCast) {
3510 unsigned Size = getContext().getTypeSize(ResultRegQualTys[i]);
3511 Address A = Dest.getAddress().withElementType(ResultRegTypes[i]);
3512
3513 if (getTargetHooks().isScalarizableAsmOperand(CGF, TruncTy)) {
3514 llvm::StoreInst *S =
3515 Builder.CreateStore(Tmp, A, Dest.isVolatileQualified());
3516 CGF.addInstToCurrentSourceAtom(S, S->getValueOperand());
3517 continue;
3518 }
3519
3520 QualType Ty = getContext().getIntTypeForBitwidth(Size, /*Signed=*/false);
3521 if (Ty.isNull()) {
3522 const Expr *OutExpr = S.getOutputExpr(i);
3523 CGM.getDiags().Report(OutExpr->getExprLoc(),
3524 diag::err_store_value_to_reg);
3525 return;
3526 }
3527
3528 // The output's type may not be an integer: an output tied to a larger
3529 // input has the input's type (e.g., a pointer), and a mask register
3530 // output ("k" on X86) is a vector of i1. Convert it to an integer of the
3531 // same size, then store only the destination's bits.
3532 llvm::Type *IntTy = llvm::IntegerType::get(CTX, Size);
3533 uint64_t TmpSize = CGM.getDataLayout().getTypeSizeInBits(Tmp->getType());
3534 Tmp = Builder.CreateBitOrPointerCast(
3535 Tmp, llvm::IntegerType::get(CTX, (unsigned)TmpSize));
3536 Tmp = Builder.CreateTrunc(Tmp, IntTy);
3537
3538 // The store writes all of the destination's members at once, so it must
3539 // be allowed to alias an access to any of them. A TBAA access type must
3540 // be a scalar, so use may-alias (char), which aliases any access. Keep
3541 // the destination's qualifiers, such as volatile.
3542 Dest = CGF.MakeAddrLValue(
3543 Dest.getAddress().withElementType(IntTy),
3544 getContext().getQualifiedType(Ty, Dest.getQuals()),
3545 Dest.getBaseInfo(), TBAAAccessInfo::getMayAliasInfo());
3546 }
3547
3548 CGF.EmitStoreThroughLValue(RValue::get(Tmp), Dest);
3549 }
3550}
3551
3553 const RecordDecl *RD = S.getCapturedRecordDecl();
3554 CanQualType RecordTy = getContext().getCanonicalTagType(RD);
3555
3556 // Initialize the captured struct.
3557 LValue SlotLV =
3558 MakeAddrLValue(CreateMemTemp(RecordTy, "agg.captured"), RecordTy);
3559
3560 RecordDecl::field_iterator CurField = RD->field_begin();
3562 E = S.capture_init_end();
3563 I != E; ++I, ++CurField) {
3564 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
3565 if (CurField->hasCapturedVLAType()) {
3566 EmitLambdaVLACapture(CurField->getCapturedVLAType(), LV);
3567 } else {
3568 EmitInitializerForField(*CurField, LV, *I);
3569 }
3570 }
3571
3572 return SlotLV;
3573}
3574
3575/// Generate an outlined function for the body of a CapturedStmt, store any
3576/// captured variables into the captured struct, and call the outlined function.
3577llvm::Function *
3579 LValue CapStruct = InitCapturedStruct(S);
3580
3581 // Emit the CapturedDecl
3582 CodeGenFunction CGF(CGM, true);
3583 CGCapturedStmtRAII CapInfoRAII(CGF, new CGCapturedStmtInfo(S, K));
3584 llvm::Function *F = CGF.GenerateCapturedStmtFunction(S);
3585 delete CGF.CapturedStmtInfo;
3586
3587 // Emit call to the helper function.
3588 EmitCallOrInvoke(F, CapStruct.getPointer(*this));
3589
3590 return F;
3591}
3592
3594 LValue CapStruct = InitCapturedStruct(S);
3595 return CapStruct.getAddress();
3596}
3597
3598/// Creates the outlined function for a CapturedStmt.
3599llvm::Function *
3601 assert(CapturedStmtInfo &&
3602 "CapturedStmtInfo should be set when generating the captured function");
3603 const CapturedDecl *CD = S.getCapturedDecl();
3604 const RecordDecl *RD = S.getCapturedRecordDecl();
3605 SourceLocation Loc = S.getBeginLoc();
3606 assert(CD->hasBody() && "missing CapturedDecl body");
3607
3608 // Build the argument list.
3609 ASTContext &Ctx = CGM.getContext();
3610 FunctionArgList Args;
3611 Args.append(CD->param_begin(), CD->param_end());
3612
3613 // Create the function declaration.
3614 const CGFunctionInfo &FuncInfo =
3615 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Args);
3616 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
3617
3618 llvm::Function *F =
3619 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
3620 CapturedStmtInfo->getHelperName(), &CGM.getModule());
3621 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
3622 if (!CGM.getCodeGenOpts().SampleProfileFile.empty())
3623 F->addFnAttr("sample-profile-suffix-elision-policy", "selected");
3624 if (CD->isNothrow())
3625 F->addFnAttr(llvm::Attribute::NoUnwind);
3626
3627 // Generate the function.
3628 StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args, CD->getLocation(),
3629 CD->getBody()->getBeginLoc());
3630 // Set the context parameter in CapturedStmtInfo.
3631 Address DeclPtr = GetAddrOfLocalVar(CD->getContextParam());
3632 CapturedStmtInfo->setContextValue(Builder.CreateLoad(DeclPtr));
3633
3634 // Initialize variable-length arrays.
3636 CapturedStmtInfo->getContextValue(), Ctx.getCanonicalTagType(RD));
3637 for (auto *FD : RD->fields()) {
3638 if (FD->hasCapturedVLAType()) {
3639 auto *ExprArg =
3641 .getScalarVal();
3642 auto VAT = FD->getCapturedVLAType();
3643 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
3644 }
3645 }
3646
3647 // If 'this' is captured, load it into CXXThisValue.
3648 if (CapturedStmtInfo->isCXXThisExprCaptured()) {
3649 FieldDecl *FD = CapturedStmtInfo->getThisFieldDecl();
3650 LValue ThisLValue = EmitLValueForField(Base, FD);
3651 CXXThisValue = EmitLoadOfLValue(ThisLValue, Loc).getScalarVal();
3652 }
3653
3654 PGO->assignRegionCounters(GlobalDecl(CD), F);
3655 CapturedStmtInfo->EmitBody(*this, CD->getBody());
3657
3658 return F;
3659}
3660
3661// Returns the first convergence entry/loop/anchor instruction found in |BB|.
3662// std::nullptr otherwise.
3663static llvm::ConvergenceControlInst *getConvergenceToken(llvm::BasicBlock *BB) {
3664 for (auto &I : *BB) {
3665 if (auto *CI = dyn_cast<llvm::ConvergenceControlInst>(&I))
3666 return CI;
3667 }
3668 return nullptr;
3669}
3670
3671void CodeGenFunction::addConvergenceControlBundle(
3672 SmallVectorImpl<llvm::OperandBundleDef> &Bundles) {
3673 if (!CGM.shouldEmitConvergenceTokens())
3674 return;
3675
3676 llvm::ConvergenceControlInst *ParentToken = ConvergenceTokenStack.back();
3677 assert(ParentToken);
3678 Bundles.emplace_back("convergencectrl", ParentToken);
3679}
3680
3681void CodeGenFunction::setConvergentCallSite(llvm::CallBase *Call,
3682 bool IsConvergent) {
3683 if (IsConvergent && !Call->isConvergent())
3684 Call->setConvergent();
3685
3686 assert((IsConvergent || !Call->isConvergent() ||
3687 !CGM.shouldEmitConvergenceTokens()) &&
3688 "convergent call is missing a convergence control token");
3689}
3690
3691llvm::ConvergenceControlInst *
3693 llvm::ConvergenceControlInst *ParentToken = ConvergenceTokenStack.back();
3694 assert(ParentToken);
3695 return llvm::ConvergenceControlInst::CreateLoop(*BB, ParentToken);
3696}
3697
3698llvm::ConvergenceControlInst *
3699CodeGenFunction::getOrEmitConvergenceEntryToken(llvm::Function *F) {
3700 llvm::BasicBlock *BB = &F->getEntryBlock();
3701 llvm::ConvergenceControlInst *Token = getConvergenceToken(BB);
3702 if (Token)
3703 return Token;
3704
3705 // Adding a convergence token requires the function to be marked as
3706 // convergent.
3707 F->setConvergent();
3708 return llvm::ConvergenceControlInst::CreateEntry(*BB);
3709}
#define V(N, I)
Defines enum values for all the target-independent builtin functions.
static bool FindCaseStatementsForValue(const SwitchStmt &S, const llvm::APSInt &ConstantCondValue, SmallVectorImpl< const Stmt * > &ResultStmts, ASTContext &C, const SwitchCase *&ResultCase)
FindCaseStatementsForValue - Find the case statement being jumped to and then invoke CollectStatement...
Definition CGStmt.cpp:2338
static llvm::ConvergenceControlInst * getConvergenceToken(llvm::BasicBlock *BB)
Definition CGStmt.cpp:3663
static bool isBPFRelocatedCase(CodeGenFunction &CGF, const CaseStmt &S)
Definition CGStmt.cpp:1785
static std::optional< SmallVector< uint64_t, 16 > > getLikelihoodWeights(ArrayRef< Stmt::Likelihood > Likelihoods)
Definition CGStmt.cpp:2392
static llvm::MDNode * getAsmSrcLocInfo(const StringLiteral *Str, CodeGenFunction &CGF)
getAsmSrcLocInfo - Return the !srcloc metadata node to attach to an inline asm call instruction.
Definition CGStmt.cpp:2729
static bool hasBPFEnumeratorRef(const Stmt *S)
Return whether S has an enumerator of a BPF preserve_access_index enum, which Sema keeps as a pseudo-...
Definition CGStmt.cpp:1755
static bool isSwiftAsyncCallee(const CallExpr *CE)
Determine if the given call uses the swiftasync calling convention.
Definition CGStmt.cpp:1560
static CSFC_Result CollectStatementsForCase(const Stmt *S, const SwitchCase *Case, bool &FoundCase, SmallVectorImpl< const Stmt * > &ResultStmts)
Definition CGStmt.cpp:2183
static const Expr * getBPFRelocatedCaseValue(CodeGenFunction &CGF, const Expr *E)
If the case value E has a relocated enumerator or an explicit __builtin_preserve_enum_value() call,...
Definition CGStmt.cpp:1773
static bool hasBPFRelocatedCase(CodeGenFunction &CGF, const SwitchStmt &S)
Definition CGStmt.cpp:2447
CSFC_Result
CollectStatementsForCase - Given the body of a 'switch' statement and a constant value that is being ...
Definition CGStmt.cpp:2182
@ CSFC_Failure
Definition CGStmt.cpp:2182
@ CSFC_Success
Definition CGStmt.cpp:2182
@ CSFC_FallThrough
Definition CGStmt.cpp:2182
Result
Implement __builtin_bit_cast and related operations.
Defines the PrettyStackTraceEntry class, which is used to make crashes give more contextual informati...
Defines the SourceManager interface.
This file defines SYCL AST classes used to represent calls to SYCL kernels.
Enumerates target-specific builtins in their own namespaces within namespace clang.
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:158
bool toIntegralConstant(APSInt &Result, QualType SrcTy, const ASTContext &Ctx) const
Try to convert this value to an integral constant.
Definition APValue.cpp:1117
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
SourceManager & getSourceManager()
Definition ASTContext.h:916
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CanQualType VoidTy
CanQualType getCanonicalTagType(const TagDecl *TD) const
AsmConstraintsInfo(CodeGenFunction &CGF, const AsmStmt &S)
Definition CGStmt.cpp:2853
AsmStmt is the base class for GCCAsmStmt and MSAsmStmt.
Definition Stmt.h:3290
Attr - This represents one attribute.
Definition Attr.h:47
Represents an attribute applied to a statement.
Definition Stmt.h:2214
Stmt * getSubStmt()
Definition Stmt.h:2250
ArrayRef< const Attr * > getAttrs() const
Definition Stmt.h:2246
BreakStmt - This represents a break.
Definition Stmt.h:3148
Represents the code generated for an expanded expansion statement.
Definition StmtCXX.h:1028
ArrayRef< Stmt * > getInstantiations() const
Definition StmtCXX.h:1069
ArrayRef< Stmt * > getPreambleStmts() const
Definition StmtCXX.h:1073
CXXForRangeStmt - This represents C++0x [stmt.ranged]'s ranged for statement, represented as 'for (ra...
Definition StmtCXX.h:136
DeclStmt * getBeginStmt()
Definition StmtCXX.h:164
DeclStmt * getLoopVarStmt()
Definition StmtCXX.h:170
DeclStmt * getEndStmt()
Definition StmtCXX.h:167
DeclStmt * getRangeStmt()
Definition StmtCXX.h:163
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:3012
Expr * getCallee()
Definition Expr.h:3159
Represents the body of a CapturedStmt, and serves as its DeclContext.
Definition Decl.h:5131
ImplicitParamDecl * getContextParam() const
Retrieve the parameter containing captured variables.
Definition Decl.h:5189
bool isNothrow() const
Definition Decl.cpp:5816
param_iterator param_end() const
Retrieve an iterator one past the last parameter decl.
Definition Decl.h:5206
param_iterator param_begin() const
Retrieve an iterator pointing to the first parameter decl.
Definition Decl.h:5204
Stmt * getBody() const override
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
Definition Decl.cpp:5813
This captures a statement into a function.
Definition Stmt.h:3950
CapturedDecl * getCapturedDecl()
Retrieve the outlined function declaration.
Definition Stmt.cpp:1493
const RecordDecl * getCapturedRecordDecl() const
Retrieve the record declaration for captured variables.
Definition Stmt.h:4071
capture_init_iterator capture_init_begin()
Retrieve the first initialization argument.
Definition Stmt.h:4127
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.h:4145
capture_init_iterator capture_init_end()
Retrieve the iterator pointing one past the last initialization argument.
Definition Stmt.h:4137
Expr *const * const_capture_init_iterator
Const iterator that walks over the capture initialization arguments.
Definition Stmt.h:4114
CapturedRegionKind getCapturedRegionKind() const
Retrieve the captured region kind.
Definition Stmt.cpp:1508
CaseStmt - Represent a case statement.
Definition Stmt.h:1931
Stmt * getSubStmt()
Definition Stmt.h:2044
Expr * getLHS()
Definition Stmt.h:2014
Expr * getRHS()
Definition Stmt.h:2026
@ Indirect
Indirect - Pass the argument indirectly via a hidden pointer with the specified alignment (0 indicate...
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
Definition Address.h:128
static Address invalid()
Definition Address.h:176
llvm::Value * emitRawPointer(CodeGenFunction &CGF) const
Return the pointer contained in this class after authenticating it and adding offset to it if necessa...
Definition Address.h:253
llvm::Type * getElementType() const
Return the type of the values stored in this address.
Definition Address.h:209
Address withElementType(llvm::Type *ElemTy) const
Return address with different element type, but same pointer and alignment.
Definition Address.h:276
llvm::PointerType * getType() const
Return the type of the pointer value.
Definition Address.h:204
An aggregate value slot.
Definition CGValue.h:551
static AggValueSlot forAddr(Address addr, Qualifiers quals, IsDestructed_t isDestructed, NeedsGCBarriers_t needsGC, IsAliased_t isAliased, Overlap_t mayOverlap, IsZeroed_t isZeroed=IsNotZeroed, IsSanitizerChecked_t isChecked=IsNotSanitizerChecked)
forAddr - Make a slot for an aggregate value.
Definition CGValue.h:634
A scoped helper to set the current source atom group for CGDebugInfo::addInstToCurrentSourceAtom.
A scoped helper to set the current debug location to the specified location or preferred location of ...
static ApplyDebugLocation CreateEmpty(CodeGenFunction &CGF)
Set the IRBuilder to not attach debug locations.
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
Definition CGBuilder.h:156
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Definition CGBuilder.h:128
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
Definition CGDebugInfo.h:60
CGFunctionInfo - Class to encapsulate the information about a function definition.
API for captured statement code generation.
RAII for correct setting/restoring of CapturedStmtInfo.
void rescopeLabels()
Change the cleanup scope of the labels in this lexical scope to match the scope of the enclosing cont...
Definition CGStmt.cpp:761
void ForceCleanup()
Force the emission of cleanups now, instead of waiting until this object is destroyed.
Enters a new scope for capturing cleanups, all of which will be executed once the scope is exited.
void ForceCleanup(std::initializer_list< llvm::Value ** > ValuesToReload={})
Force the emission of cleanups now, instead of waiting until this object is destroyed.
bool requiresCleanups() const
Determine whether this scope requires any cleanups.
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
void EmitOMPParallelMaskedTaskLoopDirective(const OMPParallelMaskedTaskLoopDirective &S)
StringRef AMDGPUAvailableVisibleMode
The mode string from the amdgpu_av attribute on the current statement, or empty if the attribute is n...
void EmitOMPParallelMaskedDirective(const OMPParallelMaskedDirective &S)
void EmitOMPTaskyieldDirective(const OMPTaskyieldDirective &S)
void EmitCXXTryStmt(const CXXTryStmt &S)
void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock, llvm::BasicBlock *FalseBlock, uint64_t TrueCount, Stmt::Likelihood LH=Stmt::LH_None, const Expr *ConditionalOp=nullptr, const VarDecl *ConditionalDecl=nullptr)
EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g.
JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target)
The given basic block lies in the current EH scope, but may be a target of a potentially scope-crossi...
llvm::DenseMap< const VarDecl *, llvm::Value * > NRVOFlags
A mapping from NRVO variables to the flags used to indicate when the NRVO has been applied to this va...
bool IsOutlinedSEHHelper
True if the current function is an outlined SEH helper.
void EmitOMPCanonicalLoop(const OMPCanonicalLoop *S)
Emit an OMPCanonicalLoop using the OpenMPIRBuilder.
static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts=false)
ContainsLabel - Return true if the statement contains a label in it.
void EmitCXXForRangeStmt(const CXXForRangeStmt &S, ArrayRef< const Attr * > Attrs={})
Definition CGStmt.cpp:1402
void EmitOMPGenericLoopDirective(const OMPGenericLoopDirective &S)
void EmitOMPScanDirective(const OMPScanDirective &S)
void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit)
EmitComplexExprIntoLValue - Emit the given expression of complex type and place its result into the s...
static bool hasScalarEvaluationKind(QualType T)
llvm::Type * ConvertType(QualType T)
void EmitOpenACCExitDataConstruct(const OpenACCExitDataConstruct &S)
friend class clang::AsmConstraintsInfo
LValue InitCapturedStruct(const CapturedStmt &S)
Definition CGStmt.cpp:3552
void EmitOMPFlattenDirective(const OMPFlattenDirective &S)
void addInstToNewSourceAtom(llvm::Instruction *KeyInstruction, llvm::Value *Backup)
Add KeyInstruction and an optional Backup instruction to a new atom group (See ApplyAtomGroup for mor...
CGCapturedStmtInfo * CapturedStmtInfo
void EmitOMPDistributeDirective(const OMPDistributeDirective &S)
void EmitOMPParallelForDirective(const OMPParallelForDirective &S)
llvm::CallBase * EmitCallOrInvoke(llvm::FunctionCallee Callee, ArrayRef< llvm::Value * > Args, const Twine &Name="")
Emits a call or invoke instruction to the given function, depending on the current state of the EH st...
Definition CGCall.cpp:5585
void EmitOMPMasterDirective(const OMPMasterDirective &S)
void EmitOMPParallelMasterTaskLoopSimdDirective(const OMPParallelMasterTaskLoopSimdDirective &S)
void EmitOpenACCInitConstruct(const OpenACCInitConstruct &S)
void EmitOMPFlushDirective(const OMPFlushDirective &S)
void EmitOMPTaskgroupDirective(const OMPTaskgroupDirective &S)
JumpDest getJumpDestForLabel(const LabelDecl *S)
getBasicBlockForLabel - Return the LLVM basicblock that the specified label maps to.
Definition CGStmt.cpp:713
void EmitCoreturnStmt(const CoreturnStmt &S)
void EmitOMPTargetTeamsDistributeParallelForSimdDirective(const OMPTargetTeamsDistributeParallelForSimdDirective &S)
SmallVector< llvm::ConvergenceControlInst *, 4 > ConvergenceTokenStack
Stack to track the controlled convergence tokens.
void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S)
Definition CGObjC.cpp:2150
void EmitOMPDistributeSimdDirective(const OMPDistributeSimdDirective &S)
llvm::Constant * EmitCheckSourceLocation(SourceLocation Loc)
Emit a description of a source location in a format suitable for passing to a runtime sanitizer handl...
Definition CGExpr.cpp:4170
llvm::SmallVector< BypassingForwardJump, 4 > BypassingForwardJumps
bool EmitSimpleStmt(const Stmt *S, ArrayRef< const Attr * > Attrs)
EmitSimpleStmt - Try to emit a "simple" statement which does not necessarily require an insertion poi...
Definition CGStmt.cpp:526
void EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S)
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
void EmitOMPTargetParallelForDirective(const OMPTargetParallelForDirective &S)
void addInstToCurrentSourceAtom(llvm::Instruction *KeyInstruction, llvm::Value *Backup)
See CGDebugInfo::addInstToCurrentSourceAtom.
const LangOptions & getLangOpts() const
RValue EmitReferenceBindingToExpr(const Expr *E)
Emits a reference binding to the passed in expression.
Definition CGExpr.cpp:705
void EmitOpenACCShutdownConstruct(const OpenACCShutdownConstruct &S)
bool InNoConvergentAttributedStmt
True if the current statement has noconvergent attribute.
void EmitOpenACCWaitConstruct(const OpenACCWaitConstruct &S)
void EmitBlockAfterUses(llvm::BasicBlock *BB)
EmitBlockAfterUses - Emit the given block somewhere hopefully near its uses, and leave the insertion ...
Definition CGStmt.cpp:696
void SimplifyForwardingBlocks(llvm::BasicBlock *BB)
SimplifyForwardingBlocks - If the given basic block is only a branch to another basic block,...
Definition CGStmt.cpp:637
void EmitOMPSplitDirective(const OMPSplitDirective &S)
void EmitBranchThroughCleanup(JumpDest Dest)
EmitBranchThroughCleanup - Emit a branch from the current insert block through the normal cleanup han...
bool InNoMergeAttributedStmt
True if the current statement has nomerge attribute.
void EmitOMPScopeDirective(const OMPScopeDirective &S)
LValue MakeAddrLValueWithoutTBAA(Address Addr, QualType T, AlignmentSource Source=AlignmentSource::Type)
bool hasSkipCounter(const Stmt *S) const
JumpDest ReturnBlock
ReturnBlock - Unified return block.
void EmitOMPTargetTeamsDistributeSimdDirective(const OMPTargetTeamsDistributeSimdDirective &S)
llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Location)
Converts Location to a DebugLoc, if debug information is enabled.
void EmitOMPInterchangeDirective(const OMPInterchangeDirective &S)
llvm::ConvergenceControlInst * emitConvergenceLoopToken(llvm::BasicBlock *BB)
Definition CGStmt.cpp:3692
void EmitBPFRelocatedCaseStmt(const CaseStmt &S, ArrayRef< const Attr * > Attrs)
Emit a case statement whose value is relocated: move the switch to a new block, and in its old block,...
Definition CGStmt.cpp:1802
void EmitAggregateCopy(LValue Dest, LValue Src, QualType EltTy, AggValueSlot::Overlap_t MayOverlap, bool isVolatile=false)
EmitAggregateCopy - Emit an aggregate copy.
LValue EmitLValueForField(LValue Base, const FieldDecl *Field, bool IsInBounds=true)
Definition CGExpr.cpp:5980
const TargetInfo & getTarget() const
Address EmitCompoundStmtWithoutScope(const CompoundStmt &S, bool GetLast=false, AggValueSlot AVS=AggValueSlot::ignored())
Definition CGStmt.cpp:588
void EmitGotoStmt(const GotoStmt &S)
Definition CGStmt.cpp:859
void EmitOMPDepobjDirective(const OMPDepobjDirective &S)
void EmitOMPMetaDirective(const OMPMetaDirective &S)
void EmitOMPCriticalDirective(const OMPCriticalDirective &S)
void EmitIgnoredExpr(const Expr *E)
EmitIgnoredExpr - Emit an expression in a context which ignores the result.
Definition CGExpr.cpp:263
void EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S)
RValue EmitLoadOfLValue(LValue V, SourceLocation Loc)
EmitLoadOfLValue - Given an expression that represents a value lvalue, this method emits the address ...
Definition CGExpr.cpp:2549
void EmitOMPCancelDirective(const OMPCancelDirective &S)
const Expr * RetExpr
If a return statement is being visited, this holds the return statment's result expression.
void EmitOMPBarrierDirective(const OMPBarrierDirective &S)
void EmitForStmt(const ForStmt &S, ArrayRef< const Attr * > Attrs={})
Definition CGStmt.cpp:1250
void EmitOMPSectionsDirective(const OMPSectionsDirective &S)
void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S)
Definition CGObjC.cpp:3708
void StartFunction(GlobalDecl GD, QualType RetTy, llvm::Function *Fn, const CGFunctionInfo &FnInfo, const FunctionArgList &Args, SourceLocation Loc=SourceLocation(), SourceLocation StartLoc=SourceLocation())
Emit code for the start of a function.
void EmitCXXExpansionStmtInstantiation(const CXXExpansionStmtInstantiation &S)
Definition CGStmt.cpp:1506
void EmitOMPInteropDirective(const OMPInteropDirective &S)
void EmitOMPParallelSectionsDirective(const OMPParallelSectionsDirective &S)
void EmitOMPTargetParallelDirective(const OMPTargetParallelDirective &S)
llvm::Value * EvaluateExprAsBool(const Expr *E)
EvaluateExprAsBool - Perform the usual unary conversions on the specified expression and compare the ...
Definition CGExpr.cpp:244
void EmitWhileStmt(const WhileStmt &S, ArrayRef< const Attr * > Attrs={})
Definition CGStmt.cpp:1048
void EmitOMPTargetParallelForSimdDirective(const OMPTargetParallelForSimdDirective &S)
void EmitOMPTargetParallelGenericLoopDirective(const OMPTargetParallelGenericLoopDirective &S)
Emit combined directive 'target parallel loop' as if its constituent constructs are 'target',...
void EmitOpenACCCombinedConstruct(const OpenACCCombinedConstruct &S)
void ResolveBranchFixups(llvm::BasicBlock *Target)
void EmitOMPTeamsDistributeParallelForSimdDirective(const OMPTeamsDistributeParallelForSimdDirective &S)
void EmitOMPMaskedDirective(const OMPMaskedDirective &S)
bool checkIfLoopMustProgress(const Expr *, bool HasEmptyBody)
Returns true if a loop must make progress, which means the mustprogress attribute can be added.
Definition CGStmt.cpp:1040
bool HaveInsertPoint() const
HaveInsertPoint - True if an insertion point is defined.
void EmitOMPTeamsDistributeSimdDirective(const OMPTeamsDistributeSimdDirective &S)
void EmitOMPOrderedBlockAssocDirective(const OMPOrderedBlockAssocDirective &S)
void EmitOMPMasterTaskLoopDirective(const OMPMasterTaskLoopDirective &S)
void EmitOMPReverseDirective(const OMPReverseDirective &S)
void EmitOMPCancellationPointDirective(const OMPCancellationPointDirective &S)
void EmitOpenACCDataConstruct(const OpenACCDataConstruct &S)
LValue EmitLValueForFieldInitialization(LValue Base, const FieldDecl *Field)
EmitLValueForFieldInitialization - Like EmitLValueForField, except that if the Field is a reference,...
Definition CGExpr.cpp:6139
void EmitOMPTargetTeamsDistributeParallelForDirective(const OMPTargetTeamsDistributeParallelForDirective &S)
void EmitOMPMaskedTaskLoopDirective(const OMPMaskedTaskLoopDirective &S)
void EmitObjCAtTryStmt(const ObjCAtTryStmt &S)
Definition CGObjC.cpp:2146
const TargetCodeGenInfo & getTargetHooks() const
void EmitOMPTargetExitDataDirective(const OMPTargetExitDataDirective &S)
void EmitSEHLeaveStmt(const SEHLeaveStmt &S)
RawAddress CreateMemTempWithoutCast(QualType T, const Twine &Name="tmp")
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen without...
Definition CGExpr.cpp:236
void EmitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective &S)
bool InNoInlineAttributedStmt
True if the current statement has noinline attribute.
void EmitOMPMaskedTaskLoopSimdDirective(const OMPMaskedTaskLoopSimdDirective &S)
void EmitCoroutineBody(const CoroutineBodyStmt &S)
void EmitOMPParallelDirective(const OMPParallelDirective &S)
void EmitOMPTaskDirective(const OMPTaskDirective &S)
void EmitOMPMasterTaskLoopSimdDirective(const OMPMasterTaskLoopSimdDirective &S)
void EmitOMPDistributeParallelForDirective(const OMPDistributeParallelForDirective &S)
void EmitOMPAssumeDirective(const OMPAssumeDirective &S)
void EmitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective &S)
void EmitStopPoint(const Stmt *S)
EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
Definition CGStmt.cpp:50
void EmitOMPTargetUpdateDirective(const OMPTargetUpdateDirective &S)
void EmitOMPTargetTeamsGenericLoopDirective(const OMPTargetTeamsGenericLoopDirective &S)
void EmitIfStmt(const IfStmt &S)
Definition CGStmt.cpp:905
void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit)
EmitStoreOfComplex - Store a complex number into the specified l-value.
void EmitDeferStmt(const DeferStmt &S)
Definition CGStmt.cpp:2155
void emitBypassedVarInitsForSource(const Stmt *Source)
Re-emit trivial-auto-var-init stores for variables bypassed by the jump Source.
Definition CGDecl.cpp:1895
void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit=false)
EmitStoreThroughLValue - Store the specified rvalue into the specified lvalue, where both are guarant...
Definition CGExpr.cpp:2801
void EmitOpenACCAtomicConstruct(const OpenACCAtomicConstruct &S)
void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S)
Definition CGObjC.cpp:2154
Address EmitCompoundStmt(const CompoundStmt &S, bool GetLast=false, AggValueSlot AVS=AggValueSlot::ignored())
EmitCompoundStmt - Emit a compound statement {..} node.
Definition CGStmt.cpp:576
void EmitOpenACCCacheConstruct(const OpenACCCacheConstruct &S)
void EmitOpenACCLoopConstruct(const OpenACCLoopConstruct &S)
void EmitOMPTeamsDistributeParallelForDirective(const OMPTeamsDistributeParallelForDirective &S)
void EmitOMPFuseDirective(const OMPFuseDirective &S)
void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init)
Definition CGClass.cpp:632
void EmitAsmStmt(const AsmStmt &S)
Definition CGStmt.cpp:2862
void EmitDefaultStmt(const DefaultStmt &S, ArrayRef< const Attr * > Attrs)
Definition CGStmt.cpp:2056
void EmitOMPTargetTeamsDistributeDirective(const OMPTargetTeamsDistributeDirective &S)
void EmitSwitchStmt(const SwitchStmt &S)
Definition CGStmt.cpp:2456
static bool mightAddDeclToScope(const Stmt *S)
Determine if the given statement might introduce a declaration into the current scope,...
void EmitAnyExprToMem(const Expr *E, Address Location, Qualifiers Quals, bool IsInitializer)
EmitAnyExprToMem - Emits the code necessary to evaluate an arbitrary expression into the given memory...
Definition CGExpr.cpp:314
RValue EmitAnyExpr(const Expr *E, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
EmitAnyExpr - Emit code to compute the specified expression which can have any type.
Definition CGExpr.cpp:285
void EmitStmt(const Stmt *S, ArrayRef< const Attr * > Attrs={})
EmitStmt - Emit the code for the statement.
Definition CGStmt.cpp:60
void EmitOMPParallelForSimdDirective(const OMPParallelForSimdDirective &S)
uint64_t getCurrentProfileCount()
Get the profiler's current count.
llvm::Type * ConvertTypeForMem(QualType T)
void EmitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective &S)
void EmitSYCLKernelCallStmt(const SYCLKernelCallStmt &S)
void EmitOMPTargetDirective(const OMPTargetDirective &S)
void EmitOpenACCEnterDataConstruct(const OpenACCEnterDataConstruct &S)
llvm::Function * EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K)
Generate an outlined function for the body of a CapturedStmt, store any captured variables into the c...
Definition CGStmt.cpp:3578
static TypeEvaluationKind getEvaluationKind(QualType T)
getEvaluationKind - Return the TypeEvaluationKind of QualType T.
void EmitOMPTeamsDirective(const OMPTeamsDirective &S)
static bool containsBreak(const Stmt *S)
containsBreak - Return true if the statement contains a break out of it.
void EmitSimpleOMPExecutableDirective(const OMPExecutableDirective &D)
Emit simple code for OpenMP directives in Simd-only mode.
HLSLControlFlowHintAttr::Spelling HLSLControlFlowAttr
HLSL Branch attribute.
bool InAlwaysInlineAttributedStmt
True if the current statement has always_inline attribute.
void EmitCaseStmt(const CaseStmt &S, ArrayRef< const Attr * > Attrs)
Definition CGStmt.cpp:1939
void EmitOMPErrorDirective(const OMPErrorDirective &S)
void EmitBreakStmt(const BreakStmt &S)
Definition CGStmt.cpp:1725
void EmitOMPParallelMaskedTaskLoopSimdDirective(const OMPParallelMaskedTaskLoopSimdDirective &S)
void EmitOMPTargetTeamsDirective(const OMPTargetTeamsDirective &S)
void EmitOpenACCComputeConstruct(const OpenACCComputeConstruct &S)
void EmitDoStmt(const DoStmt &S, ArrayRef< const Attr * > Attrs={})
Definition CGStmt.cpp:1165
void EmitOMPTargetDataDirective(const OMPTargetDataDirective &S)
Address GenerateCapturedStmtArgument(const CapturedStmt &S)
Definition CGStmt.cpp:3593
void EmitBranch(llvm::BasicBlock *Block)
EmitBranch - Emit a branch to the specified basic block from the current insert block,...
Definition CGStmt.cpp:679
void EmitOMPSimdDirective(const OMPSimdDirective &S)
RawAddress CreateMemTemp(QualType T, const Twine &Name="tmp", RawAddress *Alloca=nullptr)
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen and cas...
Definition CGExpr.cpp:200
void EmitOMPParallelGenericLoopDirective(const OMPLoopDirective &S)
RawAddress NormalCleanupDest
i32s containing the indexes of the cleanup destinations.
void EmitOMPTeamsGenericLoopDirective(const OMPTeamsGenericLoopDirective &S)
void EmitOMPTargetSimdDirective(const OMPLoopDirective &S)
Also emits 'target loop'.
void EmitOMPOrderedStandaloneDirective(const OMPOrderedStandaloneDirective &S)
AggValueSlot::Overlap_t getOverlapForReturnValue()
Determine whether a return value slot may overlap some other object.
const BreakContinue * GetDestForLoopControlStmt(const LoopControlStmt &S)
Definition CGStmt.cpp:1711
void EmitAggExpr(const Expr *E, AggValueSlot AS)
EmitAggExpr - Emit the computation of the specified expression of aggregate type.
llvm::BasicBlock * GetIndirectGotoBlock()
void EmitOpenACCHostDataConstruct(const OpenACCHostDataConstruct &S)
void EmitOpenACCUpdateConstruct(const OpenACCUpdateConstruct &S)
void EmitOMPUnrollDirective(const OMPUnrollDirective &S)
void EmitOMPStripeDirective(const OMPStripeDirective &S)
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
EmitScalarExpr - Emit the computation of the specified expression of LLVM scalar type,...
static bool hasAggregateEvaluationKind(QualType T)
void EmitCaseStmtRange(const CaseStmt &S, ArrayRef< const Attr * > Attrs)
EmitCaseStmtRange - If case statement range is not too big then add multiple cases to switch instruct...
Definition CGStmt.cpp:1853
LValue MakeAddrLValue(Address Addr, QualType T, AlignmentSource Source=AlignmentSource::Type)
void EmitOMPSingleDirective(const OMPSingleDirective &S)
void EmitReturnStmt(const ReturnStmt &S)
EmitReturnStmt - Note that due to GCC extensions, this can have an operand if the function returns vo...
Definition CGStmt.cpp:1586
void EmitLambdaVLACapture(const VariableArrayType *VAT, LValue LV)
void FinishFunction(SourceLocation EndLoc=SourceLocation())
FinishFunction - Complete IR generation of the current function.
llvm::Value * EmitCheckedArgForAssume(const Expr *E)
Emits an argument for a call to a __builtin_assume.
llvm::Function * GenerateCapturedStmtFunction(const CapturedStmt &S)
Creates the outlined function for a CapturedStmt.
Definition CGStmt.cpp:3600
const CGFunctionInfo * CurFnInfo
uint64_t getProfileCount(const Stmt *S)
Get the profiler's count for the given statement.
Address GetAddrOfLocalVar(const VarDecl *VD)
GetAddrOfLocalVar - Return the address of a local variable.
void EmitDeclStmt(const DeclStmt &S)
Definition CGStmt.cpp:1701
void EmitLabelStmt(const LabelStmt &S)
Definition CGStmt.cpp:782
bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result, bool AllowLabels=false)
ConstantFoldsToSimpleInteger - If the specified expression does not fold to a constant,...
void EmitOMPTileDirective(const OMPTileDirective &S)
void EmitDecl(const Decl &D, bool EvaluateConditionDecl=false)
EmitDecl - Emit a declaration.
Definition CGDecl.cpp:52
void EmitOMPAtomicDirective(const OMPAtomicDirective &S)
void EmitOpenACCSetConstruct(const OpenACCSetConstruct &S)
Address ReturnValue
ReturnValue - The temporary alloca to hold the return value.
LValue EmitLValue(const Expr *E, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitLValue - Emit code to compute a designator that specifies the location of the expression.
Definition CGExpr.cpp:1777
void EmitAttributedStmt(const AttributedStmt &S)
Definition CGStmt.cpp:792
void EmitOMPParallelMasterTaskLoopDirective(const OMPParallelMasterTaskLoopDirective &S)
void EmitOMPDistributeParallelForSimdDirective(const OMPDistributeParallelForSimdDirective &S)
void EmitOMPSectionDirective(const OMPSectionDirective &S)
void EnsureInsertPoint()
EnsureInsertPoint - Ensure that an insertion point is defined so that emitted IR has a place to go.
void EmitOMPForSimdDirective(const OMPForSimdDirective &S)
llvm::LLVMContext & getLLVMContext()
bool SawAsmBlock
Whether we processed a Microsoft-style asm block during CodeGen.
void incrementProfileCounter(const Stmt *S, llvm::Value *StepV=nullptr)
Increment the profiler's counter for the given statement by StepV.
void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S)
Definition CGObjC.cpp:1825
void EmitIndirectGotoStmt(const IndirectGotoStmt &S)
Definition CGStmt.cpp:881
void MaybeEmitDeferredVarDeclInit(const VarDecl *var)
Definition CGDecl.cpp:2161
bool isObviouslyBranchWithoutCleanups(JumpDest Dest) const
isObviouslyBranchWithoutCleanups - Return true if a branch to the specified destination obviously has...
void EmitSEHTryStmt(const SEHTryStmt &S)
void EmitOMPParallelMasterDirective(const OMPParallelMasterDirective &S)
void EmitBlockWithFallThrough(llvm::BasicBlock *BB, const Stmt *S)
When instrumenting to collect profile data, the counts for some blocks such as switch cases need to n...
void EmitStoreOfScalar(llvm::Value *Value, Address Addr, bool Volatile, QualType Ty, AlignmentSource Source=AlignmentSource::Type, bool isInit=false, bool isNontemporal=false)
EmitStoreOfScalar - Store a scalar value to an address, taking care to appropriately convert from the...
void EmitOMPForDirective(const OMPForDirective &S)
void EmitLabel(const LabelDecl *D)
EmitLabel - Emit the block for the given label.
Definition CGStmt.cpp:724
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition CGStmt.cpp:659
LValue MakeNaturalAlignRawAddrLValue(llvm::Value *V, QualType T)
void EmitContinueStmt(const ContinueStmt &S)
Definition CGStmt.cpp:1738
This class organizes the cross-function state that is used while generating LLVM code.
const LangOptions & getLangOpts() const
const llvm::DataLayout & getDataLayout() const
ASTContext & getContext() const
A saved depth on the scope stack.
bool encloses(stable_iterator I) const
Returns true if this scope encloses I.
static stable_iterator stable_end()
Create a stable reference to the bottom of the EH stack.
FunctionArgList - Type for representing both the decl and type of parameters to a function.
Definition CGCall.h:378
LValue - This represents an lvalue references.
Definition CGValue.h:183
llvm::Value * getPointer(CodeGenFunction &CGF) const
Address getAddress() const
Definition CGValue.h:373
RValue - This trivial value class is used to represent the result of an expression that is evaluated.
Definition CGValue.h:42
bool isScalar() const
Definition CGValue.h:64
static RValue get(llvm::Value *V)
Definition CGValue.h:99
bool isAggregate() const
Definition CGValue.h:66
Address getAggregateAddress() const
getAggregateAddr() - Return the Value* of the address of the aggregate.
Definition CGValue.h:84
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
Definition CGValue.h:72
std::pair< llvm::Value *, llvm::Value * > getComplexVal() const
getComplexVal - Return the real/imag components of this complex value.
Definition CGValue.h:79
TargetCodeGenInfo - This class organizes various target-specific codegeneration issues,...
Definition TargetInfo.h:80
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1751
Stmt *const * const_body_iterator
Definition Stmt.h:1823
body_iterator body_end()
Definition Stmt.h:1816
SourceLocation getLBracLoc() const
Definition Stmt.h:1868
body_iterator body_begin()
Definition Stmt.h:1815
Stmt * body_back()
Definition Stmt.h:1819
ContinueStmt - This represents a continue.
Definition Stmt.h:3132
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1642
decl_range decls()
Definition Stmt.h:1690
SourceLocation getBodyRBrace() const
getBodyRBrace - Gets the right brace of the body, if a body exists.
virtual bool hasBody() const
Returns true if this Decl represents a declaration for a body of code, such as a function or method d...
Definition DeclBase.h:1111
SourceLocation getLocation() const
Definition DeclBase.h:448
Stmt * getSubStmt()
Definition Stmt.h:2092
DeferStmt - This represents a deferred statement.
Definition Stmt.h:3249
DoStmt - This represents a 'do/while' stmt.
Definition Stmt.h:2843
Stmt * getBody()
Definition Stmt.h:2868
Expr * getCond()
Definition Stmt.h:2861
This represents one expression.
Definition Expr.h:114
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
Expr * IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY
Skip past any parentheses and casts which do not change the value (including ptr->int casts of the sa...
Definition Expr.cpp:3156
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
bool isEvaluatable(const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects) const
isEvaluatable - Call EvaluateAsRValue to see if this expression can be constant folded without side-e...
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition Expr.cpp:3728
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3109
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
QualType getType() const
Definition Expr.h:146
Represents a member of a struct/union/class.
Definition Decl.h:3341
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2899
Stmt * getInit()
Definition Stmt.h:2914
VarDecl * getConditionVariable() const
Retrieve the variable declared in this "for" statement, if any.
Definition Stmt.cpp:1120
Stmt * getBody()
Definition Stmt.h:2943
Expr * getInc()
Definition Stmt.h:2942
Expr * getCond()
Definition Stmt.h:2941
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4744
CallingConv getCallConv() const
Definition TypeBase.h:5099
This represents a GCC inline-assembly statement extension.
Definition Stmt.h:3459
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:60
GotoStmt - This represents a direct goto.
Definition Stmt.h:2980
LabelDecl * getLabel() const
Definition Stmt.h:2993
IfStmt - This represents an if/then/else.
Definition Stmt.h:2270
Stmt * getThen()
Definition Stmt.h:2359
Stmt * getInit()
Definition Stmt.h:2420
Expr * getCond()
Definition Stmt.h:2347
bool isConstexpr() const
Definition Stmt.h:2463
bool isNegatedConsteval() const
Definition Stmt.h:2459
Stmt * getElse()
Definition Stmt.h:2368
bool isConsteval() const
Definition Stmt.h:2450
VarDecl * getConditionVariable()
Retrieve the variable declared in this "if" statement, if any.
Definition Stmt.cpp:1068
IndirectGotoStmt - This represents an indirect goto.
Definition Stmt.h:3019
LabelDecl * getConstantTarget()
getConstantTarget - Returns the fixed target of this indirect goto, if one exists.
Definition Stmt.cpp:1269
Represents the declaration of a label.
Definition Decl.h:526
LabelStmt * getStmt() const
Definition Decl.h:550
LabelStmt - Represents a label, which has a substatement.
Definition Stmt.h:2157
LabelDecl * getDecl() const
Definition Stmt.h:2175
bool isSideEntry() const
Definition Stmt.h:2204
Stmt * getSubStmt()
Definition Stmt.h:2179
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Base class for BreakStmt and ContinueStmt.
Definition Stmt.h:3068
Represents a point when we exit a loop.
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:303
If a crash happens while one of these objects are live, the message is printed out along with the spe...
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
QualType getCanonicalType() const
Definition TypeBase.h:8630
The collection of all-type qualifiers we support.
Definition TypeBase.h:332
Represents a struct/union/class.
Definition Decl.h:4506
field_range fields() const
Definition Decl.h:4709
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4706
field_iterator field_begin() const
Definition Decl.cpp:5386
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition Stmt.h:3173
SourceLocation getBeginLoc() const
Definition Stmt.h:3225
const VarDecl * getNRVOCandidate() const
Retrieve the variable that might be used for the named return value optimization.
Definition Stmt.h:3209
Expr * getRetValue()
Definition Stmt.h:3200
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
Encodes a location in the source.
UIntTy getRawEncoding() const
When a SourceLocation itself cannot be used, this returns an (opaque) 32-bit integer encoding for it.
This class handles loading and caching of source files into memory.
A trivial tuple used to represent a source range.
Stmt - This represents one statement.
Definition Stmt.h:85
@ NoStmtClass
Definition Stmt.h:88
child_range children()
Definition Stmt.cpp:304
StmtClass getStmtClass() const
Definition Stmt.h:1504
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
Likelihood
The likelihood of a branch being taken.
Definition Stmt.h:1447
@ LH_Unlikely
Branch has the [[unlikely]] attribute.
Definition Stmt.h:1448
@ LH_None
No attribute set or branches of the IfStmt have the same attribute.
Definition Stmt.h:1449
@ LH_Likely
Branch has the [[likely]] attribute.
Definition Stmt.h:1451
static const Attr * getLikelihoodAttr(const Stmt *S)
Definition Stmt.cpp:176
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
static Likelihood getLikelihood(ArrayRef< const Attr * > Attrs)
Definition Stmt.cpp:168
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1844
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2042
SourceLocation getLocationOfByte(unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, const TargetInfo &Target, unsigned *StartToken=nullptr, unsigned *StartTokenByteOffset=nullptr) const
Return a source location that points to the specified byte of this string literal.
Definition Expr.cpp:1336
StringRef getString() const
Definition Expr.h:1912
const SwitchCase * getNextSwitchCase() const
Definition Stmt.h:1904
SwitchStmt - This represents a 'switch' stmt.
Definition Stmt.h:2520
Expr * getCond()
Definition Stmt.h:2583
Stmt * getBody()
Definition Stmt.h:2595
VarDecl * getConditionVariable()
Retrieve the variable declared in this "switch" statement, if any.
Definition Stmt.cpp:1186
Stmt * getInit()
Definition Stmt.h:2600
SwitchCase * getSwitchCaseList()
Definition Stmt.h:2651
Exposes information about the current target.
Definition TargetInfo.h:228
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Token - This structure provides full information about a lexed token.
Definition Token.h:36
bool isVoidType() const
Definition TypeBase.h:9200
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2417
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9498
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
bool isNRVOVariable() const
Determine whether this local variable can be used with the named return value optimization (NRVO).
Definition Decl.h:1549
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2708
Expr * getCond()
Definition Stmt.h:2760
SourceLocation getWhileLoc() const
Definition Stmt.h:2813
SourceLocation getRParenLoc() const
Definition Stmt.h:2818
VarDecl * getConditionVariable()
Retrieve the variable declared in this "while" statement, if any.
Definition Stmt.cpp:1247
Stmt * getBody()
Definition Stmt.h:2772
Defines the clang::TargetInfo interface.
bool checkIfLoopMustProgress(const LangOptions &LangOpts, const CodeGenOptions &CGOpts, ASTContext &Ctx, const Expr *ControllingExpression, bool HasEmptyBody, llvm::function_ref< void()> RemoveMustProgress)
Returns true if a loop must make progress, which means the mustprogress attribute can be added to it.
Definition StmtUtils.cpp:15
bool hasEmptyLoopBody(const LoopStmt &S)
Definition StmtUtils.h:39
std::pair< types::ID, const llvm::opt::Arg * > InputTy
A list of inputs and their types for the given arguments.
Definition Types.h:133
@ Address
A pointer to a ValueDecl.
Definition Primitives.h:28
Top level wrappers for InstallAPI frontend operations.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus
CapturedRegionKind
The different kinds of captured statement.
@ Asm
Assembly: we accept this only so that we can preprocess it.
@ Result
The result type of a method or function.
Definition TypeBase.h:906
@ CC_SwiftAsync
Definition Specifiers.h:297
U cast(CodeGen::Address addr)
Definition Address.h:327
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
A jump destination is an abstract label, branching to which may require a jump out through normal cle...
void setScopeDepth(EHScopeStack::stable_iterator depth)
EHScopeStack::stable_iterator getScopeDepth() const
static TBAAAccessInfo getMayAliasInfo()
Definition CodeGenTBAA.h:63
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:669
bool hasMatchingInput() const
Return true if this output operand has a matching (tied) input operand.
std::optional< std::pair< unsigned, unsigned > > getOutputOperandBounds() const
bool hasTiedOperand() const
Return true if this input operand is a matching constraint that ties it to an output operand.