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 "clang/Sema/LoopHint.h"
23 #include "clang/Sema/SemaDiagnostic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/IR/CallSite.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/InlineAsm.h"
28 #include "llvm/IR/Intrinsics.h"
29 #include "llvm/IR/MDBuilder.h"
31 using namespace clang;
32 using namespace CodeGen;
34 //===----------------------------------------------------------------------===//
36 //===----------------------------------------------------------------------===//
38 void CodeGenFunction::EmitStopPoint(const Stmt *S) {
39 if (CGDebugInfo *DI = getDebugInfo()) {
41 Loc = S->getLocStart();
42 DI->EmitLocation(Builder, Loc);
48 void CodeGenFunction::EmitStmt(const Stmt *S) {
49 assert(S && "Null statement?");
50 PGO.setCurrentStmt(S);
52 // These statements have their own debug info handling.
53 if (EmitSimpleStmt(S))
56 // Check if we are generating unreachable code.
57 if (!HaveInsertPoint()) {
58 // If so, and the statement doesn't contain a label, then we do not need to
59 // generate actual code. This is safe because (1) the current point is
60 // unreachable, so we don't need to execute the code, and (2) we've already
61 // handled the statements which update internal data structures (like the
62 // local variable map) which could be used by subsequent statements.
63 if (!ContainsLabel(S)) {
64 // Verify that any decl statements were handled as simple, they may be in
65 // scope of subsequent reachable statements.
66 assert(!isa<DeclStmt>(*S) && "Unexpected DeclStmt!");
70 // Otherwise, make a new block to hold the code.
74 // Generate a stoppoint if we are emitting debug info.
77 switch (S->getStmtClass()) {
78 case Stmt::NoStmtClass:
79 case Stmt::CXXCatchStmtClass:
80 case Stmt::SEHExceptStmtClass:
81 case Stmt::SEHFinallyStmtClass:
82 case Stmt::MSDependentExistsStmtClass:
83 llvm_unreachable("invalid statement class to emit generically");
84 case Stmt::NullStmtClass:
85 case Stmt::CompoundStmtClass:
86 case Stmt::DeclStmtClass:
87 case Stmt::LabelStmtClass:
88 case Stmt::AttributedStmtClass:
89 case Stmt::GotoStmtClass:
90 case Stmt::BreakStmtClass:
91 case Stmt::ContinueStmtClass:
92 case Stmt::DefaultStmtClass:
93 case Stmt::CaseStmtClass:
94 case Stmt::SEHLeaveStmtClass:
95 llvm_unreachable("should have emitted these statements as simple");
97 #define STMT(Type, Base)
98 #define ABSTRACT_STMT(Op)
99 #define EXPR(Type, Base) \
100 case Stmt::Type##Class:
101 #include "clang/AST/StmtNodes.inc"
103 // Remember the block we came in on.
104 llvm::BasicBlock *incoming = Builder.GetInsertBlock();
105 assert(incoming && "expression emission must have an insertion point");
107 EmitIgnoredExpr(cast<Expr>(S));
109 llvm::BasicBlock *outgoing = Builder.GetInsertBlock();
110 assert(outgoing && "expression emission cleared block!");
112 // The expression emitters assume (reasonably!) that the insertion
113 // point is always set. To maintain that, the call-emission code
114 // for noreturn functions has to enter a new block with no
115 // predecessors. We want to kill that block and mark the current
116 // insertion point unreachable in the common case of a call like
117 // "exit();". Since expression emission doesn't otherwise create
118 // blocks with no predecessors, we can just test for that.
119 // However, we must be careful not to do this to our incoming
120 // block, because *statement* emission does sometimes create
121 // reachable blocks which will have no predecessors until later in
122 // the function. This occurs with, e.g., labels that are not
123 // reachable by fallthrough.
124 if (incoming != outgoing && outgoing->use_empty()) {
125 outgoing->eraseFromParent();
126 Builder.ClearInsertionPoint();
131 case Stmt::IndirectGotoStmtClass:
132 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
134 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
135 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break;
136 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break;
137 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break;
139 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
141 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
142 case Stmt::GCCAsmStmtClass: // Intentional fall-through.
143 case Stmt::MSAsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
144 case Stmt::CoroutineBodyStmtClass:
145 EmitCoroutineBody(cast<CoroutineBodyStmt>(*S));
147 case Stmt::CoreturnStmtClass:
148 CGM.ErrorUnsupported(S, "coroutine");
150 case Stmt::CapturedStmtClass: {
151 const CapturedStmt *CS = cast<CapturedStmt>(S);
152 EmitCapturedStmt(*CS, CS->getCapturedRegionKind());
155 case Stmt::ObjCAtTryStmtClass:
156 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
158 case Stmt::ObjCAtCatchStmtClass:
160 "@catch statements should be handled by EmitObjCAtTryStmt");
161 case Stmt::ObjCAtFinallyStmtClass:
163 "@finally statements should be handled by EmitObjCAtTryStmt");
164 case Stmt::ObjCAtThrowStmtClass:
165 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
167 case Stmt::ObjCAtSynchronizedStmtClass:
168 EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
170 case Stmt::ObjCForCollectionStmtClass:
171 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
173 case Stmt::ObjCAutoreleasePoolStmtClass:
174 EmitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(*S));
177 case Stmt::CXXTryStmtClass:
178 EmitCXXTryStmt(cast<CXXTryStmt>(*S));
180 case Stmt::CXXForRangeStmtClass:
181 EmitCXXForRangeStmt(cast<CXXForRangeStmt>(*S));
183 case Stmt::SEHTryStmtClass:
184 EmitSEHTryStmt(cast<SEHTryStmt>(*S));
186 case Stmt::OMPParallelDirectiveClass:
187 EmitOMPParallelDirective(cast<OMPParallelDirective>(*S));
189 case Stmt::OMPSimdDirectiveClass:
190 EmitOMPSimdDirective(cast<OMPSimdDirective>(*S));
192 case Stmt::OMPForDirectiveClass:
193 EmitOMPForDirective(cast<OMPForDirective>(*S));
195 case Stmt::OMPForSimdDirectiveClass:
196 EmitOMPForSimdDirective(cast<OMPForSimdDirective>(*S));
198 case Stmt::OMPSectionsDirectiveClass:
199 EmitOMPSectionsDirective(cast<OMPSectionsDirective>(*S));
201 case Stmt::OMPSectionDirectiveClass:
202 EmitOMPSectionDirective(cast<OMPSectionDirective>(*S));
204 case Stmt::OMPSingleDirectiveClass:
205 EmitOMPSingleDirective(cast<OMPSingleDirective>(*S));
207 case Stmt::OMPMasterDirectiveClass:
208 EmitOMPMasterDirective(cast<OMPMasterDirective>(*S));
210 case Stmt::OMPCriticalDirectiveClass:
211 EmitOMPCriticalDirective(cast<OMPCriticalDirective>(*S));
213 case Stmt::OMPParallelForDirectiveClass:
214 EmitOMPParallelForDirective(cast<OMPParallelForDirective>(*S));
216 case Stmt::OMPParallelForSimdDirectiveClass:
217 EmitOMPParallelForSimdDirective(cast<OMPParallelForSimdDirective>(*S));
219 case Stmt::OMPParallelSectionsDirectiveClass:
220 EmitOMPParallelSectionsDirective(cast<OMPParallelSectionsDirective>(*S));
222 case Stmt::OMPTaskDirectiveClass:
223 EmitOMPTaskDirective(cast<OMPTaskDirective>(*S));
225 case Stmt::OMPTaskyieldDirectiveClass:
226 EmitOMPTaskyieldDirective(cast<OMPTaskyieldDirective>(*S));
228 case Stmt::OMPBarrierDirectiveClass:
229 EmitOMPBarrierDirective(cast<OMPBarrierDirective>(*S));
231 case Stmt::OMPTaskwaitDirectiveClass:
232 EmitOMPTaskwaitDirective(cast<OMPTaskwaitDirective>(*S));
234 case Stmt::OMPTaskgroupDirectiveClass:
235 EmitOMPTaskgroupDirective(cast<OMPTaskgroupDirective>(*S));
237 case Stmt::OMPFlushDirectiveClass:
238 EmitOMPFlushDirective(cast<OMPFlushDirective>(*S));
240 case Stmt::OMPOrderedDirectiveClass:
241 EmitOMPOrderedDirective(cast<OMPOrderedDirective>(*S));
243 case Stmt::OMPAtomicDirectiveClass:
244 EmitOMPAtomicDirective(cast<OMPAtomicDirective>(*S));
246 case Stmt::OMPTargetDirectiveClass:
247 EmitOMPTargetDirective(cast<OMPTargetDirective>(*S));
249 case Stmt::OMPTeamsDirectiveClass:
250 EmitOMPTeamsDirective(cast<OMPTeamsDirective>(*S));
252 case Stmt::OMPCancellationPointDirectiveClass:
253 EmitOMPCancellationPointDirective(cast<OMPCancellationPointDirective>(*S));
255 case Stmt::OMPCancelDirectiveClass:
256 EmitOMPCancelDirective(cast<OMPCancelDirective>(*S));
258 case Stmt::OMPTargetDataDirectiveClass:
259 EmitOMPTargetDataDirective(cast<OMPTargetDataDirective>(*S));
261 case Stmt::OMPTargetEnterDataDirectiveClass:
262 EmitOMPTargetEnterDataDirective(cast<OMPTargetEnterDataDirective>(*S));
264 case Stmt::OMPTargetExitDataDirectiveClass:
265 EmitOMPTargetExitDataDirective(cast<OMPTargetExitDataDirective>(*S));
267 case Stmt::OMPTargetParallelDirectiveClass:
268 EmitOMPTargetParallelDirective(cast<OMPTargetParallelDirective>(*S));
270 case Stmt::OMPTargetParallelForDirectiveClass:
271 EmitOMPTargetParallelForDirective(cast<OMPTargetParallelForDirective>(*S));
273 case Stmt::OMPTaskLoopDirectiveClass:
274 EmitOMPTaskLoopDirective(cast<OMPTaskLoopDirective>(*S));
276 case Stmt::OMPTaskLoopSimdDirectiveClass:
277 EmitOMPTaskLoopSimdDirective(cast<OMPTaskLoopSimdDirective>(*S));
279 case Stmt::OMPDistributeDirectiveClass:
280 EmitOMPDistributeDirective(cast<OMPDistributeDirective>(*S));
282 case Stmt::OMPTargetUpdateDirectiveClass:
283 EmitOMPTargetUpdateDirective(cast<OMPTargetUpdateDirective>(*S));
285 case Stmt::OMPDistributeParallelForDirectiveClass:
286 EmitOMPDistributeParallelForDirective(
287 cast<OMPDistributeParallelForDirective>(*S));
289 case Stmt::OMPDistributeParallelForSimdDirectiveClass:
290 EmitOMPDistributeParallelForSimdDirective(
291 cast<OMPDistributeParallelForSimdDirective>(*S));
293 case Stmt::OMPDistributeSimdDirectiveClass:
294 EmitOMPDistributeSimdDirective(cast<OMPDistributeSimdDirective>(*S));
296 case Stmt::OMPTargetParallelForSimdDirectiveClass:
297 EmitOMPTargetParallelForSimdDirective(
298 cast<OMPTargetParallelForSimdDirective>(*S));
300 case Stmt::OMPTargetSimdDirectiveClass:
301 EmitOMPTargetSimdDirective(cast<OMPTargetSimdDirective>(*S));
303 case Stmt::OMPTeamsDistributeDirectiveClass:
304 EmitOMPTeamsDistributeDirective(cast<OMPTeamsDistributeDirective>(*S));
306 case Stmt::OMPTeamsDistributeSimdDirectiveClass:
307 EmitOMPTeamsDistributeSimdDirective(
308 cast<OMPTeamsDistributeSimdDirective>(*S));
310 case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass:
311 EmitOMPTeamsDistributeParallelForSimdDirective(
312 cast<OMPTeamsDistributeParallelForSimdDirective>(*S));
314 case Stmt::OMPTeamsDistributeParallelForDirectiveClass:
315 EmitOMPTeamsDistributeParallelForDirective(
316 cast<OMPTeamsDistributeParallelForDirective>(*S));
318 case Stmt::OMPTargetTeamsDirectiveClass:
319 EmitOMPTargetTeamsDirective(cast<OMPTargetTeamsDirective>(*S));
321 case Stmt::OMPTargetTeamsDistributeDirectiveClass:
322 EmitOMPTargetTeamsDistributeDirective(
323 cast<OMPTargetTeamsDistributeDirective>(*S));
325 case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass:
326 EmitOMPTargetTeamsDistributeParallelForDirective(
327 cast<OMPTargetTeamsDistributeParallelForDirective>(*S));
332 bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
333 switch (S->getStmtClass()) {
334 default: return false;
335 case Stmt::NullStmtClass: break;
336 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
337 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
338 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
339 case Stmt::AttributedStmtClass:
340 EmitAttributedStmt(cast<AttributedStmt>(*S)); break;
341 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
342 case Stmt::BreakStmtClass: EmitBreakStmt(cast<BreakStmt>(*S)); break;
343 case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
344 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
345 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
346 case Stmt::SEHLeaveStmtClass: EmitSEHLeaveStmt(cast<SEHLeaveStmt>(*S)); break;
352 /// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
353 /// this captures the expression result of the last sub-statement and returns it
354 /// (for use by the statement expression extension).
355 Address CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
356 AggValueSlot AggSlot) {
357 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(),
358 "LLVM IR generation of compound statement ('{}')");
360 // Keep track of the current cleanup stack depth, including debug scopes.
361 LexicalScope Scope(*this, S.getSourceRange());
363 return EmitCompoundStmtWithoutScope(S, GetLast, AggSlot);
367 CodeGenFunction::EmitCompoundStmtWithoutScope(const CompoundStmt &S,
369 AggValueSlot AggSlot) {
371 for (CompoundStmt::const_body_iterator I = S.body_begin(),
372 E = S.body_end()-GetLast; I != E; ++I)
375 Address RetAlloca = Address::invalid();
377 // We have to special case labels here. They are statements, but when put
378 // at the end of a statement expression, they yield the value of their
379 // subexpression. Handle this by walking through all labels we encounter,
380 // emitting them before we evaluate the subexpr.
381 const Stmt *LastStmt = S.body_back();
382 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
383 EmitLabel(LS->getDecl());
384 LastStmt = LS->getSubStmt();
389 QualType ExprTy = cast<Expr>(LastStmt)->getType();
390 if (hasAggregateEvaluationKind(ExprTy)) {
391 EmitAggExpr(cast<Expr>(LastStmt), AggSlot);
393 // We can't return an RValue here because there might be cleanups at
394 // the end of the StmtExpr. Because of that, we have to emit the result
395 // here into a temporary alloca.
396 RetAlloca = CreateMemTemp(ExprTy);
397 EmitAnyExprToMem(cast<Expr>(LastStmt), RetAlloca, Qualifiers(),
406 void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) {
407 llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(BB->getTerminator());
409 // If there is a cleanup stack, then we it isn't worth trying to
410 // simplify this block (we would need to remove it from the scope map
411 // and cleanup entry).
412 if (!EHStack.empty())
415 // Can only simplify direct branches.
416 if (!BI || !BI->isUnconditional())
419 // Can only simplify empty blocks.
420 if (BI->getIterator() != BB->begin())
423 BB->replaceAllUsesWith(BI->getSuccessor(0));
424 BI->eraseFromParent();
425 BB->eraseFromParent();
428 void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
429 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
431 // Fall out of the current block (if necessary).
434 if (IsFinished && BB->use_empty()) {
439 // Place the block after the current block, if possible, or else at
440 // the end of the function.
441 if (CurBB && CurBB->getParent())
442 CurFn->getBasicBlockList().insertAfter(CurBB->getIterator(), BB);
444 CurFn->getBasicBlockList().push_back(BB);
445 Builder.SetInsertPoint(BB);
448 void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
449 // Emit a branch from the current block to the target one if this
450 // was a real block. If this was just a fall-through block after a
451 // terminator, don't emit it.
452 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
454 if (!CurBB || CurBB->getTerminator()) {
455 // If there is no insert point or the previous block is already
456 // terminated, don't touch it.
458 // Otherwise, create a fall-through branch.
459 Builder.CreateBr(Target);
462 Builder.ClearInsertionPoint();
465 void CodeGenFunction::EmitBlockAfterUses(llvm::BasicBlock *block) {
466 bool inserted = false;
467 for (llvm::User *u : block->users()) {
468 if (llvm::Instruction *insn = dyn_cast<llvm::Instruction>(u)) {
469 CurFn->getBasicBlockList().insertAfter(insn->getParent()->getIterator(),
477 CurFn->getBasicBlockList().push_back(block);
479 Builder.SetInsertPoint(block);
482 CodeGenFunction::JumpDest
483 CodeGenFunction::getJumpDestForLabel(const LabelDecl *D) {
484 JumpDest &Dest = LabelMap[D];
485 if (Dest.isValid()) return Dest;
487 // Create, but don't insert, the new block.
488 Dest = JumpDest(createBasicBlock(D->getName()),
489 EHScopeStack::stable_iterator::invalid(),
490 NextCleanupDestIndex++);
494 void CodeGenFunction::EmitLabel(const LabelDecl *D) {
495 // Add this label to the current lexical scope if we're within any
496 // normal cleanups. Jumps "in" to this label --- when permitted by
497 // the language --- may need to be routed around such cleanups.
498 if (EHStack.hasNormalCleanups() && CurLexicalScope)
499 CurLexicalScope->addLabel(D);
501 JumpDest &Dest = LabelMap[D];
503 // If we didn't need a forward reference to this label, just go
504 // ahead and create a destination at the current scope.
505 if (!Dest.isValid()) {
506 Dest = getJumpDestInCurrentScope(D->getName());
508 // Otherwise, we need to give this label a target depth and remove
509 // it from the branch-fixups list.
511 assert(!Dest.getScopeDepth().isValid() && "already emitted label!");
512 Dest.setScopeDepth(EHStack.stable_begin());
513 ResolveBranchFixups(Dest.getBlock());
516 EmitBlock(Dest.getBlock());
517 incrementProfileCounter(D->getStmt());
520 /// Change the cleanup scope of the labels in this lexical scope to
521 /// match the scope of the enclosing context.
522 void CodeGenFunction::LexicalScope::rescopeLabels() {
523 assert(!Labels.empty());
524 EHScopeStack::stable_iterator innermostScope
525 = CGF.EHStack.getInnermostNormalCleanup();
527 // Change the scope depth of all the labels.
528 for (SmallVectorImpl<const LabelDecl*>::const_iterator
529 i = Labels.begin(), e = Labels.end(); i != e; ++i) {
530 assert(CGF.LabelMap.count(*i));
531 JumpDest &dest = CGF.LabelMap.find(*i)->second;
532 assert(dest.getScopeDepth().isValid());
533 assert(innermostScope.encloses(dest.getScopeDepth()));
534 dest.setScopeDepth(innermostScope);
537 // Reparent the labels if the new scope also has cleanups.
538 if (innermostScope != EHScopeStack::stable_end() && ParentScope) {
539 ParentScope->Labels.append(Labels.begin(), Labels.end());
544 void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
545 EmitLabel(S.getDecl());
546 EmitStmt(S.getSubStmt());
549 void CodeGenFunction::EmitAttributedStmt(const AttributedStmt &S) {
550 const Stmt *SubStmt = S.getSubStmt();
551 switch (SubStmt->getStmtClass()) {
552 case Stmt::DoStmtClass:
553 EmitDoStmt(cast<DoStmt>(*SubStmt), S.getAttrs());
555 case Stmt::ForStmtClass:
556 EmitForStmt(cast<ForStmt>(*SubStmt), S.getAttrs());
558 case Stmt::WhileStmtClass:
559 EmitWhileStmt(cast<WhileStmt>(*SubStmt), S.getAttrs());
561 case Stmt::CXXForRangeStmtClass:
562 EmitCXXForRangeStmt(cast<CXXForRangeStmt>(*SubStmt), S.getAttrs());
569 void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
570 // If this code is reachable then emit a stop point (if generating
571 // debug info). We have to do this ourselves because we are on the
572 // "simple" statement path.
573 if (HaveInsertPoint())
576 EmitBranchThroughCleanup(getJumpDestForLabel(S.getLabel()));
580 void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
581 if (const LabelDecl *Target = S.getConstantTarget()) {
582 EmitBranchThroughCleanup(getJumpDestForLabel(Target));
586 // Ensure that we have an i8* for our PHI node.
587 llvm::Value *V = Builder.CreateBitCast(EmitScalarExpr(S.getTarget()),
589 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
591 // Get the basic block for the indirect goto.
592 llvm::BasicBlock *IndGotoBB = GetIndirectGotoBlock();
594 // The first instruction in the block has to be the PHI for the switch dest,
595 // add an entry for this branch.
596 cast<llvm::PHINode>(IndGotoBB->begin())->addIncoming(V, CurBB);
598 EmitBranch(IndGotoBB);
601 void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
602 // C99 6.8.4.1: The first substatement is executed if the expression compares
603 // unequal to 0. The condition must be a scalar type.
604 LexicalScope ConditionScope(*this, S.getCond()->getSourceRange());
607 EmitStmt(S.getInit());
609 if (S.getConditionVariable())
610 EmitAutoVarDecl(*S.getConditionVariable());
612 // If the condition constant folds and can be elided, try to avoid emitting
613 // the condition and the dead arm of the if/else.
615 if (ConstantFoldsToSimpleInteger(S.getCond(), CondConstant,
617 // Figure out which block (then or else) is executed.
618 const Stmt *Executed = S.getThen();
619 const Stmt *Skipped = S.getElse();
620 if (!CondConstant) // Condition false?
621 std::swap(Executed, Skipped);
623 // If the skipped block has no labels in it, just emit the executed block.
624 // This avoids emitting dead code and simplifies the CFG substantially.
625 if (S.isConstexpr() || !ContainsLabel(Skipped)) {
627 incrementProfileCounter(&S);
629 RunCleanupsScope ExecutedScope(*this);
636 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
637 // the conditional branch.
638 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
639 llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
640 llvm::BasicBlock *ElseBlock = ContBlock;
642 ElseBlock = createBasicBlock("if.else");
644 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock,
645 getProfileCount(S.getThen()));
647 // Emit the 'then' code.
648 EmitBlock(ThenBlock);
649 incrementProfileCounter(&S);
651 RunCleanupsScope ThenScope(*this);
652 EmitStmt(S.getThen());
654 EmitBranch(ContBlock);
656 // Emit the 'else' code if present.
657 if (const Stmt *Else = S.getElse()) {
659 // There is no need to emit line number for an unconditional branch.
660 auto NL = ApplyDebugLocation::CreateEmpty(*this);
661 EmitBlock(ElseBlock);
664 RunCleanupsScope ElseScope(*this);
668 // There is no need to emit line number for an unconditional branch.
669 auto NL = ApplyDebugLocation::CreateEmpty(*this);
670 EmitBranch(ContBlock);
674 // Emit the continuation block for code after the if.
675 EmitBlock(ContBlock, true);
678 void CodeGenFunction::EmitWhileStmt(const WhileStmt &S,
679 ArrayRef<const Attr *> WhileAttrs) {
680 // Emit the header for the loop, which will also become
681 // the continue target.
682 JumpDest LoopHeader = getJumpDestInCurrentScope("while.cond");
683 EmitBlock(LoopHeader.getBlock());
685 const SourceRange &R = S.getSourceRange();
686 LoopStack.push(LoopHeader.getBlock(), CGM.getContext(), WhileAttrs,
687 SourceLocToDebugLoc(R.getBegin()),
688 SourceLocToDebugLoc(R.getEnd()));
690 // Create an exit block for when the condition fails, which will
691 // also become the break target.
692 JumpDest LoopExit = getJumpDestInCurrentScope("while.end");
694 // Store the blocks to use for break and continue.
695 BreakContinueStack.push_back(BreakContinue(LoopExit, LoopHeader));
697 // C++ [stmt.while]p2:
698 // When the condition of a while statement is a declaration, the
699 // scope of the variable that is declared extends from its point
700 // of declaration (3.3.2) to the end of the while statement.
702 // The object created in a condition is destroyed and created
703 // with each iteration of the loop.
704 RunCleanupsScope ConditionScope(*this);
706 if (S.getConditionVariable())
707 EmitAutoVarDecl(*S.getConditionVariable());
709 // Evaluate the conditional in the while header. C99 6.8.5.1: The
710 // evaluation of the controlling expression takes place before each
711 // execution of the loop body.
712 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
714 // while(1) is common, avoid extra exit blocks. Be sure
715 // to correctly handle break/continue though.
716 bool EmitBoolCondBranch = true;
717 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
719 EmitBoolCondBranch = false;
721 // As long as the condition is true, go to the loop body.
722 llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
723 if (EmitBoolCondBranch) {
724 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
725 if (ConditionScope.requiresCleanups())
726 ExitBlock = createBasicBlock("while.exit");
727 Builder.CreateCondBr(
728 BoolCondVal, LoopBody, ExitBlock,
729 createProfileWeightsForLoop(S.getCond(), getProfileCount(S.getBody())));
731 if (ExitBlock != LoopExit.getBlock()) {
732 EmitBlock(ExitBlock);
733 EmitBranchThroughCleanup(LoopExit);
737 // Emit the loop body. We have to emit this in a cleanup scope
738 // because it might be a singleton DeclStmt.
740 RunCleanupsScope BodyScope(*this);
742 incrementProfileCounter(&S);
743 EmitStmt(S.getBody());
746 BreakContinueStack.pop_back();
748 // Immediately force cleanup.
749 ConditionScope.ForceCleanup();
752 // Branch to the loop header again.
753 EmitBranch(LoopHeader.getBlock());
757 // Emit the exit block.
758 EmitBlock(LoopExit.getBlock(), true);
760 // The LoopHeader typically is just a branch if we skipped emitting
761 // a branch, try to erase it.
762 if (!EmitBoolCondBranch)
763 SimplifyForwardingBlocks(LoopHeader.getBlock());
766 void CodeGenFunction::EmitDoStmt(const DoStmt &S,
767 ArrayRef<const Attr *> DoAttrs) {
768 JumpDest LoopExit = getJumpDestInCurrentScope("do.end");
769 JumpDest LoopCond = getJumpDestInCurrentScope("do.cond");
771 uint64_t ParentCount = getCurrentProfileCount();
773 // Store the blocks to use for break and continue.
774 BreakContinueStack.push_back(BreakContinue(LoopExit, LoopCond));
776 // Emit the body of the loop.
777 llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
779 const SourceRange &R = S.getSourceRange();
780 LoopStack.push(LoopBody, CGM.getContext(), DoAttrs,
781 SourceLocToDebugLoc(R.getBegin()),
782 SourceLocToDebugLoc(R.getEnd()));
784 EmitBlockWithFallThrough(LoopBody, &S);
786 RunCleanupsScope BodyScope(*this);
787 EmitStmt(S.getBody());
790 EmitBlock(LoopCond.getBlock());
792 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
793 // after each execution of the loop body."
795 // Evaluate the conditional in the while header.
796 // C99 6.8.5p2/p4: The first substatement is executed if the expression
797 // compares unequal to 0. The condition must be a scalar type.
798 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
800 BreakContinueStack.pop_back();
802 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
803 // to correctly handle break/continue though.
804 bool EmitBoolCondBranch = true;
805 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
807 EmitBoolCondBranch = false;
809 // As long as the condition is true, iterate the loop.
810 if (EmitBoolCondBranch) {
811 uint64_t BackedgeCount = getProfileCount(S.getBody()) - ParentCount;
812 Builder.CreateCondBr(
813 BoolCondVal, LoopBody, LoopExit.getBlock(),
814 createProfileWeightsForLoop(S.getCond(), BackedgeCount));
819 // Emit the exit block.
820 EmitBlock(LoopExit.getBlock());
822 // The DoCond block typically is just a branch if we skipped
823 // emitting a branch, try to erase it.
824 if (!EmitBoolCondBranch)
825 SimplifyForwardingBlocks(LoopCond.getBlock());
828 void CodeGenFunction::EmitForStmt(const ForStmt &S,
829 ArrayRef<const Attr *> ForAttrs) {
830 JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
832 LexicalScope ForScope(*this, S.getSourceRange());
834 // Evaluate the first part before the loop.
836 EmitStmt(S.getInit());
838 // Start the loop with a block that tests the condition.
839 // If there's an increment, the continue scope will be overwritten
841 JumpDest Continue = getJumpDestInCurrentScope("for.cond");
842 llvm::BasicBlock *CondBlock = Continue.getBlock();
843 EmitBlock(CondBlock);
845 const SourceRange &R = S.getSourceRange();
846 LoopStack.push(CondBlock, CGM.getContext(), ForAttrs,
847 SourceLocToDebugLoc(R.getBegin()),
848 SourceLocToDebugLoc(R.getEnd()));
850 // If the for loop doesn't have an increment we can just use the
851 // condition as the continue block. Otherwise we'll need to create
852 // a block for it (in the current scope, i.e. in the scope of the
853 // condition), and that we will become our continue block.
855 Continue = getJumpDestInCurrentScope("for.inc");
857 // Store the blocks to use for break and continue.
858 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
860 // Create a cleanup scope for the condition variable cleanups.
861 LexicalScope ConditionScope(*this, S.getSourceRange());
864 // If the for statement has a condition scope, emit the local variable
866 if (S.getConditionVariable()) {
867 EmitAutoVarDecl(*S.getConditionVariable());
870 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
871 // If there are any cleanups between here and the loop-exit scope,
872 // create a block to stage a loop exit along.
873 if (ForScope.requiresCleanups())
874 ExitBlock = createBasicBlock("for.cond.cleanup");
876 // As long as the condition is true, iterate the loop.
877 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
879 // C99 6.8.5p2/p4: The first substatement is executed if the expression
880 // compares unequal to 0. The condition must be a scalar type.
881 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
882 Builder.CreateCondBr(
883 BoolCondVal, ForBody, ExitBlock,
884 createProfileWeightsForLoop(S.getCond(), getProfileCount(S.getBody())));
886 if (ExitBlock != LoopExit.getBlock()) {
887 EmitBlock(ExitBlock);
888 EmitBranchThroughCleanup(LoopExit);
893 // Treat it as a non-zero constant. Don't even create a new block for the
894 // body, just fall into it.
896 incrementProfileCounter(&S);
899 // Create a separate cleanup scope for the body, in case it is not
900 // a compound statement.
901 RunCleanupsScope BodyScope(*this);
902 EmitStmt(S.getBody());
905 // If there is an increment, emit it next.
907 EmitBlock(Continue.getBlock());
908 EmitStmt(S.getInc());
911 BreakContinueStack.pop_back();
913 ConditionScope.ForceCleanup();
916 EmitBranch(CondBlock);
918 ForScope.ForceCleanup();
922 // Emit the fall-through block.
923 EmitBlock(LoopExit.getBlock(), true);
927 CodeGenFunction::EmitCXXForRangeStmt(const CXXForRangeStmt &S,
928 ArrayRef<const Attr *> ForAttrs) {
929 JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
931 LexicalScope ForScope(*this, S.getSourceRange());
933 // Evaluate the first pieces before the loop.
934 EmitStmt(S.getRangeStmt());
935 EmitStmt(S.getBeginStmt());
936 EmitStmt(S.getEndStmt());
938 // Start the loop with a block that tests the condition.
939 // If there's an increment, the continue scope will be overwritten
941 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
942 EmitBlock(CondBlock);
944 const SourceRange &R = S.getSourceRange();
945 LoopStack.push(CondBlock, CGM.getContext(), ForAttrs,
946 SourceLocToDebugLoc(R.getBegin()),
947 SourceLocToDebugLoc(R.getEnd()));
949 // If there are any cleanups between here and the loop-exit scope,
950 // create a block to stage a loop exit along.
951 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
952 if (ForScope.requiresCleanups())
953 ExitBlock = createBasicBlock("for.cond.cleanup");
955 // The loop body, consisting of the specified body and the loop variable.
956 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
958 // The body is executed if the expression, contextually converted
960 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
961 Builder.CreateCondBr(
962 BoolCondVal, ForBody, ExitBlock,
963 createProfileWeightsForLoop(S.getCond(), getProfileCount(S.getBody())));
965 if (ExitBlock != LoopExit.getBlock()) {
966 EmitBlock(ExitBlock);
967 EmitBranchThroughCleanup(LoopExit);
971 incrementProfileCounter(&S);
973 // Create a block for the increment. In case of a 'continue', we jump there.
974 JumpDest Continue = getJumpDestInCurrentScope("for.inc");
976 // Store the blocks to use for break and continue.
977 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
980 // Create a separate cleanup scope for the loop variable and body.
981 LexicalScope BodyScope(*this, S.getSourceRange());
982 EmitStmt(S.getLoopVarStmt());
983 EmitStmt(S.getBody());
987 // If there is an increment, emit it next.
988 EmitBlock(Continue.getBlock());
989 EmitStmt(S.getInc());
991 BreakContinueStack.pop_back();
993 EmitBranch(CondBlock);
995 ForScope.ForceCleanup();
999 // Emit the fall-through block.
1000 EmitBlock(LoopExit.getBlock(), true);
1003 void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
1004 if (RV.isScalar()) {
1005 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
1006 } else if (RV.isAggregate()) {
1007 EmitAggregateCopy(ReturnValue, RV.getAggregateAddress(), Ty);
1009 EmitStoreOfComplex(RV.getComplexVal(), MakeAddrLValue(ReturnValue, Ty),
1012 EmitBranchThroughCleanup(ReturnBlock);
1015 /// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
1016 /// if the function returns void, or may be missing one if the function returns
1017 /// non-void. Fun stuff :).
1018 void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
1019 // Returning from an outlined SEH helper is UB, and we already warn on it.
1020 if (IsOutlinedSEHHelper) {
1021 Builder.CreateUnreachable();
1022 Builder.ClearInsertionPoint();
1025 // Emit the result value, even if unused, to evalute the side effects.
1026 const Expr *RV = S.getRetValue();
1028 // Treat block literals in a return expression as if they appeared
1029 // in their own scope. This permits a small, easily-implemented
1030 // exception to our over-conservative rules about not jumping to
1031 // statements following block literals with non-trivial cleanups.
1032 RunCleanupsScope cleanupScope(*this);
1033 if (const ExprWithCleanups *cleanups =
1034 dyn_cast_or_null<ExprWithCleanups>(RV)) {
1035 enterFullExpression(cleanups);
1036 RV = cleanups->getSubExpr();
1039 // FIXME: Clean this up by using an LValue for ReturnTemp,
1040 // EmitStoreThroughLValue, and EmitAnyExpr.
1041 if (getLangOpts().ElideConstructors &&
1042 S.getNRVOCandidate() && S.getNRVOCandidate()->isNRVOVariable()) {
1043 // Apply the named return value optimization for this return statement,
1044 // which means doing nothing: the appropriate result has already been
1045 // constructed into the NRVO variable.
1047 // If there is an NRVO flag for this variable, set it to 1 into indicate
1048 // that the cleanup code should not destroy the variable.
1049 if (llvm::Value *NRVOFlag = NRVOFlags[S.getNRVOCandidate()])
1050 Builder.CreateFlagStore(Builder.getTrue(), NRVOFlag);
1051 } else if (!ReturnValue.isValid() || (RV && RV->getType()->isVoidType())) {
1052 // Make sure not to return anything, but evaluate the expression
1053 // for side effects.
1057 // Do nothing (return value is left uninitialized)
1058 } else if (FnRetTy->isReferenceType()) {
1059 // If this function returns a reference, take the address of the expression
1060 // rather than the value.
1061 RValue Result = EmitReferenceBindingToExpr(RV);
1062 Builder.CreateStore(Result.getScalarVal(), ReturnValue);
1064 switch (getEvaluationKind(RV->getType())) {
1066 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
1069 EmitComplexExprIntoLValue(RV, MakeAddrLValue(ReturnValue, RV->getType()),
1073 EmitAggExpr(RV, AggValueSlot::forAddr(ReturnValue,
1075 AggValueSlot::IsDestructed,
1076 AggValueSlot::DoesNotNeedGCBarriers,
1077 AggValueSlot::IsNotAliased));
1083 if (!RV || RV->isEvaluatable(getContext()))
1084 ++NumSimpleReturnExprs;
1086 cleanupScope.ForceCleanup();
1087 EmitBranchThroughCleanup(ReturnBlock);
1090 void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
1091 // As long as debug info is modeled with instructions, we have to ensure we
1092 // have a place to insert here and write the stop point here.
1093 if (HaveInsertPoint())
1096 for (const auto *I : S.decls())
1100 void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
1101 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
1103 // If this code is reachable then emit a stop point (if generating
1104 // debug info). We have to do this ourselves because we are on the
1105 // "simple" statement path.
1106 if (HaveInsertPoint())
1109 EmitBranchThroughCleanup(BreakContinueStack.back().BreakBlock);
1112 void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
1113 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
1115 // If this code is reachable then emit a stop point (if generating
1116 // debug info). We have to do this ourselves because we are on the
1117 // "simple" statement path.
1118 if (HaveInsertPoint())
1121 EmitBranchThroughCleanup(BreakContinueStack.back().ContinueBlock);
1124 /// EmitCaseStmtRange - If case statement range is not too big then
1125 /// add multiple cases to switch instruction, one for each value within
1126 /// the range. If range is too big then emit "if" condition check.
1127 void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
1128 assert(S.getRHS() && "Expected RHS value in CaseStmt");
1130 llvm::APSInt LHS = S.getLHS()->EvaluateKnownConstInt(getContext());
1131 llvm::APSInt RHS = S.getRHS()->EvaluateKnownConstInt(getContext());
1133 // Emit the code for this case. We do this first to make sure it is
1134 // properly chained from our predecessor before generating the
1135 // switch machinery to enter this block.
1136 llvm::BasicBlock *CaseDest = createBasicBlock("sw.bb");
1137 EmitBlockWithFallThrough(CaseDest, &S);
1138 EmitStmt(S.getSubStmt());
1140 // If range is empty, do nothing.
1141 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
1144 llvm::APInt Range = RHS - LHS;
1145 // FIXME: parameters such as this should not be hardcoded.
1146 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
1147 // Range is small enough to add multiple switch instruction cases.
1148 uint64_t Total = getProfileCount(&S);
1149 unsigned NCases = Range.getZExtValue() + 1;
1150 // We only have one region counter for the entire set of cases here, so we
1151 // need to divide the weights evenly between the generated cases, ensuring
1152 // that the total weight is preserved. E.g., a weight of 5 over three cases
1153 // will be distributed as weights of 2, 2, and 1.
1154 uint64_t Weight = Total / NCases, Rem = Total % NCases;
1155 for (unsigned I = 0; I != NCases; ++I) {
1157 SwitchWeights->push_back(Weight + (Rem ? 1 : 0));
1160 SwitchInsn->addCase(Builder.getInt(LHS), CaseDest);
1166 // The range is too big. Emit "if" condition into a new block,
1167 // making sure to save and restore the current insertion point.
1168 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
1170 // Push this test onto the chain of range checks (which terminates
1171 // in the default basic block). The switch's default will be changed
1172 // to the top of this chain after switch emission is complete.
1173 llvm::BasicBlock *FalseDest = CaseRangeBlock;
1174 CaseRangeBlock = createBasicBlock("sw.caserange");
1176 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
1177 Builder.SetInsertPoint(CaseRangeBlock);
1179 // Emit range check.
1181 Builder.CreateSub(SwitchInsn->getCondition(), Builder.getInt(LHS));
1183 Builder.CreateICmpULE(Diff, Builder.getInt(Range), "inbounds");
1185 llvm::MDNode *Weights = nullptr;
1186 if (SwitchWeights) {
1187 uint64_t ThisCount = getProfileCount(&S);
1188 uint64_t DefaultCount = (*SwitchWeights)[0];
1189 Weights = createProfileWeights(ThisCount, DefaultCount);
1191 // Since we're chaining the switch default through each large case range, we
1192 // need to update the weight for the default, ie, the first case, to include
1194 (*SwitchWeights)[0] += ThisCount;
1196 Builder.CreateCondBr(Cond, CaseDest, FalseDest, Weights);
1198 // Restore the appropriate insertion point.
1200 Builder.SetInsertPoint(RestoreBB);
1202 Builder.ClearInsertionPoint();
1205 void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
1206 // If there is no enclosing switch instance that we're aware of, then this
1207 // case statement and its block can be elided. This situation only happens
1208 // when we've constant-folded the switch, are emitting the constant case,
1209 // and part of the constant case includes another case statement. For
1210 // instance: switch (4) { case 4: do { case 5: } while (1); }
1212 EmitStmt(S.getSubStmt());
1216 // Handle case ranges.
1218 EmitCaseStmtRange(S);
1222 llvm::ConstantInt *CaseVal =
1223 Builder.getInt(S.getLHS()->EvaluateKnownConstInt(getContext()));
1225 // If the body of the case is just a 'break', try to not emit an empty block.
1226 // If we're profiling or we're not optimizing, leave the block in for better
1227 // debug and coverage analysis.
1228 if (!CGM.getCodeGenOpts().hasProfileClangInstr() &&
1229 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1230 isa<BreakStmt>(S.getSubStmt())) {
1231 JumpDest Block = BreakContinueStack.back().BreakBlock;
1233 // Only do this optimization if there are no cleanups that need emitting.
1234 if (isObviouslyBranchWithoutCleanups(Block)) {
1236 SwitchWeights->push_back(getProfileCount(&S));
1237 SwitchInsn->addCase(CaseVal, Block.getBlock());
1239 // If there was a fallthrough into this case, make sure to redirect it to
1240 // the end of the switch as well.
1241 if (Builder.GetInsertBlock()) {
1242 Builder.CreateBr(Block.getBlock());
1243 Builder.ClearInsertionPoint();
1249 llvm::BasicBlock *CaseDest = createBasicBlock("sw.bb");
1250 EmitBlockWithFallThrough(CaseDest, &S);
1252 SwitchWeights->push_back(getProfileCount(&S));
1253 SwitchInsn->addCase(CaseVal, CaseDest);
1255 // Recursively emitting the statement is acceptable, but is not wonderful for
1256 // code where we have many case statements nested together, i.e.:
1260 // Handling this recursively will create a new block for each case statement
1261 // that falls through to the next case which is IR intensive. It also causes
1262 // deep recursion which can run into stack depth limitations. Handle
1263 // sequential non-range case statements specially.
1264 const CaseStmt *CurCase = &S;
1265 const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
1267 // Otherwise, iteratively add consecutive cases to this switch stmt.
1268 while (NextCase && NextCase->getRHS() == nullptr) {
1270 llvm::ConstantInt *CaseVal =
1271 Builder.getInt(CurCase->getLHS()->EvaluateKnownConstInt(getContext()));
1274 SwitchWeights->push_back(getProfileCount(NextCase));
1275 if (CGM.getCodeGenOpts().hasProfileClangInstr()) {
1276 CaseDest = createBasicBlock("sw.bb");
1277 EmitBlockWithFallThrough(CaseDest, &S);
1280 SwitchInsn->addCase(CaseVal, CaseDest);
1281 NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt());
1284 // Normal default recursion for non-cases.
1285 EmitStmt(CurCase->getSubStmt());
1288 void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
1289 // If there is no enclosing switch instance that we're aware of, then this
1290 // default statement can be elided. This situation only happens when we've
1291 // constant-folded the switch.
1293 EmitStmt(S.getSubStmt());
1297 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
1298 assert(DefaultBlock->empty() &&
1299 "EmitDefaultStmt: Default block already defined?");
1301 EmitBlockWithFallThrough(DefaultBlock, &S);
1303 EmitStmt(S.getSubStmt());
1306 /// CollectStatementsForCase - Given the body of a 'switch' statement and a
1307 /// constant value that is being switched on, see if we can dead code eliminate
1308 /// the body of the switch to a simple series of statements to emit. Basically,
1309 /// on a switch (5) we want to find these statements:
1311 /// printf(...); <--
1315 /// and add them to the ResultStmts vector. If it is unsafe to do this
1316 /// transformation (for example, one of the elided statements contains a label
1317 /// that might be jumped to), return CSFC_Failure. If we handled it and 'S'
1318 /// should include statements after it (e.g. the printf() line is a substmt of
1319 /// the case) then return CSFC_FallThrough. If we handled it and found a break
1320 /// statement, then return CSFC_Success.
1322 /// If Case is non-null, then we are looking for the specified case, checking
1323 /// that nothing we jump over contains labels. If Case is null, then we found
1324 /// the case and are looking for the break.
1326 /// If the recursive walk actually finds our Case, then we set FoundCase to
1329 enum CSFC_Result { CSFC_Failure, CSFC_FallThrough, CSFC_Success };
1330 static CSFC_Result CollectStatementsForCase(const Stmt *S,
1331 const SwitchCase *Case,
1333 SmallVectorImpl<const Stmt*> &ResultStmts) {
1334 // If this is a null statement, just succeed.
1336 return Case ? CSFC_Success : CSFC_FallThrough;
1338 // If this is the switchcase (case 4: or default) that we're looking for, then
1339 // we're in business. Just add the substatement.
1340 if (const SwitchCase *SC = dyn_cast<SwitchCase>(S)) {
1343 return CollectStatementsForCase(SC->getSubStmt(), nullptr, FoundCase,
1347 // Otherwise, this is some other case or default statement, just ignore it.
1348 return CollectStatementsForCase(SC->getSubStmt(), Case, FoundCase,
1352 // If we are in the live part of the code and we found our break statement,
1353 // return a success!
1354 if (!Case && isa<BreakStmt>(S))
1355 return CSFC_Success;
1357 // If this is a switch statement, then it might contain the SwitchCase, the
1358 // break, or neither.
1359 if (const CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
1360 // Handle this as two cases: we might be looking for the SwitchCase (if so
1361 // the skipped statements must be skippable) or we might already have it.
1362 CompoundStmt::const_body_iterator I = CS->body_begin(), E = CS->body_end();
1363 bool StartedInLiveCode = FoundCase;
1364 unsigned StartSize = ResultStmts.size();
1366 // If we've not found the case yet, scan through looking for it.
1368 // Keep track of whether we see a skipped declaration. The code could be
1369 // using the declaration even if it is skipped, so we can't optimize out
1370 // the decl if the kept statements might refer to it.
1371 bool HadSkippedDecl = false;
1373 // If we're looking for the case, just see if we can skip each of the
1375 for (; Case && I != E; ++I) {
1376 HadSkippedDecl |= CodeGenFunction::mightAddDeclToScope(*I);
1378 switch (CollectStatementsForCase(*I, Case, FoundCase, ResultStmts)) {
1379 case CSFC_Failure: return CSFC_Failure;
1381 // A successful result means that either 1) that the statement doesn't
1382 // have the case and is skippable, or 2) does contain the case value
1383 // and also contains the break to exit the switch. In the later case,
1384 // we just verify the rest of the statements are elidable.
1386 // If we found the case and skipped declarations, we can't do the
1389 return CSFC_Failure;
1391 for (++I; I != E; ++I)
1392 if (CodeGenFunction::ContainsLabel(*I, true))
1393 return CSFC_Failure;
1394 return CSFC_Success;
1397 case CSFC_FallThrough:
1398 // If we have a fallthrough condition, then we must have found the
1399 // case started to include statements. Consider the rest of the
1400 // statements in the compound statement as candidates for inclusion.
1401 assert(FoundCase && "Didn't find case but returned fallthrough?");
1402 // We recursively found Case, so we're not looking for it anymore.
1405 // If we found the case and skipped declarations, we can't do the
1408 return CSFC_Failure;
1414 return CSFC_Success;
1416 assert(!HadSkippedDecl && "fallthrough after skipping decl");
1419 // If we have statements in our range, then we know that the statements are
1420 // live and need to be added to the set of statements we're tracking.
1421 bool AnyDecls = false;
1422 for (; I != E; ++I) {
1423 AnyDecls |= CodeGenFunction::mightAddDeclToScope(*I);
1425 switch (CollectStatementsForCase(*I, nullptr, FoundCase, ResultStmts)) {
1426 case CSFC_Failure: return CSFC_Failure;
1427 case CSFC_FallThrough:
1428 // A fallthrough result means that the statement was simple and just
1429 // included in ResultStmt, keep adding them afterwards.
1432 // A successful result means that we found the break statement and
1433 // stopped statement inclusion. We just ensure that any leftover stmts
1434 // are skippable and return success ourselves.
1435 for (++I; I != E; ++I)
1436 if (CodeGenFunction::ContainsLabel(*I, true))
1437 return CSFC_Failure;
1438 return CSFC_Success;
1442 // If we're about to fall out of a scope without hitting a 'break;', we
1443 // can't perform the optimization if there were any decls in that scope
1444 // (we'd lose their end-of-lifetime).
1446 // If the entire compound statement was live, there's one more thing we
1447 // can try before giving up: emit the whole thing as a single statement.
1448 // We can do that unless the statement contains a 'break;'.
1449 // FIXME: Such a break must be at the end of a construct within this one.
1450 // We could emit this by just ignoring the BreakStmts entirely.
1451 if (StartedInLiveCode && !CodeGenFunction::containsBreak(S)) {
1452 ResultStmts.resize(StartSize);
1453 ResultStmts.push_back(S);
1455 return CSFC_Failure;
1459 return CSFC_FallThrough;
1462 // Okay, this is some other statement that we don't handle explicitly, like a
1463 // for statement or increment etc. If we are skipping over this statement,
1464 // just verify it doesn't have labels, which would make it invalid to elide.
1466 if (CodeGenFunction::ContainsLabel(S, true))
1467 return CSFC_Failure;
1468 return CSFC_Success;
1471 // Otherwise, we want to include this statement. Everything is cool with that
1472 // so long as it doesn't contain a break out of the switch we're in.
1473 if (CodeGenFunction::containsBreak(S)) return CSFC_Failure;
1475 // Otherwise, everything is great. Include the statement and tell the caller
1476 // that we fall through and include the next statement as well.
1477 ResultStmts.push_back(S);
1478 return CSFC_FallThrough;
1481 /// FindCaseStatementsForValue - Find the case statement being jumped to and
1482 /// then invoke CollectStatementsForCase to find the list of statements to emit
1483 /// for a switch on constant. See the comment above CollectStatementsForCase
1484 /// for more details.
1485 static bool FindCaseStatementsForValue(const SwitchStmt &S,
1486 const llvm::APSInt &ConstantCondValue,
1487 SmallVectorImpl<const Stmt*> &ResultStmts,
1489 const SwitchCase *&ResultCase) {
1490 // First step, find the switch case that is being branched to. We can do this
1491 // efficiently by scanning the SwitchCase list.
1492 const SwitchCase *Case = S.getSwitchCaseList();
1493 const DefaultStmt *DefaultCase = nullptr;
1495 for (; Case; Case = Case->getNextSwitchCase()) {
1496 // It's either a default or case. Just remember the default statement in
1497 // case we're not jumping to any numbered cases.
1498 if (const DefaultStmt *DS = dyn_cast<DefaultStmt>(Case)) {
1503 // Check to see if this case is the one we're looking for.
1504 const CaseStmt *CS = cast<CaseStmt>(Case);
1505 // Don't handle case ranges yet.
1506 if (CS->getRHS()) return false;
1508 // If we found our case, remember it as 'case'.
1509 if (CS->getLHS()->EvaluateKnownConstInt(C) == ConstantCondValue)
1513 // If we didn't find a matching case, we use a default if it exists, or we
1514 // elide the whole switch body!
1516 // It is safe to elide the body of the switch if it doesn't contain labels
1517 // etc. If it is safe, return successfully with an empty ResultStmts list.
1519 return !CodeGenFunction::ContainsLabel(&S);
1523 // Ok, we know which case is being jumped to, try to collect all the
1524 // statements that follow it. This can fail for a variety of reasons. Also,
1525 // check to see that the recursive walk actually found our case statement.
1526 // Insane cases like this can fail to find it in the recursive walk since we
1527 // don't handle every stmt kind:
1531 bool FoundCase = false;
1533 return CollectStatementsForCase(S.getBody(), Case, FoundCase,
1534 ResultStmts) != CSFC_Failure &&
1538 void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
1539 // Handle nested switch statements.
1540 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
1541 SmallVector<uint64_t, 16> *SavedSwitchWeights = SwitchWeights;
1542 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
1544 // See if we can constant fold the condition of the switch and therefore only
1545 // emit the live case statement (if any) of the switch.
1546 llvm::APSInt ConstantCondValue;
1547 if (ConstantFoldsToSimpleInteger(S.getCond(), ConstantCondValue)) {
1548 SmallVector<const Stmt*, 4> CaseStmts;
1549 const SwitchCase *Case = nullptr;
1550 if (FindCaseStatementsForValue(S, ConstantCondValue, CaseStmts,
1551 getContext(), Case)) {
1553 incrementProfileCounter(Case);
1554 RunCleanupsScope ExecutedScope(*this);
1557 EmitStmt(S.getInit());
1559 // Emit the condition variable if needed inside the entire cleanup scope
1560 // used by this special case for constant folded switches.
1561 if (S.getConditionVariable())
1562 EmitAutoVarDecl(*S.getConditionVariable());
1564 // At this point, we are no longer "within" a switch instance, so
1565 // we can temporarily enforce this to ensure that any embedded case
1566 // statements are not emitted.
1567 SwitchInsn = nullptr;
1569 // Okay, we can dead code eliminate everything except this case. Emit the
1570 // specified series of statements and we're good.
1571 for (unsigned i = 0, e = CaseStmts.size(); i != e; ++i)
1572 EmitStmt(CaseStmts[i]);
1573 incrementProfileCounter(&S);
1575 // Now we want to restore the saved switch instance so that nested
1576 // switches continue to function properly
1577 SwitchInsn = SavedSwitchInsn;
1583 JumpDest SwitchExit = getJumpDestInCurrentScope("sw.epilog");
1585 RunCleanupsScope ConditionScope(*this);
1588 EmitStmt(S.getInit());
1590 if (S.getConditionVariable())
1591 EmitAutoVarDecl(*S.getConditionVariable());
1592 llvm::Value *CondV = EmitScalarExpr(S.getCond());
1594 // Create basic block to hold stuff that comes after switch
1595 // statement. We also need to create a default block now so that
1596 // explicit case ranges tests can have a place to jump to on
1598 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
1599 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
1600 if (PGO.haveRegionCounts()) {
1601 // Walk the SwitchCase list to find how many there are.
1602 uint64_t DefaultCount = 0;
1603 unsigned NumCases = 0;
1604 for (const SwitchCase *Case = S.getSwitchCaseList();
1606 Case = Case->getNextSwitchCase()) {
1607 if (isa<DefaultStmt>(Case))
1608 DefaultCount = getProfileCount(Case);
1611 SwitchWeights = new SmallVector<uint64_t, 16>();
1612 SwitchWeights->reserve(NumCases);
1613 // The default needs to be first. We store the edge count, so we already
1614 // know the right weight.
1615 SwitchWeights->push_back(DefaultCount);
1617 CaseRangeBlock = DefaultBlock;
1619 // Clear the insertion point to indicate we are in unreachable code.
1620 Builder.ClearInsertionPoint();
1622 // All break statements jump to NextBlock. If BreakContinueStack is non-empty
1623 // then reuse last ContinueBlock.
1624 JumpDest OuterContinue;
1625 if (!BreakContinueStack.empty())
1626 OuterContinue = BreakContinueStack.back().ContinueBlock;
1628 BreakContinueStack.push_back(BreakContinue(SwitchExit, OuterContinue));
1630 // Emit switch body.
1631 EmitStmt(S.getBody());
1633 BreakContinueStack.pop_back();
1635 // Update the default block in case explicit case range tests have
1636 // been chained on top.
1637 SwitchInsn->setDefaultDest(CaseRangeBlock);
1639 // If a default was never emitted:
1640 if (!DefaultBlock->getParent()) {
1641 // If we have cleanups, emit the default block so that there's a
1642 // place to jump through the cleanups from.
1643 if (ConditionScope.requiresCleanups()) {
1644 EmitBlock(DefaultBlock);
1646 // Otherwise, just forward the default block to the switch end.
1648 DefaultBlock->replaceAllUsesWith(SwitchExit.getBlock());
1649 delete DefaultBlock;
1653 ConditionScope.ForceCleanup();
1655 // Emit continuation.
1656 EmitBlock(SwitchExit.getBlock(), true);
1657 incrementProfileCounter(&S);
1659 // If the switch has a condition wrapped by __builtin_unpredictable,
1660 // create metadata that specifies that the switch is unpredictable.
1661 // Don't bother if not optimizing because that metadata would not be used.
1662 auto *Call = dyn_cast<CallExpr>(S.getCond());
1663 if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
1664 auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
1665 if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
1666 llvm::MDBuilder MDHelper(getLLVMContext());
1667 SwitchInsn->setMetadata(llvm::LLVMContext::MD_unpredictable,
1668 MDHelper.createUnpredictable());
1672 if (SwitchWeights) {
1673 assert(SwitchWeights->size() == 1 + SwitchInsn->getNumCases() &&
1674 "switch weights do not match switch cases");
1675 // If there's only one jump destination there's no sense weighting it.
1676 if (SwitchWeights->size() > 1)
1677 SwitchInsn->setMetadata(llvm::LLVMContext::MD_prof,
1678 createProfileWeights(*SwitchWeights));
1679 delete SwitchWeights;
1681 SwitchInsn = SavedSwitchInsn;
1682 SwitchWeights = SavedSwitchWeights;
1683 CaseRangeBlock = SavedCRBlock;
1687 SimplifyConstraint(const char *Constraint, const TargetInfo &Target,
1688 SmallVectorImpl<TargetInfo::ConstraintInfo> *OutCons=nullptr) {
1691 while (*Constraint) {
1692 switch (*Constraint) {
1694 Result += Target.convertConstraint(Constraint);
1700 case '=': // Will see this and the following in mult-alt constraints.
1703 case '#': // Ignore the rest of the constraint alternative.
1704 while (Constraint[1] && Constraint[1] != ',')
1709 Result += *Constraint;
1710 while (Constraint[1] && Constraint[1] == *Constraint)
1721 "Must pass output names to constraints with a symbolic name");
1723 bool result = Target.resolveSymbolicName(Constraint, *OutCons, Index);
1724 assert(result && "Could not resolve symbolic name"); (void)result;
1725 Result += llvm::utostr(Index);
1736 /// AddVariableConstraints - Look at AsmExpr and if it is a variable declared
1737 /// as using a particular register add that as a constraint that will be used
1738 /// in this asm stmt.
1740 AddVariableConstraints(const std::string &Constraint, const Expr &AsmExpr,
1741 const TargetInfo &Target, CodeGenModule &CGM,
1742 const AsmStmt &Stmt, const bool EarlyClobber) {
1743 const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(&AsmExpr);
1746 const ValueDecl &Value = *AsmDeclRef->getDecl();
1747 const VarDecl *Variable = dyn_cast<VarDecl>(&Value);
1750 if (Variable->getStorageClass() != SC_Register)
1752 AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>();
1755 StringRef Register = Attr->getLabel();
1756 assert(Target.isValidGCCRegisterName(Register));
1757 // We're using validateOutputConstraint here because we only care if
1758 // this is a register constraint.
1759 TargetInfo::ConstraintInfo Info(Constraint, "");
1760 if (Target.validateOutputConstraint(Info) &&
1761 !Info.allowsRegister()) {
1762 CGM.ErrorUnsupported(&Stmt, "__asm__");
1765 // Canonicalize the register here before returning it.
1766 Register = Target.getNormalizedGCCRegisterName(Register);
1767 return (EarlyClobber ? "&{" : "{") + Register.str() + "}";
1771 CodeGenFunction::EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info,
1772 LValue InputValue, QualType InputType,
1773 std::string &ConstraintStr,
1774 SourceLocation Loc) {
1776 if (Info.allowsRegister() || !Info.allowsMemory()) {
1777 if (CodeGenFunction::hasScalarEvaluationKind(InputType)) {
1778 Arg = EmitLoadOfLValue(InputValue, Loc).getScalarVal();
1780 llvm::Type *Ty = ConvertType(InputType);
1781 uint64_t Size = CGM.getDataLayout().getTypeSizeInBits(Ty);
1782 if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
1783 Ty = llvm::IntegerType::get(getLLVMContext(), Size);
1784 Ty = llvm::PointerType::getUnqual(Ty);
1786 Arg = Builder.CreateLoad(Builder.CreateBitCast(InputValue.getAddress(),
1789 Arg = InputValue.getPointer();
1790 ConstraintStr += '*';
1794 Arg = InputValue.getPointer();
1795 ConstraintStr += '*';
1801 llvm::Value* CodeGenFunction::EmitAsmInput(
1802 const TargetInfo::ConstraintInfo &Info,
1803 const Expr *InputExpr,
1804 std::string &ConstraintStr) {
1805 // If this can't be a register or memory, i.e., has to be a constant
1806 // (immediate or symbolic), try to emit it as such.
1807 if (!Info.allowsRegister() && !Info.allowsMemory()) {
1808 llvm::APSInt Result;
1809 if (InputExpr->EvaluateAsInt(Result, getContext()))
1810 return llvm::ConstantInt::get(getLLVMContext(), Result);
1811 assert(!Info.requiresImmediateConstant() &&
1812 "Required-immediate inlineasm arg isn't constant?");
1815 if (Info.allowsRegister() || !Info.allowsMemory())
1816 if (CodeGenFunction::hasScalarEvaluationKind(InputExpr->getType()))
1817 return EmitScalarExpr(InputExpr);
1818 if (InputExpr->getStmtClass() == Expr::CXXThisExprClass)
1819 return EmitScalarExpr(InputExpr);
1820 InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
1821 LValue Dest = EmitLValue(InputExpr);
1822 return EmitAsmInputLValue(Info, Dest, InputExpr->getType(), ConstraintStr,
1823 InputExpr->getExprLoc());
1826 /// getAsmSrcLocInfo - Return the !srcloc metadata node to attach to an inline
1827 /// asm call instruction. The !srcloc MDNode contains a list of constant
1828 /// integers which are the source locations of the start of each line in the
1830 static llvm::MDNode *getAsmSrcLocInfo(const StringLiteral *Str,
1831 CodeGenFunction &CGF) {
1832 SmallVector<llvm::Metadata *, 8> Locs;
1833 // Add the location of the first line to the MDNode.
1834 Locs.push_back(llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1835 CGF.Int32Ty, Str->getLocStart().getRawEncoding())));
1836 StringRef StrVal = Str->getString();
1837 if (!StrVal.empty()) {
1838 const SourceManager &SM = CGF.CGM.getContext().getSourceManager();
1839 const LangOptions &LangOpts = CGF.CGM.getLangOpts();
1840 unsigned StartToken = 0;
1841 unsigned ByteOffset = 0;
1843 // Add the location of the start of each subsequent line of the asm to the
1845 for (unsigned i = 0, e = StrVal.size() - 1; i != e; ++i) {
1846 if (StrVal[i] != '\n') continue;
1847 SourceLocation LineLoc = Str->getLocationOfByte(
1848 i + 1, SM, LangOpts, CGF.getTarget(), &StartToken, &ByteOffset);
1849 Locs.push_back(llvm::ConstantAsMetadata::get(
1850 llvm::ConstantInt::get(CGF.Int32Ty, LineLoc.getRawEncoding())));
1854 return llvm::MDNode::get(CGF.getLLVMContext(), Locs);
1857 void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
1858 // Assemble the final asm string.
1859 std::string AsmString = S.generateAsmString(getContext());
1861 // Get all the output and input constraints together.
1862 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
1863 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
1865 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
1867 if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
1868 Name = GAS->getOutputName(i);
1869 TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i), Name);
1870 bool IsValid = getTarget().validateOutputConstraint(Info); (void)IsValid;
1871 assert(IsValid && "Failed to parse output constraint");
1872 OutputConstraintInfos.push_back(Info);
1875 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1877 if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
1878 Name = GAS->getInputName(i);
1879 TargetInfo::ConstraintInfo Info(S.getInputConstraint(i), Name);
1881 getTarget().validateInputConstraint(OutputConstraintInfos, Info);
1882 assert(IsValid && "Failed to parse input constraint"); (void)IsValid;
1883 InputConstraintInfos.push_back(Info);
1886 std::string Constraints;
1888 std::vector<LValue> ResultRegDests;
1889 std::vector<QualType> ResultRegQualTys;
1890 std::vector<llvm::Type *> ResultRegTypes;
1891 std::vector<llvm::Type *> ResultTruncRegTypes;
1892 std::vector<llvm::Type *> ArgTypes;
1893 std::vector<llvm::Value*> Args;
1895 // Keep track of inout constraints.
1896 std::string InOutConstraints;
1897 std::vector<llvm::Value*> InOutArgs;
1898 std::vector<llvm::Type*> InOutArgTypes;
1900 // An inline asm can be marked readonly if it meets the following conditions:
1901 // - it doesn't have any sideeffects
1902 // - it doesn't clobber memory
1903 // - it doesn't return a value by-reference
1904 // It can be marked readnone if it doesn't have any input memory constraints
1905 // in addition to meeting the conditions listed above.
1906 bool ReadOnly = true, ReadNone = true;
1908 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
1909 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
1911 // Simplify the output constraint.
1912 std::string OutputConstraint(S.getOutputConstraint(i));
1913 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1,
1916 const Expr *OutExpr = S.getOutputExpr(i);
1917 OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
1919 OutputConstraint = AddVariableConstraints(OutputConstraint, *OutExpr,
1920 getTarget(), CGM, S,
1921 Info.earlyClobber());
1923 LValue Dest = EmitLValue(OutExpr);
1924 if (!Constraints.empty())
1927 // If this is a register output, then make the inline asm return it
1928 // by-value. If this is a memory result, return the value by-reference.
1929 if (!Info.allowsMemory() && hasScalarEvaluationKind(OutExpr->getType())) {
1930 Constraints += "=" + OutputConstraint;
1931 ResultRegQualTys.push_back(OutExpr->getType());
1932 ResultRegDests.push_back(Dest);
1933 ResultRegTypes.push_back(ConvertTypeForMem(OutExpr->getType()));
1934 ResultTruncRegTypes.push_back(ResultRegTypes.back());
1936 // If this output is tied to an input, and if the input is larger, then
1937 // we need to set the actual result type of the inline asm node to be the
1938 // same as the input type.
1939 if (Info.hasMatchingInput()) {
1941 for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) {
1942 TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo];
1943 if (Input.hasTiedOperand() && Input.getTiedOperand() == i)
1946 assert(InputNo != S.getNumInputs() && "Didn't find matching input!");
1948 QualType InputTy = S.getInputExpr(InputNo)->getType();
1949 QualType OutputType = OutExpr->getType();
1951 uint64_t InputSize = getContext().getTypeSize(InputTy);
1952 if (getContext().getTypeSize(OutputType) < InputSize) {
1953 // Form the asm to return the value as a larger integer or fp type.
1954 ResultRegTypes.back() = ConvertType(InputTy);
1957 if (llvm::Type* AdjTy =
1958 getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
1959 ResultRegTypes.back()))
1960 ResultRegTypes.back() = AdjTy;
1962 CGM.getDiags().Report(S.getAsmLoc(),
1963 diag::err_asm_invalid_type_in_input)
1964 << OutExpr->getType() << OutputConstraint;
1967 ArgTypes.push_back(Dest.getAddress().getType());
1968 Args.push_back(Dest.getPointer());
1969 Constraints += "=*";
1970 Constraints += OutputConstraint;
1971 ReadOnly = ReadNone = false;
1974 if (Info.isReadWrite()) {
1975 InOutConstraints += ',';
1977 const Expr *InputExpr = S.getOutputExpr(i);
1978 llvm::Value *Arg = EmitAsmInputLValue(Info, Dest, InputExpr->getType(),
1980 InputExpr->getExprLoc());
1982 if (llvm::Type* AdjTy =
1983 getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
1985 Arg = Builder.CreateBitCast(Arg, AdjTy);
1987 if (Info.allowsRegister())
1988 InOutConstraints += llvm::utostr(i);
1990 InOutConstraints += OutputConstraint;
1992 InOutArgTypes.push_back(Arg->getType());
1993 InOutArgs.push_back(Arg);
1997 // If this is a Microsoft-style asm blob, store the return registers (EAX:EDX)
1998 // to the return value slot. Only do this when returning in registers.
1999 if (isa<MSAsmStmt>(&S)) {
2000 const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
2001 if (RetAI.isDirect() || RetAI.isExtend()) {
2002 // Make a fake lvalue for the return value slot.
2003 LValue ReturnSlot = MakeAddrLValue(ReturnValue, FnRetTy);
2004 CGM.getTargetCodeGenInfo().addReturnRegisterOutputs(
2005 *this, ReturnSlot, Constraints, ResultRegTypes, ResultTruncRegTypes,
2006 ResultRegDests, AsmString, S.getNumOutputs());
2011 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
2012 const Expr *InputExpr = S.getInputExpr(i);
2014 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
2016 if (Info.allowsMemory())
2019 if (!Constraints.empty())
2022 // Simplify the input constraint.
2023 std::string InputConstraint(S.getInputConstraint(i));
2024 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), getTarget(),
2025 &OutputConstraintInfos);
2027 InputConstraint = AddVariableConstraints(
2028 InputConstraint, *InputExpr->IgnoreParenNoopCasts(getContext()),
2029 getTarget(), CGM, S, false /* No EarlyClobber */);
2031 llvm::Value *Arg = EmitAsmInput(Info, InputExpr, Constraints);
2033 // If this input argument is tied to a larger output result, extend the
2034 // input to be the same size as the output. The LLVM backend wants to see
2035 // the input and output of a matching constraint be the same size. Note
2036 // that GCC does not define what the top bits are here. We use zext because
2037 // that is usually cheaper, but LLVM IR should really get an anyext someday.
2038 if (Info.hasTiedOperand()) {
2039 unsigned Output = Info.getTiedOperand();
2040 QualType OutputType = S.getOutputExpr(Output)->getType();
2041 QualType InputTy = InputExpr->getType();
2043 if (getContext().getTypeSize(OutputType) >
2044 getContext().getTypeSize(InputTy)) {
2045 // Use ptrtoint as appropriate so that we can do our extension.
2046 if (isa<llvm::PointerType>(Arg->getType()))
2047 Arg = Builder.CreatePtrToInt(Arg, IntPtrTy);
2048 llvm::Type *OutputTy = ConvertType(OutputType);
2049 if (isa<llvm::IntegerType>(OutputTy))
2050 Arg = Builder.CreateZExt(Arg, OutputTy);
2051 else if (isa<llvm::PointerType>(OutputTy))
2052 Arg = Builder.CreateZExt(Arg, IntPtrTy);
2054 assert(OutputTy->isFloatingPointTy() && "Unexpected output type");
2055 Arg = Builder.CreateFPExt(Arg, OutputTy);
2059 if (llvm::Type* AdjTy =
2060 getTargetHooks().adjustInlineAsmType(*this, InputConstraint,
2062 Arg = Builder.CreateBitCast(Arg, AdjTy);
2064 CGM.getDiags().Report(S.getAsmLoc(), diag::err_asm_invalid_type_in_input)
2065 << InputExpr->getType() << InputConstraint;
2067 ArgTypes.push_back(Arg->getType());
2068 Args.push_back(Arg);
2069 Constraints += InputConstraint;
2072 // Append the "input" part of inout constraints last.
2073 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
2074 ArgTypes.push_back(InOutArgTypes[i]);
2075 Args.push_back(InOutArgs[i]);
2077 Constraints += InOutConstraints;
2080 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
2081 StringRef Clobber = S.getClobber(i);
2083 if (Clobber == "memory")
2084 ReadOnly = ReadNone = false;
2085 else if (Clobber != "cc")
2086 Clobber = getTarget().getNormalizedGCCRegisterName(Clobber);
2088 if (!Constraints.empty())
2091 Constraints += "~{";
2092 Constraints += Clobber;
2096 // Add machine specific clobbers
2097 std::string MachineClobbers = getTarget().getClobbers();
2098 if (!MachineClobbers.empty()) {
2099 if (!Constraints.empty())
2101 Constraints += MachineClobbers;
2104 llvm::Type *ResultType;
2105 if (ResultRegTypes.empty())
2106 ResultType = VoidTy;
2107 else if (ResultRegTypes.size() == 1)
2108 ResultType = ResultRegTypes[0];
2110 ResultType = llvm::StructType::get(getLLVMContext(), ResultRegTypes);
2112 llvm::FunctionType *FTy =
2113 llvm::FunctionType::get(ResultType, ArgTypes, false);
2115 bool HasSideEffect = S.isVolatile() || S.getNumOutputs() == 0;
2116 llvm::InlineAsm::AsmDialect AsmDialect = isa<MSAsmStmt>(&S) ?
2117 llvm::InlineAsm::AD_Intel : llvm::InlineAsm::AD_ATT;
2118 llvm::InlineAsm *IA =
2119 llvm::InlineAsm::get(FTy, AsmString, Constraints, HasSideEffect,
2120 /* IsAlignStack */ false, AsmDialect);
2121 llvm::CallInst *Result = Builder.CreateCall(IA, Args);
2122 Result->addAttribute(llvm::AttributeSet::FunctionIndex,
2123 llvm::Attribute::NoUnwind);
2125 // Attach readnone and readonly attributes.
2126 if (!HasSideEffect) {
2128 Result->addAttribute(llvm::AttributeSet::FunctionIndex,
2129 llvm::Attribute::ReadNone);
2131 Result->addAttribute(llvm::AttributeSet::FunctionIndex,
2132 llvm::Attribute::ReadOnly);
2135 // Slap the source location of the inline asm into a !srcloc metadata on the
2137 if (const GCCAsmStmt *gccAsmStmt = dyn_cast<GCCAsmStmt>(&S)) {
2138 Result->setMetadata("srcloc", getAsmSrcLocInfo(gccAsmStmt->getAsmString(),
2141 // At least put the line number on MS inline asm blobs.
2142 auto Loc = llvm::ConstantInt::get(Int32Ty, S.getAsmLoc().getRawEncoding());
2143 Result->setMetadata("srcloc",
2144 llvm::MDNode::get(getLLVMContext(),
2145 llvm::ConstantAsMetadata::get(Loc)));
2148 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
2149 // Conservatively, mark all inline asm blocks in CUDA as convergent
2150 // (meaning, they may call an intrinsically convergent op, such as bar.sync,
2151 // and so can't have certain optimizations applied around them).
2152 Result->addAttribute(llvm::AttributeSet::FunctionIndex,
2153 llvm::Attribute::Convergent);
2156 // Extract all of the register value results from the asm.
2157 std::vector<llvm::Value*> RegResults;
2158 if (ResultRegTypes.size() == 1) {
2159 RegResults.push_back(Result);
2161 for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) {
2162 llvm::Value *Tmp = Builder.CreateExtractValue(Result, i, "asmresult");
2163 RegResults.push_back(Tmp);
2167 assert(RegResults.size() == ResultRegTypes.size());
2168 assert(RegResults.size() == ResultTruncRegTypes.size());
2169 assert(RegResults.size() == ResultRegDests.size());
2170 for (unsigned i = 0, e = RegResults.size(); i != e; ++i) {
2171 llvm::Value *Tmp = RegResults[i];
2173 // If the result type of the LLVM IR asm doesn't match the result type of
2174 // the expression, do the conversion.
2175 if (ResultRegTypes[i] != ResultTruncRegTypes[i]) {
2176 llvm::Type *TruncTy = ResultTruncRegTypes[i];
2178 // Truncate the integer result to the right size, note that TruncTy can be
2180 if (TruncTy->isFloatingPointTy())
2181 Tmp = Builder.CreateFPTrunc(Tmp, TruncTy);
2182 else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) {
2183 uint64_t ResSize = CGM.getDataLayout().getTypeSizeInBits(TruncTy);
2184 Tmp = Builder.CreateTrunc(Tmp,
2185 llvm::IntegerType::get(getLLVMContext(), (unsigned)ResSize));
2186 Tmp = Builder.CreateIntToPtr(Tmp, TruncTy);
2187 } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) {
2188 uint64_t TmpSize =CGM.getDataLayout().getTypeSizeInBits(Tmp->getType());
2189 Tmp = Builder.CreatePtrToInt(Tmp,
2190 llvm::IntegerType::get(getLLVMContext(), (unsigned)TmpSize));
2191 Tmp = Builder.CreateTrunc(Tmp, TruncTy);
2192 } else if (TruncTy->isIntegerTy()) {
2193 Tmp = Builder.CreateTrunc(Tmp, TruncTy);
2194 } else if (TruncTy->isVectorTy()) {
2195 Tmp = Builder.CreateBitCast(Tmp, TruncTy);
2199 EmitStoreThroughLValue(RValue::get(Tmp), ResultRegDests[i]);
2203 LValue CodeGenFunction::InitCapturedStruct(const CapturedStmt &S) {
2204 const RecordDecl *RD = S.getCapturedRecordDecl();
2205 QualType RecordTy = getContext().getRecordType(RD);
2207 // Initialize the captured struct.
2209 MakeAddrLValue(CreateMemTemp(RecordTy, "agg.captured"), RecordTy);
2211 RecordDecl::field_iterator CurField = RD->field_begin();
2212 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
2213 E = S.capture_init_end();
2214 I != E; ++I, ++CurField) {
2215 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
2216 if (CurField->hasCapturedVLAType()) {
2217 auto VAT = CurField->getCapturedVLAType();
2218 EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
2220 EmitInitializerForField(*CurField, LV, *I);
2227 /// Generate an outlined function for the body of a CapturedStmt, store any
2228 /// captured variables into the captured struct, and call the outlined function.
2230 CodeGenFunction::EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K) {
2231 LValue CapStruct = InitCapturedStruct(S);
2233 // Emit the CapturedDecl
2234 CodeGenFunction CGF(CGM, true);
2235 CGCapturedStmtRAII CapInfoRAII(CGF, new CGCapturedStmtInfo(S, K));
2236 llvm::Function *F = CGF.GenerateCapturedStmtFunction(S);
2237 delete CGF.CapturedStmtInfo;
2239 // Emit call to the helper function.
2240 EmitCallOrInvoke(F, CapStruct.getPointer());
2245 Address CodeGenFunction::GenerateCapturedStmtArgument(const CapturedStmt &S) {
2246 LValue CapStruct = InitCapturedStruct(S);
2247 return CapStruct.getAddress();
2250 /// Creates the outlined function for a CapturedStmt.
2252 CodeGenFunction::GenerateCapturedStmtFunction(const CapturedStmt &S) {
2253 assert(CapturedStmtInfo &&
2254 "CapturedStmtInfo should be set when generating the captured function");
2255 const CapturedDecl *CD = S.getCapturedDecl();
2256 const RecordDecl *RD = S.getCapturedRecordDecl();
2257 SourceLocation Loc = S.getLocStart();
2258 assert(CD->hasBody() && "missing CapturedDecl body");
2260 // Build the argument list.
2261 ASTContext &Ctx = CGM.getContext();
2262 FunctionArgList Args;
2263 Args.append(CD->param_begin(), CD->param_end());
2265 // Create the function declaration.
2266 FunctionType::ExtInfo ExtInfo;
2267 const CGFunctionInfo &FuncInfo =
2268 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Args);
2269 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
2272 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
2273 CapturedStmtInfo->getHelperName(), &CGM.getModule());
2274 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
2275 if (CD->isNothrow())
2276 F->addFnAttr(llvm::Attribute::NoUnwind);
2278 // Generate the function.
2279 StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args,
2281 CD->getBody()->getLocStart());
2282 // Set the context parameter in CapturedStmtInfo.
2283 Address DeclPtr = GetAddrOfLocalVar(CD->getContextParam());
2284 CapturedStmtInfo->setContextValue(Builder.CreateLoad(DeclPtr));
2286 // Initialize variable-length arrays.
2287 LValue Base = MakeNaturalAlignAddrLValue(CapturedStmtInfo->getContextValue(),
2288 Ctx.getTagDeclType(RD));
2289 for (auto *FD : RD->fields()) {
2290 if (FD->hasCapturedVLAType()) {
2291 auto *ExprArg = EmitLoadOfLValue(EmitLValueForField(Base, FD),
2292 S.getLocStart()).getScalarVal();
2293 auto VAT = FD->getCapturedVLAType();
2294 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
2298 // If 'this' is captured, load it into CXXThisValue.
2299 if (CapturedStmtInfo->isCXXThisExprCaptured()) {
2300 FieldDecl *FD = CapturedStmtInfo->getThisFieldDecl();
2301 LValue ThisLValue = EmitLValueForField(Base, FD);
2302 CXXThisValue = EmitLoadOfLValue(ThisLValue, Loc).getScalarVal();
2305 PGO.assignRegionCounters(GlobalDecl(CD), F);
2306 CapturedStmtInfo->EmitBody(*this, CD->getBody());
2307 FinishFunction(CD->getBodyRBrace());