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"
29#include "llvm/ADT/ArrayRef.h"
30#include "llvm/ADT/DenseMap.h"
31#include "llvm/ADT/SmallSet.h"
32#include "llvm/ADT/StringExtras.h"
33#include "llvm/IR/Assumptions.h"
34#include "llvm/IR/DataLayout.h"
35#include "llvm/IR/InlineAsm.h"
36#include "llvm/IR/Intrinsics.h"
37#include "llvm/IR/MDBuilder.h"
38#include "llvm/Support/SaveAndRestore.h"
39#include <optional>
40
41using namespace clang;
42using namespace CodeGen;
43
44//===----------------------------------------------------------------------===//
45// Statement Emission
46//===----------------------------------------------------------------------===//
47
49 if (CGDebugInfo *DI = getDebugInfo()) {
51 Loc = S->getBeginLoc();
52 DI->EmitLocation(Builder, Loc);
53
54 LastStopPoint = Loc;
55 }
56}
57
59 assert(S && "Null statement?");
60 PGO->setCurrentStmt(S);
61
62 // These statements have their own debug info handling.
63 if (EmitSimpleStmt(S, Attrs))
64 return;
65
66 // Check if we are generating unreachable code.
67 if (!HaveInsertPoint()) {
68 // If so, and the statement doesn't contain a label, then we do not need to
69 // generate actual code. This is safe because (1) the current point is
70 // unreachable, so we don't need to execute the code, and (2) we've already
71 // handled the statements which update internal data structures (like the
72 // local variable map) which could be used by subsequent statements.
73 if (!ContainsLabel(S)) {
74 // Verify that any decl statements were handled as simple, they may be in
75 // scope of subsequent reachable statements.
76 assert(!isa<DeclStmt>(*S) && "Unexpected DeclStmt!");
77 PGO->markStmtMaybeUsed(S);
78 return;
79 }
80
81 // Otherwise, make a new block to hold the code.
83 }
84
85 // Generate a stoppoint if we are emitting debug info.
87
88 // Ignore all OpenMP directives except for simd if OpenMP with Simd is
89 // enabled.
90 if (getLangOpts().OpenMP && getLangOpts().OpenMPSimd) {
91 if (const auto *D = dyn_cast<OMPExecutableDirective>(S)) {
93 return;
94 }
95 }
96
97 switch (S->getStmtClass()) {
99 case Stmt::CXXCatchStmtClass:
100 case Stmt::SEHExceptStmtClass:
101 case Stmt::SEHFinallyStmtClass:
102 case Stmt::MSDependentExistsStmtClass:
103 case Stmt::UnresolvedSYCLKernelCallStmtClass:
104 llvm_unreachable("invalid statement class to emit generically");
105 case Stmt::NullStmtClass:
106 case Stmt::CompoundStmtClass:
107 case Stmt::DeclStmtClass:
108 case Stmt::LabelStmtClass:
109 case Stmt::AttributedStmtClass:
110 case Stmt::GotoStmtClass:
111 case Stmt::BreakStmtClass:
112 case Stmt::ContinueStmtClass:
113 case Stmt::DefaultStmtClass:
114 case Stmt::CaseStmtClass:
115 case Stmt::DeferStmtClass:
116 case Stmt::SEHLeaveStmtClass:
117 case Stmt::SYCLKernelCallStmtClass:
118 llvm_unreachable("should have emitted these statements as simple");
119
120#define STMT(Type, Base)
121#define ABSTRACT_STMT(Op)
122#define EXPR(Type, Base) \
123 case Stmt::Type##Class:
124#include "clang/AST/StmtNodes.inc"
125 {
126 // Remember the block we came in on.
127 llvm::BasicBlock *incoming = Builder.GetInsertBlock();
128 assert(incoming && "expression emission must have an insertion point");
129
131
132 llvm::BasicBlock *outgoing = Builder.GetInsertBlock();
133 assert(outgoing && "expression emission cleared block!");
134
135 // The expression emitters assume (reasonably!) that the insertion
136 // point is always set. To maintain that, the call-emission code
137 // for noreturn functions has to enter a new block with no
138 // predecessors. We want to kill that block and mark the current
139 // insertion point unreachable in the common case of a call like
140 // "exit();". Since expression emission doesn't otherwise create
141 // blocks with no predecessors, we can just test for that.
142 // However, we must be careful not to do this to our incoming
143 // block, because *statement* emission does sometimes create
144 // reachable blocks which will have no predecessors until later in
145 // the function. This occurs with, e.g., labels that are not
146 // reachable by fallthrough.
147 if (incoming != outgoing && outgoing->use_empty()) {
148 outgoing->eraseFromParent();
149 Builder.ClearInsertionPoint();
150 }
151 break;
152 }
153
154 case Stmt::IndirectGotoStmtClass:
156
157 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
158 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S), Attrs); break;
159 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S), Attrs); break;
160 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S), Attrs); break;
161
162 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
163
164 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
165 case Stmt::GCCAsmStmtClass: // Intentional fall-through.
166 case Stmt::MSAsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
167 case Stmt::CoroutineBodyStmtClass:
169 break;
170 case Stmt::CoreturnStmtClass:
172 break;
173 case Stmt::CapturedStmtClass: {
174 const CapturedStmt *CS = cast<CapturedStmt>(S);
176 }
177 break;
178 case Stmt::ObjCAtTryStmtClass:
180 break;
181 case Stmt::ObjCAtCatchStmtClass:
182 llvm_unreachable(
183 "@catch statements should be handled by EmitObjCAtTryStmt");
184 case Stmt::ObjCAtFinallyStmtClass:
185 llvm_unreachable(
186 "@finally statements should be handled by EmitObjCAtTryStmt");
187 case Stmt::ObjCAtThrowStmtClass:
189 break;
190 case Stmt::ObjCAtSynchronizedStmtClass:
192 break;
193 case Stmt::ObjCForCollectionStmtClass:
195 break;
196 case Stmt::ObjCAutoreleasePoolStmtClass:
198 break;
199
200 case Stmt::CXXTryStmtClass:
202 break;
203 case Stmt::CXXForRangeStmtClass:
205 break;
206 case Stmt::CXXExpansionStmtPatternClass:
207 llvm_unreachable("unexpanded expansion statements should not be emitted");
208 case Stmt::CXXExpansionStmtInstantiationClass:
210 break;
211 case Stmt::SEHTryStmtClass:
213 break;
214 case Stmt::OMPMetaDirectiveClass:
216 break;
217 case Stmt::OMPCanonicalLoopClass:
219 break;
220 case Stmt::OMPParallelDirectiveClass:
222 break;
223 case Stmt::OMPSimdDirectiveClass:
225 break;
226 case Stmt::OMPTileDirectiveClass:
228 break;
229 case Stmt::OMPStripeDirectiveClass:
231 break;
232 case Stmt::OMPUnrollDirectiveClass:
234 break;
235 case Stmt::OMPReverseDirectiveClass:
237 break;
238 case Stmt::OMPSplitDirectiveClass:
240 break;
241 case Stmt::OMPInterchangeDirectiveClass:
243 break;
244 case Stmt::OMPFlattenDirectiveClass:
246 break;
247 case Stmt::OMPFuseDirectiveClass:
249 break;
250 case Stmt::OMPForDirectiveClass:
252 break;
253 case Stmt::OMPForSimdDirectiveClass:
255 break;
256 case Stmt::OMPSectionsDirectiveClass:
258 break;
259 case Stmt::OMPSectionDirectiveClass:
261 break;
262 case Stmt::OMPSingleDirectiveClass:
264 break;
265 case Stmt::OMPMasterDirectiveClass:
267 break;
268 case Stmt::OMPCriticalDirectiveClass:
270 break;
271 case Stmt::OMPParallelForDirectiveClass:
273 break;
274 case Stmt::OMPParallelForSimdDirectiveClass:
276 break;
277 case Stmt::OMPParallelMasterDirectiveClass:
279 break;
280 case Stmt::OMPParallelSectionsDirectiveClass:
282 break;
283 case Stmt::OMPTaskDirectiveClass:
285 break;
286 case Stmt::OMPTaskyieldDirectiveClass:
288 break;
289 case Stmt::OMPErrorDirectiveClass:
291 break;
292 case Stmt::OMPBarrierDirectiveClass:
294 break;
295 case Stmt::OMPTaskwaitDirectiveClass:
297 break;
298 case Stmt::OMPTaskgroupDirectiveClass:
300 break;
301 case Stmt::OMPFlushDirectiveClass:
303 break;
304 case Stmt::OMPDepobjDirectiveClass:
306 break;
307 case Stmt::OMPScanDirectiveClass:
309 break;
310 case Stmt::OMPOrderedStandaloneDirectiveClass:
312 break;
313 case Stmt::OMPOrderedBlockAssocDirectiveClass:
315 break;
316 case Stmt::OMPAtomicDirectiveClass:
318 break;
319 case Stmt::OMPTargetDirectiveClass:
321 break;
322 case Stmt::OMPTeamsDirectiveClass:
324 break;
325 case Stmt::OMPCancellationPointDirectiveClass:
327 break;
328 case Stmt::OMPCancelDirectiveClass:
330 break;
331 case Stmt::OMPTargetDataDirectiveClass:
333 break;
334 case Stmt::OMPTargetEnterDataDirectiveClass:
336 break;
337 case Stmt::OMPTargetExitDataDirectiveClass:
339 break;
340 case Stmt::OMPTargetParallelDirectiveClass:
342 break;
343 case Stmt::OMPTargetParallelForDirectiveClass:
345 break;
346 case Stmt::OMPTaskLoopDirectiveClass:
348 break;
349 case Stmt::OMPTaskLoopSimdDirectiveClass:
351 break;
352 case Stmt::OMPMasterTaskLoopDirectiveClass:
354 break;
355 case Stmt::OMPMaskedTaskLoopDirectiveClass:
357 break;
358 case Stmt::OMPMasterTaskLoopSimdDirectiveClass:
361 break;
362 case Stmt::OMPMaskedTaskLoopSimdDirectiveClass:
365 break;
366 case Stmt::OMPParallelMasterTaskLoopDirectiveClass:
369 break;
370 case Stmt::OMPParallelMaskedTaskLoopDirectiveClass:
373 break;
374 case Stmt::OMPParallelMasterTaskLoopSimdDirectiveClass:
377 break;
378 case Stmt::OMPParallelMaskedTaskLoopSimdDirectiveClass:
381 break;
382 case Stmt::OMPDistributeDirectiveClass:
384 break;
385 case Stmt::OMPTargetUpdateDirectiveClass:
387 break;
388 case Stmt::OMPDistributeParallelForDirectiveClass:
391 break;
392 case Stmt::OMPDistributeParallelForSimdDirectiveClass:
395 break;
396 case Stmt::OMPDistributeSimdDirectiveClass:
398 break;
399 case Stmt::OMPTargetParallelForSimdDirectiveClass:
402 break;
403 case Stmt::OMPTargetSimdDirectiveClass:
405 break;
406 case Stmt::OMPTeamsDistributeDirectiveClass:
408 break;
409 case Stmt::OMPTeamsDistributeSimdDirectiveClass:
412 break;
413 case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass:
416 break;
417 case Stmt::OMPTeamsDistributeParallelForDirectiveClass:
420 break;
421 case Stmt::OMPTargetTeamsDirectiveClass:
423 break;
424 case Stmt::OMPTargetTeamsDistributeDirectiveClass:
427 break;
428 case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass:
431 break;
432 case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass:
435 break;
436 case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass:
439 break;
440 case Stmt::OMPInteropDirectiveClass:
442 break;
443 case Stmt::OMPDispatchDirectiveClass:
444 CGM.ErrorUnsupported(S, "OpenMP dispatch directive");
445 break;
446 case Stmt::OMPScopeDirectiveClass:
448 break;
449 case Stmt::OMPMaskedDirectiveClass:
451 break;
452 case Stmt::OMPGenericLoopDirectiveClass:
454 break;
455 case Stmt::OMPTeamsGenericLoopDirectiveClass:
457 break;
458 case Stmt::OMPTargetTeamsGenericLoopDirectiveClass:
461 break;
462 case Stmt::OMPParallelGenericLoopDirectiveClass:
465 break;
466 case Stmt::OMPTargetParallelGenericLoopDirectiveClass:
469 break;
470 case Stmt::OMPParallelMaskedDirectiveClass:
472 break;
473 case Stmt::OMPAssumeDirectiveClass:
475 break;
476 case Stmt::OpenACCComputeConstructClass:
478 break;
479 case Stmt::OpenACCLoopConstructClass:
481 break;
482 case Stmt::OpenACCCombinedConstructClass:
484 break;
485 case Stmt::OpenACCDataConstructClass:
487 break;
488 case Stmt::OpenACCEnterDataConstructClass:
490 break;
491 case Stmt::OpenACCExitDataConstructClass:
493 break;
494 case Stmt::OpenACCHostDataConstructClass:
496 break;
497 case Stmt::OpenACCWaitConstructClass:
499 break;
500 case Stmt::OpenACCInitConstructClass:
502 break;
503 case Stmt::OpenACCShutdownConstructClass:
505 break;
506 case Stmt::OpenACCSetConstructClass:
508 break;
509 case Stmt::OpenACCUpdateConstructClass:
511 break;
512 case Stmt::OpenACCAtomicConstructClass:
514 break;
515 case Stmt::OpenACCCacheConstructClass:
517 break;
518 }
519}
520
523 switch (S->getStmtClass()) {
524 default:
525 return false;
526 case Stmt::NullStmtClass:
527 break;
528 case Stmt::CompoundStmtClass:
530 break;
531 case Stmt::DeclStmtClass:
533 break;
534 case Stmt::LabelStmtClass:
536 break;
537 case Stmt::AttributedStmtClass:
539 break;
540 case Stmt::GotoStmtClass:
542 break;
543 case Stmt::BreakStmtClass:
545 break;
546 case Stmt::ContinueStmtClass:
548 break;
549 case Stmt::DefaultStmtClass:
551 break;
552 case Stmt::CaseStmtClass:
553 EmitCaseStmt(cast<CaseStmt>(*S), Attrs);
554 break;
555 case Stmt::DeferStmtClass:
557 break;
558 case Stmt::SEHLeaveStmtClass:
560 break;
561 case Stmt::SYCLKernelCallStmtClass:
563 break;
564 }
565 return true;
566}
567
568/// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
569/// this captures the expression result of the last sub-statement and returns it
570/// (for use by the statement expression extension).
572 AggValueSlot AggSlot) {
573 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(),
574 "LLVM IR generation of compound statement ('{}')");
575
576 // Keep track of the current cleanup stack depth, including debug scopes.
578
579 return EmitCompoundStmtWithoutScope(S, GetLast, AggSlot);
580}
581
584 bool GetLast,
585 AggValueSlot AggSlot) {
586
588 E = S.body_end() - GetLast;
589 I != E; ++I)
590 EmitStmt(*I);
591
592 Address RetAlloca = Address::invalid();
593 if (GetLast) {
594 // We have to special case labels here. They are statements, but when put
595 // at the end of a statement expression, they yield the value of their
596 // subexpression. Handle this by walking through all labels we encounter,
597 // emitting them before we evaluate the subexpr.
598 // Similar issues arise for attributed statements.
599 const Stmt *LastStmt = S.body_back();
600 while (!isa<Expr>(LastStmt)) {
601 if (const auto *LS = dyn_cast<LabelStmt>(LastStmt)) {
602 EmitLabel(LS->getDecl());
603 LastStmt = LS->getSubStmt();
604 } else if (const auto *AS = dyn_cast<AttributedStmt>(LastStmt)) {
605 // FIXME: Update this if we ever have attributes that affect the
606 // semantics of an expression.
607 LastStmt = AS->getSubStmt();
608 } else {
609 llvm_unreachable("unknown value statement");
610 }
611 }
612
614
615 const Expr *E = cast<Expr>(LastStmt);
616 QualType ExprTy = E->getType();
617 if (hasAggregateEvaluationKind(ExprTy)) {
618 EmitAggExpr(E, AggSlot);
619 } else {
620 // We can't return an RValue here because there might be cleanups at
621 // the end of the StmtExpr. Because of that, we have to emit the result
622 // here into a temporary alloca.
623 RetAlloca = CreateMemTempWithoutCast(ExprTy);
624 EmitAnyExprToMem(E, RetAlloca, Qualifiers(),
625 /*IsInit*/ false);
626 }
627 }
628
629 return RetAlloca;
630}
631
633 llvm::UncondBrInst *BI = dyn_cast<llvm::UncondBrInst>(BB->getTerminator());
634
635 // If there is a cleanup stack, then we it isn't worth trying to
636 // simplify this block (we would need to remove it from the scope map
637 // and cleanup entry).
638 if (!EHStack.empty())
639 return;
640
641 // Can only simplify direct branches.
642 if (!BI)
643 return;
644
645 // Can only simplify empty blocks.
646 if (BI->getIterator() != BB->begin())
647 return;
648
649 BB->replaceAllUsesWith(BI->getSuccessor());
650 BI->eraseFromParent();
651 BB->eraseFromParent();
652}
653
654void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
655 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
656
657 // Fall out of the current block (if necessary).
658 EmitBranch(BB);
659
660 if (IsFinished && BB->use_empty()) {
661 delete BB;
662 return;
663 }
664
665 // Place the block after the current block, if possible, or else at
666 // the end of the function.
667 if (CurBB && CurBB->getParent())
668 CurFn->insert(std::next(CurBB->getIterator()), BB);
669 else
670 CurFn->insert(CurFn->end(), BB);
671 Builder.SetInsertPoint(BB);
672}
673
674void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
675 // Emit a branch from the current block to the target one if this
676 // was a real block. If this was just a fall-through block after a
677 // terminator, don't emit it.
678 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
679
680 if (!CurBB || CurBB->hasTerminator()) {
681 // If there is no insert point or the previous block is already
682 // terminated, don't touch it.
683 } else {
684 // Otherwise, create a fall-through branch.
685 Builder.CreateBr(Target);
686 }
687
688 Builder.ClearInsertionPoint();
689}
690
691void CodeGenFunction::EmitBlockAfterUses(llvm::BasicBlock *block) {
692 bool inserted = false;
693 for (llvm::User *u : block->users()) {
694 if (llvm::Instruction *insn = dyn_cast<llvm::Instruction>(u)) {
695 CurFn->insert(std::next(insn->getParent()->getIterator()), block);
696 inserted = true;
697 break;
698 }
699 }
700
701 if (!inserted)
702 CurFn->insert(CurFn->end(), block);
703
704 Builder.SetInsertPoint(block);
705}
706
709 JumpDest &Dest = LabelMap[D];
710 if (Dest.isValid()) return Dest;
711
712 // Create, but don't insert, the new block.
713 Dest = JumpDest(createBasicBlock(D->getName()),
716 return Dest;
717}
718
720 // Add this label to the current lexical scope if we're within any
721 // normal cleanups. Jumps "in" to this label --- when permitted by
722 // the language --- may need to be routed around such cleanups.
723 if (EHStack.hasNormalCleanups() && CurLexicalScope)
724 CurLexicalScope->addLabel(D);
725
726 JumpDest &Dest = LabelMap[D];
727
728 // If we didn't need a forward reference to this label, just go
729 // ahead and create a destination at the current scope.
730 if (!Dest.isValid()) {
732
733 // Otherwise, we need to give this label a target depth and remove
734 // it from the branch-fixups list.
735 } else {
736 assert(!Dest.getScopeDepth().isValid() && "already emitted label!");
737 Dest.setScopeDepth(EHStack.stable_begin());
739 }
740
741 EmitBlock(Dest.getBlock());
742
743 // Emit debug info for labels.
744 if (CGDebugInfo *DI = getDebugInfo()) {
745 if (CGM.getCodeGenOpts().hasReducedDebugInfo()) {
746 DI->setLocation(D->getLocation());
747 DI->EmitLabel(D, Builder);
748 }
749 }
750
752}
753
754/// Change the cleanup scope of the labels in this lexical scope to
755/// match the scope of the enclosing context.
757 assert(!Labels.empty());
758 EHScopeStack::stable_iterator innermostScope
759 = CGF.EHStack.getInnermostNormalCleanup();
760
761 // Change the scope depth of all the labels.
762 for (const LabelDecl *Label : Labels) {
763 assert(CGF.LabelMap.count(Label));
764 JumpDest &dest = CGF.LabelMap.find(Label)->second;
765 assert(dest.getScopeDepth().isValid());
766 assert(innermostScope.encloses(dest.getScopeDepth()));
767 dest.setScopeDepth(innermostScope);
768 }
769
770 // Reparent the labels if the new scope also has cleanups.
771 if (innermostScope != EHScopeStack::stable_end() && ParentScope) {
772 ParentScope->Labels.append(Labels.begin(), Labels.end());
773 }
774}
775
776
778 EmitLabel(S.getDecl());
779
780 // IsEHa - emit eha.scope.begin if it's a side entry of a scope
781 if (getLangOpts().EHAsynch && S.isSideEntry())
783
784 EmitStmt(S.getSubStmt());
785}
786
788 bool nomerge = InNoMergeAttributedStmt;
789 bool noinline = InNoInlineAttributedStmt;
790 bool alwaysinline = InAlwaysInlineAttributedStmt;
791 bool noconvergent = InNoConvergentAttributedStmt;
792 StringRef amdgpuAVMode = AMDGPUAvailableVisibleMode;
793 HLSLControlFlowHintAttr::Spelling flattenOrBranch = HLSLControlFlowAttr;
794 const CallExpr *musttail = MustTailCall;
795 const AtomicAttr *AA = nullptr;
796
797 for (const auto *A : S.getAttrs()) {
798 switch (A->getKind()) {
799 default:
800 break;
801 case attr::NoMerge:
802 nomerge = true;
803 break;
804 case attr::NoInline:
805 noinline = true;
806 alwaysinline = false;
807 break;
808 case attr::AlwaysInline:
809 alwaysinline = true;
810 noinline = false;
811 break;
812 case attr::NoConvergent:
813 noconvergent = true;
814 break;
815 case attr::MustTail: {
816 const Stmt *Sub = S.getSubStmt();
817 const ReturnStmt *R = cast<ReturnStmt>(Sub);
818 musttail = cast<CallExpr>(R->getRetValue()->IgnoreParens());
819 } break;
820 case attr::CXXAssume: {
821 const Expr *Assumption = cast<CXXAssumeAttr>(A)->getAssumption();
822 if (getLangOpts().CXXAssumptions && Builder.GetInsertBlock() &&
823 !Assumption->HasSideEffects(getContext())) {
824 llvm::Value *AssumptionVal = EmitCheckedArgForAssume(Assumption);
825 Builder.CreateAssumption(AssumptionVal);
826 }
827 } break;
828 case attr::Atomic:
829 AA = cast<AtomicAttr>(A);
830 break;
831 case attr::AMDGPUAvailableVisible:
832 amdgpuAVMode = cast<AMDGPUAvailableVisibleAttr>(A)->getMode();
833 break;
834 case attr::HLSLControlFlowHint: {
835 flattenOrBranch = cast<HLSLControlFlowHintAttr>(A)->getSemanticSpelling();
836 } break;
837 }
838 }
839
840 assert(!(alwaysinline && noinline) &&
841 "alwaysinline and noinline are mutually exclusive");
842
843 SaveAndRestore save_nomerge(InNoMergeAttributedStmt, nomerge);
844 SaveAndRestore save_noinline(InNoInlineAttributedStmt, noinline);
845 SaveAndRestore save_alwaysinline(InAlwaysInlineAttributedStmt, alwaysinline);
846 SaveAndRestore save_noconvergent(InNoConvergentAttributedStmt, noconvergent);
847 SaveAndRestore save_amdgpuav(AMDGPUAvailableVisibleMode, amdgpuAVMode);
848 SaveAndRestore save_musttail(MustTailCall, musttail);
849 SaveAndRestore save_flattenOrBranch(HLSLControlFlowAttr, flattenOrBranch);
850 CGAtomicOptionsRAII AORAII(CGM, AA);
851 EmitStmt(S.getSubStmt(), S.getAttrs());
852}
853
855 // If this code is reachable then emit a stop point (if generating
856 // debug info). We have to do this ourselves because we are on the
857 // "simple" statement path.
858 if (HaveInsertPoint())
859 EmitStopPoint(&S);
860
863}
864
865
868 if (const LabelDecl *Target = S.getConstantTarget()) {
870 return;
871 }
872
873 // Ensure that we have an i8* for our PHI node.
874 llvm::Value *V = Builder.CreateBitCast(EmitScalarExpr(S.getTarget()),
875 Int8PtrTy, "addr");
876 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
877
878 // Get the basic block for the indirect goto.
879 llvm::BasicBlock *IndGotoBB = GetIndirectGotoBlock();
880
881 // The first instruction in the block has to be the PHI for the switch dest,
882 // add an entry for this branch.
883 cast<llvm::PHINode>(IndGotoBB->begin())->addIncoming(V, CurBB);
884
885 EmitBranch(IndGotoBB);
886 if (CurBB && CurBB->hasTerminator())
887 addInstToCurrentSourceAtom(CurBB->getTerminator(), nullptr);
888}
889
891 const Stmt *Else = S.getElse();
892
893 // The else branch of a consteval if statement is always the only branch that
894 // can be runtime evaluated.
895 if (S.isConsteval()) {
896 const Stmt *Executed = S.isNegatedConsteval() ? S.getThen() : Else;
897 if (Executed) {
898 RunCleanupsScope ExecutedScope(*this);
899 EmitStmt(Executed);
900 }
901 return;
902 }
903
904 // C99 6.8.4.1: The first substatement is executed if the expression compares
905 // unequal to 0. The condition must be a scalar type.
906 LexicalScope ConditionScope(*this, S.getCond()->getSourceRange());
907 ApplyDebugLocation DL(*this, S.getCond());
908
909 if (S.getInit()) {
910 EmitStmt(S.getInit());
911
912 // The init statement may have cleared the insertion point (e.g. it ended in
913 // a 'noreturn' call); the condition emitted below needs a valid one.
915 }
916
917 if (S.getConditionVariable())
919
920 // If the condition constant folds and can be elided, try to avoid emitting
921 // the condition and the dead arm of the if/else.
922 bool CondConstant;
923 if (ConstantFoldsToSimpleInteger(S.getCond(), CondConstant,
924 S.isConstexpr())) {
925 // Figure out which block (then or else) is executed.
926 const Stmt *Executed = S.getThen();
927 const Stmt *Skipped = Else;
928 if (!CondConstant) // Condition false?
929 std::swap(Executed, Skipped);
930
931 // If the skipped block has no labels in it, just emit the executed block.
932 // This avoids emitting dead code and simplifies the CFG substantially.
933 if (S.isConstexpr() || !ContainsLabel(Skipped)) {
935 /*UseBoth=*/true);
936 if (Executed) {
938 RunCleanupsScope ExecutedScope(*this);
939 EmitStmt(Executed);
940 }
941 PGO->markStmtMaybeUsed(Skipped);
942 return;
943 }
944 }
945
946 auto HasSkip = hasSkipCounter(&S);
947
948 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
949 // the conditional branch.
950 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
951 llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
952 llvm::BasicBlock *ElseBlock =
953 (Else || HasSkip ? createBasicBlock("if.else") : ContBlock);
954 // Prefer the PGO based weights over the likelihood attribute.
955 // When the build isn't optimized the metadata isn't used, so don't generate
956 // it.
957 // Also, differentiate between disabled PGO and a never executed branch with
958 // PGO. Assuming PGO is in use:
959 // - we want to ignore the [[likely]] attribute if the branch is never
960 // executed,
961 // - assuming the profile is poor, preserving the attribute may still be
962 // beneficial.
963 // As an approximation, preserve the attribute only if both the branch and the
964 // parent context were not executed.
966 uint64_t ThenCount = getProfileCount(S.getThen());
967 if (!ThenCount && !getCurrentProfileCount() &&
968 CGM.getCodeGenOpts().OptimizationLevel)
969 LH = Stmt::getLikelihood(S.getThen(), Else);
970
971 // When measuring MC/DC, always fully evaluate the condition up front using
972 // EvaluateExprAsBool() so that the test vector bitmap can be updated prior to
973 // executing the body of the if.then or if.else. This is useful for when
974 // there is a 'return' within the body, but this is particularly beneficial
975 // when one if-stmt is nested within another if-stmt so that all of the MC/DC
976 // updates are kept linear and consistent.
977 if (!CGM.getCodeGenOpts().MCDCCoverage) {
978 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock, ThenCount, LH,
979 /*ConditionalOp=*/nullptr,
980 /*ConditionalDecl=*/S.getConditionVariable());
981 } else {
982 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
984 Builder.CreateCondBr(BoolCondVal, ThenBlock, ElseBlock);
985 }
986
987 // Emit the 'then' code.
988 EmitBlock(ThenBlock);
990 {
991 RunCleanupsScope ThenScope(*this);
992 EmitStmt(S.getThen());
993 }
994 EmitBranch(ContBlock);
995
996 // Emit the 'else' code if present.
997 if (Else) {
998 {
999 // There is no need to emit line number for an unconditional branch.
1000 auto NL = ApplyDebugLocation::CreateEmpty(*this);
1001 EmitBlock(ElseBlock);
1002 }
1003 // Add a counter to else block unless it has CounterExpr.
1004 if (HasSkip)
1006 {
1007 RunCleanupsScope ElseScope(*this);
1008 EmitStmt(Else);
1009 }
1010 {
1011 // There is no need to emit line number for an unconditional branch.
1012 auto NL = ApplyDebugLocation::CreateEmpty(*this);
1013 EmitBranch(ContBlock);
1014 }
1015 } else if (HasSkip) {
1016 EmitBlock(ElseBlock);
1018 EmitBranch(ContBlock);
1019 }
1020
1021 // Emit the continuation block for code after the if.
1022 EmitBlock(ContBlock, true);
1023}
1024
1025bool CodeGenFunction::checkIfLoopMustProgress(const Expr *ControllingExpression,
1026 bool HasEmptyBody) {
1027 if (CGM.getCodeGenOpts().getFiniteLoops() ==
1029 return false;
1030
1031 // Now apply rules for plain C (see 6.8.5.6 in C11).
1032 // Loops with constant conditions do not have to make progress in any C
1033 // version.
1034 // As an extension, we consisider loops whose constant expression
1035 // can be constant-folded.
1037 bool CondIsConstInt =
1038 !ControllingExpression ||
1039 (ControllingExpression->EvaluateAsInt(Result, getContext()) &&
1040 Result.Val.isInt());
1041
1042 bool CondIsTrue = CondIsConstInt && (!ControllingExpression ||
1043 Result.Val.getInt().getBoolValue());
1044
1045 // Loops with non-constant conditions must make progress in C11 and later.
1046 if (getLangOpts().C11 && !CondIsConstInt)
1047 return true;
1048
1049 // [C++26][intro.progress] (DR)
1050 // The implementation may assume that any thread will eventually do one of the
1051 // following:
1052 // [...]
1053 // - continue execution of a trivial infinite loop ([stmt.iter.general]).
1054 if (CGM.getCodeGenOpts().getFiniteLoops() ==
1057 if (HasEmptyBody && CondIsTrue) {
1058 CurFn->removeFnAttr(llvm::Attribute::MustProgress);
1059 return false;
1060 }
1061 return true;
1062 }
1063 return false;
1064}
1065
1066// [C++26][stmt.iter.general] (DR)
1067// A trivially empty iteration statement is an iteration statement matching one
1068// of the following forms:
1069// - while ( expression ) ;
1070// - while ( expression ) { }
1071// - do ; while ( expression ) ;
1072// - do { } while ( expression ) ;
1073// - for ( init-statement expression(opt); ) ;
1074// - for ( init-statement expression(opt); ) { }
1075template <typename LoopStmt> static bool hasEmptyLoopBody(const LoopStmt &S) {
1076 if constexpr (std::is_same_v<LoopStmt, ForStmt>) {
1077 if (S.getInc())
1078 return false;
1079 }
1080 const Stmt *Body = S.getBody();
1081 if (!Body || isa<NullStmt>(Body))
1082 return true;
1083 if (const CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body))
1084 return Compound->body_empty();
1085 return false;
1086}
1087
1089 ArrayRef<const Attr *> WhileAttrs) {
1090 // Emit the header for the loop, which will also become
1091 // the continue target.
1092 JumpDest LoopHeader = getJumpDestInCurrentScope("while.cond");
1093 EmitBlock(LoopHeader.getBlock());
1094
1095 if (CGM.shouldEmitConvergenceTokens())
1096 ConvergenceTokenStack.push_back(
1097 emitConvergenceLoopToken(LoopHeader.getBlock()));
1098
1099 // Create an exit block for when the condition fails, which will
1100 // also become the break target.
1102
1103 // Store the blocks to use for break and continue.
1104 BreakContinueStack.push_back(BreakContinue(S, LoopExit, LoopHeader));
1105
1106 // C++ [stmt.while]p2:
1107 // When the condition of a while statement is a declaration, the
1108 // scope of the variable that is declared extends from its point
1109 // of declaration (3.3.2) to the end of the while statement.
1110 // [...]
1111 // The object created in a condition is destroyed and created
1112 // with each iteration of the loop.
1113 RunCleanupsScope ConditionScope(*this);
1114
1115 if (S.getConditionVariable())
1117
1118 // Evaluate the conditional in the while header. C99 6.8.5.1: The
1119 // evaluation of the controlling expression takes place before each
1120 // execution of the loop body.
1121 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
1122
1124
1125 // while(1) is common, avoid extra exit blocks. Be sure
1126 // to correctly handle break/continue though.
1127 llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal);
1128 bool EmitBoolCondBranch = !C || !C->isOne();
1129 const SourceRange &R = S.getSourceRange();
1130 LoopStack.push(LoopHeader.getBlock(), CGM.getContext(), CGM.getCodeGenOpts(),
1131 WhileAttrs, SourceLocToDebugLoc(R.getBegin()),
1132 SourceLocToDebugLoc(R.getEnd()),
1134
1135 // As long as the condition is true, go to the loop body.
1136 llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
1137 if (EmitBoolCondBranch) {
1138 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
1139 if (hasSkipCounter(&S) || ConditionScope.requiresCleanups())
1140 ExitBlock = createBasicBlock("while.exit");
1141 llvm::MDNode *Weights =
1142 createProfileWeightsForLoop(S.getCond(), getProfileCount(S.getBody()));
1143 if (!Weights && CGM.getCodeGenOpts().OptimizationLevel)
1144 BoolCondVal = emitCondLikelihoodViaExpectIntrinsic(
1145 BoolCondVal, Stmt::getLikelihood(S.getBody()));
1146 auto *I = Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock, Weights);
1147 // Key Instructions: Emit the condition and branch as separate source
1148 // location atoms otherwise we may omit a step onto the loop condition in
1149 // favour of the `while` keyword.
1150 // FIXME: We could have the branch as the backup location for the condition,
1151 // which would probably be a better experience. Explore this later.
1152 if (auto *CondI = dyn_cast<llvm::Instruction>(BoolCondVal))
1153 addInstToNewSourceAtom(CondI, nullptr);
1154 addInstToNewSourceAtom(I, nullptr);
1155
1156 if (ExitBlock != LoopExit.getBlock()) {
1157 EmitBlock(ExitBlock);
1160 }
1161 } else if (const Attr *A = Stmt::getLikelihoodAttr(S.getBody())) {
1162 CGM.getDiags().Report(A->getLocation(),
1163 diag::warn_attribute_has_no_effect_on_infinite_loop)
1164 << A << A->getRange();
1165 CGM.getDiags().Report(
1166 S.getWhileLoc(),
1167 diag::note_attribute_has_no_effect_on_infinite_loop_here)
1169 }
1170
1171 // Emit the loop body. We have to emit this in a cleanup scope
1172 // because it might be a singleton DeclStmt.
1173 {
1174 RunCleanupsScope BodyScope(*this);
1175 EmitBlock(LoopBody);
1177 EmitStmt(S.getBody());
1178 }
1179
1180 BreakContinueStack.pop_back();
1181
1182 // Immediately force cleanup.
1183 ConditionScope.ForceCleanup();
1184
1185 EmitStopPoint(&S);
1186 // Branch to the loop header again.
1187 EmitBranch(LoopHeader.getBlock());
1188
1189 LoopStack.pop();
1190
1191 // Emit the exit block.
1192 EmitBlock(LoopExit.getBlock(), true);
1193
1194 // The LoopHeader typically is just a branch if we skipped emitting
1195 // a branch, try to erase it.
1196 if (!EmitBoolCondBranch) {
1197 SimplifyForwardingBlocks(LoopHeader.getBlock());
1198 PGO->markStmtAsUsed(true, &S);
1199 }
1200
1201 if (CGM.shouldEmitConvergenceTokens())
1202 ConvergenceTokenStack.pop_back();
1203}
1204
1206 ArrayRef<const Attr *> DoAttrs) {
1208 JumpDest LoopCond = getJumpDestInCurrentScope("do.cond");
1209
1210 uint64_t ParentCount = getCurrentProfileCount();
1211
1212 // Store the blocks to use for break and continue.
1213 BreakContinueStack.push_back(BreakContinue(S, LoopExit, LoopCond));
1214
1215 // Emit the body of the loop.
1216 llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
1217
1218 EmitBlockWithFallThrough(LoopBody, &S);
1219
1220 if (CGM.shouldEmitConvergenceTokens())
1222
1223 {
1224 RunCleanupsScope BodyScope(*this);
1225 EmitStmt(S.getBody());
1226 }
1227
1228 EmitBlock(LoopCond.getBlock());
1229
1230 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
1231 // after each execution of the loop body."
1232
1233 // Evaluate the conditional in the while header.
1234 // C99 6.8.5p2/p4: The first substatement is executed if the expression
1235 // compares unequal to 0. The condition must be a scalar type.
1236 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
1237
1238 BreakContinueStack.pop_back();
1239
1240 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
1241 // to correctly handle break/continue though.
1242 llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal);
1243 bool EmitBoolCondBranch = !C || !C->isZero();
1244
1245 const SourceRange &R = S.getSourceRange();
1246 LoopStack.push(LoopBody, CGM.getContext(), CGM.getCodeGenOpts(), DoAttrs,
1247 SourceLocToDebugLoc(R.getBegin()),
1248 SourceLocToDebugLoc(R.getEnd()),
1250
1251 auto *LoopFalse = (hasSkipCounter(&S) ? createBasicBlock("do.loopfalse")
1252 : LoopExit.getBlock());
1253
1254 // As long as the condition is true, iterate the loop.
1255 if (EmitBoolCondBranch) {
1256 uint64_t BackedgeCount = getProfileCount(S.getBody()) - ParentCount;
1257 auto *I = Builder.CreateCondBr(
1258 BoolCondVal, LoopBody, LoopFalse,
1259 createProfileWeightsForLoop(S.getCond(), BackedgeCount));
1260
1261 // Key Instructions: Emit the condition and branch as separate source
1262 // location atoms otherwise we may omit a step onto the loop condition in
1263 // favour of the closing brace.
1264 // FIXME: We could have the branch as the backup location for the condition,
1265 // which would probably be a better experience (no jumping to the brace).
1266 if (auto *CondI = dyn_cast<llvm::Instruction>(BoolCondVal))
1267 addInstToNewSourceAtom(CondI, nullptr);
1268 addInstToNewSourceAtom(I, nullptr);
1269 }
1270
1271 LoopStack.pop();
1272
1273 if (LoopFalse != LoopExit.getBlock()) {
1274 EmitBlock(LoopFalse);
1275 incrementProfileCounter(UseSkipPath, &S, /*UseBoth=*/true);
1276 }
1277
1278 // Emit the exit block.
1279 EmitBlock(LoopExit.getBlock());
1280
1281 // The DoCond block typically is just a branch if we skipped
1282 // emitting a branch, try to erase it.
1283 if (!EmitBoolCondBranch)
1285
1286 if (CGM.shouldEmitConvergenceTokens())
1287 ConvergenceTokenStack.pop_back();
1288}
1289
1291 ArrayRef<const Attr *> ForAttrs) {
1293
1294 std::optional<LexicalScope> ForScope;
1296 ForScope.emplace(*this, S.getSourceRange());
1297
1298 // Evaluate the first part before the loop.
1299 if (S.getInit())
1300 EmitStmt(S.getInit());
1301
1302 // Start the loop with a block that tests the condition.
1303 // If there's an increment, the continue scope will be overwritten
1304 // later.
1305 JumpDest CondDest = getJumpDestInCurrentScope("for.cond");
1306 llvm::BasicBlock *CondBlock = CondDest.getBlock();
1307 EmitBlock(CondBlock);
1308
1309 if (CGM.shouldEmitConvergenceTokens())
1310 ConvergenceTokenStack.push_back(emitConvergenceLoopToken(CondBlock));
1311
1312 const SourceRange &R = S.getSourceRange();
1313 LoopStack.push(CondBlock, CGM.getContext(), CGM.getCodeGenOpts(), ForAttrs,
1314 SourceLocToDebugLoc(R.getBegin()),
1315 SourceLocToDebugLoc(R.getEnd()),
1317
1318 // Create a cleanup scope for the condition variable cleanups.
1319 LexicalScope ConditionScope(*this, S.getSourceRange());
1320
1321 // If the for loop doesn't have an increment we can just use the condition as
1322 // the continue block. Otherwise, if there is no condition variable, we can
1323 // form the continue block now. If there is a condition variable, we can't
1324 // form the continue block until after we've emitted the condition, because
1325 // the condition is in scope in the increment, but Sema's jump diagnostics
1326 // ensure that there are no continues from the condition variable that jump
1327 // to the loop increment.
1328 JumpDest Continue;
1329 if (!S.getInc())
1330 Continue = CondDest;
1331 else if (!S.getConditionVariable())
1332 Continue = getJumpDestInCurrentScope("for.inc");
1333 BreakContinueStack.push_back(BreakContinue(S, LoopExit, Continue));
1334
1335 if (S.getCond()) {
1336 // If the for statement has a condition scope, emit the local variable
1337 // declaration.
1338 if (S.getConditionVariable()) {
1340
1341 // We have entered the condition variable's scope, so we're now able to
1342 // jump to the continue block.
1343 Continue = S.getInc() ? getJumpDestInCurrentScope("for.inc") : CondDest;
1344 BreakContinueStack.back().ContinueBlock = Continue;
1345 }
1346
1347 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
1348 // If there are any cleanups between here and the loop-exit scope,
1349 // create a block to stage a loop exit along.
1350 if (hasSkipCounter(&S) || (ForScope && ForScope->requiresCleanups()))
1351 ExitBlock = createBasicBlock("for.cond.cleanup");
1352
1353 // As long as the condition is true, iterate the loop.
1354 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1355
1356 // C99 6.8.5p2/p4: The first substatement is executed if the expression
1357 // compares unequal to 0. The condition must be a scalar type.
1358 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
1359
1361
1362 llvm::MDNode *Weights =
1363 createProfileWeightsForLoop(S.getCond(), getProfileCount(S.getBody()));
1364 if (!Weights && CGM.getCodeGenOpts().OptimizationLevel)
1365 BoolCondVal = emitCondLikelihoodViaExpectIntrinsic(
1366 BoolCondVal, Stmt::getLikelihood(S.getBody()));
1367
1368 auto *I = Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock, Weights);
1369 // Key Instructions: Emit the condition and branch as separate atoms to
1370 // match existing loop stepping behaviour. FIXME: We could have the branch
1371 // as the backup location for the condition, which would probably be a
1372 // better experience (no jumping to the brace).
1373 if (auto *CondI = dyn_cast<llvm::Instruction>(BoolCondVal))
1374 addInstToNewSourceAtom(CondI, nullptr);
1375 addInstToNewSourceAtom(I, nullptr);
1376
1377 if (ExitBlock != LoopExit.getBlock()) {
1378 EmitBlock(ExitBlock);
1381 }
1382
1383 EmitBlock(ForBody);
1384 } else {
1385 // Treat it as a non-zero constant. Don't even create a new block for the
1386 // body, just fall into it.
1387 PGO->markStmtAsUsed(true, &S);
1388 }
1389
1391
1392 {
1393 // Create a separate cleanup scope for the body, in case it is not
1394 // a compound statement.
1395 RunCleanupsScope BodyScope(*this);
1396 EmitStmt(S.getBody());
1397 }
1398
1399 // The last block in the loop's body (which unconditionally branches to the
1400 // `inc` block if there is one).
1401 auto *FinalBodyBB = Builder.GetInsertBlock();
1402
1403 // If there is an increment, emit it next.
1404 if (S.getInc()) {
1405 EmitBlock(Continue.getBlock());
1406 EmitStmt(S.getInc());
1407 }
1408
1409 BreakContinueStack.pop_back();
1410
1411 ConditionScope.ForceCleanup();
1412
1413 EmitStopPoint(&S);
1414 EmitBranch(CondBlock);
1415
1416 if (ForScope)
1417 ForScope->ForceCleanup();
1418
1419 LoopStack.pop();
1420
1421 // Emit the fall-through block.
1422 EmitBlock(LoopExit.getBlock(), true);
1423
1424 if (CGM.shouldEmitConvergenceTokens())
1425 ConvergenceTokenStack.pop_back();
1426
1427 if (FinalBodyBB) {
1428 // Key Instructions: We want the for closing brace to be step-able on to
1429 // match existing behaviour.
1430 addInstToNewSourceAtom(FinalBodyBB->getTerminator(), nullptr);
1431 }
1432}
1433
1434void
1436 ArrayRef<const Attr *> ForAttrs) {
1438
1439 LexicalScope ForScope(*this, S.getSourceRange());
1440
1441 // Evaluate the first pieces before the loop.
1442 if (S.getInit())
1443 EmitStmt(S.getInit());
1446 EmitStmt(S.getEndStmt());
1447
1448 // Start the loop with a block that tests the condition.
1449 // If there's an increment, the continue scope will be overwritten
1450 // later.
1451 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1452 EmitBlock(CondBlock);
1453
1454 if (CGM.shouldEmitConvergenceTokens())
1455 ConvergenceTokenStack.push_back(emitConvergenceLoopToken(CondBlock));
1456
1457 const SourceRange &R = S.getSourceRange();
1458 LoopStack.push(CondBlock, CGM.getContext(), CGM.getCodeGenOpts(), ForAttrs,
1459 SourceLocToDebugLoc(R.getBegin()),
1460 SourceLocToDebugLoc(R.getEnd()));
1461
1462 // If there are any cleanups between here and the loop-exit scope,
1463 // create a block to stage a loop exit along.
1464 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
1465 if (hasSkipCounter(&S) || ForScope.requiresCleanups())
1466 ExitBlock = createBasicBlock("for.cond.cleanup");
1467
1468 // The loop body, consisting of the specified body and the loop variable.
1469 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1470
1471 // The body is executed if the expression, contextually converted
1472 // to bool, is true.
1473 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
1474 llvm::MDNode *Weights =
1475 createProfileWeightsForLoop(S.getCond(), getProfileCount(S.getBody()));
1476 if (!Weights && CGM.getCodeGenOpts().OptimizationLevel)
1477 BoolCondVal = emitCondLikelihoodViaExpectIntrinsic(
1478 BoolCondVal, Stmt::getLikelihood(S.getBody()));
1479 auto *I = Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock, Weights);
1480 // Key Instructions: Emit the condition and branch as separate atoms to
1481 // match existing loop stepping behaviour. FIXME: We could have the branch as
1482 // the backup location for the condition, which would probably be a better
1483 // experience.
1484 if (auto *CondI = dyn_cast<llvm::Instruction>(BoolCondVal))
1485 addInstToNewSourceAtom(CondI, nullptr);
1486 addInstToNewSourceAtom(I, nullptr);
1487
1488 if (ExitBlock != LoopExit.getBlock()) {
1489 EmitBlock(ExitBlock);
1492 }
1493
1494 EmitBlock(ForBody);
1496
1497 // Create a block for the increment. In case of a 'continue', we jump there.
1498 JumpDest Continue = getJumpDestInCurrentScope("for.inc");
1499
1500 // Store the blocks to use for break and continue.
1501 BreakContinueStack.push_back(BreakContinue(S, LoopExit, Continue));
1502
1503 {
1504 // Create a separate cleanup scope for the loop variable and body.
1505 LexicalScope BodyScope(*this, S.getSourceRange());
1507 EmitStmt(S.getBody());
1508 }
1509 // The last block in the loop's body (which unconditionally branches to the
1510 // `inc` block if there is one).
1511 auto *FinalBodyBB = Builder.GetInsertBlock();
1512
1513 EmitStopPoint(&S);
1514 // If there is an increment, emit it next.
1515 EmitBlock(Continue.getBlock());
1516 EmitStmt(S.getInc());
1517
1518 BreakContinueStack.pop_back();
1519
1520 EmitBranch(CondBlock);
1521
1522 ForScope.ForceCleanup();
1523
1524 LoopStack.pop();
1525
1526 // Emit the fall-through block.
1527 EmitBlock(LoopExit.getBlock(), true);
1528
1529 if (CGM.shouldEmitConvergenceTokens())
1530 ConvergenceTokenStack.pop_back();
1531
1532 if (FinalBodyBB) {
1533 // We want the for closing brace to be step-able on to match existing
1534 // behaviour.
1535 addInstToNewSourceAtom(FinalBodyBB->getTerminator(), nullptr);
1536 }
1537}
1538
1541 LexicalScope Scope(*this, S.getSourceRange());
1542
1543 for (const Stmt *DS : S.getPreambleStmts())
1544 EmitStmt(DS);
1545
1546 if (S.getInstantiations().empty())
1547 return;
1548
1549 JumpDest ExpandExit = getJumpDestInCurrentScope("expand.end");
1550 JumpDest ContinueDest;
1551 for (auto [N, Inst] : enumerate(S.getInstantiations())) {
1552 if (N == S.getInstantiations().size() - 1)
1553 ContinueDest = ExpandExit;
1554 else
1555 ContinueDest = getJumpDestInCurrentScope("expand.next");
1556
1557 LexicalScope ExpansionScope(*this, Inst->getSourceRange());
1558 BreakContinueStack.push_back(BreakContinue(S, ExpandExit, ContinueDest));
1559 EmitStmt(Inst);
1560 BreakContinueStack.pop_back();
1561 EmitBlock(ContinueDest.getBlock(), true);
1562 }
1563}
1564
1565void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
1566 if (RV.isScalar()) {
1567 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
1568 } else if (RV.isAggregate()) {
1569 LValue Dest = MakeAddrLValue(ReturnValue, Ty);
1572 } else {
1574 /*init*/ true);
1575 }
1577}
1578
1579namespace {
1580// RAII struct used to save and restore a return statment's result expression.
1581struct SaveRetExprRAII {
1582 SaveRetExprRAII(const Expr *RetExpr, CodeGenFunction &CGF)
1583 : OldRetExpr(CGF.RetExpr), CGF(CGF) {
1584 CGF.RetExpr = RetExpr;
1585 }
1586 ~SaveRetExprRAII() { CGF.RetExpr = OldRetExpr; }
1587 const Expr *OldRetExpr;
1588 CodeGenFunction &CGF;
1589};
1590} // namespace
1591
1592/// Determine if the given call uses the swiftasync calling convention.
1593static bool isSwiftAsyncCallee(const CallExpr *CE) {
1594 auto calleeQualType = CE->getCallee()->getType();
1595 const FunctionType *calleeType = nullptr;
1596 if (calleeQualType->isFunctionPointerType() ||
1597 calleeQualType->isFunctionReferenceType() ||
1598 calleeQualType->isBlockPointerType() ||
1599 calleeQualType->isMemberFunctionPointerType()) {
1600 calleeType = calleeQualType->getPointeeType()->castAs<FunctionType>();
1601 } else if (auto *ty = dyn_cast<FunctionType>(calleeQualType)) {
1602 calleeType = ty;
1603 } else if (auto CMCE = dyn_cast<CXXMemberCallExpr>(CE)) {
1604 if (auto methodDecl = CMCE->getMethodDecl()) {
1605 // getMethodDecl() doesn't handle member pointers at the moment.
1606 calleeType = methodDecl->getType()->castAs<FunctionType>();
1607 } else {
1608 return false;
1609 }
1610 } else {
1611 return false;
1612 }
1613 return calleeType->getCallConv() == CallingConv::CC_SwiftAsync;
1614}
1615
1616/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
1617/// if the function returns void, or may be missing one if the function returns
1618/// non-void. Fun stuff :).
1621 if (requiresReturnValueCheck()) {
1622 llvm::Constant *SLoc = EmitCheckSourceLocation(S.getBeginLoc());
1623 auto *SLocPtr =
1624 new llvm::GlobalVariable(CGM.getModule(), SLoc->getType(), false,
1625 llvm::GlobalVariable::PrivateLinkage, SLoc);
1626 SLocPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1627 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(SLocPtr);
1628 assert(ReturnLocation.isValid() && "No valid return location");
1629 Builder.CreateStore(SLocPtr, ReturnLocation);
1630 }
1631
1632 // Returning from an outlined SEH helper is UB, and we already warn on it.
1633 if (IsOutlinedSEHHelper) {
1634 Builder.CreateUnreachable();
1635 Builder.ClearInsertionPoint();
1636 }
1637
1638 // Emit the result value, even if unused, to evaluate the side effects.
1639 const Expr *RV = S.getRetValue();
1640
1641 // Record the result expression of the return statement. The recorded
1642 // expression is used to determine whether a block capture's lifetime should
1643 // end at the end of the full expression as opposed to the end of the scope
1644 // enclosing the block expression.
1645 //
1646 // This permits a small, easily-implemented exception to our over-conservative
1647 // rules about not jumping to statements following block literals with
1648 // non-trivial cleanups.
1649 SaveRetExprRAII SaveRetExpr(RV, *this);
1650
1651 RunCleanupsScope cleanupScope(*this);
1652 if (const auto *EWC = dyn_cast_or_null<ExprWithCleanups>(RV))
1653 RV = EWC->getSubExpr();
1654
1655 // If we're in a swiftasynccall function, and the return expression is a
1656 // call to a swiftasynccall function, mark the call as the musttail call.
1657 std::optional<llvm::SaveAndRestore<const CallExpr *>> SaveMustTail;
1658 if (RV && CurFnInfo &&
1659 CurFnInfo->getASTCallingConvention() == CallingConv::CC_SwiftAsync) {
1660 if (auto CE = dyn_cast<CallExpr>(RV)) {
1661 if (isSwiftAsyncCallee(CE)) {
1662 SaveMustTail.emplace(MustTailCall, CE);
1663 }
1664 }
1665 }
1666
1667 // FIXME: Clean this up by using an LValue for ReturnTemp,
1668 // EmitStoreThroughLValue, and EmitAnyExpr.
1669 // Check if the NRVO candidate was not globalized in OpenMP mode.
1670 if (getLangOpts().ElideConstructors && S.getNRVOCandidate() &&
1672 (!getLangOpts().OpenMP ||
1673 !CGM.getOpenMPRuntime()
1674 .getAddressOfLocalVariable(*this, S.getNRVOCandidate())
1675 .isValid())) {
1676 // Apply the named return value optimization for this return statement,
1677 // which means doing nothing: the appropriate result has already been
1678 // constructed into the NRVO variable.
1679
1680 // If there is an NRVO flag for this variable, set it to 1 into indicate
1681 // that the cleanup code should not destroy the variable.
1682 if (llvm::Value *NRVOFlag = NRVOFlags[S.getNRVOCandidate()])
1683 Builder.CreateFlagStore(Builder.getTrue(), NRVOFlag);
1684 } else if (!ReturnValue.isValid() || (RV && RV->getType()->isVoidType())) {
1685 // Make sure not to return anything, but evaluate the expression
1686 // for side effects.
1687 if (RV) {
1688 EmitAnyExpr(RV);
1689 }
1690 } else if (!RV) {
1691 // Do nothing (return value is left uninitialized)
1692 } else if (FnRetTy->isReferenceType()) {
1693 // If this function returns a reference, take the address of the expression
1694 // rather than the value.
1696 auto *I = Builder.CreateStore(Result.getScalarVal(), ReturnValue);
1697 addInstToCurrentSourceAtom(I, I->getValueOperand());
1698 } else {
1699 switch (getEvaluationKind(RV->getType())) {
1700 case TEK_Scalar: {
1701 llvm::Value *Ret = EmitScalarExpr(RV);
1702 if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect) {
1704 /*isInit*/ true);
1705 } else {
1706 auto *I = Builder.CreateStore(Ret, ReturnValue);
1707 addInstToCurrentSourceAtom(I, I->getValueOperand());
1708 }
1709 break;
1710 }
1711 case TEK_Complex:
1713 /*isInit*/ true);
1714 break;
1715 case TEK_Aggregate:
1722 break;
1723 }
1724 }
1725
1726 ++NumReturnExprs;
1727 if (!RV || RV->isEvaluatable(getContext()))
1728 ++NumSimpleReturnExprs;
1729
1730 cleanupScope.ForceCleanup();
1732}
1733
1735 // As long as debug info is modeled with instructions, we have to ensure we
1736 // have a place to insert here and write the stop point here.
1737 if (HaveInsertPoint())
1738 EmitStopPoint(&S);
1739
1740 for (const auto *I : S.decls())
1741 EmitDecl(*I, /*EvaluateConditionDecl=*/true);
1742}
1743
1745 -> const BreakContinue * {
1746 if (!S.hasLabelTarget())
1747 return &BreakContinueStack.back();
1748
1749 const Stmt *LoopOrSwitch = S.getNamedLoopOrSwitch();
1750 assert(LoopOrSwitch && "break/continue target not set?");
1751 for (const BreakContinue &BC : llvm::reverse(BreakContinueStack))
1752 if (BC.LoopOrSwitch == LoopOrSwitch)
1753 return &BC;
1754
1755 llvm_unreachable("break/continue target not found");
1756}
1757
1759 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
1760
1761 // If this code is reachable then emit a stop point (if generating
1762 // debug info). We have to do this ourselves because we are on the
1763 // "simple" statement path.
1764 if (HaveInsertPoint())
1765 EmitStopPoint(&S);
1766
1769}
1770
1772 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
1773
1774 // If this code is reachable then emit a stop point (if generating
1775 // debug info). We have to do this ourselves because we are on the
1776 // "simple" statement path.
1777 if (HaveInsertPoint())
1778 EmitStopPoint(&S);
1779
1782}
1783
1784/// EmitCaseStmtRange - If case statement range is not too big then
1785/// add multiple cases to switch instruction, one for each value within
1786/// the range. If range is too big then emit "if" condition check.
1788 ArrayRef<const Attr *> Attrs) {
1789 assert(S.getRHS() && "Expected RHS value in CaseStmt");
1790
1791 llvm::APSInt LHS = S.getLHS()->EvaluateKnownConstInt(getContext());
1792 llvm::APSInt RHS = S.getRHS()->EvaluateKnownConstInt(getContext());
1793
1794 // Emit the code for this case. We do this first to make sure it is
1795 // properly chained from our predecessor before generating the
1796 // switch machinery to enter this block.
1797 llvm::BasicBlock *CaseDest = createBasicBlock("sw.bb");
1798 EmitBlockWithFallThrough(CaseDest, &S);
1799 EmitStmt(S.getSubStmt());
1800
1801 // If range is empty, do nothing.
1802 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
1803 return;
1804
1806 llvm::APInt Range = RHS - LHS;
1807 // FIXME: parameters such as this should not be hardcoded.
1808 if (Range.getBitWidth() < 7 ||
1809 Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
1810 // Range is small enough to add multiple switch instruction cases.
1811 uint64_t Total = getProfileCount(&S);
1812 unsigned NCases = Range.getZExtValue() + 1;
1813 // We only have one region counter for the entire set of cases here, so we
1814 // need to divide the weights evenly between the generated cases, ensuring
1815 // that the total weight is preserved. E.g., a weight of 5 over three cases
1816 // will be distributed as weights of 2, 2, and 1.
1817 uint64_t Weight = Total / NCases, Rem = Total % NCases;
1818 for (unsigned I = 0; I != NCases; ++I) {
1819 if (SwitchWeights)
1820 SwitchWeights->push_back(Weight + (Rem ? 1 : 0));
1821 else if (SwitchLikelihood)
1822 SwitchLikelihood->push_back(LH);
1823
1824 if (Rem)
1825 Rem--;
1826 SwitchInsn->addCase(Builder.getInt(LHS), CaseDest);
1827 ++LHS;
1828 }
1829 return;
1830 }
1831
1832 // The range is too big. Emit "if" condition into a new block,
1833 // making sure to save and restore the current insertion point.
1834 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
1835
1836 // Push this test onto the chain of range checks (which terminates
1837 // in the default basic block). The switch's default will be changed
1838 // to the top of this chain after switch emission is complete.
1839 llvm::BasicBlock *FalseDest = CaseRangeBlock;
1840 CaseRangeBlock = createBasicBlock("sw.caserange");
1841
1842 CurFn->insert(CurFn->end(), CaseRangeBlock);
1843 Builder.SetInsertPoint(CaseRangeBlock);
1844
1845 // Emit range check.
1846 llvm::Value *Diff =
1847 Builder.CreateSub(SwitchInsn->getCondition(), Builder.getInt(LHS));
1848 llvm::Value *Cond =
1849 Builder.CreateICmpULE(Diff, Builder.getInt(Range), "inbounds");
1850
1851 llvm::MDNode *Weights = nullptr;
1852 if (SwitchWeights) {
1853 uint64_t ThisCount = getProfileCount(&S);
1854 uint64_t DefaultCount = (*SwitchWeights)[0];
1855 Weights = createProfileWeights(ThisCount, DefaultCount);
1856
1857 // Since we're chaining the switch default through each large case range, we
1858 // need to update the weight for the default, ie, the first case, to include
1859 // this case.
1860 (*SwitchWeights)[0] += ThisCount;
1861 } else if (SwitchLikelihood)
1862 Cond = emitCondLikelihoodViaExpectIntrinsic(Cond, LH);
1863
1864 Builder.CreateCondBr(Cond, CaseDest, FalseDest, Weights);
1865
1866 // Restore the appropriate insertion point.
1867 if (RestoreBB)
1868 Builder.SetInsertPoint(RestoreBB);
1869 else
1870 Builder.ClearInsertionPoint();
1871}
1872
1874 ArrayRef<const Attr *> Attrs) {
1875 // If there is no enclosing switch instance that we're aware of, then this
1876 // case statement and its block can be elided. This situation only happens
1877 // when we've constant-folded the switch, are emitting the constant case,
1878 // and part of the constant case includes another case statement. For
1879 // instance: switch (4) { case 4: do { case 5: } while (1); }
1880 if (!SwitchInsn) {
1881 EmitStmt(S.getSubStmt());
1882 return;
1883 }
1884
1885 // Handle case ranges.
1886 if (S.getRHS()) {
1887 EmitCaseStmtRange(S, Attrs);
1888 return;
1889 }
1890
1891 llvm::ConstantInt *CaseVal =
1893
1894 // Emit debuginfo for the case value if it is an enum value.
1895 const ConstantExpr *CE;
1896 if (auto ICE = dyn_cast<ImplicitCastExpr>(S.getLHS()))
1897 CE = dyn_cast<ConstantExpr>(ICE->getSubExpr());
1898 else
1899 CE = dyn_cast<ConstantExpr>(S.getLHS());
1900 if (CE) {
1901 if (auto DE = dyn_cast<DeclRefExpr>(CE->getSubExpr()))
1902 if (CGDebugInfo *Dbg = getDebugInfo())
1903 if (CGM.getCodeGenOpts().hasReducedDebugInfo())
1904 Dbg->EmitGlobalVariable(DE->getDecl(),
1905 APValue(llvm::APSInt(CaseVal->getValue())));
1906 }
1907
1908 if (SwitchLikelihood)
1909 SwitchLikelihood->push_back(Stmt::getLikelihood(Attrs));
1910
1911 // If the body of the case is just a 'break', try to not emit an empty block.
1912 // If we're profiling or we're not optimizing, leave the block in for better
1913 // debug and coverage analysis.
1914 if (!CGM.getCodeGenOpts().hasProfileClangInstr() &&
1915 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1917 JumpDest Block = BreakContinueStack.back().BreakBlock;
1918
1919 // Only do this optimization if there are no cleanups that need emitting.
1921 if (SwitchWeights)
1922 SwitchWeights->push_back(getProfileCount(&S));
1923 SwitchInsn->addCase(CaseVal, Block.getBlock());
1924
1925 // If there was a fallthrough into this case, make sure to redirect it to
1926 // the end of the switch as well.
1927 if (Builder.GetInsertBlock()) {
1928 Builder.CreateBr(Block.getBlock());
1929 Builder.ClearInsertionPoint();
1930 }
1931 return;
1932 }
1933 }
1934
1935 llvm::BasicBlock *CaseDest = createBasicBlock("sw.bb");
1936 EmitBlockWithFallThrough(CaseDest, &S);
1937 if (SwitchWeights)
1938 SwitchWeights->push_back(getProfileCount(&S));
1939 SwitchInsn->addCase(CaseVal, CaseDest);
1940
1941 // Recursively emitting the statement is acceptable, but is not wonderful for
1942 // code where we have many case statements nested together, i.e.:
1943 // case 1:
1944 // case 2:
1945 // case 3: etc.
1946 // Handling this recursively will create a new block for each case statement
1947 // that falls through to the next case which is IR intensive. It also causes
1948 // deep recursion which can run into stack depth limitations. Handle
1949 // sequential non-range case statements specially.
1950 //
1951 // TODO When the next case has a likelihood attribute the code returns to the
1952 // recursive algorithm. Maybe improve this case if it becomes common practice
1953 // to use a lot of attributes.
1954 const CaseStmt *CurCase = &S;
1955 const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
1956
1957 // Otherwise, iteratively add consecutive cases to this switch stmt.
1958 while (NextCase && NextCase->getRHS() == nullptr) {
1959 CurCase = NextCase;
1960 llvm::ConstantInt *CaseVal =
1961 Builder.getInt(CurCase->getLHS()->EvaluateKnownConstInt(getContext()));
1962
1963 if (SwitchWeights)
1964 SwitchWeights->push_back(getProfileCount(NextCase));
1965 if (CGM.getCodeGenOpts().hasProfileClangInstr()) {
1966 CaseDest = createBasicBlock("sw.bb");
1967 EmitBlockWithFallThrough(CaseDest, CurCase);
1968 }
1969 // Since this loop is only executed when the CaseStmt has no attributes
1970 // use a hard-coded value.
1971 if (SwitchLikelihood)
1972 SwitchLikelihood->push_back(Stmt::LH_None);
1973
1974 SwitchInsn->addCase(CaseVal, CaseDest);
1975 NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt());
1976 }
1977
1978 // Generate a stop point for debug info if the case statement is
1979 // followed by a default statement. A fallthrough case before a
1980 // default case gets its own branch target.
1981 if (CurCase->getSubStmt()->getStmtClass() == Stmt::DefaultStmtClass)
1982 EmitStopPoint(CurCase);
1983
1984 // Normal default recursion for non-cases.
1985 EmitStmt(CurCase->getSubStmt());
1986}
1987
1989 ArrayRef<const Attr *> Attrs) {
1990 // If there is no enclosing switch instance that we're aware of, then this
1991 // default statement can be elided. This situation only happens when we've
1992 // constant-folded the switch.
1993 if (!SwitchInsn) {
1994 EmitStmt(S.getSubStmt());
1995 return;
1996 }
1997
1998 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
1999 assert(DefaultBlock->empty() &&
2000 "EmitDefaultStmt: Default block already defined?");
2001
2002 if (SwitchLikelihood)
2003 SwitchLikelihood->front() = Stmt::getLikelihood(Attrs);
2004
2005 EmitBlockWithFallThrough(DefaultBlock, &S);
2006
2007 EmitStmt(S.getSubStmt());
2008}
2009
2010namespace {
2011struct EmitDeferredStatement final : EHScopeStack::Cleanup {
2012 const DeferStmt &Stmt;
2013 EmitDeferredStatement(const DeferStmt *Stmt) : Stmt(*Stmt) {}
2014
2015 void Emit(CodeGenFunction &CGF, Flags) override {
2016 // Take care that any cleanups pushed by the body of a '_Defer' statement
2017 // don't clobber the current cleanup slot value.
2018 //
2019 // Assume we have a scope that pushes a cleanup; when that scope is exited,
2020 // we need to run that cleanup; this is accomplished by emitting the cleanup
2021 // into a separate block and then branching to that block at scope exit.
2022 //
2023 // Where this gets complicated is if we exit the scope in multiple different
2024 // ways; e.g. in a 'for' loop, we may exit the scope of its body by falling
2025 // off the end (in which case we need to run the cleanup and then branch to
2026 // the increment), or by 'break'ing out of the loop (in which case we need
2027 // to run the cleanup and then branch to the loop exit block); in both cases
2028 // we first branch to the cleanup block to run the cleanup, but the block we
2029 // need to jump to *after* running the cleanup is different.
2030 //
2031 // This is accomplished using a local integer variable called the 'cleanup
2032 // slot': before branching to the cleanup block, we store a value into that
2033 // slot. Then, in the cleanup block, after running the cleanup, we load the
2034 // value of that variable and 'switch' on it to branch to the appropriate
2035 // continuation block.
2036 //
2037 // The problem that arises once '_Defer' statements are involved is that the
2038 // body of a '_Defer' is an arbitrary statement which itself can create more
2039 // cleanups. This means we may end up overwriting the cleanup slot before we
2040 // ever have a chance to 'switch' on it, which means that once we *do* get
2041 // to the 'switch', we end up in whatever block the cleanup code happened to
2042 // pick as the default 'switch' exit label!
2043 //
2044 // That is, what is normally supposed to happen is something like:
2045 //
2046 // 1. Store 'X' to cleanup slot.
2047 // 2. Branch to cleanup block.
2048 // 3. Execute cleanup.
2049 // 4. Read value from cleanup slot.
2050 // 5. Branch to the block associated with 'X'.
2051 //
2052 // But if we encounter a _Defer' statement that contains a cleanup, then
2053 // what might instead happen is:
2054 //
2055 // 1. Store 'X' to cleanup slot.
2056 // 2. Branch to cleanup block.
2057 // 3. Execute cleanup; this ends up pushing another cleanup, so:
2058 // 3a. Store 'Y' to cleanup slot.
2059 // 3b. Run steps 2–5 recursively.
2060 // 4. Read value from cleanup slot, which is now 'Y' instead of 'X'.
2061 // 5. Branch to the block associated with 'Y'... which doesn't even
2062 // exist because the value 'Y' is only meaningful for the inner
2063 // cleanup. The result is we just branch 'somewhere random'.
2064 //
2065 // The rest of the cleanup code simply isn't prepared to handle this case
2066 // because most other cleanups can't push more cleanups, and thus, emitting
2067 // other cleanups generally cannot clobber the cleanup slot.
2068 //
2069 // To prevent this from happening, save the current cleanup slot value and
2070 // restore it after emitting the '_Defer' statement.
2071 llvm::Value *SavedCleanupDest = nullptr;
2072 if (CGF.NormalCleanupDest.isValid())
2073 SavedCleanupDest =
2074 CGF.Builder.CreateLoad(CGF.NormalCleanupDest, "cleanup.dest.saved");
2075
2076 CGF.EmitStmt(Stmt.getBody());
2077
2078 if (SavedCleanupDest && CGF.HaveInsertPoint())
2079 CGF.Builder.CreateStore(SavedCleanupDest, CGF.NormalCleanupDest);
2080
2081 // Cleanups must end with an insert point.
2082 CGF.EnsureInsertPoint();
2083 }
2084};
2085} // namespace
2086
2088 EHStack.pushCleanup<EmitDeferredStatement>(NormalAndEHCleanup, &S);
2089}
2090
2091/// CollectStatementsForCase - Given the body of a 'switch' statement and a
2092/// constant value that is being switched on, see if we can dead code eliminate
2093/// the body of the switch to a simple series of statements to emit. Basically,
2094/// on a switch (5) we want to find these statements:
2095/// case 5:
2096/// printf(...); <--
2097/// ++i; <--
2098/// break;
2099///
2100/// and add them to the ResultStmts vector. If it is unsafe to do this
2101/// transformation (for example, one of the elided statements contains a label
2102/// that might be jumped to), return CSFC_Failure. If we handled it and 'S'
2103/// should include statements after it (e.g. the printf() line is a substmt of
2104/// the case) then return CSFC_FallThrough. If we handled it and found a break
2105/// statement, then return CSFC_Success.
2106///
2107/// If Case is non-null, then we are looking for the specified case, checking
2108/// that nothing we jump over contains labels. If Case is null, then we found
2109/// the case and are looking for the break.
2110///
2111/// If the recursive walk actually finds our Case, then we set FoundCase to
2112/// true.
2113///
2116 const SwitchCase *Case,
2117 bool &FoundCase,
2118 SmallVectorImpl<const Stmt*> &ResultStmts) {
2119 // If this is a null statement, just succeed.
2120 if (!S)
2121 return Case ? CSFC_Success : CSFC_FallThrough;
2122
2123 // If this is the switchcase (case 4: or default) that we're looking for, then
2124 // we're in business. Just add the substatement.
2125 if (const SwitchCase *SC = dyn_cast<SwitchCase>(S)) {
2126 if (S == Case) {
2127 FoundCase = true;
2128 return CollectStatementsForCase(SC->getSubStmt(), nullptr, FoundCase,
2129 ResultStmts);
2130 }
2131
2132 // Otherwise, this is some other case or default statement, just ignore it.
2133 return CollectStatementsForCase(SC->getSubStmt(), Case, FoundCase,
2134 ResultStmts);
2135 }
2136
2137 // If we are in the live part of the code and we found our break statement,
2138 // return a success!
2139 if (!Case && isa<BreakStmt>(S))
2140 return CSFC_Success;
2141
2142 // If this is a switch statement, then it might contain the SwitchCase, the
2143 // break, or neither.
2144 if (const CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
2145 // Handle this as two cases: we might be looking for the SwitchCase (if so
2146 // the skipped statements must be skippable) or we might already have it.
2147 CompoundStmt::const_body_iterator I = CS->body_begin(), E = CS->body_end();
2148 bool StartedInLiveCode = FoundCase;
2149 unsigned StartSize = ResultStmts.size();
2150
2151 // If we've not found the case yet, scan through looking for it.
2152 if (Case) {
2153 // Keep track of whether we see a skipped declaration. The code could be
2154 // using the declaration even if it is skipped, so we can't optimize out
2155 // the decl if the kept statements might refer to it.
2156 bool HadSkippedDecl = false;
2157
2158 // If we're looking for the case, just see if we can skip each of the
2159 // substatements.
2160 for (; Case && I != E; ++I) {
2161 HadSkippedDecl |= CodeGenFunction::mightAddDeclToScope(*I);
2162
2163 switch (CollectStatementsForCase(*I, Case, FoundCase, ResultStmts)) {
2164 case CSFC_Failure: return CSFC_Failure;
2165 case CSFC_Success:
2166 // A successful result means that either 1) that the statement doesn't
2167 // have the case and is skippable, or 2) does contain the case value
2168 // and also contains the break to exit the switch. In the later case,
2169 // we just verify the rest of the statements are elidable.
2170 if (FoundCase) {
2171 // If we found the case and skipped declarations, we can't do the
2172 // optimization.
2173 if (HadSkippedDecl)
2174 return CSFC_Failure;
2175
2176 for (++I; I != E; ++I)
2177 if (CodeGenFunction::ContainsLabel(*I, true))
2178 return CSFC_Failure;
2179 return CSFC_Success;
2180 }
2181 break;
2182 case CSFC_FallThrough:
2183 // If we have a fallthrough condition, then we must have found the
2184 // case started to include statements. Consider the rest of the
2185 // statements in the compound statement as candidates for inclusion.
2186 assert(FoundCase && "Didn't find case but returned fallthrough?");
2187 // We recursively found Case, so we're not looking for it anymore.
2188 Case = nullptr;
2189
2190 // If we found the case and skipped declarations, we can't do the
2191 // optimization.
2192 if (HadSkippedDecl)
2193 return CSFC_Failure;
2194 break;
2195 }
2196 }
2197
2198 if (!FoundCase)
2199 return CSFC_Success;
2200
2201 assert(!HadSkippedDecl && "fallthrough after skipping decl");
2202 }
2203
2204 // If we have statements in our range, then we know that the statements are
2205 // live and need to be added to the set of statements we're tracking.
2206 bool AnyDecls = false;
2207 for (; I != E; ++I) {
2209
2210 switch (CollectStatementsForCase(*I, nullptr, FoundCase, ResultStmts)) {
2211 case CSFC_Failure: return CSFC_Failure;
2212 case CSFC_FallThrough:
2213 // A fallthrough result means that the statement was simple and just
2214 // included in ResultStmt, keep adding them afterwards.
2215 break;
2216 case CSFC_Success:
2217 // A successful result means that we found the break statement and
2218 // stopped statement inclusion. We just ensure that any leftover stmts
2219 // are skippable and return success ourselves.
2220 for (++I; I != E; ++I)
2221 if (CodeGenFunction::ContainsLabel(*I, true))
2222 return CSFC_Failure;
2223 return CSFC_Success;
2224 }
2225 }
2226
2227 // If we're about to fall out of a scope without hitting a 'break;', we
2228 // can't perform the optimization if there were any decls in that scope
2229 // (we'd lose their end-of-lifetime).
2230 if (AnyDecls) {
2231 // If the entire compound statement was live, there's one more thing we
2232 // can try before giving up: emit the whole thing as a single statement.
2233 // We can do that unless the statement contains a 'break;'.
2234 // FIXME: Such a break must be at the end of a construct within this one.
2235 // We could emit this by just ignoring the BreakStmts entirely.
2236 if (StartedInLiveCode && !CodeGenFunction::containsBreak(S)) {
2237 ResultStmts.resize(StartSize);
2238 ResultStmts.push_back(S);
2239 } else {
2240 return CSFC_Failure;
2241 }
2242 }
2243
2244 return CSFC_FallThrough;
2245 }
2246
2247 // Okay, this is some other statement that we don't handle explicitly, like a
2248 // for statement or increment etc. If we are skipping over this statement,
2249 // just verify it doesn't have labels, which would make it invalid to elide.
2250 if (Case) {
2251 if (CodeGenFunction::ContainsLabel(S, true))
2252 return CSFC_Failure;
2253 return CSFC_Success;
2254 }
2255
2256 // Otherwise, we want to include this statement. Everything is cool with that
2257 // so long as it doesn't contain a break out of the switch we're in.
2259
2260 // Otherwise, everything is great. Include the statement and tell the caller
2261 // that we fall through and include the next statement as well.
2262 ResultStmts.push_back(S);
2263 return CSFC_FallThrough;
2264}
2265
2266/// FindCaseStatementsForValue - Find the case statement being jumped to and
2267/// then invoke CollectStatementsForCase to find the list of statements to emit
2268/// for a switch on constant. See the comment above CollectStatementsForCase
2269/// for more details.
2271 const llvm::APSInt &ConstantCondValue,
2272 SmallVectorImpl<const Stmt*> &ResultStmts,
2273 ASTContext &C,
2274 const SwitchCase *&ResultCase) {
2275 // First step, find the switch case that is being branched to. We can do this
2276 // efficiently by scanning the SwitchCase list.
2277 const SwitchCase *Case = S.getSwitchCaseList();
2278 const DefaultStmt *DefaultCase = nullptr;
2279
2280 for (; Case; Case = Case->getNextSwitchCase()) {
2281 // It's either a default or case. Just remember the default statement in
2282 // case we're not jumping to any numbered cases.
2283 if (const DefaultStmt *DS = dyn_cast<DefaultStmt>(Case)) {
2284 DefaultCase = DS;
2285 continue;
2286 }
2287
2288 // Check to see if this case is the one we're looking for.
2289 const CaseStmt *CS = cast<CaseStmt>(Case);
2290 // Don't handle case ranges yet.
2291 if (CS->getRHS()) return false;
2292
2293 // If we found our case, remember it as 'case'.
2294 if (CS->getLHS()->EvaluateKnownConstInt(C) == ConstantCondValue)
2295 break;
2296 }
2297
2298 // If we didn't find a matching case, we use a default if it exists, or we
2299 // elide the whole switch body!
2300 if (!Case) {
2301 // It is safe to elide the body of the switch if it doesn't contain labels
2302 // etc. If it is safe, return successfully with an empty ResultStmts list.
2303 if (!DefaultCase)
2305 Case = DefaultCase;
2306 }
2307
2308 // Ok, we know which case is being jumped to, try to collect all the
2309 // statements that follow it. This can fail for a variety of reasons. Also,
2310 // check to see that the recursive walk actually found our case statement.
2311 // Insane cases like this can fail to find it in the recursive walk since we
2312 // don't handle every stmt kind:
2313 // switch (4) {
2314 // while (1) {
2315 // case 4: ...
2316 bool FoundCase = false;
2317 ResultCase = Case;
2318 return CollectStatementsForCase(S.getBody(), Case, FoundCase,
2319 ResultStmts) != CSFC_Failure &&
2320 FoundCase;
2321}
2322
2323static std::optional<SmallVector<uint64_t, 16>>
2325 // Are there enough branches to weight them?
2326 if (Likelihoods.size() <= 1)
2327 return std::nullopt;
2328
2329 uint64_t NumUnlikely = 0;
2330 uint64_t NumNone = 0;
2331 uint64_t NumLikely = 0;
2332 for (const auto LH : Likelihoods) {
2333 switch (LH) {
2334 case Stmt::LH_Unlikely:
2335 ++NumUnlikely;
2336 break;
2337 case Stmt::LH_None:
2338 ++NumNone;
2339 break;
2340 case Stmt::LH_Likely:
2341 ++NumLikely;
2342 break;
2343 }
2344 }
2345
2346 // Is there a likelihood attribute used?
2347 if (NumUnlikely == 0 && NumLikely == 0)
2348 return std::nullopt;
2349
2350 // When multiple cases share the same code they can be combined during
2351 // optimization. In that case the weights of the branch will be the sum of
2352 // the individual weights. Make sure the combined sum of all neutral cases
2353 // doesn't exceed the value of a single likely attribute.
2354 // The additions both avoid divisions by 0 and make sure the weights of None
2355 // don't exceed the weight of Likely.
2356 const uint64_t Likely = INT32_MAX / (NumLikely + 2);
2357 const uint64_t None = Likely / (NumNone + 1);
2358 const uint64_t Unlikely = 0;
2359
2361 Result.reserve(Likelihoods.size());
2362 for (const auto LH : Likelihoods) {
2363 switch (LH) {
2364 case Stmt::LH_Unlikely:
2365 Result.push_back(Unlikely);
2366 break;
2367 case Stmt::LH_None:
2368 Result.push_back(None);
2369 break;
2370 case Stmt::LH_Likely:
2371 Result.push_back(Likely);
2372 break;
2373 }
2374 }
2375
2376 return Result;
2377}
2378
2380 // Handle nested switch statements.
2381 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
2382 SmallVector<uint64_t, 16> *SavedSwitchWeights = SwitchWeights;
2383 SmallVector<Stmt::Likelihood, 16> *SavedSwitchLikelihood = SwitchLikelihood;
2384 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
2385
2386 // See if we can constant fold the condition of the switch and therefore only
2387 // emit the live case statement (if any) of the switch.
2388 llvm::APSInt ConstantCondValue;
2389 if (ConstantFoldsToSimpleInteger(S.getCond(), ConstantCondValue)) {
2391 const SwitchCase *Case = nullptr;
2392 if (FindCaseStatementsForValue(S, ConstantCondValue, CaseStmts,
2393 getContext(), Case)) {
2394 if (Case)
2396 RunCleanupsScope ExecutedScope(*this);
2397
2398 if (S.getInit())
2399 EmitStmt(S.getInit());
2400
2401 // Emit the condition variable if needed inside the entire cleanup scope
2402 // used by this special case for constant folded switches.
2403 if (S.getConditionVariable())
2404 EmitDecl(*S.getConditionVariable(), /*EvaluateConditionDecl=*/true);
2405
2406 // At this point, we are no longer "within" a switch instance, so
2407 // we can temporarily enforce this to ensure that any embedded case
2408 // statements are not emitted.
2409 SwitchInsn = nullptr;
2410
2411 // Okay, we can dead code eliminate everything except this case. Emit the
2412 // specified series of statements and we're good.
2413 for (const Stmt *CaseStmt : CaseStmts)
2416 PGO->markStmtMaybeUsed(S.getBody());
2417
2418 // Now we want to restore the saved switch instance so that nested
2419 // switches continue to function properly
2420 SwitchInsn = SavedSwitchInsn;
2421
2422 return;
2423 }
2424 }
2425
2426 JumpDest SwitchExit = getJumpDestInCurrentScope("sw.epilog");
2427
2428 RunCleanupsScope ConditionScope(*this);
2429
2430 if (S.getInit()) {
2431 EmitStmt(S.getInit());
2432
2433 // The init statement may have cleared the insertion point (e.g. it ended in
2434 // a 'noreturn' call); the condition emitted below needs a valid one.
2436 }
2437
2438 if (S.getConditionVariable())
2440 llvm::Value *CondV = EmitScalarExpr(S.getCond());
2442
2443 // Create basic block to hold stuff that comes after switch
2444 // statement. We also need to create a default block now so that
2445 // explicit case ranges tests can have a place to jump to on
2446 // failure.
2447 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
2448 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
2449 addInstToNewSourceAtom(SwitchInsn, CondV);
2450
2451 if (HLSLControlFlowAttr != HLSLControlFlowHintAttr::SpellingNotCalculated) {
2452 llvm::MDBuilder MDHelper(CGM.getLLVMContext());
2453 llvm::ConstantInt *BranchHintConstant =
2455 HLSLControlFlowHintAttr::Spelling::Microsoft_branch
2456 ? llvm::ConstantInt::get(CGM.Int32Ty, 1)
2457 : llvm::ConstantInt::get(CGM.Int32Ty, 2);
2458 llvm::Metadata *Vals[] = {MDHelper.createString("hlsl.controlflow.hint"),
2459 MDHelper.createConstant(BranchHintConstant)};
2460 SwitchInsn->setMetadata("hlsl.controlflow.hint",
2461 llvm::MDNode::get(CGM.getLLVMContext(), Vals));
2462 }
2463
2464 if (PGO->haveRegionCounts()) {
2465 // Walk the SwitchCase list to find how many there are.
2466 uint64_t DefaultCount = 0;
2467 unsigned NumCases = 0;
2468 for (const SwitchCase *Case = S.getSwitchCaseList();
2469 Case;
2470 Case = Case->getNextSwitchCase()) {
2471 if (isa<DefaultStmt>(Case))
2472 DefaultCount = getProfileCount(Case);
2473 NumCases += 1;
2474 }
2475 SwitchWeights = new SmallVector<uint64_t, 16>();
2476 SwitchWeights->reserve(NumCases);
2477 // The default needs to be first. We store the edge count, so we already
2478 // know the right weight.
2479 SwitchWeights->push_back(DefaultCount);
2480 } else if (CGM.getCodeGenOpts().OptimizationLevel) {
2481 SwitchLikelihood = new SmallVector<Stmt::Likelihood, 16>();
2482 // Initialize the default case.
2483 SwitchLikelihood->push_back(Stmt::LH_None);
2484 }
2485
2486 CaseRangeBlock = DefaultBlock;
2487
2488 // Clear the insertion point to indicate we are in unreachable code.
2489 Builder.ClearInsertionPoint();
2490
2491 // All break statements jump to NextBlock. If BreakContinueStack is non-empty
2492 // then reuse last ContinueBlock.
2493 JumpDest OuterContinue;
2494 if (!BreakContinueStack.empty())
2495 OuterContinue = BreakContinueStack.back().ContinueBlock;
2496
2497 BreakContinueStack.push_back(BreakContinue(S, SwitchExit, OuterContinue));
2498
2499 // Emit switch body.
2500 EmitStmt(S.getBody());
2501
2502 BreakContinueStack.pop_back();
2503
2504 // Update the default block in case explicit case range tests have
2505 // been chained on top.
2506 SwitchInsn->setDefaultDest(CaseRangeBlock);
2507
2508 // If a default was never emitted:
2509 if (!DefaultBlock->getParent()) {
2510 // If we have cleanups, emit the default block so that there's a
2511 // place to jump through the cleanups from.
2512 if (ConditionScope.requiresCleanups()) {
2513 EmitBlock(DefaultBlock);
2514
2515 // Otherwise, just forward the default block to the switch end.
2516 } else {
2517 DefaultBlock->replaceAllUsesWith(SwitchExit.getBlock());
2518 delete DefaultBlock;
2519 }
2520 }
2521
2522 ConditionScope.ForceCleanup();
2523
2524 // Close the last case (or DefaultBlock).
2525 EmitBranch(SwitchExit.getBlock());
2526
2527 // Insert a False Counter if SwitchStmt doesn't have DefaultStmt.
2528 if (hasSkipCounter(S.getCond())) {
2529 auto *ImplicitDefaultBlock = createBasicBlock("sw.false");
2530 EmitBlock(ImplicitDefaultBlock);
2532 Builder.CreateBr(SwitchInsn->getDefaultDest());
2533 SwitchInsn->setDefaultDest(ImplicitDefaultBlock);
2534 }
2535
2536 // Emit continuation.
2537 EmitBlock(SwitchExit.getBlock(), true);
2539
2540 // If the switch has a condition wrapped by __builtin_unpredictable,
2541 // create metadata that specifies that the switch is unpredictable.
2542 // Don't bother if not optimizing because that metadata would not be used.
2543 auto *Call = dyn_cast<CallExpr>(S.getCond());
2544 if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
2545 auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
2546 if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
2547 llvm::MDBuilder MDHelper(getLLVMContext());
2548 SwitchInsn->setMetadata(llvm::LLVMContext::MD_unpredictable,
2549 MDHelper.createUnpredictable());
2550 }
2551 }
2552
2553 if (SwitchWeights) {
2554 assert(SwitchWeights->size() == 1 + SwitchInsn->getNumCases() &&
2555 "switch weights do not match switch cases");
2556 // If there's only one jump destination there's no sense weighting it.
2557 if (SwitchWeights->size() > 1)
2558 SwitchInsn->setMetadata(llvm::LLVMContext::MD_prof,
2559 createProfileWeights(*SwitchWeights));
2560 delete SwitchWeights;
2561 } else if (SwitchLikelihood) {
2562 assert(SwitchLikelihood->size() == 1 + SwitchInsn->getNumCases() &&
2563 "switch likelihoods do not match switch cases");
2564 std::optional<SmallVector<uint64_t, 16>> LHW =
2565 getLikelihoodWeights(*SwitchLikelihood);
2566 if (LHW) {
2567 llvm::MDBuilder MDHelper(CGM.getLLVMContext());
2568 SwitchInsn->setMetadata(llvm::LLVMContext::MD_prof,
2569 createProfileWeights(*LHW));
2570 }
2571 delete SwitchLikelihood;
2572 }
2573 SwitchInsn = SavedSwitchInsn;
2574 SwitchWeights = SavedSwitchWeights;
2575 SwitchLikelihood = SavedSwitchLikelihood;
2576 CaseRangeBlock = SavedCRBlock;
2577}
2578
2579std::pair<llvm::Value*, llvm::Type *> CodeGenFunction::EmitAsmInputLValue(
2580 const TargetInfo::ConstraintInfo &Info, LValue InputValue,
2581 QualType InputType, std::string &ConstraintStr, SourceLocation Loc) {
2582 if (Info.allowsRegister() || !Info.allowsMemory()) {
2584 return {EmitLoadOfLValue(InputValue, Loc).getScalarVal(), nullptr};
2585
2586 llvm::Type *Ty = ConvertType(InputType);
2587 uint64_t Size = CGM.getDataLayout().getTypeSizeInBits(Ty);
2588 if ((Size <= 64 && llvm::isPowerOf2_64(Size)) ||
2589 getTargetHooks().isScalarizableAsmOperand(*this, Ty)) {
2590 Ty = llvm::IntegerType::get(getLLVMContext(), Size);
2591
2592 return {Builder.CreateLoad(InputValue.getAddress().withElementType(Ty)),
2593 nullptr};
2594 }
2595 }
2596
2597 Address Addr = InputValue.getAddress();
2598 ConstraintStr += '*';
2599 return {InputValue.getPointer(*this), Addr.getElementType()};
2600}
2601std::pair<llvm::Value *, llvm::Type *>
2602CodeGenFunction::EmitAsmInput(const TargetInfo::ConstraintInfo &Info,
2603 const Expr *InputExpr,
2604 std::string &ConstraintStr) {
2605 // If this can't be a register or memory, i.e., has to be a constant
2606 // (immediate or symbolic), try to emit it as such.
2607 if (!Info.allowsRegister() && !Info.allowsMemory()) {
2608 if (Info.requiresImmediateConstant()) {
2609 Expr::EvalResult EVResult;
2610 InputExpr->EvaluateAsRValue(EVResult, getContext(), true);
2611
2612 llvm::APSInt IntResult;
2613 if (EVResult.Val.toIntegralConstant(IntResult, InputExpr->getType(),
2614 getContext()))
2615 return {llvm::ConstantInt::get(getLLVMContext(), IntResult), nullptr};
2616 }
2617
2618 Expr::EvalResult Result;
2619 if (InputExpr->EvaluateAsInt(Result, getContext()))
2620 return {llvm::ConstantInt::get(getLLVMContext(), Result.Val.getInt()),
2621 nullptr};
2622 }
2623
2624 if (Info.allowsRegister() || !Info.allowsMemory())
2626 return {EmitScalarExpr(InputExpr), nullptr};
2627 if (InputExpr->getStmtClass() == Expr::CXXThisExprClass)
2628 return {EmitScalarExpr(InputExpr), nullptr};
2629 InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
2630 LValue Dest = EmitLValue(InputExpr);
2631 return EmitAsmInputLValue(Info, Dest, InputExpr->getType(), ConstraintStr,
2632 InputExpr->getExprLoc());
2633}
2634
2635/// getAsmSrcLocInfo - Return the !srcloc metadata node to attach to an inline
2636/// asm call instruction. The !srcloc MDNode contains a list of constant
2637/// integers which are the source locations of the start of each line in the
2638/// asm.
2639static llvm::MDNode *getAsmSrcLocInfo(const StringLiteral *Str,
2640 CodeGenFunction &CGF) {
2642 // Add the location of the first line to the MDNode.
2643 Locs.push_back(llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
2644 CGF.Int64Ty, Str->getBeginLoc().getRawEncoding())));
2645 StringRef StrVal = Str->getString();
2646 if (!StrVal.empty()) {
2647 const SourceManager &SM = CGF.CGM.getContext().getSourceManager();
2648 const LangOptions &LangOpts = CGF.CGM.getLangOpts();
2649 unsigned StartToken = 0;
2650 unsigned ByteOffset = 0;
2651
2652 // Add the location of the start of each subsequent line of the asm to the
2653 // MDNode.
2654 for (unsigned i = 0, e = StrVal.size() - 1; i != e; ++i) {
2655 if (StrVal[i] != '\n') continue;
2656 SourceLocation LineLoc = Str->getLocationOfByte(
2657 i + 1, SM, LangOpts, CGF.getTarget(), &StartToken, &ByteOffset);
2658 Locs.push_back(llvm::ConstantAsMetadata::get(
2659 llvm::ConstantInt::get(CGF.Int64Ty, LineLoc.getRawEncoding())));
2660 }
2661 }
2662
2663 return llvm::MDNode::get(CGF.getLLVMContext(), Locs);
2664}
2665
2666namespace clang {
2667
2668/// This structure holds the information gathered about the constraints for an
2669/// inline assembly statement. It helps in separating the constraint processing
2670/// from the code generation.
2672 CodeGenFunction &CGF;
2673 CodeGenModule &CGM; // Per-module state.
2674 const AsmStmt &S;
2675 CGBuilderTy &Builder;
2676
2677 // The final asm string.
2678 std::string AsmString;
2679
2680 // The output and input constraints.
2681 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
2682 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
2683
2684 // Constraint strings.
2685 std::string Constraints;
2686 std::string InOutConstraints;
2687
2688 // Keep track of out constraints for tied input operand.
2689 std::vector<std::string> OutputConstraints;
2690
2691 // Keep track of argument types.
2692 std::vector<llvm::Value *> Args;
2693 std::vector<llvm::Type *> ArgTypes;
2694 std::vector<llvm::Type *> ArgElemTypes;
2695
2696 // Keep track of result register constraints.
2697 std::vector<LValue> ResultRegDests;
2698 std::vector<QualType> ResultRegQualTys;
2699 std::vector<llvm::Type *> ResultRegTypes;
2700 std::vector<llvm::Type *> ResultTruncRegTypes;
2701
2702 llvm::BitVector ResultTypeRequiresCast;
2703
2704 // Keep track of in/out constraints.
2705 std::vector<llvm::Value *> InOutArgs;
2706 std::vector<llvm::Type *> InOutArgTypes;
2707 std::vector<llvm::Type *> InOutArgElemTypes;
2708
2709 // Destination blocks for 'asm gotos'.
2710 llvm::BasicBlock *DefaultDest = nullptr;
2712
2713 std::vector<std::optional<std::pair<unsigned, unsigned>>> ResultBounds;
2714
2715 // An inline asm can be marked readonly if it meets the following
2716 // conditions:
2717 //
2718 // - it doesn't have any sideeffects
2719 // - it doesn't clobber memory
2720 // - it doesn't return a value by-reference
2721 //
2722 // It can be marked readnone if it doesn't have any input memory
2723 // constraints in addition to meeting the conditions listed above.
2724 bool ReadOnly = true;
2725 bool ReadNone = true;
2726
2727 bool GetOutputAndInputConstraints();
2728 void HandleOutputConstraints();
2729 void HandleMSStyleAsmBlob();
2730 void HandleInputConstraints();
2731 bool HandleLabels();
2732 bool HandleClobbers();
2733 void UpdateAsmCallInst(llvm::CallBase &Result, bool HasSideEffect,
2734 bool HasUnwindClobber, bool NoMerge, bool NoConvergent,
2735 std::vector<llvm::Value *> &RegResults);
2736 void EmitAsmStores(const llvm::ArrayRef<llvm::Value *> RegResults);
2737
2738 void EmitHipStdParUnsupportedAsm() {
2739 constexpr auto Name = "__ASM__hipstdpar_unsupported";
2740
2741 std::string Asm;
2742 if (auto GCCAsm = dyn_cast<GCCAsmStmt>(&S))
2743 Asm = GCCAsm->getAsmString();
2744
2745 auto &Ctx = getLLVMContext();
2746 auto StrTy = llvm::ConstantDataArray::getString(Ctx, Asm);
2747 auto FnTy = llvm::FunctionType::get(llvm::Type::getVoidTy(Ctx),
2748 {StrTy->getType()}, false);
2749 auto UBF = CGM.getModule().getOrInsertFunction(Name, FnTy);
2750
2751 Builder.CreateCall(UBF, {StrTy});
2752 }
2753
2754 ASTContext &getContext() { return CGF.getContext(); }
2755 llvm::LLVMContext &getLLVMContext() { return CGF.getLLVMContext(); }
2756 const TargetInfo &getTarget() const { return CGF.getTarget(); }
2757 const LangOptions &getLangOpts() const { return CGF.getLangOpts(); }
2758 const TargetCodeGenInfo &getTargetHooks() const {
2759 return CGM.getTargetCodeGenInfo();
2760 }
2761
2762public:
2764 : CGF(CGF), CGM(CGF.CGM), S(S), Builder(CGF.Builder),
2765 AsmString(S.generateAsmString(CGF.getContext())) {}
2766
2767 void EmitAsmStmt();
2768};
2769
2770} // namespace clang
2771
2773 // Pop all cleanup blocks at the end of the asm statement.
2774 CodeGenFunction::RunCleanupsScope Cleanups(*this);
2775
2776 // Get all the output and input constraints together.
2777 AsmConstraintsInfo AsmInfo(*this, S);
2778 AsmInfo.EmitAsmStmt();
2779}
2780
2782 if (!GetOutputAndInputConstraints())
2783 return EmitHipStdParUnsupportedAsm();
2784
2785 // Handle output constraints.
2786 HandleOutputConstraints();
2787
2788 // If this is a Microsoft-style asm blob, store the return registers (EAX:EDX)
2789 // to the return value slot. Only do this when returning in registers.
2790 HandleMSStyleAsmBlob();
2791
2792 // Handle input constraints.
2793 HandleInputConstraints();
2794
2795 // Handle 'asm goto' labels.
2796 bool IsGCCAsmGoto = HandleLabels();
2797
2798 // Handle any clobbers.
2799 bool HasUnwindClobber = HandleClobbers();
2800 assert(!(HasUnwindClobber && IsGCCAsmGoto) &&
2801 "unwind clobber can't be used with asm goto");
2802
2803 // Add machine specific clobbers
2804 std::string_view MachineClobbers = getTarget().getClobbers();
2805 if (!MachineClobbers.empty()) {
2806 if (!Constraints.empty())
2807 Constraints += ',';
2808 Constraints += MachineClobbers;
2809 }
2810
2811 llvm::Type *ResultType;
2812 if (ResultRegTypes.empty())
2813 ResultType = CGF.VoidTy;
2814 else if (ResultRegTypes.size() == 1)
2815 ResultType = ResultRegTypes[0];
2816 else
2817 ResultType = llvm::StructType::get(getLLVMContext(), ResultRegTypes);
2818
2819 llvm::FunctionType *FTy =
2820 llvm::FunctionType::get(ResultType, ArgTypes, false);
2821
2822 bool HasSideEffect = S.isVolatile() || S.getNumOutputs() == 0;
2823
2824 llvm::InlineAsm::AsmDialect GnuAsmDialect =
2825 CGM.getCodeGenOpts().getInlineAsmDialect() == CodeGenOptions::IAD_ATT
2826 ? llvm::InlineAsm::AD_ATT
2827 : llvm::InlineAsm::AD_Intel;
2828 llvm::InlineAsm::AsmDialect AsmDialect =
2829 isa<MSAsmStmt>(&S) ? llvm::InlineAsm::AD_Intel : GnuAsmDialect;
2830
2831 llvm::InlineAsm *IA = llvm::InlineAsm::get(
2832 FTy, AsmString, Constraints, HasSideEffect,
2833 /* IsAlignStack */ false, AsmDialect, HasUnwindClobber);
2834 std::vector<llvm::Value *> RegResults;
2835 llvm::CallBrInst *CBR;
2836 llvm::DenseMap<llvm::BasicBlock *, SmallVector<llvm::Value *, 4>>
2837 CBRRegResults;
2838
2839 if (IsGCCAsmGoto) {
2840 CBR = Builder.CreateCallBr(IA, DefaultDest, IndirectDests, Args);
2841 CGF.EmitBlock(DefaultDest);
2842 UpdateAsmCallInst(*CBR, HasSideEffect,
2843 /*HasUnwindClobber=*/false, CGF.InNoMergeAttributedStmt,
2844 CGF.InNoConvergentAttributedStmt, RegResults);
2845
2846 // Because we are emitting code top to bottom, we don't have enough
2847 // information at this point to know precisely whether we have a critical
2848 // edge. If we have outputs, split all indirect destinations.
2849 if (!RegResults.empty()) {
2850 unsigned I = 0;
2851 for (llvm::BasicBlock *Dest : CBR->getIndirectDests()) {
2852 llvm::Twine SynthName = Dest->getName() + ".split";
2853 llvm::BasicBlock *SynthBB = CGF.createBasicBlock(SynthName);
2854 llvm::IRBuilderBase::InsertPointGuard IPG(Builder);
2855 Builder.SetInsertPoint(SynthBB);
2856
2857 if (ResultRegTypes.size() == 1) {
2858 CBRRegResults[SynthBB].push_back(CBR);
2859 } else {
2860 for (unsigned J = 0, E = ResultRegTypes.size(); J != E; ++J) {
2861 llvm::Value *Tmp = Builder.CreateExtractValue(CBR, J, "asmresult");
2862 CBRRegResults[SynthBB].push_back(Tmp);
2863 }
2864 }
2865
2866 CGF.EmitBranch(Dest);
2867 CGF.EmitBlock(SynthBB);
2868 CBR->setIndirectDest(I++, SynthBB);
2869 }
2870 }
2871 } else if (HasUnwindClobber) {
2872 llvm::CallBase *Result = CGF.EmitCallOrInvoke(IA, Args, "");
2873 UpdateAsmCallInst(*Result, HasSideEffect,
2874 /*HasUnwindClobber=*/true, CGF.InNoMergeAttributedStmt,
2875 CGF.InNoConvergentAttributedStmt, RegResults);
2876 } else {
2877 llvm::CallInst *Result =
2878 Builder.CreateCall(IA, Args, CGF.getBundlesForFunclet(IA));
2879 UpdateAsmCallInst(*Result, HasSideEffect,
2880 /*HasUnwindClobber=*/false, CGF.InNoMergeAttributedStmt,
2881 CGF.InNoConvergentAttributedStmt, RegResults);
2882 }
2883
2884 EmitAsmStores(RegResults);
2885
2886 // If this is an asm goto with outputs, repeat EmitAsmStores, but with a
2887 // different insertion point; one for each indirect destination and with
2888 // CBRRegResults rather than RegResults.
2889 if (IsGCCAsmGoto && !CBRRegResults.empty()) {
2890 for (llvm::BasicBlock *Succ : CBR->getIndirectDests()) {
2891 llvm::IRBuilderBase::InsertPointGuard IPG(Builder);
2892 Builder.SetInsertPoint(Succ, --(Succ->end()));
2893 EmitAsmStores(CBRRegResults[Succ]);
2894 }
2895 }
2896}
2897
2898/// Gather and validate the output and input constraints for the given inline
2899/// assembly statement. This ensures that the constraints are valid for the
2900/// target and prepares them for further processing.
2901bool AsmConstraintsInfo::GetOutputAndInputConstraints() {
2902 bool IsValidTargetAsm = true;
2903 bool IsHipStdPar = getLangOpts().HIPStdPar && getLangOpts().CUDAIsDevice;
2904 for (unsigned I = 0, E = S.getNumOutputs(); I != E && IsValidTargetAsm; I++) {
2905 StringRef Name;
2906 if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
2907 Name = GAS->getOutputName(I);
2908
2909 TargetInfo::ConstraintInfo Info(S.getOutputConstraint(I), Name);
2910
2911 bool IsValid = getTarget().validateOutputConstraint(Info);
2912 if (IsHipStdPar && !IsValid)
2913 IsValidTargetAsm = false;
2914 else
2915 assert(IsValid && "Failed to parse output constraint");
2916
2917 OutputConstraintInfos.push_back(Info);
2918 }
2919
2920 for (unsigned I = 0, E = S.getNumInputs(); I != E && IsValidTargetAsm; I++) {
2921 StringRef Name;
2922 if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
2923 Name = GAS->getInputName(I);
2924
2925 TargetInfo::ConstraintInfo Info(S.getInputConstraint(I), Name);
2926
2927 bool IsValid =
2928 getTarget().validateInputConstraint(OutputConstraintInfos, Info);
2929 if (IsHipStdPar && !IsValid)
2930 IsValidTargetAsm = false;
2931 else
2932 assert(IsValid && "Failed to parse input constraint");
2933
2934 InputConstraintInfos.push_back(Info);
2935 }
2936
2937 return IsValidTargetAsm;
2938}
2939
2940/// Process the output constraints of an inline assembly statement. This method
2941/// handles the complexity of determining whether an output should be a
2942/// register or memory operand, manages tied operands, and prepares the
2943/// necessary arguments for the LLVM inline asm call.
2944void AsmConstraintsInfo::HandleOutputConstraints() {
2945 // Keep track of defined physregs.
2946 llvm::SmallSet<std::string, 8> PhysRegOutputs;
2947
2948 for (unsigned I = 0, E = S.getNumOutputs(); I != E; I++) {
2949 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[I];
2950
2951 // Simplify the output constraint.
2952 std::string OutputConstraint(S.getOutputConstraint(I));
2953 OutputConstraint = getTarget().simplifyConstraint(
2954 StringRef(OutputConstraint).substr(1), &OutputConstraintInfos);
2955
2956 const Expr *OutExpr = S.getOutputExpr(I);
2957 OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
2958
2959 std::string GCCReg;
2960 OutputConstraint = S.addVariableConstraints(
2961 OutputConstraint, *OutExpr, getTarget(), Info.earlyClobber(),
2962 [&](const Stmt *UnspStmt, StringRef Msg) {
2963 CGM.ErrorUnsupported(UnspStmt, Msg);
2964 },
2965 &GCCReg);
2966
2967 // Give an error on multiple outputs to same physreg.
2968 if (!GCCReg.empty() && !PhysRegOutputs.insert(GCCReg).second)
2969 CGM.Error(S.getAsmLoc(), "multiple outputs to hard register: " + GCCReg);
2970
2971 OutputConstraints.push_back(OutputConstraint);
2972 LValue Dest = CGF.EmitLValue(OutExpr);
2973 if (!Constraints.empty())
2974 Constraints += ',';
2975
2976 // If this is a register output, then make the inline asm return it
2977 // by-value. If this is a memory result, return the value by-reference.
2978 QualType QTy = OutExpr->getType();
2979 const bool IsScalarOrAggregate =
2982
2983 if (!Info.allowsMemory() && IsScalarOrAggregate) {
2984 Constraints += "=" + OutputConstraint;
2985 ResultRegQualTys.push_back(QTy);
2986 ResultRegDests.push_back(Dest);
2987
2988 ResultBounds.emplace_back(Info.getOutputOperandBounds());
2989
2990 llvm::Type *Ty = CGF.ConvertTypeForMem(QTy);
2991 const bool RequiresCast =
2992 Info.allowsRegister() &&
2993 (getTargetHooks().isScalarizableAsmOperand(CGF, Ty) ||
2994 Ty->isAggregateType());
2995
2996 ResultTruncRegTypes.push_back(Ty);
2997 ResultTypeRequiresCast.push_back(RequiresCast);
2998
2999 if (RequiresCast) {
3000 if (unsigned Size = getContext().getTypeSize(QTy))
3001 Ty = llvm::IntegerType::get(getLLVMContext(), Size);
3002 else
3003 CGM.Error(OutExpr->getExprLoc(), "output size should not be zero");
3004 }
3005
3006 ResultRegTypes.push_back(Ty);
3007
3008 // If this output is tied to an input, and if the input is larger, then
3009 // we need to set the actual result type of the inline asm node to be the
3010 // same as the input type.
3011 if (Info.hasMatchingInput()) {
3012 unsigned InputNo;
3013 for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) {
3014 TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo];
3015 if (Input.hasTiedOperand() && Input.getTiedOperand() == I)
3016 break;
3017 }
3018 assert(InputNo != S.getNumInputs() && "Didn't find matching input!");
3019
3020 QualType InputTy = S.getInputExpr(InputNo)->getType();
3021 QualType OutputType = OutExpr->getType();
3022
3023 uint64_t InputSize = getContext().getTypeSize(InputTy);
3024 if (getContext().getTypeSize(OutputType) < InputSize)
3025 // Form the asm to return the value as a larger integer or fp type.
3026 ResultRegTypes.back() = CGF.ConvertType(InputTy);
3027 }
3028
3029 if (llvm::Type *AdjTy = getTargetHooks().adjustInlineAsmType(
3030 CGF, OutputConstraint, ResultRegTypes.back()))
3031 ResultRegTypes.back() = AdjTy;
3032 else
3033 CGM.getDiags().Report(S.getAsmLoc(),
3034 diag::err_asm_invalid_type_in_input)
3035 << OutExpr->getType() << OutputConstraint;
3036
3037 // Update largest vector width for any vector types.
3038 if (auto *VT = dyn_cast<llvm::VectorType>(ResultRegTypes.back()))
3039 CGF.LargestVectorWidth =
3040 std::max((uint64_t)CGF.LargestVectorWidth,
3041 VT->getPrimitiveSizeInBits().getKnownMinValue());
3042 } else {
3043 Address DestAddr = Dest.getAddress();
3044
3045 // Matrix types in memory are represented by arrays, but accessed through
3046 // vector pointers, with the alignment specified on the access operation.
3047 // For inline assembly, update pointer arguments to use vector pointers.
3048 // Otherwise there will be a mis-match if the matrix is also an
3049 // input-argument which is represented as vector.
3050 if (isa<MatrixType>(OutExpr->getType().getCanonicalType()))
3051 DestAddr =
3052 DestAddr.withElementType(CGF.ConvertType(OutExpr->getType()));
3053
3054 ArgTypes.push_back(DestAddr.getType());
3055 ArgElemTypes.push_back(DestAddr.getElementType());
3056 Args.push_back(DestAddr.emitRawPointer(CGF));
3057
3058 Constraints += "=*" + OutputConstraint;
3059 ReadOnly = false;
3060 ReadNone = false;
3061 }
3062
3063 if (!Info.isReadWrite())
3064 continue;
3065
3066 InOutConstraints += ',';
3067
3068 const Expr *InputExpr = S.getOutputExpr(I);
3069 llvm::Value *Arg;
3070 llvm::Type *ArgElemType;
3071 std::tie(Arg, ArgElemType) =
3072 CGF.EmitAsmInputLValue(Info, Dest, InputExpr->getType(),
3073 InOutConstraints, InputExpr->getExprLoc());
3074
3075 if (llvm::Type *AdjTy = getTargetHooks().adjustInlineAsmType(
3076 CGF, OutputConstraint, Arg->getType()))
3077 Arg = Builder.CreateBitCast(Arg, AdjTy);
3078
3079 // Update largest vector width for any vector types.
3080 if (auto *VT = dyn_cast<llvm::VectorType>(Arg->getType()))
3081 CGF.LargestVectorWidth =
3082 std::max((uint64_t)CGF.LargestVectorWidth,
3083 VT->getPrimitiveSizeInBits().getKnownMinValue());
3084
3085 // Only tie earlyclobber physregs.
3086 if (Info.allowsRegister() && (GCCReg.empty() || Info.earlyClobber()))
3087 InOutConstraints += llvm::utostr(I);
3088 else
3089 InOutConstraints += OutputConstraint;
3090
3091 InOutArgTypes.push_back(Arg->getType());
3092 InOutArgElemTypes.push_back(ArgElemType);
3093 InOutArgs.push_back(Arg);
3094 }
3095}
3096
3097/// Special handling for Microsoft-style inline assembly blocks. This ensures
3098/// that return registers (like EAX:EDX) are correctly mapped to the function's
3099/// return value slot when necessary.
3100void AsmConstraintsInfo::HandleMSStyleAsmBlob() {
3101 if (!isa<MSAsmStmt>(&S))
3102 return;
3103
3104 const ABIArgInfo &RetAI = CGF.CurFnInfo->getReturnInfo();
3105 if (!RetAI.isDirect() && !RetAI.isExtend())
3106 return;
3107
3108 // Make a fake lvalue for the return value slot.
3109 LValue ReturnSlot =
3111 CGM.getTargetCodeGenInfo().addReturnRegisterOutputs(
3112 CGF, ReturnSlot, Constraints, ResultRegTypes, ResultTruncRegTypes,
3113 ResultRegDests, AsmString, S.getNumOutputs());
3114 CGF.SawAsmBlock = true;
3115}
3116
3117/// Process the input constraints of an inline assembly statement. It handles
3118/// type conversions, extensions for tied operands, and collects the necessary
3119/// LLVM values to be passed to the inline assembly call.
3120void AsmConstraintsInfo::HandleInputConstraints() {
3121 ASTContext &Ctx = getContext();
3122
3123 for (unsigned I = 0, E = S.getNumInputs(); I != E; I++) {
3124 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[I];
3125 const Expr *InputExpr = S.getInputExpr(I);
3126
3127 if (Info.allowsMemory())
3128 ReadNone = false;
3129
3130 if (!Constraints.empty())
3131 Constraints += ',';
3132
3133 // Simplify the input constraint.
3134 std::string InputConstraint(S.getInputConstraint(I));
3135 InputConstraint =
3136 getTarget().simplifyConstraint(InputConstraint, &OutputConstraintInfos);
3137
3138 InputConstraint = S.addVariableConstraints(
3139 InputConstraint, *InputExpr->IgnoreParenNoopCasts(Ctx), getTarget(),
3140 false /* No EarlyClobber */,
3141 [&](const Stmt *UnspStmt, std::string_view Msg) {
3142 CGM.ErrorUnsupported(UnspStmt, Msg);
3143 });
3144
3145 std::string ReplaceConstraint(InputConstraint);
3146 llvm::Value *Arg;
3147 llvm::Type *ArgElemType;
3148 std::tie(Arg, ArgElemType) = CGF.EmitAsmInput(Info, InputExpr, Constraints);
3149
3150 // If this input argument is tied to a larger output result, extend the
3151 // input to be the same size as the output. The LLVM backend wants to see
3152 // the input and output of a matching constraint be the same size. Note
3153 // that GCC does not define what the top bits are here. We use zext because
3154 // that is usually cheaper, but LLVM IR should really get an anyext someday.
3155 if (Info.hasTiedOperand()) {
3156 unsigned Output = Info.getTiedOperand();
3157 QualType OutputType = S.getOutputExpr(Output)->getType();
3158 QualType InputTy = InputExpr->getType();
3159
3160 if (Ctx.getTypeSize(OutputType) > Ctx.getTypeSize(InputTy)) {
3161 // Use ptrtoint as appropriate so that we can do our extension.
3162 if (isa<llvm::PointerType>(Arg->getType()))
3163 Arg = Builder.CreatePtrToInt(Arg, CGF.IntPtrTy);
3164
3165 llvm::Type *OutputTy = CGF.ConvertType(OutputType);
3166 if (isa<llvm::IntegerType>(OutputTy))
3167 Arg = Builder.CreateZExt(Arg, OutputTy);
3168 else if (isa<llvm::PointerType>(OutputTy))
3169 Arg = Builder.CreateZExt(Arg, CGF.IntPtrTy);
3170 else if (OutputTy->isFloatingPointTy())
3171 Arg = Builder.CreateFPExt(Arg, OutputTy);
3172 }
3173
3174 // Deal with the tied operands' constraint code in adjustInlineAsmType.
3175 ReplaceConstraint = OutputConstraints[Output];
3176 }
3177
3178 if (llvm::Type *AdjTy = getTargetHooks().adjustInlineAsmType(
3179 CGF, ReplaceConstraint, Arg->getType()))
3180 Arg = Builder.CreateBitCast(Arg, AdjTy);
3181 else
3182 CGM.getDiags().Report(S.getAsmLoc(), diag::err_asm_invalid_type_in_input)
3183 << InputExpr->getType() << InputConstraint;
3184
3185 // Update largest vector width for any vector types.
3186 if (auto *VT = dyn_cast<llvm::VectorType>(Arg->getType()))
3187 CGF.LargestVectorWidth =
3188 std::max((uint64_t)CGF.LargestVectorWidth,
3189 VT->getPrimitiveSizeInBits().getKnownMinValue());
3190
3191 ArgTypes.push_back(Arg->getType());
3192 ArgElemTypes.push_back(ArgElemType);
3193 Args.push_back(Arg);
3194
3195 Constraints += InputConstraint;
3196 }
3197
3198 // Append the "input" part of in/out constraints.
3199 for (unsigned I = 0, E = InOutArgs.size(); I != E; I++) {
3200 ArgTypes.push_back(InOutArgTypes[I]);
3201 ArgElemTypes.push_back(InOutArgElemTypes[I]);
3202 Args.push_back(InOutArgs[I]);
3203 }
3204
3205 Constraints += InOutConstraints;
3206}
3207
3208/// Handle labels in an 'asm goto' statement. This method resolves the symbolic
3209/// labels to LLVM basic blocks and updates the constraint string to reflect
3210/// the indirect jump targets.
3211bool AsmConstraintsInfo::HandleLabels() {
3212 if (const auto *GS = dyn_cast<GCCAsmStmt>(&S); GS && GS->isAsmGoto()) {
3213 for (const auto *E : GS->labels()) {
3214 CodeGenFunction::JumpDest Dest = CGF.getJumpDestForLabel(E->getLabel());
3215 IndirectDests.push_back(Dest.getBlock());
3216
3217 if (!Constraints.empty())
3218 Constraints += ',';
3219
3220 Constraints += "!i";
3221 }
3222
3223 DefaultDest = CGF.createBasicBlock("asm.fallthrough");
3224 return true;
3225 }
3226
3227 return false;
3228}
3229
3230/// Process clobber constraints for an inline assembly statement. This
3231/// identifies which registers or system state (like "memory" or "cc") are
3232/// modified by the assembly block, which is crucial for correct optimization
3233/// and side-effect modeling.
3234bool AsmConstraintsInfo::HandleClobbers() {
3235 bool HasUnwindClobber = false;
3236 for (unsigned I = 0, E = S.getNumClobbers(); I != E; I++) {
3237 std::string Clobber = S.getClobber(I);
3238
3239 if (Clobber == "unwind") {
3240 HasUnwindClobber = true;
3241 continue;
3242 }
3243
3244 if (Clobber == "memory") {
3245 ReadOnly = false;
3246 ReadNone = false;
3247 } else if (Clobber != "cc") {
3248 Clobber = getTarget().getNormalizedGCCRegisterName(Clobber);
3249 if (CGM.getCodeGenOpts().StackClashProtector &&
3250 getTarget().isSPRegName(Clobber)) {
3251 CGM.getDiags().Report(S.getAsmLoc(),
3252 diag::warn_stack_clash_protection_inline_asm);
3253 }
3254 }
3255
3256 if (isa<MSAsmStmt>(&S)) {
3257 if (Clobber == "eax" || Clobber == "edx") {
3258 if (Constraints.find("=&A") != std::string::npos)
3259 continue;
3260
3261 std::string::size_type position1 =
3262 Constraints.find("={" + Clobber + "}");
3263 if (position1 != std::string::npos) {
3264 Constraints.insert(position1 + 1, "&");
3265 continue;
3266 }
3267
3268 std::string::size_type position2 = Constraints.find("=A");
3269 if (position2 != std::string::npos) {
3270 Constraints.insert(position2 + 1, "&");
3271 continue;
3272 }
3273 }
3274 }
3275
3276 if (!Constraints.empty())
3277 Constraints += ',';
3278
3279 Constraints += "~{" + Clobber + '}';
3280 }
3281
3282 return HasUnwindClobber;
3283}
3284
3285void AsmConstraintsInfo::UpdateAsmCallInst(
3286 llvm::CallBase &Result, bool HasSideEffect, bool HasUnwindClobber,
3287 bool NoMerge, bool NoConvergent, std::vector<llvm::Value *> &RegResults) {
3288 if (!HasUnwindClobber)
3289 Result.addFnAttr(llvm::Attribute::NoUnwind);
3290
3291 if (NoMerge)
3292 Result.addFnAttr(llvm::Attribute::NoMerge);
3293
3294 // Attach readnone and readonly attributes.
3295 if (!HasSideEffect) {
3296 if (ReadNone)
3297 Result.setDoesNotAccessMemory();
3298 else if (ReadOnly)
3299 Result.setOnlyReadsMemory();
3300 }
3301
3302 // Add elementtype attribute for indirect constraints.
3303 for (auto Pair : llvm::enumerate(ArgElemTypes)) {
3304 if (Pair.value()) {
3305 auto Attr = llvm::Attribute::get(
3306 getLLVMContext(), llvm::Attribute::ElementType, Pair.value());
3307 Result.addParamAttr(Pair.index(), Attr);
3308 }
3309 }
3310
3311 // Slap the source location of the inline asm into a !srcloc metadata on the
3312 // call.
3313 const StringLiteral *SL;
3314 if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(&S);
3315 gccAsmStmt &&
3316 (SL = dyn_cast<StringLiteral>(gccAsmStmt->getAsmStringExpr()))) {
3317 Result.setMetadata("srcloc", getAsmSrcLocInfo(SL, CGF));
3318 } else {
3319 // At least put the line number on MS inline asm blobs and GCC asm constexpr
3320 // strings.
3321 llvm::Constant *Loc =
3322 llvm::ConstantInt::get(CGF.Int64Ty, S.getAsmLoc().getRawEncoding());
3323 Result.setMetadata("srcloc",
3324 llvm::MDNode::get(getLLVMContext(),
3325 llvm::ConstantAsMetadata::get(Loc)));
3326 }
3327
3328 // Make inline-asm calls Key for the debug info feature Key Instructions.
3329 CGF.addInstToNewSourceAtom(&Result, nullptr);
3330
3331 if (!NoConvergent && getLangOpts().assumeFunctionsAreConvergent())
3332 // Conservatively, mark all inline asm blocks in CUDA or OpenCL as
3333 // convergent (meaning, they may call an intrinsically convergent op, such
3334 // as bar.sync, and so can't have certain optimizations applied around
3335 // them) unless it's explicitly marked 'noconvergent'.
3336 Result.addFnAttr(llvm::Attribute::Convergent);
3337
3338 // Extract all of the register value results from the asm.
3339 if (ResultRegTypes.size() == 1) {
3340 RegResults.push_back(&Result);
3341 } else {
3342 for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) {
3343 llvm::Value *Tmp = Builder.CreateExtractValue(&Result, i, "asmresult");
3344 RegResults.push_back(Tmp);
3345 }
3346 }
3347}
3348
3349void AsmConstraintsInfo::EmitAsmStores(
3350 const llvm::ArrayRef<llvm::Value *> RegResults) {
3351 llvm::LLVMContext &CTX = getLLVMContext();
3352
3353 assert(RegResults.size() == ResultRegTypes.size());
3354 assert(RegResults.size() == ResultTruncRegTypes.size());
3355 assert(RegResults.size() == ResultRegDests.size());
3356
3357 // ResultRegDests can also be populated by addReturnRegisterOutputs() above,
3358 // in which case its size may grow.
3359 assert(ResultTypeRequiresCast.size() <= ResultRegDests.size());
3360 assert(ResultBounds.size() <= ResultRegDests.size());
3361
3362 for (unsigned i = 0, e = RegResults.size(); i != e; ++i) {
3363 llvm::Value *Tmp = RegResults[i];
3364 llvm::Type *TruncTy = ResultTruncRegTypes[i];
3365
3366 if (i < ResultBounds.size() && ResultBounds[i].has_value()) {
3367 const auto [LowerBound, UpperBound] = ResultBounds[i].value();
3368
3369 // FIXME: Support for nonzero lower bounds not yet implemented.
3370 assert(LowerBound == 0 && "Output operand lower bound is not zero.");
3371
3372 llvm::Constant *UpperBoundConst =
3373 llvm::ConstantInt::get(Tmp->getType(), UpperBound);
3374 llvm::Value *IsBooleanValue =
3375 Builder.CreateCmp(llvm::CmpInst::ICMP_ULT, Tmp, UpperBoundConst);
3376 llvm::Function *FnAssume = CGM.getIntrinsic(llvm::Intrinsic::assume);
3377
3378 Builder.CreateCall(FnAssume, IsBooleanValue);
3379 }
3380
3381 // If the result type of the LLVM IR asm doesn't match the result type of
3382 // the expression, do the conversion.
3383 if (ResultRegTypes[i] != TruncTy) {
3384 // Truncate the integer result to the right size, note that TruncTy can be
3385 // a pointer.
3386 if (TruncTy->isFloatingPointTy())
3387 Tmp = Builder.CreateFPTrunc(Tmp, TruncTy);
3388 else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) {
3389 uint64_t ResSize = CGM.getDataLayout().getTypeSizeInBits(TruncTy);
3390 Tmp = Builder.CreateTrunc(
3391 Tmp, llvm::IntegerType::get(CTX, (unsigned)ResSize));
3392 Tmp = Builder.CreateIntToPtr(Tmp, TruncTy);
3393 } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) {
3394 uint64_t TmpSize =
3395 CGM.getDataLayout().getTypeSizeInBits(Tmp->getType());
3396 Tmp = Builder.CreatePtrToInt(
3397 Tmp, llvm::IntegerType::get(CTX, (unsigned)TmpSize));
3398 Tmp = Builder.CreateTrunc(Tmp, TruncTy);
3399 } else if (Tmp->getType()->isIntegerTy() && TruncTy->isIntegerTy()) {
3400 Tmp = Builder.CreateZExtOrTrunc(Tmp, TruncTy);
3401 } else if (Tmp->getType()->isVectorTy() || TruncTy->isVectorTy()) {
3402 Tmp = Builder.CreateBitCast(Tmp, TruncTy);
3403 }
3404 }
3405
3406 ApplyAtomGroup Grp(CGF.getDebugInfo());
3407 LValue Dest = ResultRegDests[i];
3408
3409 // ResultTypeRequiresCast elements correspond to the first
3410 // ResultTypeRequiresCast.size() elements of RegResults.
3411 if (i < ResultTypeRequiresCast.size() && ResultTypeRequiresCast[i]) {
3412 unsigned Size = getContext().getTypeSize(ResultRegQualTys[i]);
3413 Address A = Dest.getAddress().withElementType(ResultRegTypes[i]);
3414
3415 if (getTargetHooks().isScalarizableAsmOperand(CGF, TruncTy)) {
3416 llvm::StoreInst *S = Builder.CreateStore(Tmp, A);
3417 CGF.addInstToCurrentSourceAtom(S, S->getValueOperand());
3418 continue;
3419 }
3420
3421 QualType Ty = getContext().getIntTypeForBitwidth(Size, /*Signed=*/false);
3422 if (Ty.isNull()) {
3423 const Expr *OutExpr = S.getOutputExpr(i);
3424 CGM.getDiags().Report(OutExpr->getExprLoc(),
3425 diag::err_store_value_to_reg);
3426 return;
3427 }
3428
3429 Dest = CGF.MakeAddrLValue(A, Ty);
3430 }
3431
3432 CGF.EmitStoreThroughLValue(RValue::get(Tmp), Dest);
3433 }
3434}
3435
3437 const RecordDecl *RD = S.getCapturedRecordDecl();
3438 CanQualType RecordTy = getContext().getCanonicalTagType(RD);
3439
3440 // Initialize the captured struct.
3441 LValue SlotLV =
3442 MakeAddrLValue(CreateMemTemp(RecordTy, "agg.captured"), RecordTy);
3443
3444 RecordDecl::field_iterator CurField = RD->field_begin();
3446 E = S.capture_init_end();
3447 I != E; ++I, ++CurField) {
3448 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
3449 if (CurField->hasCapturedVLAType()) {
3450 EmitLambdaVLACapture(CurField->getCapturedVLAType(), LV);
3451 } else {
3452 EmitInitializerForField(*CurField, LV, *I);
3453 }
3454 }
3455
3456 return SlotLV;
3457}
3458
3459/// Generate an outlined function for the body of a CapturedStmt, store any
3460/// captured variables into the captured struct, and call the outlined function.
3461llvm::Function *
3463 LValue CapStruct = InitCapturedStruct(S);
3464
3465 // Emit the CapturedDecl
3466 CodeGenFunction CGF(CGM, true);
3467 CGCapturedStmtRAII CapInfoRAII(CGF, new CGCapturedStmtInfo(S, K));
3468 llvm::Function *F = CGF.GenerateCapturedStmtFunction(S);
3469 delete CGF.CapturedStmtInfo;
3470
3471 // Emit call to the helper function.
3472 EmitCallOrInvoke(F, CapStruct.getPointer(*this));
3473
3474 return F;
3475}
3476
3478 LValue CapStruct = InitCapturedStruct(S);
3479 return CapStruct.getAddress();
3480}
3481
3482/// Creates the outlined function for a CapturedStmt.
3483llvm::Function *
3485 assert(CapturedStmtInfo &&
3486 "CapturedStmtInfo should be set when generating the captured function");
3487 const CapturedDecl *CD = S.getCapturedDecl();
3488 const RecordDecl *RD = S.getCapturedRecordDecl();
3489 SourceLocation Loc = S.getBeginLoc();
3490 assert(CD->hasBody() && "missing CapturedDecl body");
3491
3492 // Build the argument list.
3493 ASTContext &Ctx = CGM.getContext();
3494 FunctionArgList Args;
3495 Args.append(CD->param_begin(), CD->param_end());
3496
3497 // Create the function declaration.
3498 const CGFunctionInfo &FuncInfo =
3499 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Args);
3500 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
3501
3502 llvm::Function *F =
3503 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
3504 CapturedStmtInfo->getHelperName(), &CGM.getModule());
3505 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
3506 if (!CGM.getCodeGenOpts().SampleProfileFile.empty())
3507 F->addFnAttr("sample-profile-suffix-elision-policy", "selected");
3508 if (CD->isNothrow())
3509 F->addFnAttr(llvm::Attribute::NoUnwind);
3510
3511 // Generate the function.
3512 StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args, CD->getLocation(),
3513 CD->getBody()->getBeginLoc());
3514 // Set the context parameter in CapturedStmtInfo.
3515 Address DeclPtr = GetAddrOfLocalVar(CD->getContextParam());
3516 CapturedStmtInfo->setContextValue(Builder.CreateLoad(DeclPtr));
3517
3518 // Initialize variable-length arrays.
3520 CapturedStmtInfo->getContextValue(), Ctx.getCanonicalTagType(RD));
3521 for (auto *FD : RD->fields()) {
3522 if (FD->hasCapturedVLAType()) {
3523 auto *ExprArg =
3525 .getScalarVal();
3526 auto VAT = FD->getCapturedVLAType();
3527 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
3528 }
3529 }
3530
3531 // If 'this' is captured, load it into CXXThisValue.
3532 if (CapturedStmtInfo->isCXXThisExprCaptured()) {
3533 FieldDecl *FD = CapturedStmtInfo->getThisFieldDecl();
3534 LValue ThisLValue = EmitLValueForField(Base, FD);
3535 CXXThisValue = EmitLoadOfLValue(ThisLValue, Loc).getScalarVal();
3536 }
3537
3538 PGO->assignRegionCounters(GlobalDecl(CD), F);
3539 CapturedStmtInfo->EmitBody(*this, CD->getBody());
3541
3542 return F;
3543}
3544
3545// Returns the first convergence entry/loop/anchor instruction found in |BB|.
3546// std::nullptr otherwise.
3547static llvm::ConvergenceControlInst *getConvergenceToken(llvm::BasicBlock *BB) {
3548 for (auto &I : *BB) {
3549 if (auto *CI = dyn_cast<llvm::ConvergenceControlInst>(&I))
3550 return CI;
3551 }
3552 return nullptr;
3553}
3554
3555llvm::CallBase *
3556CodeGenFunction::addConvergenceControlToken(llvm::CallBase *Input) {
3557 llvm::ConvergenceControlInst *ParentToken = ConvergenceTokenStack.back();
3558 assert(ParentToken);
3559
3560 llvm::Value *bundleArgs[] = {ParentToken};
3561 llvm::OperandBundleDef OB("convergencectrl", bundleArgs);
3562 auto *Output = llvm::CallBase::addOperandBundle(
3563 Input, llvm::LLVMContext::OB_convergencectrl, OB, Input->getIterator());
3564 Input->replaceAllUsesWith(Output);
3565 Input->eraseFromParent();
3566 return Output;
3567}
3568
3569llvm::ConvergenceControlInst *
3571 llvm::ConvergenceControlInst *ParentToken = ConvergenceTokenStack.back();
3572 assert(ParentToken);
3573 return llvm::ConvergenceControlInst::CreateLoop(*BB, ParentToken);
3574}
3575
3576llvm::ConvergenceControlInst *
3577CodeGenFunction::getOrEmitConvergenceEntryToken(llvm::Function *F) {
3578 llvm::BasicBlock *BB = &F->getEntryBlock();
3579 llvm::ConvergenceControlInst *Token = getConvergenceToken(BB);
3580 if (Token)
3581 return Token;
3582
3583 // Adding a convergence token requires the function to be marked as
3584 // convergent.
3585 F->setConvergent();
3586 return llvm::ConvergenceControlInst::CreateEntry(*BB);
3587}
#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:2270
static llvm::ConvergenceControlInst * getConvergenceToken(llvm::BasicBlock *BB)
Definition CGStmt.cpp:3547
static std::optional< SmallVector< uint64_t, 16 > > getLikelihoodWeights(ArrayRef< Stmt::Likelihood > Likelihoods)
Definition CGStmt.cpp:2324
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:2639
static bool isSwiftAsyncCallee(const CallExpr *CE)
Determine if the given call uses the swiftasync calling convention.
Definition CGStmt.cpp:1593
static CSFC_Result CollectStatementsForCase(const Stmt *S, const SwitchCase *Case, bool &FoundCase, SmallVectorImpl< const Stmt * > &ResultStmts)
Definition CGStmt.cpp:2115
static bool hasEmptyLoopBody(const LoopStmt &S)
Definition CGStmt.cpp:1075
CSFC_Result
CollectStatementsForCase - Given the body of a 'switch' statement and a constant value that is being ...
Definition CGStmt.cpp:2114
@ CSFC_Failure
Definition CGStmt.cpp:2114
@ CSFC_Success
Definition CGStmt.cpp:2114
@ CSFC_FallThrough
Definition CGStmt.cpp:2114
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.
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
bool toIntegralConstant(APSInt &Result, QualType SrcTy, const ASTContext &Ctx) const
Try to convert this value to an integral constant.
Definition APValue.cpp:992
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:239
SourceManager & getSourceManager()
Definition ASTContext.h:907
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:2763
AsmStmt is the base class for GCCAsmStmt and MSAsmStmt.
Definition Stmt.h:3289
Attr - This represents one attribute.
Definition Attr.h:46
Represents an attribute applied to a statement.
Definition Stmt.h:2215
Stmt * getSubStmt()
Definition Stmt.h:2251
ArrayRef< const Attr * > getAttrs() const
Definition Stmt.h:2247
BreakStmt - This represents a break.
Definition Stmt.h:3147
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:2987
Expr * getCallee()
Definition Expr.h:3134
Represents the body of a CapturedStmt, and serves as its DeclContext.
Definition Decl.h:5082
ImplicitParamDecl * getContextParam() const
Retrieve the parameter containing captured variables.
Definition Decl.h:5140
bool isNothrow() const
Definition Decl.cpp:5771
param_iterator param_end() const
Retrieve an iterator one past the last parameter decl.
Definition Decl.h:5157
param_iterator param_begin() const
Retrieve an iterator pointing to the first parameter decl.
Definition Decl.h:5155
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:5768
This captures a statement into a function.
Definition Stmt.h:3949
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:4070
capture_init_iterator capture_init_begin()
Retrieve the first initialization argument.
Definition Stmt.h:4126
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.h:4144
capture_init_iterator capture_init_end()
Retrieve the iterator pointing one past the last initialization argument.
Definition Stmt.h:4136
Expr *const * const_capture_init_iterator
Const iterator that walks over the capture initialization arguments.
Definition Stmt.h:4113
CapturedRegionKind getCapturedRegionKind() const
Retrieve the captured region kind.
Definition Stmt.cpp:1508
CaseStmt - Represent a case statement.
Definition Stmt.h:1932
Stmt * getSubStmt()
Definition Stmt.h:2045
Expr * getLHS()
Definition Stmt.h:2015
Expr * getRHS()
Definition Stmt.h:2027
@ 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:146
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Definition CGBuilder.h:118
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
Definition CGDebugInfo.h:59
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:756
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:1435
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:3436
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:5520
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:708
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:2148
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:4151
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:521
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:697
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:691
void SimplifyForwardingBlocks(llvm::BasicBlock *BB)
SimplifyForwardingBlocks - If the given basic block is only a branch to another basic block,...
Definition CGStmt.cpp:632
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:3570
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:5962
const TargetInfo & getTarget() const
Address EmitCompoundStmtWithoutScope(const CompoundStmt &S, bool GetLast=false, AggValueSlot AVS=AggValueSlot::ignored())
Definition CGStmt.cpp:583
void EmitGotoStmt(const GotoStmt &S)
Definition CGStmt.cpp:854
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:261
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:2539
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:1290
void EmitOMPSectionsDirective(const OMPSectionsDirective &S)
void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S)
Definition CGObjC.cpp:3707
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:1539
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:242
void EmitWhileStmt(const WhileStmt &S, ArrayRef< const Attr * > Attrs={})
Definition CGStmt.cpp:1088
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:1025
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:6124
void EmitOMPTargetTeamsDistributeParallelForDirective(const OMPTargetTeamsDistributeParallelForDirective &S)
void EmitOMPMaskedTaskLoopDirective(const OMPMaskedTaskLoopDirective &S)
void EmitObjCAtTryStmt(const ObjCAtTryStmt &S)
Definition CGObjC.cpp:2144
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:234
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:48
void EmitOMPTargetUpdateDirective(const OMPTargetUpdateDirective &S)
void EmitOMPTargetTeamsGenericLoopDirective(const OMPTargetTeamsGenericLoopDirective &S)
void EmitIfStmt(const IfStmt &S)
Definition CGStmt.cpp:890
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:2087
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:2791
void EmitOpenACCAtomicConstruct(const OpenACCAtomicConstruct &S)
void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S)
Definition CGObjC.cpp:2152
Address EmitCompoundStmt(const CompoundStmt &S, bool GetLast=false, AggValueSlot AVS=AggValueSlot::ignored())
EmitCompoundStmt - Emit a compound statement {..} node.
Definition CGStmt.cpp:571
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:2772
void EmitDefaultStmt(const DefaultStmt &S, ArrayRef< const Attr * > Attrs)
Definition CGStmt.cpp:1988
void EmitOMPTargetTeamsDistributeDirective(const OMPTargetTeamsDistributeDirective &S)
void EmitSwitchStmt(const SwitchStmt &S)
Definition CGStmt.cpp:2379
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:312
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:283
void EmitStmt(const Stmt *S, ArrayRef< const Attr * > Attrs={})
EmitStmt - Emit the code for the statement.
Definition CGStmt.cpp:58
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:3462
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:1873
void EmitOMPErrorDirective(const OMPErrorDirective &S)
void EmitBreakStmt(const BreakStmt &S)
Definition CGStmt.cpp:1758
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:1205
void EmitOMPTargetDataDirective(const OMPTargetDataDirective &S)
Address GenerateCapturedStmtArgument(const CapturedStmt &S)
Definition CGStmt.cpp:3477
void EmitBranch(llvm::BasicBlock *Block)
EmitBranch - Emit a branch to the specified basic block from the current insert block,...
Definition CGStmt.cpp:674
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:198
void EmitOMPParallelGenericLoopDirective(const OMPLoopDirective &S)
void EmitOMPTargetSimdDirective(const OMPTargetSimdDirective &S)
RawAddress NormalCleanupDest
i32s containing the indexes of the cleanup destinations.
void EmitOMPTeamsGenericLoopDirective(const OMPTeamsGenericLoopDirective &S)
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:1744
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:1787
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:1619
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:3484
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:1734
void EmitLabelStmt(const LabelStmt &S)
Definition CGStmt.cpp:777
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:1734
void EmitAttributedStmt(const AttributedStmt &S)
Definition CGStmt.cpp:787
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:1823
void EmitIndirectGotoStmt(const IndirectGotoStmt &S)
Definition CGStmt.cpp:866
void MaybeEmitDeferredVarDeclInit(const VarDecl *var)
Definition CGDecl.cpp:2096
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:719
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition CGStmt.cpp:654
LValue MakeNaturalAlignRawAddrLValue(llvm::Value *V, QualType T)
void EmitContinueStmt(const ContinueStmt &S)
Definition CGStmt.cpp:1771
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:1752
Stmt *const * const_body_iterator
Definition Stmt.h:1824
body_iterator body_end()
Definition Stmt.h:1817
SourceLocation getLBracLoc() const
Definition Stmt.h:1869
body_iterator body_begin()
Definition Stmt.h:1816
Stmt * body_back()
Definition Stmt.h:1820
ConstantExpr - An expression that occurs in a constant context and optionally the result of evaluatin...
Definition Expr.h:1102
ContinueStmt - This represents a continue.
Definition Stmt.h:3131
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1643
decl_range decls()
Definition Stmt.h:1691
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:1110
SourceLocation getLocation() const
Definition DeclBase.h:447
Stmt * getSubStmt()
Definition Stmt.h:2093
DeferStmt - This represents a deferred statement.
Definition Stmt.h:3248
DoStmt - This represents a 'do/while' stmt.
Definition Stmt.h:2844
Stmt * getBody()
Definition Stmt.h:2869
Expr * getCond()
Definition Stmt.h:2862
This represents one expression.
Definition Expr.h:113
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:3150
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:3722
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:145
Represents a member of a struct/union/class.
Definition Decl.h:3295
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2900
Stmt * getInit()
Definition Stmt.h:2915
VarDecl * getConditionVariable() const
Retrieve the variable declared in this "for" statement, if any.
Definition Stmt.cpp:1120
Stmt * getBody()
Definition Stmt.h:2944
Expr * getInc()
Definition Stmt.h:2943
Expr * getCond()
Definition Stmt.h:2942
const Expr * getSubExpr() const
Definition Expr.h:1082
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4594
CallingConv getCallConv() const
Definition TypeBase.h:4949
This represents a GCC inline-assembly statement extension.
Definition Stmt.h:3458
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:60
GotoStmt - This represents a direct goto.
Definition Stmt.h:2981
LabelDecl * getLabel() const
Definition Stmt.h:2994
IfStmt - This represents an if/then/else.
Definition Stmt.h:2271
Stmt * getThen()
Definition Stmt.h:2360
Stmt * getInit()
Definition Stmt.h:2421
Expr * getCond()
Definition Stmt.h:2348
bool isConstexpr() const
Definition Stmt.h:2464
bool isNegatedConsteval() const
Definition Stmt.h:2460
Stmt * getElse()
Definition Stmt.h:2369
bool isConsteval() const
Definition Stmt.h:2451
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:3020
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:525
LabelStmt * getStmt() const
Definition Decl.h:549
LabelStmt - Represents a label, which has a substatement.
Definition Stmt.h:2158
LabelDecl * getDecl() const
Definition Stmt.h:2176
bool isSideEntry() const
Definition Stmt.h:2205
Stmt * getSubStmt()
Definition Stmt.h:2180
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:3069
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:302
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:8480
The collection of all-type qualifiers we support.
Definition TypeBase.h:332
Represents a struct/union/class.
Definition Decl.h:4460
field_range fields() const
Definition Decl.h:4663
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4660
field_iterator field_begin() const
Definition Decl.cpp:5340
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition Stmt.h:3172
SourceLocation getBeginLoc() const
Definition Stmt.h:3224
const VarDecl * getNRVOCandidate() const
Retrieve the variable that might be used for the named return value optimization.
Definition Stmt.h:3208
Expr * getRetValue()
Definition Stmt.h:3199
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
StmtClass getStmtClass() const
Definition Stmt.h:1505
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:1448
@ LH_Unlikely
Branch has the [[unlikely]] attribute.
Definition Stmt.h:1449
@ LH_None
No attribute set or branches of the IfStmt have the same attribute.
Definition Stmt.h:1450
@ LH_Likely
Branch has the [[likely]] attribute.
Definition Stmt.h:1452
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:1819
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2017
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:1332
StringRef getString() const
Definition Expr.h:1887
const SwitchCase * getNextSwitchCase() const
Definition Stmt.h:1905
SwitchStmt - This represents a 'switch' stmt.
Definition Stmt.h:2521
Expr * getCond()
Definition Stmt.h:2584
Stmt * getBody()
Definition Stmt.h:2596
VarDecl * getConditionVariable()
Retrieve the variable declared in this "switch" statement, if any.
Definition Stmt.cpp:1186
Stmt * getInit()
Definition Stmt.h:2601
SwitchCase * getSwitchCaseList()
Definition Stmt.h:2652
Exposes information about the current target.
Definition TargetInfo.h:226
Token - This structure provides full information about a lexed token.
Definition Token.h:36
bool isVoidType() const
Definition TypeBase.h:9037
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9331
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:881
bool isNRVOVariable() const
Determine whether this local variable can be used with the named return value optimization (NRVO).
Definition Decl.h:1537
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2709
Expr * getCond()
Definition Stmt.h:2761
SourceLocation getWhileLoc() const
Definition Stmt.h:2814
SourceLocation getRParenLoc() const
Definition Stmt.h:2819
VarDecl * getConditionVariable()
Retrieve the variable declared in this "while" statement, if any.
Definition Stmt.cpp:1247
Stmt * getBody()
Definition Stmt.h:2773
Defines the clang::TargetInfo interface.
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
@ CPlusPlus11
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:294
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
The alignment was not explicit in code.
Definition ASTContext.h:176
unsigned long 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
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:666
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:668
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.