1 //===--- CGStmt.cpp - Emit LLVM Code from Statements ----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This contains code to emit Stmt nodes as LLVM code.
12 //===----------------------------------------------------------------------===//
14 #include "CodeGenFunction.h"
15 #include "CGDebugInfo.h"
16 #include "CodeGenModule.h"
17 #include "TargetInfo.h"
18 #include "clang/AST/StmtVisitor.h"
19 #include "clang/Basic/Builtins.h"
20 #include "clang/Basic/PrettyStackTrace.h"
21 #include "clang/Basic/TargetInfo.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/IR/CallSite.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/InlineAsm.h"
26 #include "llvm/IR/Intrinsics.h"
27 #include "llvm/IR/MDBuilder.h"
29 using namespace clang;
30 using namespace CodeGen;
32 //===----------------------------------------------------------------------===//
34 //===----------------------------------------------------------------------===//
36 void CodeGenFunction::EmitStopPoint(const Stmt *S) {
37 if (CGDebugInfo *DI = getDebugInfo()) {
39 Loc = S->getBeginLoc();
40 DI->EmitLocation(Builder, Loc);
46 void CodeGenFunction::EmitStmt(const Stmt *S, ArrayRef<const Attr *> Attrs) {
47 assert(S && "Null statement?");
48 PGO.setCurrentStmt(S);
50 // These statements have their own debug info handling.
51 if (EmitSimpleStmt(S))
54 // Check if we are generating unreachable code.
55 if (!HaveInsertPoint()) {
56 // If so, and the statement doesn't contain a label, then we do not need to
57 // generate actual code. This is safe because (1) the current point is
58 // unreachable, so we don't need to execute the code, and (2) we've already
59 // handled the statements which update internal data structures (like the
60 // local variable map) which could be used by subsequent statements.
61 if (!ContainsLabel(S)) {
62 // Verify that any decl statements were handled as simple, they may be in
63 // scope of subsequent reachable statements.
64 assert(!isa<DeclStmt>(*S) && "Unexpected DeclStmt!");
68 // Otherwise, make a new block to hold the code.
72 // Generate a stoppoint if we are emitting debug info.
75 // Ignore all OpenMP directives except for simd if OpenMP with Simd is
77 if (getLangOpts().OpenMP && getLangOpts().OpenMPSimd) {
78 if (const auto *D = dyn_cast<OMPExecutableDirective>(S)) {
79 EmitSimpleOMPExecutableDirective(*D);
84 switch (S->getStmtClass()) {
85 case Stmt::NoStmtClass:
86 case Stmt::CXXCatchStmtClass:
87 case Stmt::SEHExceptStmtClass:
88 case Stmt::SEHFinallyStmtClass:
89 case Stmt::MSDependentExistsStmtClass:
90 llvm_unreachable("invalid statement class to emit generically");
91 case Stmt::NullStmtClass:
92 case Stmt::CompoundStmtClass:
93 case Stmt::DeclStmtClass:
94 case Stmt::LabelStmtClass:
95 case Stmt::AttributedStmtClass:
96 case Stmt::GotoStmtClass:
97 case Stmt::BreakStmtClass:
98 case Stmt::ContinueStmtClass:
99 case Stmt::DefaultStmtClass:
100 case Stmt::CaseStmtClass:
101 case Stmt::SEHLeaveStmtClass:
102 llvm_unreachable("should have emitted these statements as simple");
104 #define STMT(Type, Base)
105 #define ABSTRACT_STMT(Op)
106 #define EXPR(Type, Base) \
107 case Stmt::Type##Class:
108 #include "clang/AST/StmtNodes.inc"
110 // Remember the block we came in on.
111 llvm::BasicBlock *incoming = Builder.GetInsertBlock();
112 assert(incoming && "expression emission must have an insertion point");
114 EmitIgnoredExpr(cast<Expr>(S));
116 llvm::BasicBlock *outgoing = Builder.GetInsertBlock();
117 assert(outgoing && "expression emission cleared block!");
119 // The expression emitters assume (reasonably!) that the insertion
120 // point is always set. To maintain that, the call-emission code
121 // for noreturn functions has to enter a new block with no
122 // predecessors. We want to kill that block and mark the current
123 // insertion point unreachable in the common case of a call like
124 // "exit();". Since expression emission doesn't otherwise create
125 // blocks with no predecessors, we can just test for that.
126 // However, we must be careful not to do this to our incoming
127 // block, because *statement* emission does sometimes create
128 // reachable blocks which will have no predecessors until later in
129 // the function. This occurs with, e.g., labels that are not
130 // reachable by fallthrough.
131 if (incoming != outgoing && outgoing->use_empty()) {
132 outgoing->eraseFromParent();
133 Builder.ClearInsertionPoint();
138 case Stmt::IndirectGotoStmtClass:
139 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
141 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
142 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S), Attrs); break;
143 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S), Attrs); break;
144 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S), Attrs); break;
146 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
148 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
149 case Stmt::GCCAsmStmtClass: // Intentional fall-through.
150 case Stmt::MSAsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
151 case Stmt::CoroutineBodyStmtClass:
152 EmitCoroutineBody(cast<CoroutineBodyStmt>(*S));
154 case Stmt::CoreturnStmtClass:
155 EmitCoreturnStmt(cast<CoreturnStmt>(*S));
157 case Stmt::CapturedStmtClass: {
158 const CapturedStmt *CS = cast<CapturedStmt>(S);
159 EmitCapturedStmt(*CS, CS->getCapturedRegionKind());
162 case Stmt::ObjCAtTryStmtClass:
163 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
165 case Stmt::ObjCAtCatchStmtClass:
167 "@catch statements should be handled by EmitObjCAtTryStmt");
168 case Stmt::ObjCAtFinallyStmtClass:
170 "@finally statements should be handled by EmitObjCAtTryStmt");
171 case Stmt::ObjCAtThrowStmtClass:
172 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
174 case Stmt::ObjCAtSynchronizedStmtClass:
175 EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
177 case Stmt::ObjCForCollectionStmtClass:
178 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
180 case Stmt::ObjCAutoreleasePoolStmtClass:
181 EmitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(*S));
184 case Stmt::CXXTryStmtClass:
185 EmitCXXTryStmt(cast<CXXTryStmt>(*S));
187 case Stmt::CXXForRangeStmtClass:
188 EmitCXXForRangeStmt(cast<CXXForRangeStmt>(*S), Attrs);
190 case Stmt::SEHTryStmtClass:
191 EmitSEHTryStmt(cast<SEHTryStmt>(*S));
193 case Stmt::OMPParallelDirectiveClass:
194 EmitOMPParallelDirective(cast<OMPParallelDirective>(*S));
196 case Stmt::OMPSimdDirectiveClass:
197 EmitOMPSimdDirective(cast<OMPSimdDirective>(*S));
199 case Stmt::OMPForDirectiveClass:
200 EmitOMPForDirective(cast<OMPForDirective>(*S));
202 case Stmt::OMPForSimdDirectiveClass:
203 EmitOMPForSimdDirective(cast<OMPForSimdDirective>(*S));
205 case Stmt::OMPSectionsDirectiveClass:
206 EmitOMPSectionsDirective(cast<OMPSectionsDirective>(*S));
208 case Stmt::OMPSectionDirectiveClass:
209 EmitOMPSectionDirective(cast<OMPSectionDirective>(*S));
211 case Stmt::OMPSingleDirectiveClass:
212 EmitOMPSingleDirective(cast<OMPSingleDirective>(*S));
214 case Stmt::OMPMasterDirectiveClass:
215 EmitOMPMasterDirective(cast<OMPMasterDirective>(*S));
217 case Stmt::OMPCriticalDirectiveClass:
218 EmitOMPCriticalDirective(cast<OMPCriticalDirective>(*S));
220 case Stmt::OMPParallelForDirectiveClass:
221 EmitOMPParallelForDirective(cast<OMPParallelForDirective>(*S));
223 case Stmt::OMPParallelForSimdDirectiveClass:
224 EmitOMPParallelForSimdDirective(cast<OMPParallelForSimdDirective>(*S));
226 case Stmt::OMPParallelSectionsDirectiveClass:
227 EmitOMPParallelSectionsDirective(cast<OMPParallelSectionsDirective>(*S));
229 case Stmt::OMPTaskDirectiveClass:
230 EmitOMPTaskDirective(cast<OMPTaskDirective>(*S));
232 case Stmt::OMPTaskyieldDirectiveClass:
233 EmitOMPTaskyieldDirective(cast<OMPTaskyieldDirective>(*S));
235 case Stmt::OMPBarrierDirectiveClass:
236 EmitOMPBarrierDirective(cast<OMPBarrierDirective>(*S));
238 case Stmt::OMPTaskwaitDirectiveClass:
239 EmitOMPTaskwaitDirective(cast<OMPTaskwaitDirective>(*S));
241 case Stmt::OMPTaskgroupDirectiveClass:
242 EmitOMPTaskgroupDirective(cast<OMPTaskgroupDirective>(*S));
244 case Stmt::OMPFlushDirectiveClass:
245 EmitOMPFlushDirective(cast<OMPFlushDirective>(*S));
247 case Stmt::OMPOrderedDirectiveClass:
248 EmitOMPOrderedDirective(cast<OMPOrderedDirective>(*S));
250 case Stmt::OMPAtomicDirectiveClass:
251 EmitOMPAtomicDirective(cast<OMPAtomicDirective>(*S));
253 case Stmt::OMPTargetDirectiveClass:
254 EmitOMPTargetDirective(cast<OMPTargetDirective>(*S));
256 case Stmt::OMPTeamsDirectiveClass:
257 EmitOMPTeamsDirective(cast<OMPTeamsDirective>(*S));
259 case Stmt::OMPCancellationPointDirectiveClass:
260 EmitOMPCancellationPointDirective(cast<OMPCancellationPointDirective>(*S));
262 case Stmt::OMPCancelDirectiveClass:
263 EmitOMPCancelDirective(cast<OMPCancelDirective>(*S));
265 case Stmt::OMPTargetDataDirectiveClass:
266 EmitOMPTargetDataDirective(cast<OMPTargetDataDirective>(*S));
268 case Stmt::OMPTargetEnterDataDirectiveClass:
269 EmitOMPTargetEnterDataDirective(cast<OMPTargetEnterDataDirective>(*S));
271 case Stmt::OMPTargetExitDataDirectiveClass:
272 EmitOMPTargetExitDataDirective(cast<OMPTargetExitDataDirective>(*S));
274 case Stmt::OMPTargetParallelDirectiveClass:
275 EmitOMPTargetParallelDirective(cast<OMPTargetParallelDirective>(*S));
277 case Stmt::OMPTargetParallelForDirectiveClass:
278 EmitOMPTargetParallelForDirective(cast<OMPTargetParallelForDirective>(*S));
280 case Stmt::OMPTaskLoopDirectiveClass:
281 EmitOMPTaskLoopDirective(cast<OMPTaskLoopDirective>(*S));
283 case Stmt::OMPTaskLoopSimdDirectiveClass:
284 EmitOMPTaskLoopSimdDirective(cast<OMPTaskLoopSimdDirective>(*S));
286 case Stmt::OMPDistributeDirectiveClass:
287 EmitOMPDistributeDirective(cast<OMPDistributeDirective>(*S));
289 case Stmt::OMPTargetUpdateDirectiveClass:
290 EmitOMPTargetUpdateDirective(cast<OMPTargetUpdateDirective>(*S));
292 case Stmt::OMPDistributeParallelForDirectiveClass:
293 EmitOMPDistributeParallelForDirective(
294 cast<OMPDistributeParallelForDirective>(*S));
296 case Stmt::OMPDistributeParallelForSimdDirectiveClass:
297 EmitOMPDistributeParallelForSimdDirective(
298 cast<OMPDistributeParallelForSimdDirective>(*S));
300 case Stmt::OMPDistributeSimdDirectiveClass:
301 EmitOMPDistributeSimdDirective(cast<OMPDistributeSimdDirective>(*S));
303 case Stmt::OMPTargetParallelForSimdDirectiveClass:
304 EmitOMPTargetParallelForSimdDirective(
305 cast<OMPTargetParallelForSimdDirective>(*S));
307 case Stmt::OMPTargetSimdDirectiveClass:
308 EmitOMPTargetSimdDirective(cast<OMPTargetSimdDirective>(*S));
310 case Stmt::OMPTeamsDistributeDirectiveClass:
311 EmitOMPTeamsDistributeDirective(cast<OMPTeamsDistributeDirective>(*S));
313 case Stmt::OMPTeamsDistributeSimdDirectiveClass:
314 EmitOMPTeamsDistributeSimdDirective(
315 cast<OMPTeamsDistributeSimdDirective>(*S));
317 case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass:
318 EmitOMPTeamsDistributeParallelForSimdDirective(
319 cast<OMPTeamsDistributeParallelForSimdDirective>(*S));
321 case Stmt::OMPTeamsDistributeParallelForDirectiveClass:
322 EmitOMPTeamsDistributeParallelForDirective(
323 cast<OMPTeamsDistributeParallelForDirective>(*S));
325 case Stmt::OMPTargetTeamsDirectiveClass:
326 EmitOMPTargetTeamsDirective(cast<OMPTargetTeamsDirective>(*S));
328 case Stmt::OMPTargetTeamsDistributeDirectiveClass:
329 EmitOMPTargetTeamsDistributeDirective(
330 cast<OMPTargetTeamsDistributeDirective>(*S));
332 case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass:
333 EmitOMPTargetTeamsDistributeParallelForDirective(
334 cast<OMPTargetTeamsDistributeParallelForDirective>(*S));
336 case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass:
337 EmitOMPTargetTeamsDistributeParallelForSimdDirective(
338 cast<OMPTargetTeamsDistributeParallelForSimdDirective>(*S));
340 case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass:
341 EmitOMPTargetTeamsDistributeSimdDirective(
342 cast<OMPTargetTeamsDistributeSimdDirective>(*S));
347 bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
348 switch (S->getStmtClass()) {
349 default: return false;
350 case Stmt::NullStmtClass: break;
351 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
352 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
353 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
354 case Stmt::AttributedStmtClass:
355 EmitAttributedStmt(cast<AttributedStmt>(*S)); break;
356 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
357 case Stmt::BreakStmtClass: EmitBreakStmt(cast<BreakStmt>(*S)); break;
358 case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
359 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
360 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
361 case Stmt::SEHLeaveStmtClass: EmitSEHLeaveStmt(cast<SEHLeaveStmt>(*S)); break;
367 /// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
368 /// this captures the expression result of the last sub-statement and returns it
369 /// (for use by the statement expression extension).
370 Address CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
371 AggValueSlot AggSlot) {
372 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(),
373 "LLVM IR generation of compound statement ('{}')");
375 // Keep track of the current cleanup stack depth, including debug scopes.
376 LexicalScope Scope(*this, S.getSourceRange());
378 return EmitCompoundStmtWithoutScope(S, GetLast, AggSlot);
382 CodeGenFunction::EmitCompoundStmtWithoutScope(const CompoundStmt &S,
384 AggValueSlot AggSlot) {
386 for (CompoundStmt::const_body_iterator I = S.body_begin(),
387 E = S.body_end()-GetLast; I != E; ++I)
390 Address RetAlloca = Address::invalid();
392 // We have to special case labels here. They are statements, but when put
393 // at the end of a statement expression, they yield the value of their
394 // subexpression. Handle this by walking through all labels we encounter,
395 // emitting them before we evaluate the subexpr.
396 const Stmt *LastStmt = S.body_back();
397 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
398 EmitLabel(LS->getDecl());
399 LastStmt = LS->getSubStmt();
404 QualType ExprTy = cast<Expr>(LastStmt)->getType();
405 if (hasAggregateEvaluationKind(ExprTy)) {
406 EmitAggExpr(cast<Expr>(LastStmt), AggSlot);
408 // We can't return an RValue here because there might be cleanups at
409 // the end of the StmtExpr. Because of that, we have to emit the result
410 // here into a temporary alloca.
411 RetAlloca = CreateMemTemp(ExprTy);
412 EmitAnyExprToMem(cast<Expr>(LastStmt), RetAlloca, Qualifiers(),
421 void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) {
422 llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(BB->getTerminator());
424 // If there is a cleanup stack, then we it isn't worth trying to
425 // simplify this block (we would need to remove it from the scope map
426 // and cleanup entry).
427 if (!EHStack.empty())
430 // Can only simplify direct branches.
431 if (!BI || !BI->isUnconditional())
434 // Can only simplify empty blocks.
435 if (BI->getIterator() != BB->begin())
438 BB->replaceAllUsesWith(BI->getSuccessor(0));
439 BI->eraseFromParent();
440 BB->eraseFromParent();
443 void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
444 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
446 // Fall out of the current block (if necessary).
449 if (IsFinished && BB->use_empty()) {
454 // Place the block after the current block, if possible, or else at
455 // the end of the function.
456 if (CurBB && CurBB->getParent())
457 CurFn->getBasicBlockList().insertAfter(CurBB->getIterator(), BB);
459 CurFn->getBasicBlockList().push_back(BB);
460 Builder.SetInsertPoint(BB);
463 void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
464 // Emit a branch from the current block to the target one if this
465 // was a real block. If this was just a fall-through block after a
466 // terminator, don't emit it.
467 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
469 if (!CurBB || CurBB->getTerminator()) {
470 // If there is no insert point or the previous block is already
471 // terminated, don't touch it.
473 // Otherwise, create a fall-through branch.
474 Builder.CreateBr(Target);
477 Builder.ClearInsertionPoint();
480 void CodeGenFunction::EmitBlockAfterUses(llvm::BasicBlock *block) {
481 bool inserted = false;
482 for (llvm::User *u : block->users()) {
483 if (llvm::Instruction *insn = dyn_cast<llvm::Instruction>(u)) {
484 CurFn->getBasicBlockList().insertAfter(insn->getParent()->getIterator(),
492 CurFn->getBasicBlockList().push_back(block);
494 Builder.SetInsertPoint(block);
497 CodeGenFunction::JumpDest
498 CodeGenFunction::getJumpDestForLabel(const LabelDecl *D) {
499 JumpDest &Dest = LabelMap[D];
500 if (Dest.isValid()) return Dest;
502 // Create, but don't insert, the new block.
503 Dest = JumpDest(createBasicBlock(D->getName()),
504 EHScopeStack::stable_iterator::invalid(),
505 NextCleanupDestIndex++);
509 void CodeGenFunction::EmitLabel(const LabelDecl *D) {
510 // Add this label to the current lexical scope if we're within any
511 // normal cleanups. Jumps "in" to this label --- when permitted by
512 // the language --- may need to be routed around such cleanups.
513 if (EHStack.hasNormalCleanups() && CurLexicalScope)
514 CurLexicalScope->addLabel(D);
516 JumpDest &Dest = LabelMap[D];
518 // If we didn't need a forward reference to this label, just go
519 // ahead and create a destination at the current scope.
520 if (!Dest.isValid()) {
521 Dest = getJumpDestInCurrentScope(D->getName());
523 // Otherwise, we need to give this label a target depth and remove
524 // it from the branch-fixups list.
526 assert(!Dest.getScopeDepth().isValid() && "already emitted label!");
527 Dest.setScopeDepth(EHStack.stable_begin());
528 ResolveBranchFixups(Dest.getBlock());
531 EmitBlock(Dest.getBlock());
532 incrementProfileCounter(D->getStmt());
535 /// Change the cleanup scope of the labels in this lexical scope to
536 /// match the scope of the enclosing context.
537 void CodeGenFunction::LexicalScope::rescopeLabels() {
538 assert(!Labels.empty());
539 EHScopeStack::stable_iterator innermostScope
540 = CGF.EHStack.getInnermostNormalCleanup();
542 // Change the scope depth of all the labels.
543 for (SmallVectorImpl<const LabelDecl*>::const_iterator
544 i = Labels.begin(), e = Labels.end(); i != e; ++i) {
545 assert(CGF.LabelMap.count(*i));
546 JumpDest &dest = CGF.LabelMap.find(*i)->second;
547 assert(dest.getScopeDepth().isValid());
548 assert(innermostScope.encloses(dest.getScopeDepth()));
549 dest.setScopeDepth(innermostScope);
552 // Reparent the labels if the new scope also has cleanups.
553 if (innermostScope != EHScopeStack::stable_end() && ParentScope) {
554 ParentScope->Labels.append(Labels.begin(), Labels.end());
559 void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
560 EmitLabel(S.getDecl());
561 EmitStmt(S.getSubStmt());
564 void CodeGenFunction::EmitAttributedStmt(const AttributedStmt &S) {
565 EmitStmt(S.getSubStmt(), S.getAttrs());
568 void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
569 // If this code is reachable then emit a stop point (if generating
570 // debug info). We have to do this ourselves because we are on the
571 // "simple" statement path.
572 if (HaveInsertPoint())
575 EmitBranchThroughCleanup(getJumpDestForLabel(S.getLabel()));
579 void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
580 if (const LabelDecl *Target = S.getConstantTarget()) {
581 EmitBranchThroughCleanup(getJumpDestForLabel(Target));
585 // Ensure that we have an i8* for our PHI node.
586 llvm::Value *V = Builder.CreateBitCast(EmitScalarExpr(S.getTarget()),
588 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
590 // Get the basic block for the indirect goto.
591 llvm::BasicBlock *IndGotoBB = GetIndirectGotoBlock();
593 // The first instruction in the block has to be the PHI for the switch dest,
594 // add an entry for this branch.
595 cast<llvm::PHINode>(IndGotoBB->begin())->addIncoming(V, CurBB);
597 EmitBranch(IndGotoBB);
600 void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
601 // C99 6.8.4.1: The first substatement is executed if the expression compares
602 // unequal to 0. The condition must be a scalar type.
603 LexicalScope ConditionScope(*this, S.getCond()->getSourceRange());
606 EmitStmt(S.getInit());
608 if (S.getConditionVariable())
609 EmitDecl(*S.getConditionVariable());
611 // If the condition constant folds and can be elided, try to avoid emitting
612 // the condition and the dead arm of the if/else.
614 if (ConstantFoldsToSimpleInteger(S.getCond(), CondConstant,
616 // Figure out which block (then or else) is executed.
617 const Stmt *Executed = S.getThen();
618 const Stmt *Skipped = S.getElse();
619 if (!CondConstant) // Condition false?
620 std::swap(Executed, Skipped);
622 // If the skipped block has no labels in it, just emit the executed block.
623 // This avoids emitting dead code and simplifies the CFG substantially.
624 if (S.isConstexpr() || !ContainsLabel(Skipped)) {
626 incrementProfileCounter(&S);
628 RunCleanupsScope ExecutedScope(*this);
635 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
636 // the conditional branch.
637 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
638 llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
639 llvm::BasicBlock *ElseBlock = ContBlock;
641 ElseBlock = createBasicBlock("if.else");
643 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock,
644 getProfileCount(S.getThen()));
646 // Emit the 'then' code.
647 EmitBlock(ThenBlock);
648 incrementProfileCounter(&S);
650 RunCleanupsScope ThenScope(*this);
651 EmitStmt(S.getThen());
653 EmitBranch(ContBlock);
655 // Emit the 'else' code if present.
656 if (const Stmt *Else = S.getElse()) {
658 // There is no need to emit line number for an unconditional branch.
659 auto NL = ApplyDebugLocation::CreateEmpty(*this);
660 EmitBlock(ElseBlock);
663 RunCleanupsScope ElseScope(*this);
667 // There is no need to emit line number for an unconditional branch.
668 auto NL = ApplyDebugLocation::CreateEmpty(*this);
669 EmitBranch(ContBlock);
673 // Emit the continuation block for code after the if.
674 EmitBlock(ContBlock, true);
677 void CodeGenFunction::EmitWhileStmt(const WhileStmt &S,
678 ArrayRef<const Attr *> WhileAttrs) {
679 // Emit the header for the loop, which will also become
680 // the continue target.
681 JumpDest LoopHeader = getJumpDestInCurrentScope("while.cond");
682 EmitBlock(LoopHeader.getBlock());
684 const SourceRange &R = S.getSourceRange();
685 LoopStack.push(LoopHeader.getBlock(), CGM.getContext(), WhileAttrs,
686 SourceLocToDebugLoc(R.getBegin()),
687 SourceLocToDebugLoc(R.getEnd()));
689 // Create an exit block for when the condition fails, which will
690 // also become the break target.
691 JumpDest LoopExit = getJumpDestInCurrentScope("while.end");
693 // Store the blocks to use for break and continue.
694 BreakContinueStack.push_back(BreakContinue(LoopExit, LoopHeader));
696 // C++ [stmt.while]p2:
697 // When the condition of a while statement is a declaration, the
698 // scope of the variable that is declared extends from its point
699 // of declaration (3.3.2) to the end of the while statement.
701 // The object created in a condition is destroyed and created
702 // with each iteration of the loop.
703 RunCleanupsScope ConditionScope(*this);
705 if (S.getConditionVariable())
706 EmitDecl(*S.getConditionVariable());
708 // Evaluate the conditional in the while header. C99 6.8.5.1: The
709 // evaluation of the controlling expression takes place before each
710 // execution of the loop body.
711 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
713 // while(1) is common, avoid extra exit blocks. Be sure
714 // to correctly handle break/continue though.
715 bool EmitBoolCondBranch = true;
716 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
718 EmitBoolCondBranch = false;
720 // As long as the condition is true, go to the loop body.
721 llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
722 if (EmitBoolCondBranch) {
723 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
724 if (ConditionScope.requiresCleanups())
725 ExitBlock = createBasicBlock("while.exit");
726 Builder.CreateCondBr(
727 BoolCondVal, LoopBody, ExitBlock,
728 createProfileWeightsForLoop(S.getCond(), getProfileCount(S.getBody())));
730 if (ExitBlock != LoopExit.getBlock()) {
731 EmitBlock(ExitBlock);
732 EmitBranchThroughCleanup(LoopExit);
736 // Emit the loop body. We have to emit this in a cleanup scope
737 // because it might be a singleton DeclStmt.
739 RunCleanupsScope BodyScope(*this);
741 incrementProfileCounter(&S);
742 EmitStmt(S.getBody());
745 BreakContinueStack.pop_back();
747 // Immediately force cleanup.
748 ConditionScope.ForceCleanup();
751 // Branch to the loop header again.
752 EmitBranch(LoopHeader.getBlock());
756 // Emit the exit block.
757 EmitBlock(LoopExit.getBlock(), true);
759 // The LoopHeader typically is just a branch if we skipped emitting
760 // a branch, try to erase it.
761 if (!EmitBoolCondBranch)
762 SimplifyForwardingBlocks(LoopHeader.getBlock());
765 void CodeGenFunction::EmitDoStmt(const DoStmt &S,
766 ArrayRef<const Attr *> DoAttrs) {
767 JumpDest LoopExit = getJumpDestInCurrentScope("do.end");
768 JumpDest LoopCond = getJumpDestInCurrentScope("do.cond");
770 uint64_t ParentCount = getCurrentProfileCount();
772 // Store the blocks to use for break and continue.
773 BreakContinueStack.push_back(BreakContinue(LoopExit, LoopCond));
775 // Emit the body of the loop.
776 llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
778 EmitBlockWithFallThrough(LoopBody, &S);
780 RunCleanupsScope BodyScope(*this);
781 EmitStmt(S.getBody());
784 EmitBlock(LoopCond.getBlock());
786 const SourceRange &R = S.getSourceRange();
787 LoopStack.push(LoopBody, CGM.getContext(), DoAttrs,
788 SourceLocToDebugLoc(R.getBegin()),
789 SourceLocToDebugLoc(R.getEnd()));
791 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
792 // after each execution of the loop body."
794 // Evaluate the conditional in the while header.
795 // C99 6.8.5p2/p4: The first substatement is executed if the expression
796 // compares unequal to 0. The condition must be a scalar type.
797 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
799 BreakContinueStack.pop_back();
801 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
802 // to correctly handle break/continue though.
803 bool EmitBoolCondBranch = true;
804 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
806 EmitBoolCondBranch = false;
808 // As long as the condition is true, iterate the loop.
809 if (EmitBoolCondBranch) {
810 uint64_t BackedgeCount = getProfileCount(S.getBody()) - ParentCount;
811 Builder.CreateCondBr(
812 BoolCondVal, LoopBody, LoopExit.getBlock(),
813 createProfileWeightsForLoop(S.getCond(), BackedgeCount));
818 // Emit the exit block.
819 EmitBlock(LoopExit.getBlock());
821 // The DoCond block typically is just a branch if we skipped
822 // emitting a branch, try to erase it.
823 if (!EmitBoolCondBranch)
824 SimplifyForwardingBlocks(LoopCond.getBlock());
827 void CodeGenFunction::EmitForStmt(const ForStmt &S,
828 ArrayRef<const Attr *> ForAttrs) {
829 JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
831 LexicalScope ForScope(*this, S.getSourceRange());
833 // Evaluate the first part before the loop.
835 EmitStmt(S.getInit());
837 // Start the loop with a block that tests the condition.
838 // If there's an increment, the continue scope will be overwritten
840 JumpDest Continue = getJumpDestInCurrentScope("for.cond");
841 llvm::BasicBlock *CondBlock = Continue.getBlock();
842 EmitBlock(CondBlock);
844 const SourceRange &R = S.getSourceRange();
845 LoopStack.push(CondBlock, CGM.getContext(), ForAttrs,
846 SourceLocToDebugLoc(R.getBegin()),
847 SourceLocToDebugLoc(R.getEnd()));
849 // If the for loop doesn't have an increment we can just use the
850 // condition as the continue block. Otherwise we'll need to create
851 // a block for it (in the current scope, i.e. in the scope of the
852 // condition), and that we will become our continue block.
854 Continue = getJumpDestInCurrentScope("for.inc");
856 // Store the blocks to use for break and continue.
857 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
859 // Create a cleanup scope for the condition variable cleanups.
860 LexicalScope ConditionScope(*this, S.getSourceRange());
863 // If the for statement has a condition scope, emit the local variable
865 if (S.getConditionVariable()) {
866 EmitDecl(*S.getConditionVariable());
869 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
870 // If there are any cleanups between here and the loop-exit scope,
871 // create a block to stage a loop exit along.
872 if (ForScope.requiresCleanups())
873 ExitBlock = createBasicBlock("for.cond.cleanup");
875 // As long as the condition is true, iterate the loop.
876 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
878 // C99 6.8.5p2/p4: The first substatement is executed if the expression
879 // compares unequal to 0. The condition must be a scalar type.
880 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
881 Builder.CreateCondBr(
882 BoolCondVal, ForBody, ExitBlock,
883 createProfileWeightsForLoop(S.getCond(), getProfileCount(S.getBody())));
885 if (ExitBlock != LoopExit.getBlock()) {
886 EmitBlock(ExitBlock);
887 EmitBranchThroughCleanup(LoopExit);
892 // Treat it as a non-zero constant. Don't even create a new block for the
893 // body, just fall into it.
895 incrementProfileCounter(&S);
898 // Create a separate cleanup scope for the body, in case it is not
899 // a compound statement.
900 RunCleanupsScope BodyScope(*this);
901 EmitStmt(S.getBody());
904 // If there is an increment, emit it next.
906 EmitBlock(Continue.getBlock());
907 EmitStmt(S.getInc());
910 BreakContinueStack.pop_back();
912 ConditionScope.ForceCleanup();
915 EmitBranch(CondBlock);
917 ForScope.ForceCleanup();
921 // Emit the fall-through block.
922 EmitBlock(LoopExit.getBlock(), true);
926 CodeGenFunction::EmitCXXForRangeStmt(const CXXForRangeStmt &S,
927 ArrayRef<const Attr *> ForAttrs) {
928 JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
930 LexicalScope ForScope(*this, S.getSourceRange());
932 // Evaluate the first pieces before the loop.
934 EmitStmt(S.getInit());
935 EmitStmt(S.getRangeStmt());
936 EmitStmt(S.getBeginStmt());
937 EmitStmt(S.getEndStmt());
939 // Start the loop with a block that tests the condition.
940 // If there's an increment, the continue scope will be overwritten
942 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
943 EmitBlock(CondBlock);
945 const SourceRange &R = S.getSourceRange();
946 LoopStack.push(CondBlock, CGM.getContext(), ForAttrs,
947 SourceLocToDebugLoc(R.getBegin()),
948 SourceLocToDebugLoc(R.getEnd()));
950 // If there are any cleanups between here and the loop-exit scope,
951 // create a block to stage a loop exit along.
952 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
953 if (ForScope.requiresCleanups())
954 ExitBlock = createBasicBlock("for.cond.cleanup");
956 // The loop body, consisting of the specified body and the loop variable.
957 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
959 // The body is executed if the expression, contextually converted
961 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
962 Builder.CreateCondBr(
963 BoolCondVal, ForBody, ExitBlock,
964 createProfileWeightsForLoop(S.getCond(), getProfileCount(S.getBody())));
966 if (ExitBlock != LoopExit.getBlock()) {
967 EmitBlock(ExitBlock);
968 EmitBranchThroughCleanup(LoopExit);
972 incrementProfileCounter(&S);
974 // Create a block for the increment. In case of a 'continue', we jump there.
975 JumpDest Continue = getJumpDestInCurrentScope("for.inc");
977 // Store the blocks to use for break and continue.
978 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
981 // Create a separate cleanup scope for the loop variable and body.
982 LexicalScope BodyScope(*this, S.getSourceRange());
983 EmitStmt(S.getLoopVarStmt());
984 EmitStmt(S.getBody());
988 // If there is an increment, emit it next.
989 EmitBlock(Continue.getBlock());
990 EmitStmt(S.getInc());
992 BreakContinueStack.pop_back();
994 EmitBranch(CondBlock);
996 ForScope.ForceCleanup();
1000 // Emit the fall-through block.
1001 EmitBlock(LoopExit.getBlock(), true);
1004 void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
1005 if (RV.isScalar()) {
1006 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
1007 } else if (RV.isAggregate()) {
1008 LValue Dest = MakeAddrLValue(ReturnValue, Ty);
1009 LValue Src = MakeAddrLValue(RV.getAggregateAddress(), Ty);
1010 EmitAggregateCopy(Dest, Src, Ty, overlapForReturnValue());
1012 EmitStoreOfComplex(RV.getComplexVal(), MakeAddrLValue(ReturnValue, Ty),
1015 EmitBranchThroughCleanup(ReturnBlock);
1018 /// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
1019 /// if the function returns void, or may be missing one if the function returns
1020 /// non-void. Fun stuff :).
1021 void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
1022 if (requiresReturnValueCheck()) {
1023 llvm::Constant *SLoc = EmitCheckSourceLocation(S.getBeginLoc());
1025 new llvm::GlobalVariable(CGM.getModule(), SLoc->getType(), false,
1026 llvm::GlobalVariable::PrivateLinkage, SLoc);
1027 SLocPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1028 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(SLocPtr);
1029 assert(ReturnLocation.isValid() && "No valid return location");
1030 Builder.CreateStore(Builder.CreateBitCast(SLocPtr, Int8PtrTy),
1034 // Returning from an outlined SEH helper is UB, and we already warn on it.
1035 if (IsOutlinedSEHHelper) {
1036 Builder.CreateUnreachable();
1037 Builder.ClearInsertionPoint();
1040 // Emit the result value, even if unused, to evaluate the side effects.
1041 const Expr *RV = S.getRetValue();
1043 // Treat block literals in a return expression as if they appeared
1044 // in their own scope. This permits a small, easily-implemented
1045 // exception to our over-conservative rules about not jumping to
1046 // statements following block literals with non-trivial cleanups.
1047 RunCleanupsScope cleanupScope(*this);
1048 if (const FullExpr *fe = dyn_cast_or_null<FullExpr>(RV)) {
1049 enterFullExpression(fe);
1050 RV = fe->getSubExpr();
1053 // FIXME: Clean this up by using an LValue for ReturnTemp,
1054 // EmitStoreThroughLValue, and EmitAnyExpr.
1055 if (getLangOpts().ElideConstructors &&
1056 S.getNRVOCandidate() && S.getNRVOCandidate()->isNRVOVariable()) {
1057 // Apply the named return value optimization for this return statement,
1058 // which means doing nothing: the appropriate result has already been
1059 // constructed into the NRVO variable.
1061 // If there is an NRVO flag for this variable, set it to 1 into indicate
1062 // that the cleanup code should not destroy the variable.
1063 if (llvm::Value *NRVOFlag = NRVOFlags[S.getNRVOCandidate()])
1064 Builder.CreateFlagStore(Builder.getTrue(), NRVOFlag);
1065 } else if (!ReturnValue.isValid() || (RV && RV->getType()->isVoidType())) {
1066 // Make sure not to return anything, but evaluate the expression
1067 // for side effects.
1071 // Do nothing (return value is left uninitialized)
1072 } else if (FnRetTy->isReferenceType()) {
1073 // If this function returns a reference, take the address of the expression
1074 // rather than the value.
1075 RValue Result = EmitReferenceBindingToExpr(RV);
1076 Builder.CreateStore(Result.getScalarVal(), ReturnValue);
1078 switch (getEvaluationKind(RV->getType())) {
1080 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
1083 EmitComplexExprIntoLValue(RV, MakeAddrLValue(ReturnValue, RV->getType()),
1087 EmitAggExpr(RV, AggValueSlot::forAddr(
1088 ReturnValue, Qualifiers(),
1089 AggValueSlot::IsDestructed,
1090 AggValueSlot::DoesNotNeedGCBarriers,
1091 AggValueSlot::IsNotAliased,
1092 overlapForReturnValue()));
1098 if (!RV || RV->isEvaluatable(getContext()))
1099 ++NumSimpleReturnExprs;
1101 cleanupScope.ForceCleanup();
1102 EmitBranchThroughCleanup(ReturnBlock);
1105 void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
1106 // As long as debug info is modeled with instructions, we have to ensure we
1107 // have a place to insert here and write the stop point here.
1108 if (HaveInsertPoint())
1111 for (const auto *I : S.decls())
1115 void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
1116 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
1118 // If this code is reachable then emit a stop point (if generating
1119 // debug info). We have to do this ourselves because we are on the
1120 // "simple" statement path.
1121 if (HaveInsertPoint())
1124 EmitBranchThroughCleanup(BreakContinueStack.back().BreakBlock);
1127 void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
1128 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
1130 // If this code is reachable then emit a stop point (if generating
1131 // debug info). We have to do this ourselves because we are on the
1132 // "simple" statement path.
1133 if (HaveInsertPoint())
1136 EmitBranchThroughCleanup(BreakContinueStack.back().ContinueBlock);
1139 /// EmitCaseStmtRange - If case statement range is not too big then
1140 /// add multiple cases to switch instruction, one for each value within
1141 /// the range. If range is too big then emit "if" condition check.
1142 void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
1143 assert(S.getRHS() && "Expected RHS value in CaseStmt");
1145 llvm::APSInt LHS = S.getLHS()->EvaluateKnownConstInt(getContext());
1146 llvm::APSInt RHS = S.getRHS()->EvaluateKnownConstInt(getContext());
1148 // Emit the code for this case. We do this first to make sure it is
1149 // properly chained from our predecessor before generating the
1150 // switch machinery to enter this block.
1151 llvm::BasicBlock *CaseDest = createBasicBlock("sw.bb");
1152 EmitBlockWithFallThrough(CaseDest, &S);
1153 EmitStmt(S.getSubStmt());
1155 // If range is empty, do nothing.
1156 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
1159 llvm::APInt Range = RHS - LHS;
1160 // FIXME: parameters such as this should not be hardcoded.
1161 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
1162 // Range is small enough to add multiple switch instruction cases.
1163 uint64_t Total = getProfileCount(&S);
1164 unsigned NCases = Range.getZExtValue() + 1;
1165 // We only have one region counter for the entire set of cases here, so we
1166 // need to divide the weights evenly between the generated cases, ensuring
1167 // that the total weight is preserved. E.g., a weight of 5 over three cases
1168 // will be distributed as weights of 2, 2, and 1.
1169 uint64_t Weight = Total / NCases, Rem = Total % NCases;
1170 for (unsigned I = 0; I != NCases; ++I) {
1172 SwitchWeights->push_back(Weight + (Rem ? 1 : 0));
1175 SwitchInsn->addCase(Builder.getInt(LHS), CaseDest);
1181 // The range is too big. Emit "if" condition into a new block,
1182 // making sure to save and restore the current insertion point.
1183 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
1185 // Push this test onto the chain of range checks (which terminates
1186 // in the default basic block). The switch's default will be changed
1187 // to the top of this chain after switch emission is complete.
1188 llvm::BasicBlock *FalseDest = CaseRangeBlock;
1189 CaseRangeBlock = createBasicBlock("sw.caserange");
1191 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
1192 Builder.SetInsertPoint(CaseRangeBlock);
1194 // Emit range check.
1196 Builder.CreateSub(SwitchInsn->getCondition(), Builder.getInt(LHS));
1198 Builder.CreateICmpULE(Diff, Builder.getInt(Range), "inbounds");
1200 llvm::MDNode *Weights = nullptr;
1201 if (SwitchWeights) {
1202 uint64_t ThisCount = getProfileCount(&S);
1203 uint64_t DefaultCount = (*SwitchWeights)[0];
1204 Weights = createProfileWeights(ThisCount, DefaultCount);
1206 // Since we're chaining the switch default through each large case range, we
1207 // need to update the weight for the default, ie, the first case, to include
1209 (*SwitchWeights)[0] += ThisCount;
1211 Builder.CreateCondBr(Cond, CaseDest, FalseDest, Weights);
1213 // Restore the appropriate insertion point.
1215 Builder.SetInsertPoint(RestoreBB);
1217 Builder.ClearInsertionPoint();
1220 void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
1221 // If there is no enclosing switch instance that we're aware of, then this
1222 // case statement and its block can be elided. This situation only happens
1223 // when we've constant-folded the switch, are emitting the constant case,
1224 // and part of the constant case includes another case statement. For
1225 // instance: switch (4) { case 4: do { case 5: } while (1); }
1227 EmitStmt(S.getSubStmt());
1231 // Handle case ranges.
1233 EmitCaseStmtRange(S);
1237 llvm::ConstantInt *CaseVal =
1238 Builder.getInt(S.getLHS()->EvaluateKnownConstInt(getContext()));
1240 // If the body of the case is just a 'break', try to not emit an empty block.
1241 // If we're profiling or we're not optimizing, leave the block in for better
1242 // debug and coverage analysis.
1243 if (!CGM.getCodeGenOpts().hasProfileClangInstr() &&
1244 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1245 isa<BreakStmt>(S.getSubStmt())) {
1246 JumpDest Block = BreakContinueStack.back().BreakBlock;
1248 // Only do this optimization if there are no cleanups that need emitting.
1249 if (isObviouslyBranchWithoutCleanups(Block)) {
1251 SwitchWeights->push_back(getProfileCount(&S));
1252 SwitchInsn->addCase(CaseVal, Block.getBlock());
1254 // If there was a fallthrough into this case, make sure to redirect it to
1255 // the end of the switch as well.
1256 if (Builder.GetInsertBlock()) {
1257 Builder.CreateBr(Block.getBlock());
1258 Builder.ClearInsertionPoint();
1264 llvm::BasicBlock *CaseDest = createBasicBlock("sw.bb");
1265 EmitBlockWithFallThrough(CaseDest, &S);
1267 SwitchWeights->push_back(getProfileCount(&S));
1268 SwitchInsn->addCase(CaseVal, CaseDest);
1270 // Recursively emitting the statement is acceptable, but is not wonderful for
1271 // code where we have many case statements nested together, i.e.:
1275 // Handling this recursively will create a new block for each case statement
1276 // that falls through to the next case which is IR intensive. It also causes
1277 // deep recursion which can run into stack depth limitations. Handle
1278 // sequential non-range case statements specially.
1279 const CaseStmt *CurCase = &S;
1280 const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
1282 // Otherwise, iteratively add consecutive cases to this switch stmt.
1283 while (NextCase && NextCase->getRHS() == nullptr) {
1285 llvm::ConstantInt *CaseVal =
1286 Builder.getInt(CurCase->getLHS()->EvaluateKnownConstInt(getContext()));
1289 SwitchWeights->push_back(getProfileCount(NextCase));
1290 if (CGM.getCodeGenOpts().hasProfileClangInstr()) {
1291 CaseDest = createBasicBlock("sw.bb");
1292 EmitBlockWithFallThrough(CaseDest, &S);
1295 SwitchInsn->addCase(CaseVal, CaseDest);
1296 NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt());
1299 // Normal default recursion for non-cases.
1300 EmitStmt(CurCase->getSubStmt());
1303 void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
1304 // If there is no enclosing switch instance that we're aware of, then this
1305 // default statement can be elided. This situation only happens when we've
1306 // constant-folded the switch.
1308 EmitStmt(S.getSubStmt());
1312 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
1313 assert(DefaultBlock->empty() &&
1314 "EmitDefaultStmt: Default block already defined?");
1316 EmitBlockWithFallThrough(DefaultBlock, &S);
1318 EmitStmt(S.getSubStmt());
1321 /// CollectStatementsForCase - Given the body of a 'switch' statement and a
1322 /// constant value that is being switched on, see if we can dead code eliminate
1323 /// the body of the switch to a simple series of statements to emit. Basically,
1324 /// on a switch (5) we want to find these statements:
1326 /// printf(...); <--
1330 /// and add them to the ResultStmts vector. If it is unsafe to do this
1331 /// transformation (for example, one of the elided statements contains a label
1332 /// that might be jumped to), return CSFC_Failure. If we handled it and 'S'
1333 /// should include statements after it (e.g. the printf() line is a substmt of
1334 /// the case) then return CSFC_FallThrough. If we handled it and found a break
1335 /// statement, then return CSFC_Success.
1337 /// If Case is non-null, then we are looking for the specified case, checking
1338 /// that nothing we jump over contains labels. If Case is null, then we found
1339 /// the case and are looking for the break.
1341 /// If the recursive walk actually finds our Case, then we set FoundCase to
1344 enum CSFC_Result { CSFC_Failure, CSFC_FallThrough, CSFC_Success };
1345 static CSFC_Result CollectStatementsForCase(const Stmt *S,
1346 const SwitchCase *Case,
1348 SmallVectorImpl<const Stmt*> &ResultStmts) {
1349 // If this is a null statement, just succeed.
1351 return Case ? CSFC_Success : CSFC_FallThrough;
1353 // If this is the switchcase (case 4: or default) that we're looking for, then
1354 // we're in business. Just add the substatement.
1355 if (const SwitchCase *SC = dyn_cast<SwitchCase>(S)) {
1358 return CollectStatementsForCase(SC->getSubStmt(), nullptr, FoundCase,
1362 // Otherwise, this is some other case or default statement, just ignore it.
1363 return CollectStatementsForCase(SC->getSubStmt(), Case, FoundCase,
1367 // If we are in the live part of the code and we found our break statement,
1368 // return a success!
1369 if (!Case && isa<BreakStmt>(S))
1370 return CSFC_Success;
1372 // If this is a switch statement, then it might contain the SwitchCase, the
1373 // break, or neither.
1374 if (const CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
1375 // Handle this as two cases: we might be looking for the SwitchCase (if so
1376 // the skipped statements must be skippable) or we might already have it.
1377 CompoundStmt::const_body_iterator I = CS->body_begin(), E = CS->body_end();
1378 bool StartedInLiveCode = FoundCase;
1379 unsigned StartSize = ResultStmts.size();
1381 // If we've not found the case yet, scan through looking for it.
1383 // Keep track of whether we see a skipped declaration. The code could be
1384 // using the declaration even if it is skipped, so we can't optimize out
1385 // the decl if the kept statements might refer to it.
1386 bool HadSkippedDecl = false;
1388 // If we're looking for the case, just see if we can skip each of the
1390 for (; Case && I != E; ++I) {
1391 HadSkippedDecl |= CodeGenFunction::mightAddDeclToScope(*I);
1393 switch (CollectStatementsForCase(*I, Case, FoundCase, ResultStmts)) {
1394 case CSFC_Failure: return CSFC_Failure;
1396 // A successful result means that either 1) that the statement doesn't
1397 // have the case and is skippable, or 2) does contain the case value
1398 // and also contains the break to exit the switch. In the later case,
1399 // we just verify the rest of the statements are elidable.
1401 // If we found the case and skipped declarations, we can't do the
1404 return CSFC_Failure;
1406 for (++I; I != E; ++I)
1407 if (CodeGenFunction::ContainsLabel(*I, true))
1408 return CSFC_Failure;
1409 return CSFC_Success;
1412 case CSFC_FallThrough:
1413 // If we have a fallthrough condition, then we must have found the
1414 // case started to include statements. Consider the rest of the
1415 // statements in the compound statement as candidates for inclusion.
1416 assert(FoundCase && "Didn't find case but returned fallthrough?");
1417 // We recursively found Case, so we're not looking for it anymore.
1420 // If we found the case and skipped declarations, we can't do the
1423 return CSFC_Failure;
1429 return CSFC_Success;
1431 assert(!HadSkippedDecl && "fallthrough after skipping decl");
1434 // If we have statements in our range, then we know that the statements are
1435 // live and need to be added to the set of statements we're tracking.
1436 bool AnyDecls = false;
1437 for (; I != E; ++I) {
1438 AnyDecls |= CodeGenFunction::mightAddDeclToScope(*I);
1440 switch (CollectStatementsForCase(*I, nullptr, FoundCase, ResultStmts)) {
1441 case CSFC_Failure: return CSFC_Failure;
1442 case CSFC_FallThrough:
1443 // A fallthrough result means that the statement was simple and just
1444 // included in ResultStmt, keep adding them afterwards.
1447 // A successful result means that we found the break statement and
1448 // stopped statement inclusion. We just ensure that any leftover stmts
1449 // are skippable and return success ourselves.
1450 for (++I; I != E; ++I)
1451 if (CodeGenFunction::ContainsLabel(*I, true))
1452 return CSFC_Failure;
1453 return CSFC_Success;
1457 // If we're about to fall out of a scope without hitting a 'break;', we
1458 // can't perform the optimization if there were any decls in that scope
1459 // (we'd lose their end-of-lifetime).
1461 // If the entire compound statement was live, there's one more thing we
1462 // can try before giving up: emit the whole thing as a single statement.
1463 // We can do that unless the statement contains a 'break;'.
1464 // FIXME: Such a break must be at the end of a construct within this one.
1465 // We could emit this by just ignoring the BreakStmts entirely.
1466 if (StartedInLiveCode && !CodeGenFunction::containsBreak(S)) {
1467 ResultStmts.resize(StartSize);
1468 ResultStmts.push_back(S);
1470 return CSFC_Failure;
1474 return CSFC_FallThrough;
1477 // Okay, this is some other statement that we don't handle explicitly, like a
1478 // for statement or increment etc. If we are skipping over this statement,
1479 // just verify it doesn't have labels, which would make it invalid to elide.
1481 if (CodeGenFunction::ContainsLabel(S, true))
1482 return CSFC_Failure;
1483 return CSFC_Success;
1486 // Otherwise, we want to include this statement. Everything is cool with that
1487 // so long as it doesn't contain a break out of the switch we're in.
1488 if (CodeGenFunction::containsBreak(S)) return CSFC_Failure;
1490 // Otherwise, everything is great. Include the statement and tell the caller
1491 // that we fall through and include the next statement as well.
1492 ResultStmts.push_back(S);
1493 return CSFC_FallThrough;
1496 /// FindCaseStatementsForValue - Find the case statement being jumped to and
1497 /// then invoke CollectStatementsForCase to find the list of statements to emit
1498 /// for a switch on constant. See the comment above CollectStatementsForCase
1499 /// for more details.
1500 static bool FindCaseStatementsForValue(const SwitchStmt &S,
1501 const llvm::APSInt &ConstantCondValue,
1502 SmallVectorImpl<const Stmt*> &ResultStmts,
1504 const SwitchCase *&ResultCase) {
1505 // First step, find the switch case that is being branched to. We can do this
1506 // efficiently by scanning the SwitchCase list.
1507 const SwitchCase *Case = S.getSwitchCaseList();
1508 const DefaultStmt *DefaultCase = nullptr;
1510 for (; Case; Case = Case->getNextSwitchCase()) {
1511 // It's either a default or case. Just remember the default statement in
1512 // case we're not jumping to any numbered cases.
1513 if (const DefaultStmt *DS = dyn_cast<DefaultStmt>(Case)) {
1518 // Check to see if this case is the one we're looking for.
1519 const CaseStmt *CS = cast<CaseStmt>(Case);
1520 // Don't handle case ranges yet.
1521 if (CS->getRHS()) return false;
1523 // If we found our case, remember it as 'case'.
1524 if (CS->getLHS()->EvaluateKnownConstInt(C) == ConstantCondValue)
1528 // If we didn't find a matching case, we use a default if it exists, or we
1529 // elide the whole switch body!
1531 // It is safe to elide the body of the switch if it doesn't contain labels
1532 // etc. If it is safe, return successfully with an empty ResultStmts list.
1534 return !CodeGenFunction::ContainsLabel(&S);
1538 // Ok, we know which case is being jumped to, try to collect all the
1539 // statements that follow it. This can fail for a variety of reasons. Also,
1540 // check to see that the recursive walk actually found our case statement.
1541 // Insane cases like this can fail to find it in the recursive walk since we
1542 // don't handle every stmt kind:
1546 bool FoundCase = false;
1548 return CollectStatementsForCase(S.getBody(), Case, FoundCase,
1549 ResultStmts) != CSFC_Failure &&
1553 void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
1554 // Handle nested switch statements.
1555 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
1556 SmallVector<uint64_t, 16> *SavedSwitchWeights = SwitchWeights;
1557 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
1559 // See if we can constant fold the condition of the switch and therefore only
1560 // emit the live case statement (if any) of the switch.
1561 llvm::APSInt ConstantCondValue;
1562 if (ConstantFoldsToSimpleInteger(S.getCond(), ConstantCondValue)) {
1563 SmallVector<const Stmt*, 4> CaseStmts;
1564 const SwitchCase *Case = nullptr;
1565 if (FindCaseStatementsForValue(S, ConstantCondValue, CaseStmts,
1566 getContext(), Case)) {
1568 incrementProfileCounter(Case);
1569 RunCleanupsScope ExecutedScope(*this);
1572 EmitStmt(S.getInit());
1574 // Emit the condition variable if needed inside the entire cleanup scope
1575 // used by this special case for constant folded switches.
1576 if (S.getConditionVariable())
1577 EmitDecl(*S.getConditionVariable());
1579 // At this point, we are no longer "within" a switch instance, so
1580 // we can temporarily enforce this to ensure that any embedded case
1581 // statements are not emitted.
1582 SwitchInsn = nullptr;
1584 // Okay, we can dead code eliminate everything except this case. Emit the
1585 // specified series of statements and we're good.
1586 for (unsigned i = 0, e = CaseStmts.size(); i != e; ++i)
1587 EmitStmt(CaseStmts[i]);
1588 incrementProfileCounter(&S);
1590 // Now we want to restore the saved switch instance so that nested
1591 // switches continue to function properly
1592 SwitchInsn = SavedSwitchInsn;
1598 JumpDest SwitchExit = getJumpDestInCurrentScope("sw.epilog");
1600 RunCleanupsScope ConditionScope(*this);
1603 EmitStmt(S.getInit());
1605 if (S.getConditionVariable())
1606 EmitDecl(*S.getConditionVariable());
1607 llvm::Value *CondV = EmitScalarExpr(S.getCond());
1609 // Create basic block to hold stuff that comes after switch
1610 // statement. We also need to create a default block now so that
1611 // explicit case ranges tests can have a place to jump to on
1613 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
1614 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
1615 if (PGO.haveRegionCounts()) {
1616 // Walk the SwitchCase list to find how many there are.
1617 uint64_t DefaultCount = 0;
1618 unsigned NumCases = 0;
1619 for (const SwitchCase *Case = S.getSwitchCaseList();
1621 Case = Case->getNextSwitchCase()) {
1622 if (isa<DefaultStmt>(Case))
1623 DefaultCount = getProfileCount(Case);
1626 SwitchWeights = new SmallVector<uint64_t, 16>();
1627 SwitchWeights->reserve(NumCases);
1628 // The default needs to be first. We store the edge count, so we already
1629 // know the right weight.
1630 SwitchWeights->push_back(DefaultCount);
1632 CaseRangeBlock = DefaultBlock;
1634 // Clear the insertion point to indicate we are in unreachable code.
1635 Builder.ClearInsertionPoint();
1637 // All break statements jump to NextBlock. If BreakContinueStack is non-empty
1638 // then reuse last ContinueBlock.
1639 JumpDest OuterContinue;
1640 if (!BreakContinueStack.empty())
1641 OuterContinue = BreakContinueStack.back().ContinueBlock;
1643 BreakContinueStack.push_back(BreakContinue(SwitchExit, OuterContinue));
1645 // Emit switch body.
1646 EmitStmt(S.getBody());
1648 BreakContinueStack.pop_back();
1650 // Update the default block in case explicit case range tests have
1651 // been chained on top.
1652 SwitchInsn->setDefaultDest(CaseRangeBlock);
1654 // If a default was never emitted:
1655 if (!DefaultBlock->getParent()) {
1656 // If we have cleanups, emit the default block so that there's a
1657 // place to jump through the cleanups from.
1658 if (ConditionScope.requiresCleanups()) {
1659 EmitBlock(DefaultBlock);
1661 // Otherwise, just forward the default block to the switch end.
1663 DefaultBlock->replaceAllUsesWith(SwitchExit.getBlock());
1664 delete DefaultBlock;
1668 ConditionScope.ForceCleanup();
1670 // Emit continuation.
1671 EmitBlock(SwitchExit.getBlock(), true);
1672 incrementProfileCounter(&S);
1674 // If the switch has a condition wrapped by __builtin_unpredictable,
1675 // create metadata that specifies that the switch is unpredictable.
1676 // Don't bother if not optimizing because that metadata would not be used.
1677 auto *Call = dyn_cast<CallExpr>(S.getCond());
1678 if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
1679 auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
1680 if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
1681 llvm::MDBuilder MDHelper(getLLVMContext());
1682 SwitchInsn->setMetadata(llvm::LLVMContext::MD_unpredictable,
1683 MDHelper.createUnpredictable());
1687 if (SwitchWeights) {
1688 assert(SwitchWeights->size() == 1 + SwitchInsn->getNumCases() &&
1689 "switch weights do not match switch cases");
1690 // If there's only one jump destination there's no sense weighting it.
1691 if (SwitchWeights->size() > 1)
1692 SwitchInsn->setMetadata(llvm::LLVMContext::MD_prof,
1693 createProfileWeights(*SwitchWeights));
1694 delete SwitchWeights;
1696 SwitchInsn = SavedSwitchInsn;
1697 SwitchWeights = SavedSwitchWeights;
1698 CaseRangeBlock = SavedCRBlock;
1702 SimplifyConstraint(const char *Constraint, const TargetInfo &Target,
1703 SmallVectorImpl<TargetInfo::ConstraintInfo> *OutCons=nullptr) {
1706 while (*Constraint) {
1707 switch (*Constraint) {
1709 Result += Target.convertConstraint(Constraint);
1715 case '=': // Will see this and the following in mult-alt constraints.
1718 case '#': // Ignore the rest of the constraint alternative.
1719 while (Constraint[1] && Constraint[1] != ',')
1724 Result += *Constraint;
1725 while (Constraint[1] && Constraint[1] == *Constraint)
1736 "Must pass output names to constraints with a symbolic name");
1738 bool result = Target.resolveSymbolicName(Constraint, *OutCons, Index);
1739 assert(result && "Could not resolve symbolic name"); (void)result;
1740 Result += llvm::utostr(Index);
1751 /// AddVariableConstraints - Look at AsmExpr and if it is a variable declared
1752 /// as using a particular register add that as a constraint that will be used
1753 /// in this asm stmt.
1755 AddVariableConstraints(const std::string &Constraint, const Expr &AsmExpr,
1756 const TargetInfo &Target, CodeGenModule &CGM,
1757 const AsmStmt &Stmt, const bool EarlyClobber) {
1758 const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(&AsmExpr);
1761 const ValueDecl &Value = *AsmDeclRef->getDecl();
1762 const VarDecl *Variable = dyn_cast<VarDecl>(&Value);
1765 if (Variable->getStorageClass() != SC_Register)
1767 AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>();
1770 StringRef Register = Attr->getLabel();
1771 assert(Target.isValidGCCRegisterName(Register));
1772 // We're using validateOutputConstraint here because we only care if
1773 // this is a register constraint.
1774 TargetInfo::ConstraintInfo Info(Constraint, "");
1775 if (Target.validateOutputConstraint(Info) &&
1776 !Info.allowsRegister()) {
1777 CGM.ErrorUnsupported(&Stmt, "__asm__");
1780 // Canonicalize the register here before returning it.
1781 Register = Target.getNormalizedGCCRegisterName(Register);
1782 return (EarlyClobber ? "&{" : "{") + Register.str() + "}";
1786 CodeGenFunction::EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info,
1787 LValue InputValue, QualType InputType,
1788 std::string &ConstraintStr,
1789 SourceLocation Loc) {
1791 if (Info.allowsRegister() || !Info.allowsMemory()) {
1792 if (CodeGenFunction::hasScalarEvaluationKind(InputType)) {
1793 Arg = EmitLoadOfLValue(InputValue, Loc).getScalarVal();
1795 llvm::Type *Ty = ConvertType(InputType);
1796 uint64_t Size = CGM.getDataLayout().getTypeSizeInBits(Ty);
1797 if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
1798 Ty = llvm::IntegerType::get(getLLVMContext(), Size);
1799 Ty = llvm::PointerType::getUnqual(Ty);
1801 Arg = Builder.CreateLoad(Builder.CreateBitCast(InputValue.getAddress(),
1804 Arg = InputValue.getPointer();
1805 ConstraintStr += '*';
1809 Arg = InputValue.getPointer();
1810 ConstraintStr += '*';
1816 llvm::Value* CodeGenFunction::EmitAsmInput(
1817 const TargetInfo::ConstraintInfo &Info,
1818 const Expr *InputExpr,
1819 std::string &ConstraintStr) {
1820 // If this can't be a register or memory, i.e., has to be a constant
1821 // (immediate or symbolic), try to emit it as such.
1822 if (!Info.allowsRegister() && !Info.allowsMemory()) {
1823 if (Info.requiresImmediateConstant()) {
1824 Expr::EvalResult EVResult;
1825 InputExpr->EvaluateAsRValue(EVResult, getContext(), true);
1827 llvm::APSInt IntResult;
1828 if (!EVResult.Val.toIntegralConstant(IntResult, InputExpr->getType(),
1830 llvm_unreachable("Invalid immediate constant!");
1832 return llvm::ConstantInt::get(getLLVMContext(), IntResult);
1835 Expr::EvalResult Result;
1836 if (InputExpr->EvaluateAsInt(Result, getContext()))
1837 return llvm::ConstantInt::get(getLLVMContext(), Result.Val.getInt());
1840 if (Info.allowsRegister() || !Info.allowsMemory())
1841 if (CodeGenFunction::hasScalarEvaluationKind(InputExpr->getType()))
1842 return EmitScalarExpr(InputExpr);
1843 if (InputExpr->getStmtClass() == Expr::CXXThisExprClass)
1844 return EmitScalarExpr(InputExpr);
1845 InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
1846 LValue Dest = EmitLValue(InputExpr);
1847 return EmitAsmInputLValue(Info, Dest, InputExpr->getType(), ConstraintStr,
1848 InputExpr->getExprLoc());
1851 /// getAsmSrcLocInfo - Return the !srcloc metadata node to attach to an inline
1852 /// asm call instruction. The !srcloc MDNode contains a list of constant
1853 /// integers which are the source locations of the start of each line in the
1855 static llvm::MDNode *getAsmSrcLocInfo(const StringLiteral *Str,
1856 CodeGenFunction &CGF) {
1857 SmallVector<llvm::Metadata *, 8> Locs;
1858 // Add the location of the first line to the MDNode.
1859 Locs.push_back(llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1860 CGF.Int32Ty, Str->getBeginLoc().getRawEncoding())));
1861 StringRef StrVal = Str->getString();
1862 if (!StrVal.empty()) {
1863 const SourceManager &SM = CGF.CGM.getContext().getSourceManager();
1864 const LangOptions &LangOpts = CGF.CGM.getLangOpts();
1865 unsigned StartToken = 0;
1866 unsigned ByteOffset = 0;
1868 // Add the location of the start of each subsequent line of the asm to the
1870 for (unsigned i = 0, e = StrVal.size() - 1; i != e; ++i) {
1871 if (StrVal[i] != '\n') continue;
1872 SourceLocation LineLoc = Str->getLocationOfByte(
1873 i + 1, SM, LangOpts, CGF.getTarget(), &StartToken, &ByteOffset);
1874 Locs.push_back(llvm::ConstantAsMetadata::get(
1875 llvm::ConstantInt::get(CGF.Int32Ty, LineLoc.getRawEncoding())));
1879 return llvm::MDNode::get(CGF.getLLVMContext(), Locs);
1882 void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
1883 // Assemble the final asm string.
1884 std::string AsmString = S.generateAsmString(getContext());
1886 // Get all the output and input constraints together.
1887 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
1888 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
1890 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
1892 if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
1893 Name = GAS->getOutputName(i);
1894 TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i), Name);
1895 bool IsValid = getTarget().validateOutputConstraint(Info); (void)IsValid;
1896 assert(IsValid && "Failed to parse output constraint");
1897 OutputConstraintInfos.push_back(Info);
1900 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1902 if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
1903 Name = GAS->getInputName(i);
1904 TargetInfo::ConstraintInfo Info(S.getInputConstraint(i), Name);
1906 getTarget().validateInputConstraint(OutputConstraintInfos, Info);
1907 assert(IsValid && "Failed to parse input constraint"); (void)IsValid;
1908 InputConstraintInfos.push_back(Info);
1911 std::string Constraints;
1913 std::vector<LValue> ResultRegDests;
1914 std::vector<QualType> ResultRegQualTys;
1915 std::vector<llvm::Type *> ResultRegTypes;
1916 std::vector<llvm::Type *> ResultTruncRegTypes;
1917 std::vector<llvm::Type *> ArgTypes;
1918 std::vector<llvm::Value*> Args;
1920 // Keep track of inout constraints.
1921 std::string InOutConstraints;
1922 std::vector<llvm::Value*> InOutArgs;
1923 std::vector<llvm::Type*> InOutArgTypes;
1925 // An inline asm can be marked readonly if it meets the following conditions:
1926 // - it doesn't have any sideeffects
1927 // - it doesn't clobber memory
1928 // - it doesn't return a value by-reference
1929 // It can be marked readnone if it doesn't have any input memory constraints
1930 // in addition to meeting the conditions listed above.
1931 bool ReadOnly = true, ReadNone = true;
1933 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
1934 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
1936 // Simplify the output constraint.
1937 std::string OutputConstraint(S.getOutputConstraint(i));
1938 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1,
1939 getTarget(), &OutputConstraintInfos);
1941 const Expr *OutExpr = S.getOutputExpr(i);
1942 OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
1944 OutputConstraint = AddVariableConstraints(OutputConstraint, *OutExpr,
1945 getTarget(), CGM, S,
1946 Info.earlyClobber());
1948 LValue Dest = EmitLValue(OutExpr);
1949 if (!Constraints.empty())
1952 // If this is a register output, then make the inline asm return it
1953 // by-value. If this is a memory result, return the value by-reference.
1954 if (!Info.allowsMemory() && hasScalarEvaluationKind(OutExpr->getType())) {
1955 Constraints += "=" + OutputConstraint;
1956 ResultRegQualTys.push_back(OutExpr->getType());
1957 ResultRegDests.push_back(Dest);
1958 ResultRegTypes.push_back(ConvertTypeForMem(OutExpr->getType()));
1959 ResultTruncRegTypes.push_back(ResultRegTypes.back());
1961 // If this output is tied to an input, and if the input is larger, then
1962 // we need to set the actual result type of the inline asm node to be the
1963 // same as the input type.
1964 if (Info.hasMatchingInput()) {
1966 for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) {
1967 TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo];
1968 if (Input.hasTiedOperand() && Input.getTiedOperand() == i)
1971 assert(InputNo != S.getNumInputs() && "Didn't find matching input!");
1973 QualType InputTy = S.getInputExpr(InputNo)->getType();
1974 QualType OutputType = OutExpr->getType();
1976 uint64_t InputSize = getContext().getTypeSize(InputTy);
1977 if (getContext().getTypeSize(OutputType) < InputSize) {
1978 // Form the asm to return the value as a larger integer or fp type.
1979 ResultRegTypes.back() = ConvertType(InputTy);
1982 if (llvm::Type* AdjTy =
1983 getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
1984 ResultRegTypes.back()))
1985 ResultRegTypes.back() = AdjTy;
1987 CGM.getDiags().Report(S.getAsmLoc(),
1988 diag::err_asm_invalid_type_in_input)
1989 << OutExpr->getType() << OutputConstraint;
1992 // Update largest vector width for any vector types.
1993 if (auto *VT = dyn_cast<llvm::VectorType>(ResultRegTypes.back()))
1994 LargestVectorWidth = std::max(LargestVectorWidth,
1995 VT->getPrimitiveSizeInBits());
1997 ArgTypes.push_back(Dest.getAddress().getType());
1998 Args.push_back(Dest.getPointer());
1999 Constraints += "=*";
2000 Constraints += OutputConstraint;
2001 ReadOnly = ReadNone = false;
2004 if (Info.isReadWrite()) {
2005 InOutConstraints += ',';
2007 const Expr *InputExpr = S.getOutputExpr(i);
2008 llvm::Value *Arg = EmitAsmInputLValue(Info, Dest, InputExpr->getType(),
2010 InputExpr->getExprLoc());
2012 if (llvm::Type* AdjTy =
2013 getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
2015 Arg = Builder.CreateBitCast(Arg, AdjTy);
2017 // Update largest vector width for any vector types.
2018 if (auto *VT = dyn_cast<llvm::VectorType>(Arg->getType()))
2019 LargestVectorWidth = std::max(LargestVectorWidth,
2020 VT->getPrimitiveSizeInBits());
2021 if (Info.allowsRegister())
2022 InOutConstraints += llvm::utostr(i);
2024 InOutConstraints += OutputConstraint;
2026 InOutArgTypes.push_back(Arg->getType());
2027 InOutArgs.push_back(Arg);
2031 // If this is a Microsoft-style asm blob, store the return registers (EAX:EDX)
2032 // to the return value slot. Only do this when returning in registers.
2033 if (isa<MSAsmStmt>(&S)) {
2034 const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
2035 if (RetAI.isDirect() || RetAI.isExtend()) {
2036 // Make a fake lvalue for the return value slot.
2037 LValue ReturnSlot = MakeAddrLValue(ReturnValue, FnRetTy);
2038 CGM.getTargetCodeGenInfo().addReturnRegisterOutputs(
2039 *this, ReturnSlot, Constraints, ResultRegTypes, ResultTruncRegTypes,
2040 ResultRegDests, AsmString, S.getNumOutputs());
2045 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
2046 const Expr *InputExpr = S.getInputExpr(i);
2048 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
2050 if (Info.allowsMemory())
2053 if (!Constraints.empty())
2056 // Simplify the input constraint.
2057 std::string InputConstraint(S.getInputConstraint(i));
2058 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), getTarget(),
2059 &OutputConstraintInfos);
2061 InputConstraint = AddVariableConstraints(
2062 InputConstraint, *InputExpr->IgnoreParenNoopCasts(getContext()),
2063 getTarget(), CGM, S, false /* No EarlyClobber */);
2065 llvm::Value *Arg = EmitAsmInput(Info, InputExpr, Constraints);
2067 // If this input argument is tied to a larger output result, extend the
2068 // input to be the same size as the output. The LLVM backend wants to see
2069 // the input and output of a matching constraint be the same size. Note
2070 // that GCC does not define what the top bits are here. We use zext because
2071 // that is usually cheaper, but LLVM IR should really get an anyext someday.
2072 if (Info.hasTiedOperand()) {
2073 unsigned Output = Info.getTiedOperand();
2074 QualType OutputType = S.getOutputExpr(Output)->getType();
2075 QualType InputTy = InputExpr->getType();
2077 if (getContext().getTypeSize(OutputType) >
2078 getContext().getTypeSize(InputTy)) {
2079 // Use ptrtoint as appropriate so that we can do our extension.
2080 if (isa<llvm::PointerType>(Arg->getType()))
2081 Arg = Builder.CreatePtrToInt(Arg, IntPtrTy);
2082 llvm::Type *OutputTy = ConvertType(OutputType);
2083 if (isa<llvm::IntegerType>(OutputTy))
2084 Arg = Builder.CreateZExt(Arg, OutputTy);
2085 else if (isa<llvm::PointerType>(OutputTy))
2086 Arg = Builder.CreateZExt(Arg, IntPtrTy);
2088 assert(OutputTy->isFloatingPointTy() && "Unexpected output type");
2089 Arg = Builder.CreateFPExt(Arg, OutputTy);
2093 if (llvm::Type* AdjTy =
2094 getTargetHooks().adjustInlineAsmType(*this, InputConstraint,
2096 Arg = Builder.CreateBitCast(Arg, AdjTy);
2098 CGM.getDiags().Report(S.getAsmLoc(), diag::err_asm_invalid_type_in_input)
2099 << InputExpr->getType() << InputConstraint;
2101 // Update largest vector width for any vector types.
2102 if (auto *VT = dyn_cast<llvm::VectorType>(Arg->getType()))
2103 LargestVectorWidth = std::max(LargestVectorWidth,
2104 VT->getPrimitiveSizeInBits());
2106 ArgTypes.push_back(Arg->getType());
2107 Args.push_back(Arg);
2108 Constraints += InputConstraint;
2111 // Append the "input" part of inout constraints last.
2112 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
2113 ArgTypes.push_back(InOutArgTypes[i]);
2114 Args.push_back(InOutArgs[i]);
2116 Constraints += InOutConstraints;
2119 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
2120 StringRef Clobber = S.getClobber(i);
2122 if (Clobber == "memory")
2123 ReadOnly = ReadNone = false;
2124 else if (Clobber != "cc")
2125 Clobber = getTarget().getNormalizedGCCRegisterName(Clobber);
2127 if (!Constraints.empty())
2130 Constraints += "~{";
2131 Constraints += Clobber;
2135 // Add machine specific clobbers
2136 std::string MachineClobbers = getTarget().getClobbers();
2137 if (!MachineClobbers.empty()) {
2138 if (!Constraints.empty())
2140 Constraints += MachineClobbers;
2143 llvm::Type *ResultType;
2144 if (ResultRegTypes.empty())
2145 ResultType = VoidTy;
2146 else if (ResultRegTypes.size() == 1)
2147 ResultType = ResultRegTypes[0];
2149 ResultType = llvm::StructType::get(getLLVMContext(), ResultRegTypes);
2151 llvm::FunctionType *FTy =
2152 llvm::FunctionType::get(ResultType, ArgTypes, false);
2154 bool HasSideEffect = S.isVolatile() || S.getNumOutputs() == 0;
2155 llvm::InlineAsm::AsmDialect AsmDialect = isa<MSAsmStmt>(&S) ?
2156 llvm::InlineAsm::AD_Intel : llvm::InlineAsm::AD_ATT;
2157 llvm::InlineAsm *IA =
2158 llvm::InlineAsm::get(FTy, AsmString, Constraints, HasSideEffect,
2159 /* IsAlignStack */ false, AsmDialect);
2160 llvm::CallInst *Result =
2161 Builder.CreateCall(IA, Args, getBundlesForFunclet(IA));
2162 Result->addAttribute(llvm::AttributeList::FunctionIndex,
2163 llvm::Attribute::NoUnwind);
2165 // Attach readnone and readonly attributes.
2166 if (!HasSideEffect) {
2168 Result->addAttribute(llvm::AttributeList::FunctionIndex,
2169 llvm::Attribute::ReadNone);
2171 Result->addAttribute(llvm::AttributeList::FunctionIndex,
2172 llvm::Attribute::ReadOnly);
2175 // Slap the source location of the inline asm into a !srcloc metadata on the
2177 if (const GCCAsmStmt *gccAsmStmt = dyn_cast<GCCAsmStmt>(&S)) {
2178 Result->setMetadata("srcloc", getAsmSrcLocInfo(gccAsmStmt->getAsmString(),
2181 // At least put the line number on MS inline asm blobs.
2182 auto Loc = llvm::ConstantInt::get(Int32Ty, S.getAsmLoc().getRawEncoding());
2183 Result->setMetadata("srcloc",
2184 llvm::MDNode::get(getLLVMContext(),
2185 llvm::ConstantAsMetadata::get(Loc)));
2188 if (getLangOpts().assumeFunctionsAreConvergent()) {
2189 // Conservatively, mark all inline asm blocks in CUDA or OpenCL as
2190 // convergent (meaning, they may call an intrinsically convergent op, such
2191 // as bar.sync, and so can't have certain optimizations applied around
2193 Result->addAttribute(llvm::AttributeList::FunctionIndex,
2194 llvm::Attribute::Convergent);
2197 // Extract all of the register value results from the asm.
2198 std::vector<llvm::Value*> RegResults;
2199 if (ResultRegTypes.size() == 1) {
2200 RegResults.push_back(Result);
2202 for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) {
2203 llvm::Value *Tmp = Builder.CreateExtractValue(Result, i, "asmresult");
2204 RegResults.push_back(Tmp);
2208 assert(RegResults.size() == ResultRegTypes.size());
2209 assert(RegResults.size() == ResultTruncRegTypes.size());
2210 assert(RegResults.size() == ResultRegDests.size());
2211 for (unsigned i = 0, e = RegResults.size(); i != e; ++i) {
2212 llvm::Value *Tmp = RegResults[i];
2214 // If the result type of the LLVM IR asm doesn't match the result type of
2215 // the expression, do the conversion.
2216 if (ResultRegTypes[i] != ResultTruncRegTypes[i]) {
2217 llvm::Type *TruncTy = ResultTruncRegTypes[i];
2219 // Truncate the integer result to the right size, note that TruncTy can be
2221 if (TruncTy->isFloatingPointTy())
2222 Tmp = Builder.CreateFPTrunc(Tmp, TruncTy);
2223 else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) {
2224 uint64_t ResSize = CGM.getDataLayout().getTypeSizeInBits(TruncTy);
2225 Tmp = Builder.CreateTrunc(Tmp,
2226 llvm::IntegerType::get(getLLVMContext(), (unsigned)ResSize));
2227 Tmp = Builder.CreateIntToPtr(Tmp, TruncTy);
2228 } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) {
2229 uint64_t TmpSize =CGM.getDataLayout().getTypeSizeInBits(Tmp->getType());
2230 Tmp = Builder.CreatePtrToInt(Tmp,
2231 llvm::IntegerType::get(getLLVMContext(), (unsigned)TmpSize));
2232 Tmp = Builder.CreateTrunc(Tmp, TruncTy);
2233 } else if (TruncTy->isIntegerTy()) {
2234 Tmp = Builder.CreateZExtOrTrunc(Tmp, TruncTy);
2235 } else if (TruncTy->isVectorTy()) {
2236 Tmp = Builder.CreateBitCast(Tmp, TruncTy);
2240 EmitStoreThroughLValue(RValue::get(Tmp), ResultRegDests[i]);
2244 LValue CodeGenFunction::InitCapturedStruct(const CapturedStmt &S) {
2245 const RecordDecl *RD = S.getCapturedRecordDecl();
2246 QualType RecordTy = getContext().getRecordType(RD);
2248 // Initialize the captured struct.
2250 MakeAddrLValue(CreateMemTemp(RecordTy, "agg.captured"), RecordTy);
2252 RecordDecl::field_iterator CurField = RD->field_begin();
2253 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
2254 E = S.capture_init_end();
2255 I != E; ++I, ++CurField) {
2256 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
2257 if (CurField->hasCapturedVLAType()) {
2258 auto VAT = CurField->getCapturedVLAType();
2259 EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
2261 EmitInitializerForField(*CurField, LV, *I);
2268 /// Generate an outlined function for the body of a CapturedStmt, store any
2269 /// captured variables into the captured struct, and call the outlined function.
2271 CodeGenFunction::EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K) {
2272 LValue CapStruct = InitCapturedStruct(S);
2274 // Emit the CapturedDecl
2275 CodeGenFunction CGF(CGM, true);
2276 CGCapturedStmtRAII CapInfoRAII(CGF, new CGCapturedStmtInfo(S, K));
2277 llvm::Function *F = CGF.GenerateCapturedStmtFunction(S);
2278 delete CGF.CapturedStmtInfo;
2280 // Emit call to the helper function.
2281 EmitCallOrInvoke(F, CapStruct.getPointer());
2286 Address CodeGenFunction::GenerateCapturedStmtArgument(const CapturedStmt &S) {
2287 LValue CapStruct = InitCapturedStruct(S);
2288 return CapStruct.getAddress();
2291 /// Creates the outlined function for a CapturedStmt.
2293 CodeGenFunction::GenerateCapturedStmtFunction(const CapturedStmt &S) {
2294 assert(CapturedStmtInfo &&
2295 "CapturedStmtInfo should be set when generating the captured function");
2296 const CapturedDecl *CD = S.getCapturedDecl();
2297 const RecordDecl *RD = S.getCapturedRecordDecl();
2298 SourceLocation Loc = S.getBeginLoc();
2299 assert(CD->hasBody() && "missing CapturedDecl body");
2301 // Build the argument list.
2302 ASTContext &Ctx = CGM.getContext();
2303 FunctionArgList Args;
2304 Args.append(CD->param_begin(), CD->param_end());
2306 // Create the function declaration.
2307 const CGFunctionInfo &FuncInfo =
2308 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Args);
2309 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
2312 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
2313 CapturedStmtInfo->getHelperName(), &CGM.getModule());
2314 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
2315 if (CD->isNothrow())
2316 F->addFnAttr(llvm::Attribute::NoUnwind);
2318 // Generate the function.
2319 StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args, CD->getLocation(),
2320 CD->getBody()->getBeginLoc());
2321 // Set the context parameter in CapturedStmtInfo.
2322 Address DeclPtr = GetAddrOfLocalVar(CD->getContextParam());
2323 CapturedStmtInfo->setContextValue(Builder.CreateLoad(DeclPtr));
2325 // Initialize variable-length arrays.
2326 LValue Base = MakeNaturalAlignAddrLValue(CapturedStmtInfo->getContextValue(),
2327 Ctx.getTagDeclType(RD));
2328 for (auto *FD : RD->fields()) {
2329 if (FD->hasCapturedVLAType()) {
2331 EmitLoadOfLValue(EmitLValueForField(Base, FD), S.getBeginLoc())
2333 auto VAT = FD->getCapturedVLAType();
2334 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
2338 // If 'this' is captured, load it into CXXThisValue.
2339 if (CapturedStmtInfo->isCXXThisExprCaptured()) {
2340 FieldDecl *FD = CapturedStmtInfo->getThisFieldDecl();
2341 LValue ThisLValue = EmitLValueForField(Base, FD);
2342 CXXThisValue = EmitLoadOfLValue(ThisLValue, Loc).getScalarVal();
2345 PGO.assignRegionCounters(GlobalDecl(CD), F);
2346 CapturedStmtInfo->EmitBody(*this, CD->getBody());
2347 FinishFunction(CD->getBodyRBrace());