Home | History | Annotate | Download | only in CodeGen
      1 //===--- CGStmt.cpp - Emit LLVM Code from Statements ----------------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This contains code to emit Stmt nodes as LLVM code.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     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/PrettyStackTrace.h"
     20 #include "clang/Basic/TargetInfo.h"
     21 #include "clang/Sema/LoopHint.h"
     22 #include "clang/Sema/SemaDiagnostic.h"
     23 #include "llvm/ADT/StringExtras.h"
     24 #include "llvm/IR/CallSite.h"
     25 #include "llvm/IR/DataLayout.h"
     26 #include "llvm/IR/InlineAsm.h"
     27 #include "llvm/IR/Intrinsics.h"
     28 using namespace clang;
     29 using namespace CodeGen;
     30 
     31 //===----------------------------------------------------------------------===//
     32 //                              Statement Emission
     33 //===----------------------------------------------------------------------===//
     34 
     35 void CodeGenFunction::EmitStopPoint(const Stmt *S) {
     36   if (CGDebugInfo *DI = getDebugInfo()) {
     37     SourceLocation Loc;
     38     Loc = S->getLocStart();
     39     DI->EmitLocation(Builder, Loc);
     40 
     41     LastStopPoint = Loc;
     42   }
     43 }
     44 
     45 void CodeGenFunction::EmitStmt(const Stmt *S) {
     46   assert(S && "Null statement?");
     47   PGO.setCurrentStmt(S);
     48 
     49   // These statements have their own debug info handling.
     50   if (EmitSimpleStmt(S))
     51     return;
     52 
     53   // Check if we are generating unreachable code.
     54   if (!HaveInsertPoint()) {
     55     // If so, and the statement doesn't contain a label, then we do not need to
     56     // generate actual code. This is safe because (1) the current point is
     57     // unreachable, so we don't need to execute the code, and (2) we've already
     58     // handled the statements which update internal data structures (like the
     59     // local variable map) which could be used by subsequent statements.
     60     if (!ContainsLabel(S)) {
     61       // Verify that any decl statements were handled as simple, they may be in
     62       // scope of subsequent reachable statements.
     63       assert(!isa<DeclStmt>(*S) && "Unexpected DeclStmt!");
     64       return;
     65     }
     66 
     67     // Otherwise, make a new block to hold the code.
     68     EnsureInsertPoint();
     69   }
     70 
     71   // Generate a stoppoint if we are emitting debug info.
     72   EmitStopPoint(S);
     73 
     74   switch (S->getStmtClass()) {
     75   case Stmt::NoStmtClass:
     76   case Stmt::CXXCatchStmtClass:
     77   case Stmt::SEHExceptStmtClass:
     78   case Stmt::SEHFinallyStmtClass:
     79   case Stmt::MSDependentExistsStmtClass:
     80     llvm_unreachable("invalid statement class to emit generically");
     81   case Stmt::NullStmtClass:
     82   case Stmt::CompoundStmtClass:
     83   case Stmt::DeclStmtClass:
     84   case Stmt::LabelStmtClass:
     85   case Stmt::AttributedStmtClass:
     86   case Stmt::GotoStmtClass:
     87   case Stmt::BreakStmtClass:
     88   case Stmt::ContinueStmtClass:
     89   case Stmt::DefaultStmtClass:
     90   case Stmt::CaseStmtClass:
     91   case Stmt::SEHLeaveStmtClass:
     92     llvm_unreachable("should have emitted these statements as simple");
     93 
     94 #define STMT(Type, Base)
     95 #define ABSTRACT_STMT(Op)
     96 #define EXPR(Type, Base) \
     97   case Stmt::Type##Class:
     98 #include "clang/AST/StmtNodes.inc"
     99   {
    100     // Remember the block we came in on.
    101     llvm::BasicBlock *incoming = Builder.GetInsertBlock();
    102     assert(incoming && "expression emission must have an insertion point");
    103 
    104     EmitIgnoredExpr(cast<Expr>(S));
    105 
    106     llvm::BasicBlock *outgoing = Builder.GetInsertBlock();
    107     assert(outgoing && "expression emission cleared block!");
    108 
    109     // The expression emitters assume (reasonably!) that the insertion
    110     // point is always set.  To maintain that, the call-emission code
    111     // for noreturn functions has to enter a new block with no
    112     // predecessors.  We want to kill that block and mark the current
    113     // insertion point unreachable in the common case of a call like
    114     // "exit();".  Since expression emission doesn't otherwise create
    115     // blocks with no predecessors, we can just test for that.
    116     // However, we must be careful not to do this to our incoming
    117     // block, because *statement* emission does sometimes create
    118     // reachable blocks which will have no predecessors until later in
    119     // the function.  This occurs with, e.g., labels that are not
    120     // reachable by fallthrough.
    121     if (incoming != outgoing && outgoing->use_empty()) {
    122       outgoing->eraseFromParent();
    123       Builder.ClearInsertionPoint();
    124     }
    125     break;
    126   }
    127 
    128   case Stmt::IndirectGotoStmtClass:
    129     EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
    130 
    131   case Stmt::IfStmtClass:       EmitIfStmt(cast<IfStmt>(*S));             break;
    132   case Stmt::WhileStmtClass:    EmitWhileStmt(cast<WhileStmt>(*S));       break;
    133   case Stmt::DoStmtClass:       EmitDoStmt(cast<DoStmt>(*S));             break;
    134   case Stmt::ForStmtClass:      EmitForStmt(cast<ForStmt>(*S));           break;
    135 
    136   case Stmt::ReturnStmtClass:   EmitReturnStmt(cast<ReturnStmt>(*S));     break;
    137 
    138   case Stmt::SwitchStmtClass:   EmitSwitchStmt(cast<SwitchStmt>(*S));     break;
    139   case Stmt::GCCAsmStmtClass:   // Intentional fall-through.
    140   case Stmt::MSAsmStmtClass:    EmitAsmStmt(cast<AsmStmt>(*S));           break;
    141   case Stmt::CapturedStmtClass: {
    142     const CapturedStmt *CS = cast<CapturedStmt>(S);
    143     EmitCapturedStmt(*CS, CS->getCapturedRegionKind());
    144     }
    145     break;
    146   case Stmt::ObjCAtTryStmtClass:
    147     EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
    148     break;
    149   case Stmt::ObjCAtCatchStmtClass:
    150     llvm_unreachable(
    151                     "@catch statements should be handled by EmitObjCAtTryStmt");
    152   case Stmt::ObjCAtFinallyStmtClass:
    153     llvm_unreachable(
    154                   "@finally statements should be handled by EmitObjCAtTryStmt");
    155   case Stmt::ObjCAtThrowStmtClass:
    156     EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
    157     break;
    158   case Stmt::ObjCAtSynchronizedStmtClass:
    159     EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
    160     break;
    161   case Stmt::ObjCForCollectionStmtClass:
    162     EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
    163     break;
    164   case Stmt::ObjCAutoreleasePoolStmtClass:
    165     EmitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(*S));
    166     break;
    167 
    168   case Stmt::CXXTryStmtClass:
    169     EmitCXXTryStmt(cast<CXXTryStmt>(*S));
    170     break;
    171   case Stmt::CXXForRangeStmtClass:
    172     EmitCXXForRangeStmt(cast<CXXForRangeStmt>(*S));
    173     break;
    174   case Stmt::SEHTryStmtClass:
    175     EmitSEHTryStmt(cast<SEHTryStmt>(*S));
    176     break;
    177   case Stmt::OMPParallelDirectiveClass:
    178     EmitOMPParallelDirective(cast<OMPParallelDirective>(*S));
    179     break;
    180   case Stmt::OMPSimdDirectiveClass:
    181     EmitOMPSimdDirective(cast<OMPSimdDirective>(*S));
    182     break;
    183   case Stmt::OMPForDirectiveClass:
    184     EmitOMPForDirective(cast<OMPForDirective>(*S));
    185     break;
    186   case Stmt::OMPForSimdDirectiveClass:
    187     EmitOMPForSimdDirective(cast<OMPForSimdDirective>(*S));
    188     break;
    189   case Stmt::OMPSectionsDirectiveClass:
    190     EmitOMPSectionsDirective(cast<OMPSectionsDirective>(*S));
    191     break;
    192   case Stmt::OMPSectionDirectiveClass:
    193     EmitOMPSectionDirective(cast<OMPSectionDirective>(*S));
    194     break;
    195   case Stmt::OMPSingleDirectiveClass:
    196     EmitOMPSingleDirective(cast<OMPSingleDirective>(*S));
    197     break;
    198   case Stmt::OMPMasterDirectiveClass:
    199     EmitOMPMasterDirective(cast<OMPMasterDirective>(*S));
    200     break;
    201   case Stmt::OMPCriticalDirectiveClass:
    202     EmitOMPCriticalDirective(cast<OMPCriticalDirective>(*S));
    203     break;
    204   case Stmt::OMPParallelForDirectiveClass:
    205     EmitOMPParallelForDirective(cast<OMPParallelForDirective>(*S));
    206     break;
    207   case Stmt::OMPParallelForSimdDirectiveClass:
    208     EmitOMPParallelForSimdDirective(cast<OMPParallelForSimdDirective>(*S));
    209     break;
    210   case Stmt::OMPParallelSectionsDirectiveClass:
    211     EmitOMPParallelSectionsDirective(cast<OMPParallelSectionsDirective>(*S));
    212     break;
    213   case Stmt::OMPTaskDirectiveClass:
    214     EmitOMPTaskDirective(cast<OMPTaskDirective>(*S));
    215     break;
    216   case Stmt::OMPTaskyieldDirectiveClass:
    217     EmitOMPTaskyieldDirective(cast<OMPTaskyieldDirective>(*S));
    218     break;
    219   case Stmt::OMPBarrierDirectiveClass:
    220     EmitOMPBarrierDirective(cast<OMPBarrierDirective>(*S));
    221     break;
    222   case Stmt::OMPTaskwaitDirectiveClass:
    223     EmitOMPTaskwaitDirective(cast<OMPTaskwaitDirective>(*S));
    224     break;
    225   case Stmt::OMPFlushDirectiveClass:
    226     EmitOMPFlushDirective(cast<OMPFlushDirective>(*S));
    227     break;
    228   case Stmt::OMPOrderedDirectiveClass:
    229     EmitOMPOrderedDirective(cast<OMPOrderedDirective>(*S));
    230     break;
    231   case Stmt::OMPAtomicDirectiveClass:
    232     EmitOMPAtomicDirective(cast<OMPAtomicDirective>(*S));
    233     break;
    234   case Stmt::OMPTargetDirectiveClass:
    235     EmitOMPTargetDirective(cast<OMPTargetDirective>(*S));
    236     break;
    237   case Stmt::OMPTeamsDirectiveClass:
    238     EmitOMPTeamsDirective(cast<OMPTeamsDirective>(*S));
    239     break;
    240   }
    241 }
    242 
    243 bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
    244   switch (S->getStmtClass()) {
    245   default: return false;
    246   case Stmt::NullStmtClass: break;
    247   case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
    248   case Stmt::DeclStmtClass:     EmitDeclStmt(cast<DeclStmt>(*S));         break;
    249   case Stmt::LabelStmtClass:    EmitLabelStmt(cast<LabelStmt>(*S));       break;
    250   case Stmt::AttributedStmtClass:
    251                             EmitAttributedStmt(cast<AttributedStmt>(*S)); break;
    252   case Stmt::GotoStmtClass:     EmitGotoStmt(cast<GotoStmt>(*S));         break;
    253   case Stmt::BreakStmtClass:    EmitBreakStmt(cast<BreakStmt>(*S));       break;
    254   case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
    255   case Stmt::DefaultStmtClass:  EmitDefaultStmt(cast<DefaultStmt>(*S));   break;
    256   case Stmt::CaseStmtClass:     EmitCaseStmt(cast<CaseStmt>(*S));         break;
    257   case Stmt::SEHLeaveStmtClass: EmitSEHLeaveStmt(cast<SEHLeaveStmt>(*S)); break;
    258   }
    259 
    260   return true;
    261 }
    262 
    263 /// EmitCompoundStmt - Emit a compound statement {..} node.  If GetLast is true,
    264 /// this captures the expression result of the last sub-statement and returns it
    265 /// (for use by the statement expression extension).
    266 llvm::Value* CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
    267                                                AggValueSlot AggSlot) {
    268   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(),
    269                              "LLVM IR generation of compound statement ('{}')");
    270 
    271   // Keep track of the current cleanup stack depth, including debug scopes.
    272   LexicalScope Scope(*this, S.getSourceRange());
    273 
    274   return EmitCompoundStmtWithoutScope(S, GetLast, AggSlot);
    275 }
    276 
    277 llvm::Value*
    278 CodeGenFunction::EmitCompoundStmtWithoutScope(const CompoundStmt &S,
    279                                               bool GetLast,
    280                                               AggValueSlot AggSlot) {
    281 
    282   for (CompoundStmt::const_body_iterator I = S.body_begin(),
    283        E = S.body_end()-GetLast; I != E; ++I)
    284     EmitStmt(*I);
    285 
    286   llvm::Value *RetAlloca = nullptr;
    287   if (GetLast) {
    288     // We have to special case labels here.  They are statements, but when put
    289     // at the end of a statement expression, they yield the value of their
    290     // subexpression.  Handle this by walking through all labels we encounter,
    291     // emitting them before we evaluate the subexpr.
    292     const Stmt *LastStmt = S.body_back();
    293     while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
    294       EmitLabel(LS->getDecl());
    295       LastStmt = LS->getSubStmt();
    296     }
    297 
    298     EnsureInsertPoint();
    299 
    300     QualType ExprTy = cast<Expr>(LastStmt)->getType();
    301     if (hasAggregateEvaluationKind(ExprTy)) {
    302       EmitAggExpr(cast<Expr>(LastStmt), AggSlot);
    303     } else {
    304       // We can't return an RValue here because there might be cleanups at
    305       // the end of the StmtExpr.  Because of that, we have to emit the result
    306       // here into a temporary alloca.
    307       RetAlloca = CreateMemTemp(ExprTy);
    308       EmitAnyExprToMem(cast<Expr>(LastStmt), RetAlloca, Qualifiers(),
    309                        /*IsInit*/false);
    310     }
    311 
    312   }
    313 
    314   return RetAlloca;
    315 }
    316 
    317 void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) {
    318   llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(BB->getTerminator());
    319 
    320   // If there is a cleanup stack, then we it isn't worth trying to
    321   // simplify this block (we would need to remove it from the scope map
    322   // and cleanup entry).
    323   if (!EHStack.empty())
    324     return;
    325 
    326   // Can only simplify direct branches.
    327   if (!BI || !BI->isUnconditional())
    328     return;
    329 
    330   // Can only simplify empty blocks.
    331   if (BI != BB->begin())
    332     return;
    333 
    334   BB->replaceAllUsesWith(BI->getSuccessor(0));
    335   BI->eraseFromParent();
    336   BB->eraseFromParent();
    337 }
    338 
    339 void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
    340   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
    341 
    342   // Fall out of the current block (if necessary).
    343   EmitBranch(BB);
    344 
    345   if (IsFinished && BB->use_empty()) {
    346     delete BB;
    347     return;
    348   }
    349 
    350   // Place the block after the current block, if possible, or else at
    351   // the end of the function.
    352   if (CurBB && CurBB->getParent())
    353     CurFn->getBasicBlockList().insertAfter(CurBB, BB);
    354   else
    355     CurFn->getBasicBlockList().push_back(BB);
    356   Builder.SetInsertPoint(BB);
    357 }
    358 
    359 void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
    360   // Emit a branch from the current block to the target one if this
    361   // was a real block.  If this was just a fall-through block after a
    362   // terminator, don't emit it.
    363   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
    364 
    365   if (!CurBB || CurBB->getTerminator()) {
    366     // If there is no insert point or the previous block is already
    367     // terminated, don't touch it.
    368   } else {
    369     // Otherwise, create a fall-through branch.
    370     Builder.CreateBr(Target);
    371   }
    372 
    373   Builder.ClearInsertionPoint();
    374 }
    375 
    376 void CodeGenFunction::EmitBlockAfterUses(llvm::BasicBlock *block) {
    377   bool inserted = false;
    378   for (llvm::User *u : block->users()) {
    379     if (llvm::Instruction *insn = dyn_cast<llvm::Instruction>(u)) {
    380       CurFn->getBasicBlockList().insertAfter(insn->getParent(), block);
    381       inserted = true;
    382       break;
    383     }
    384   }
    385 
    386   if (!inserted)
    387     CurFn->getBasicBlockList().push_back(block);
    388 
    389   Builder.SetInsertPoint(block);
    390 }
    391 
    392 CodeGenFunction::JumpDest
    393 CodeGenFunction::getJumpDestForLabel(const LabelDecl *D) {
    394   JumpDest &Dest = LabelMap[D];
    395   if (Dest.isValid()) return Dest;
    396 
    397   // Create, but don't insert, the new block.
    398   Dest = JumpDest(createBasicBlock(D->getName()),
    399                   EHScopeStack::stable_iterator::invalid(),
    400                   NextCleanupDestIndex++);
    401   return Dest;
    402 }
    403 
    404 void CodeGenFunction::EmitLabel(const LabelDecl *D) {
    405   // Add this label to the current lexical scope if we're within any
    406   // normal cleanups.  Jumps "in" to this label --- when permitted by
    407   // the language --- may need to be routed around such cleanups.
    408   if (EHStack.hasNormalCleanups() && CurLexicalScope)
    409     CurLexicalScope->addLabel(D);
    410 
    411   JumpDest &Dest = LabelMap[D];
    412 
    413   // If we didn't need a forward reference to this label, just go
    414   // ahead and create a destination at the current scope.
    415   if (!Dest.isValid()) {
    416     Dest = getJumpDestInCurrentScope(D->getName());
    417 
    418   // Otherwise, we need to give this label a target depth and remove
    419   // it from the branch-fixups list.
    420   } else {
    421     assert(!Dest.getScopeDepth().isValid() && "already emitted label!");
    422     Dest.setScopeDepth(EHStack.stable_begin());
    423     ResolveBranchFixups(Dest.getBlock());
    424   }
    425 
    426   RegionCounter Cnt = getPGORegionCounter(D->getStmt());
    427   EmitBlock(Dest.getBlock());
    428   Cnt.beginRegion(Builder);
    429 }
    430 
    431 /// Change the cleanup scope of the labels in this lexical scope to
    432 /// match the scope of the enclosing context.
    433 void CodeGenFunction::LexicalScope::rescopeLabels() {
    434   assert(!Labels.empty());
    435   EHScopeStack::stable_iterator innermostScope
    436     = CGF.EHStack.getInnermostNormalCleanup();
    437 
    438   // Change the scope depth of all the labels.
    439   for (SmallVectorImpl<const LabelDecl*>::const_iterator
    440          i = Labels.begin(), e = Labels.end(); i != e; ++i) {
    441     assert(CGF.LabelMap.count(*i));
    442     JumpDest &dest = CGF.LabelMap.find(*i)->second;
    443     assert(dest.getScopeDepth().isValid());
    444     assert(innermostScope.encloses(dest.getScopeDepth()));
    445     dest.setScopeDepth(innermostScope);
    446   }
    447 
    448   // Reparent the labels if the new scope also has cleanups.
    449   if (innermostScope != EHScopeStack::stable_end() && ParentScope) {
    450     ParentScope->Labels.append(Labels.begin(), Labels.end());
    451   }
    452 }
    453 
    454 
    455 void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
    456   EmitLabel(S.getDecl());
    457   EmitStmt(S.getSubStmt());
    458 }
    459 
    460 void CodeGenFunction::EmitAttributedStmt(const AttributedStmt &S) {
    461   const Stmt *SubStmt = S.getSubStmt();
    462   switch (SubStmt->getStmtClass()) {
    463   case Stmt::DoStmtClass:
    464     EmitDoStmt(cast<DoStmt>(*SubStmt), S.getAttrs());
    465     break;
    466   case Stmt::ForStmtClass:
    467     EmitForStmt(cast<ForStmt>(*SubStmt), S.getAttrs());
    468     break;
    469   case Stmt::WhileStmtClass:
    470     EmitWhileStmt(cast<WhileStmt>(*SubStmt), S.getAttrs());
    471     break;
    472   case Stmt::CXXForRangeStmtClass:
    473     EmitCXXForRangeStmt(cast<CXXForRangeStmt>(*SubStmt), S.getAttrs());
    474     break;
    475   default:
    476     EmitStmt(SubStmt);
    477   }
    478 }
    479 
    480 void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
    481   // If this code is reachable then emit a stop point (if generating
    482   // debug info). We have to do this ourselves because we are on the
    483   // "simple" statement path.
    484   if (HaveInsertPoint())
    485     EmitStopPoint(&S);
    486 
    487   EmitBranchThroughCleanup(getJumpDestForLabel(S.getLabel()));
    488 }
    489 
    490 
    491 void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
    492   if (const LabelDecl *Target = S.getConstantTarget()) {
    493     EmitBranchThroughCleanup(getJumpDestForLabel(Target));
    494     return;
    495   }
    496 
    497   // Ensure that we have an i8* for our PHI node.
    498   llvm::Value *V = Builder.CreateBitCast(EmitScalarExpr(S.getTarget()),
    499                                          Int8PtrTy, "addr");
    500   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
    501 
    502   // Get the basic block for the indirect goto.
    503   llvm::BasicBlock *IndGotoBB = GetIndirectGotoBlock();
    504 
    505   // The first instruction in the block has to be the PHI for the switch dest,
    506   // add an entry for this branch.
    507   cast<llvm::PHINode>(IndGotoBB->begin())->addIncoming(V, CurBB);
    508 
    509   EmitBranch(IndGotoBB);
    510 }
    511 
    512 void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
    513   // C99 6.8.4.1: The first substatement is executed if the expression compares
    514   // unequal to 0.  The condition must be a scalar type.
    515   LexicalScope ConditionScope(*this, S.getCond()->getSourceRange());
    516   RegionCounter Cnt = getPGORegionCounter(&S);
    517 
    518   if (S.getConditionVariable())
    519     EmitAutoVarDecl(*S.getConditionVariable());
    520 
    521   // If the condition constant folds and can be elided, try to avoid emitting
    522   // the condition and the dead arm of the if/else.
    523   bool CondConstant;
    524   if (ConstantFoldsToSimpleInteger(S.getCond(), CondConstant)) {
    525     // Figure out which block (then or else) is executed.
    526     const Stmt *Executed = S.getThen();
    527     const Stmt *Skipped  = S.getElse();
    528     if (!CondConstant)  // Condition false?
    529       std::swap(Executed, Skipped);
    530 
    531     // If the skipped block has no labels in it, just emit the executed block.
    532     // This avoids emitting dead code and simplifies the CFG substantially.
    533     if (!ContainsLabel(Skipped)) {
    534       if (CondConstant)
    535         Cnt.beginRegion(Builder);
    536       if (Executed) {
    537         RunCleanupsScope ExecutedScope(*this);
    538         EmitStmt(Executed);
    539       }
    540       return;
    541     }
    542   }
    543 
    544   // Otherwise, the condition did not fold, or we couldn't elide it.  Just emit
    545   // the conditional branch.
    546   llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
    547   llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
    548   llvm::BasicBlock *ElseBlock = ContBlock;
    549   if (S.getElse())
    550     ElseBlock = createBasicBlock("if.else");
    551 
    552   EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock, Cnt.getCount());
    553 
    554   // Emit the 'then' code.
    555   EmitBlock(ThenBlock);
    556   Cnt.beginRegion(Builder);
    557   {
    558     RunCleanupsScope ThenScope(*this);
    559     EmitStmt(S.getThen());
    560   }
    561   EmitBranch(ContBlock);
    562 
    563   // Emit the 'else' code if present.
    564   if (const Stmt *Else = S.getElse()) {
    565     {
    566       // There is no need to emit line number for an unconditional branch.
    567       auto NL = ApplyDebugLocation::CreateEmpty(*this);
    568       EmitBlock(ElseBlock);
    569     }
    570     {
    571       RunCleanupsScope ElseScope(*this);
    572       EmitStmt(Else);
    573     }
    574     {
    575       // There is no need to emit line number for an unconditional branch.
    576       auto NL = ApplyDebugLocation::CreateEmpty(*this);
    577       EmitBranch(ContBlock);
    578     }
    579   }
    580 
    581   // Emit the continuation block for code after the if.
    582   EmitBlock(ContBlock, true);
    583 }
    584 
    585 void CodeGenFunction::EmitCondBrHints(llvm::LLVMContext &Context,
    586                                       llvm::BranchInst *CondBr,
    587                                       ArrayRef<const Attr *> Attrs) {
    588   // Return if there are no hints.
    589   if (Attrs.empty())
    590     return;
    591 
    592   // Add vectorize and unroll hints to the metadata on the conditional branch.
    593   //
    594   // FIXME: Should this really start with a size of 1?
    595   SmallVector<llvm::Metadata *, 2> Metadata(1);
    596   for (const auto *Attr : Attrs) {
    597     const LoopHintAttr *LH = dyn_cast<LoopHintAttr>(Attr);
    598 
    599     // Skip non loop hint attributes
    600     if (!LH)
    601       continue;
    602 
    603     LoopHintAttr::OptionType Option = LH->getOption();
    604     LoopHintAttr::LoopHintState State = LH->getState();
    605     const char *MetadataName;
    606     switch (Option) {
    607     case LoopHintAttr::Vectorize:
    608     case LoopHintAttr::VectorizeWidth:
    609       MetadataName = "llvm.loop.vectorize.width";
    610       break;
    611     case LoopHintAttr::Interleave:
    612     case LoopHintAttr::InterleaveCount:
    613       MetadataName = "llvm.loop.interleave.count";
    614       break;
    615     case LoopHintAttr::Unroll:
    616       // With the unroll loop hint, a non-zero value indicates full unrolling.
    617       MetadataName = State == LoopHintAttr::Disable ? "llvm.loop.unroll.disable"
    618                                                     : "llvm.loop.unroll.full";
    619       break;
    620     case LoopHintAttr::UnrollCount:
    621       MetadataName = "llvm.loop.unroll.count";
    622       break;
    623     }
    624 
    625     Expr *ValueExpr = LH->getValue();
    626     int ValueInt = 1;
    627     if (ValueExpr) {
    628       llvm::APSInt ValueAPS =
    629           ValueExpr->EvaluateKnownConstInt(CGM.getContext());
    630       ValueInt = static_cast<int>(ValueAPS.getSExtValue());
    631     }
    632 
    633     llvm::Constant *Value;
    634     llvm::MDString *Name;
    635     switch (Option) {
    636     case LoopHintAttr::Vectorize:
    637     case LoopHintAttr::Interleave:
    638       if (State != LoopHintAttr::Disable) {
    639         // FIXME: In the future I will modifiy the behavior of the metadata
    640         // so we can enable/disable vectorization and interleaving separately.
    641         Name = llvm::MDString::get(Context, "llvm.loop.vectorize.enable");
    642         Value = Builder.getTrue();
    643         break;
    644       }
    645       // Vectorization/interleaving is disabled, set width/count to 1.
    646       ValueInt = 1;
    647       // Fallthrough.
    648     case LoopHintAttr::VectorizeWidth:
    649     case LoopHintAttr::InterleaveCount:
    650     case LoopHintAttr::UnrollCount:
    651       Name = llvm::MDString::get(Context, MetadataName);
    652       Value = llvm::ConstantInt::get(Int32Ty, ValueInt);
    653       break;
    654     case LoopHintAttr::Unroll:
    655       Name = llvm::MDString::get(Context, MetadataName);
    656       Value = nullptr;
    657       break;
    658     }
    659 
    660     SmallVector<llvm::Metadata *, 2> OpValues;
    661     OpValues.push_back(Name);
    662     if (Value)
    663       OpValues.push_back(llvm::ConstantAsMetadata::get(Value));
    664 
    665     // Set or overwrite metadata indicated by Name.
    666     Metadata.push_back(llvm::MDNode::get(Context, OpValues));
    667   }
    668 
    669   // FIXME: This condition is never false.  Should it be an assert?
    670   if (!Metadata.empty()) {
    671     // Add llvm.loop MDNode to CondBr.
    672     llvm::MDNode *LoopID = llvm::MDNode::get(Context, Metadata);
    673     LoopID->replaceOperandWith(0, LoopID); // First op points to itself.
    674 
    675     CondBr->setMetadata("llvm.loop", LoopID);
    676   }
    677 }
    678 
    679 void CodeGenFunction::EmitWhileStmt(const WhileStmt &S,
    680                                     ArrayRef<const Attr *> WhileAttrs) {
    681   RegionCounter Cnt = getPGORegionCounter(&S);
    682 
    683   // Emit the header for the loop, which will also become
    684   // the continue target.
    685   JumpDest LoopHeader = getJumpDestInCurrentScope("while.cond");
    686   EmitBlock(LoopHeader.getBlock());
    687 
    688   LoopStack.push(LoopHeader.getBlock());
    689 
    690   // Create an exit block for when the condition fails, which will
    691   // also become the break target.
    692   JumpDest LoopExit = getJumpDestInCurrentScope("while.end");
    693 
    694   // Store the blocks to use for break and continue.
    695   BreakContinueStack.push_back(BreakContinue(LoopExit, LoopHeader));
    696 
    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.
    701   //   [...]
    702   //   The object created in a condition is destroyed and created
    703   //   with each iteration of the loop.
    704   RunCleanupsScope ConditionScope(*this);
    705 
    706   if (S.getConditionVariable())
    707     EmitAutoVarDecl(*S.getConditionVariable());
    708 
    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());
    713 
    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))
    718     if (C->isOne())
    719       EmitBoolCondBranch = false;
    720 
    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     llvm::BranchInst *CondBr =
    728         Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock,
    729                              PGO.createLoopWeights(S.getCond(), Cnt));
    730 
    731     if (ExitBlock != LoopExit.getBlock()) {
    732       EmitBlock(ExitBlock);
    733       EmitBranchThroughCleanup(LoopExit);
    734     }
    735 
    736     // Attach metadata to loop body conditional branch.
    737     EmitCondBrHints(LoopBody->getContext(), CondBr, WhileAttrs);
    738   }
    739 
    740   // Emit the loop body.  We have to emit this in a cleanup scope
    741   // because it might be a singleton DeclStmt.
    742   {
    743     RunCleanupsScope BodyScope(*this);
    744     EmitBlock(LoopBody);
    745     Cnt.beginRegion(Builder);
    746     EmitStmt(S.getBody());
    747   }
    748 
    749   BreakContinueStack.pop_back();
    750 
    751   // Immediately force cleanup.
    752   ConditionScope.ForceCleanup();
    753 
    754   EmitStopPoint(&S);
    755   // Branch to the loop header again.
    756   EmitBranch(LoopHeader.getBlock());
    757 
    758   LoopStack.pop();
    759 
    760   // Emit the exit block.
    761   EmitBlock(LoopExit.getBlock(), true);
    762 
    763   // The LoopHeader typically is just a branch if we skipped emitting
    764   // a branch, try to erase it.
    765   if (!EmitBoolCondBranch)
    766     SimplifyForwardingBlocks(LoopHeader.getBlock());
    767 }
    768 
    769 void CodeGenFunction::EmitDoStmt(const DoStmt &S,
    770                                  ArrayRef<const Attr *> DoAttrs) {
    771   JumpDest LoopExit = getJumpDestInCurrentScope("do.end");
    772   JumpDest LoopCond = getJumpDestInCurrentScope("do.cond");
    773 
    774   RegionCounter Cnt = getPGORegionCounter(&S);
    775 
    776   // Store the blocks to use for break and continue.
    777   BreakContinueStack.push_back(BreakContinue(LoopExit, LoopCond));
    778 
    779   // Emit the body of the loop.
    780   llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
    781 
    782   LoopStack.push(LoopBody);
    783 
    784   EmitBlockWithFallThrough(LoopBody, Cnt);
    785   {
    786     RunCleanupsScope BodyScope(*this);
    787     EmitStmt(S.getBody());
    788   }
    789 
    790   EmitBlock(LoopCond.getBlock());
    791 
    792   // C99 6.8.5.2: "The evaluation of the controlling expression takes place
    793   // after each execution of the loop body."
    794 
    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());
    799 
    800   BreakContinueStack.pop_back();
    801 
    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))
    806     if (C->isZero())
    807       EmitBoolCondBranch = false;
    808 
    809   // As long as the condition is true, iterate the loop.
    810   if (EmitBoolCondBranch) {
    811     llvm::BranchInst *CondBr =
    812         Builder.CreateCondBr(BoolCondVal, LoopBody, LoopExit.getBlock(),
    813                              PGO.createLoopWeights(S.getCond(), Cnt));
    814 
    815     // Attach metadata to loop body conditional branch.
    816     EmitCondBrHints(LoopBody->getContext(), CondBr, DoAttrs);
    817   }
    818 
    819   LoopStack.pop();
    820 
    821   // Emit the exit block.
    822   EmitBlock(LoopExit.getBlock());
    823 
    824   // The DoCond block typically is just a branch if we skipped
    825   // emitting a branch, try to erase it.
    826   if (!EmitBoolCondBranch)
    827     SimplifyForwardingBlocks(LoopCond.getBlock());
    828 }
    829 
    830 void CodeGenFunction::EmitForStmt(const ForStmt &S,
    831                                   ArrayRef<const Attr *> ForAttrs) {
    832   JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
    833 
    834   LexicalScope ForScope(*this, S.getSourceRange());
    835 
    836   // Evaluate the first part before the loop.
    837   if (S.getInit())
    838     EmitStmt(S.getInit());
    839 
    840   RegionCounter Cnt = getPGORegionCounter(&S);
    841 
    842   // Start the loop with a block that tests the condition.
    843   // If there's an increment, the continue scope will be overwritten
    844   // later.
    845   JumpDest Continue = getJumpDestInCurrentScope("for.cond");
    846   llvm::BasicBlock *CondBlock = Continue.getBlock();
    847   EmitBlock(CondBlock);
    848 
    849   LoopStack.push(CondBlock);
    850 
    851   // If the for loop doesn't have an increment we can just use the
    852   // condition as the continue block.  Otherwise we'll need to create
    853   // a block for it (in the current scope, i.e. in the scope of the
    854   // condition), and that we will become our continue block.
    855   if (S.getInc())
    856     Continue = getJumpDestInCurrentScope("for.inc");
    857 
    858   // Store the blocks to use for break and continue.
    859   BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
    860 
    861   // Create a cleanup scope for the condition variable cleanups.
    862   LexicalScope ConditionScope(*this, S.getSourceRange());
    863 
    864   if (S.getCond()) {
    865     // If the for statement has a condition scope, emit the local variable
    866     // declaration.
    867     if (S.getConditionVariable()) {
    868       EmitAutoVarDecl(*S.getConditionVariable());
    869     }
    870 
    871     llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
    872     // If there are any cleanups between here and the loop-exit scope,
    873     // create a block to stage a loop exit along.
    874     if (ForScope.requiresCleanups())
    875       ExitBlock = createBasicBlock("for.cond.cleanup");
    876 
    877     // As long as the condition is true, iterate the loop.
    878     llvm::BasicBlock *ForBody = createBasicBlock("for.body");
    879 
    880     // C99 6.8.5p2/p4: The first substatement is executed if the expression
    881     // compares unequal to 0.  The condition must be a scalar type.
    882     llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
    883     llvm::BranchInst *CondBr =
    884         Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock,
    885                              PGO.createLoopWeights(S.getCond(), Cnt));
    886 
    887     // Attach metadata to loop body conditional branch.
    888     EmitCondBrHints(ForBody->getContext(), CondBr, ForAttrs);
    889 
    890     if (ExitBlock != LoopExit.getBlock()) {
    891       EmitBlock(ExitBlock);
    892       EmitBranchThroughCleanup(LoopExit);
    893     }
    894 
    895     EmitBlock(ForBody);
    896   } else {
    897     // Treat it as a non-zero constant.  Don't even create a new block for the
    898     // body, just fall into it.
    899   }
    900   Cnt.beginRegion(Builder);
    901 
    902   {
    903     // Create a separate cleanup scope for the body, in case it is not
    904     // a compound statement.
    905     RunCleanupsScope BodyScope(*this);
    906     EmitStmt(S.getBody());
    907   }
    908 
    909   // If there is an increment, emit it next.
    910   if (S.getInc()) {
    911     EmitBlock(Continue.getBlock());
    912     EmitStmt(S.getInc());
    913   }
    914 
    915   BreakContinueStack.pop_back();
    916 
    917   ConditionScope.ForceCleanup();
    918 
    919   EmitStopPoint(&S);
    920   EmitBranch(CondBlock);
    921 
    922   ForScope.ForceCleanup();
    923 
    924   LoopStack.pop();
    925 
    926   // Emit the fall-through block.
    927   EmitBlock(LoopExit.getBlock(), true);
    928 }
    929 
    930 void
    931 CodeGenFunction::EmitCXXForRangeStmt(const CXXForRangeStmt &S,
    932                                      ArrayRef<const Attr *> ForAttrs) {
    933   JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
    934 
    935   LexicalScope ForScope(*this, S.getSourceRange());
    936 
    937   // Evaluate the first pieces before the loop.
    938   EmitStmt(S.getRangeStmt());
    939   EmitStmt(S.getBeginEndStmt());
    940 
    941   RegionCounter Cnt = getPGORegionCounter(&S);
    942 
    943   // Start the loop with a block that tests the condition.
    944   // If there's an increment, the continue scope will be overwritten
    945   // later.
    946   llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
    947   EmitBlock(CondBlock);
    948 
    949   LoopStack.push(CondBlock);
    950 
    951   // If there are any cleanups between here and the loop-exit scope,
    952   // create a block to stage a loop exit along.
    953   llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
    954   if (ForScope.requiresCleanups())
    955     ExitBlock = createBasicBlock("for.cond.cleanup");
    956 
    957   // The loop body, consisting of the specified body and the loop variable.
    958   llvm::BasicBlock *ForBody = createBasicBlock("for.body");
    959 
    960   // The body is executed if the expression, contextually converted
    961   // to bool, is true.
    962   llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
    963   llvm::BranchInst *CondBr = Builder.CreateCondBr(
    964       BoolCondVal, ForBody, ExitBlock, PGO.createLoopWeights(S.getCond(), Cnt));
    965 
    966   // Attach metadata to loop body conditional branch.
    967   EmitCondBrHints(ForBody->getContext(), CondBr, ForAttrs);
    968 
    969   if (ExitBlock != LoopExit.getBlock()) {
    970     EmitBlock(ExitBlock);
    971     EmitBranchThroughCleanup(LoopExit);
    972   }
    973 
    974   EmitBlock(ForBody);
    975   Cnt.beginRegion(Builder);
    976 
    977   // Create a block for the increment. In case of a 'continue', we jump there.
    978   JumpDest Continue = getJumpDestInCurrentScope("for.inc");
    979 
    980   // Store the blocks to use for break and continue.
    981   BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
    982 
    983   {
    984     // Create a separate cleanup scope for the loop variable and body.
    985     LexicalScope BodyScope(*this, S.getSourceRange());
    986     EmitStmt(S.getLoopVarStmt());
    987     EmitStmt(S.getBody());
    988   }
    989 
    990   EmitStopPoint(&S);
    991   // If there is an increment, emit it next.
    992   EmitBlock(Continue.getBlock());
    993   EmitStmt(S.getInc());
    994 
    995   BreakContinueStack.pop_back();
    996 
    997   EmitBranch(CondBlock);
    998 
    999   ForScope.ForceCleanup();
   1000 
   1001   LoopStack.pop();
   1002 
   1003   // Emit the fall-through block.
   1004   EmitBlock(LoopExit.getBlock(), true);
   1005 }
   1006 
   1007 void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
   1008   if (RV.isScalar()) {
   1009     Builder.CreateStore(RV.getScalarVal(), ReturnValue);
   1010   } else if (RV.isAggregate()) {
   1011     EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
   1012   } else {
   1013     EmitStoreOfComplex(RV.getComplexVal(),
   1014                        MakeNaturalAlignAddrLValue(ReturnValue, Ty),
   1015                        /*init*/ true);
   1016   }
   1017   EmitBranchThroughCleanup(ReturnBlock);
   1018 }
   1019 
   1020 /// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
   1021 /// if the function returns void, or may be missing one if the function returns
   1022 /// non-void.  Fun stuff :).
   1023 void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
   1024   // Returning from an outlined SEH helper is UB, and we already warn on it.
   1025   if (IsOutlinedSEHHelper) {
   1026     Builder.CreateUnreachable();
   1027     Builder.ClearInsertionPoint();
   1028   }
   1029 
   1030   // Emit the result value, even if unused, to evalute the side effects.
   1031   const Expr *RV = S.getRetValue();
   1032 
   1033   // Treat block literals in a return expression as if they appeared
   1034   // in their own scope.  This permits a small, easily-implemented
   1035   // exception to our over-conservative rules about not jumping to
   1036   // statements following block literals with non-trivial cleanups.
   1037   RunCleanupsScope cleanupScope(*this);
   1038   if (const ExprWithCleanups *cleanups =
   1039         dyn_cast_or_null<ExprWithCleanups>(RV)) {
   1040     enterFullExpression(cleanups);
   1041     RV = cleanups->getSubExpr();
   1042   }
   1043 
   1044   // FIXME: Clean this up by using an LValue for ReturnTemp,
   1045   // EmitStoreThroughLValue, and EmitAnyExpr.
   1046   if (getLangOpts().ElideConstructors &&
   1047       S.getNRVOCandidate() && S.getNRVOCandidate()->isNRVOVariable()) {
   1048     // Apply the named return value optimization for this return statement,
   1049     // which means doing nothing: the appropriate result has already been
   1050     // constructed into the NRVO variable.
   1051 
   1052     // If there is an NRVO flag for this variable, set it to 1 into indicate
   1053     // that the cleanup code should not destroy the variable.
   1054     if (llvm::Value *NRVOFlag = NRVOFlags[S.getNRVOCandidate()])
   1055       Builder.CreateStore(Builder.getTrue(), NRVOFlag);
   1056   } else if (!ReturnValue || (RV && RV->getType()->isVoidType())) {
   1057     // Make sure not to return anything, but evaluate the expression
   1058     // for side effects.
   1059     if (RV)
   1060       EmitAnyExpr(RV);
   1061   } else if (!RV) {
   1062     // Do nothing (return value is left uninitialized)
   1063   } else if (FnRetTy->isReferenceType()) {
   1064     // If this function returns a reference, take the address of the expression
   1065     // rather than the value.
   1066     RValue Result = EmitReferenceBindingToExpr(RV);
   1067     Builder.CreateStore(Result.getScalarVal(), ReturnValue);
   1068   } else {
   1069     switch (getEvaluationKind(RV->getType())) {
   1070     case TEK_Scalar:
   1071       Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
   1072       break;
   1073     case TEK_Complex:
   1074       EmitComplexExprIntoLValue(RV,
   1075                      MakeNaturalAlignAddrLValue(ReturnValue, RV->getType()),
   1076                                 /*isInit*/ true);
   1077       break;
   1078     case TEK_Aggregate: {
   1079       CharUnits Alignment = getContext().getTypeAlignInChars(RV->getType());
   1080       EmitAggExpr(RV, AggValueSlot::forAddr(ReturnValue, Alignment,
   1081                                             Qualifiers(),
   1082                                             AggValueSlot::IsDestructed,
   1083                                             AggValueSlot::DoesNotNeedGCBarriers,
   1084                                             AggValueSlot::IsNotAliased));
   1085       break;
   1086     }
   1087     }
   1088   }
   1089 
   1090   ++NumReturnExprs;
   1091   if (!RV || RV->isEvaluatable(getContext()))
   1092     ++NumSimpleReturnExprs;
   1093 
   1094   cleanupScope.ForceCleanup();
   1095   EmitBranchThroughCleanup(ReturnBlock);
   1096 }
   1097 
   1098 void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
   1099   // As long as debug info is modeled with instructions, we have to ensure we
   1100   // have a place to insert here and write the stop point here.
   1101   if (HaveInsertPoint())
   1102     EmitStopPoint(&S);
   1103 
   1104   for (const auto *I : S.decls())
   1105     EmitDecl(*I);
   1106 }
   1107 
   1108 void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
   1109   assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
   1110 
   1111   // If this code is reachable then emit a stop point (if generating
   1112   // debug info). We have to do this ourselves because we are on the
   1113   // "simple" statement path.
   1114   if (HaveInsertPoint())
   1115     EmitStopPoint(&S);
   1116 
   1117   EmitBranchThroughCleanup(BreakContinueStack.back().BreakBlock);
   1118 }
   1119 
   1120 void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
   1121   assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
   1122 
   1123   // If this code is reachable then emit a stop point (if generating
   1124   // debug info). We have to do this ourselves because we are on the
   1125   // "simple" statement path.
   1126   if (HaveInsertPoint())
   1127     EmitStopPoint(&S);
   1128 
   1129   EmitBranchThroughCleanup(BreakContinueStack.back().ContinueBlock);
   1130 }
   1131 
   1132 /// EmitCaseStmtRange - If case statement range is not too big then
   1133 /// add multiple cases to switch instruction, one for each value within
   1134 /// the range. If range is too big then emit "if" condition check.
   1135 void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
   1136   assert(S.getRHS() && "Expected RHS value in CaseStmt");
   1137 
   1138   llvm::APSInt LHS = S.getLHS()->EvaluateKnownConstInt(getContext());
   1139   llvm::APSInt RHS = S.getRHS()->EvaluateKnownConstInt(getContext());
   1140 
   1141   RegionCounter CaseCnt = getPGORegionCounter(&S);
   1142 
   1143   // Emit the code for this case. We do this first to make sure it is
   1144   // properly chained from our predecessor before generating the
   1145   // switch machinery to enter this block.
   1146   llvm::BasicBlock *CaseDest = createBasicBlock("sw.bb");
   1147   EmitBlockWithFallThrough(CaseDest, CaseCnt);
   1148   EmitStmt(S.getSubStmt());
   1149 
   1150   // If range is empty, do nothing.
   1151   if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
   1152     return;
   1153 
   1154   llvm::APInt Range = RHS - LHS;
   1155   // FIXME: parameters such as this should not be hardcoded.
   1156   if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
   1157     // Range is small enough to add multiple switch instruction cases.
   1158     uint64_t Total = CaseCnt.getCount();
   1159     unsigned NCases = Range.getZExtValue() + 1;
   1160     // We only have one region counter for the entire set of cases here, so we
   1161     // need to divide the weights evenly between the generated cases, ensuring
   1162     // that the total weight is preserved. E.g., a weight of 5 over three cases
   1163     // will be distributed as weights of 2, 2, and 1.
   1164     uint64_t Weight = Total / NCases, Rem = Total % NCases;
   1165     for (unsigned I = 0; I != NCases; ++I) {
   1166       if (SwitchWeights)
   1167         SwitchWeights->push_back(Weight + (Rem ? 1 : 0));
   1168       if (Rem)
   1169         Rem--;
   1170       SwitchInsn->addCase(Builder.getInt(LHS), CaseDest);
   1171       LHS++;
   1172     }
   1173     return;
   1174   }
   1175 
   1176   // The range is too big. Emit "if" condition into a new block,
   1177   // making sure to save and restore the current insertion point.
   1178   llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
   1179 
   1180   // Push this test onto the chain of range checks (which terminates
   1181   // in the default basic block). The switch's default will be changed
   1182   // to the top of this chain after switch emission is complete.
   1183   llvm::BasicBlock *FalseDest = CaseRangeBlock;
   1184   CaseRangeBlock = createBasicBlock("sw.caserange");
   1185 
   1186   CurFn->getBasicBlockList().push_back(CaseRangeBlock);
   1187   Builder.SetInsertPoint(CaseRangeBlock);
   1188 
   1189   // Emit range check.
   1190   llvm::Value *Diff =
   1191     Builder.CreateSub(SwitchInsn->getCondition(), Builder.getInt(LHS));
   1192   llvm::Value *Cond =
   1193     Builder.CreateICmpULE(Diff, Builder.getInt(Range), "inbounds");
   1194 
   1195   llvm::MDNode *Weights = nullptr;
   1196   if (SwitchWeights) {
   1197     uint64_t ThisCount = CaseCnt.getCount();
   1198     uint64_t DefaultCount = (*SwitchWeights)[0];
   1199     Weights = PGO.createBranchWeights(ThisCount, DefaultCount);
   1200 
   1201     // Since we're chaining the switch default through each large case range, we
   1202     // need to update the weight for the default, ie, the first case, to include
   1203     // this case.
   1204     (*SwitchWeights)[0] += ThisCount;
   1205   }
   1206   Builder.CreateCondBr(Cond, CaseDest, FalseDest, Weights);
   1207 
   1208   // Restore the appropriate insertion point.
   1209   if (RestoreBB)
   1210     Builder.SetInsertPoint(RestoreBB);
   1211   else
   1212     Builder.ClearInsertionPoint();
   1213 }
   1214 
   1215 void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
   1216   // If there is no enclosing switch instance that we're aware of, then this
   1217   // case statement and its block can be elided.  This situation only happens
   1218   // when we've constant-folded the switch, are emitting the constant case,
   1219   // and part of the constant case includes another case statement.  For
   1220   // instance: switch (4) { case 4: do { case 5: } while (1); }
   1221   if (!SwitchInsn) {
   1222     EmitStmt(S.getSubStmt());
   1223     return;
   1224   }
   1225 
   1226   // Handle case ranges.
   1227   if (S.getRHS()) {
   1228     EmitCaseStmtRange(S);
   1229     return;
   1230   }
   1231 
   1232   RegionCounter CaseCnt = getPGORegionCounter(&S);
   1233   llvm::ConstantInt *CaseVal =
   1234     Builder.getInt(S.getLHS()->EvaluateKnownConstInt(getContext()));
   1235 
   1236   // If the body of the case is just a 'break', try to not emit an empty block.
   1237   // If we're profiling or we're not optimizing, leave the block in for better
   1238   // debug and coverage analysis.
   1239   if (!CGM.getCodeGenOpts().ProfileInstrGenerate &&
   1240       CGM.getCodeGenOpts().OptimizationLevel > 0 &&
   1241       isa<BreakStmt>(S.getSubStmt())) {
   1242     JumpDest Block = BreakContinueStack.back().BreakBlock;
   1243 
   1244     // Only do this optimization if there are no cleanups that need emitting.
   1245     if (isObviouslyBranchWithoutCleanups(Block)) {
   1246       if (SwitchWeights)
   1247         SwitchWeights->push_back(CaseCnt.getCount());
   1248       SwitchInsn->addCase(CaseVal, Block.getBlock());
   1249 
   1250       // If there was a fallthrough into this case, make sure to redirect it to
   1251       // the end of the switch as well.
   1252       if (Builder.GetInsertBlock()) {
   1253         Builder.CreateBr(Block.getBlock());
   1254         Builder.ClearInsertionPoint();
   1255       }
   1256       return;
   1257     }
   1258   }
   1259 
   1260   llvm::BasicBlock *CaseDest = createBasicBlock("sw.bb");
   1261   EmitBlockWithFallThrough(CaseDest, CaseCnt);
   1262   if (SwitchWeights)
   1263     SwitchWeights->push_back(CaseCnt.getCount());
   1264   SwitchInsn->addCase(CaseVal, CaseDest);
   1265 
   1266   // Recursively emitting the statement is acceptable, but is not wonderful for
   1267   // code where we have many case statements nested together, i.e.:
   1268   //  case 1:
   1269   //    case 2:
   1270   //      case 3: etc.
   1271   // Handling this recursively will create a new block for each case statement
   1272   // that falls through to the next case which is IR intensive.  It also causes
   1273   // deep recursion which can run into stack depth limitations.  Handle
   1274   // sequential non-range case statements specially.
   1275   const CaseStmt *CurCase = &S;
   1276   const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
   1277 
   1278   // Otherwise, iteratively add consecutive cases to this switch stmt.
   1279   while (NextCase && NextCase->getRHS() == nullptr) {
   1280     CurCase = NextCase;
   1281     llvm::ConstantInt *CaseVal =
   1282       Builder.getInt(CurCase->getLHS()->EvaluateKnownConstInt(getContext()));
   1283 
   1284     CaseCnt = getPGORegionCounter(NextCase);
   1285     if (SwitchWeights)
   1286       SwitchWeights->push_back(CaseCnt.getCount());
   1287     if (CGM.getCodeGenOpts().ProfileInstrGenerate) {
   1288       CaseDest = createBasicBlock("sw.bb");
   1289       EmitBlockWithFallThrough(CaseDest, CaseCnt);
   1290     }
   1291 
   1292     SwitchInsn->addCase(CaseVal, CaseDest);
   1293     NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt());
   1294   }
   1295 
   1296   // Normal default recursion for non-cases.
   1297   EmitStmt(CurCase->getSubStmt());
   1298 }
   1299 
   1300 void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
   1301   llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
   1302   assert(DefaultBlock->empty() &&
   1303          "EmitDefaultStmt: Default block already defined?");
   1304 
   1305   RegionCounter Cnt = getPGORegionCounter(&S);
   1306   EmitBlockWithFallThrough(DefaultBlock, Cnt);
   1307 
   1308   EmitStmt(S.getSubStmt());
   1309 }
   1310 
   1311 /// CollectStatementsForCase - Given the body of a 'switch' statement and a
   1312 /// constant value that is being switched on, see if we can dead code eliminate
   1313 /// the body of the switch to a simple series of statements to emit.  Basically,
   1314 /// on a switch (5) we want to find these statements:
   1315 ///    case 5:
   1316 ///      printf(...);    <--
   1317 ///      ++i;            <--
   1318 ///      break;
   1319 ///
   1320 /// and add them to the ResultStmts vector.  If it is unsafe to do this
   1321 /// transformation (for example, one of the elided statements contains a label
   1322 /// that might be jumped to), return CSFC_Failure.  If we handled it and 'S'
   1323 /// should include statements after it (e.g. the printf() line is a substmt of
   1324 /// the case) then return CSFC_FallThrough.  If we handled it and found a break
   1325 /// statement, then return CSFC_Success.
   1326 ///
   1327 /// If Case is non-null, then we are looking for the specified case, checking
   1328 /// that nothing we jump over contains labels.  If Case is null, then we found
   1329 /// the case and are looking for the break.
   1330 ///
   1331 /// If the recursive walk actually finds our Case, then we set FoundCase to
   1332 /// true.
   1333 ///
   1334 enum CSFC_Result { CSFC_Failure, CSFC_FallThrough, CSFC_Success };
   1335 static CSFC_Result CollectStatementsForCase(const Stmt *S,
   1336                                             const SwitchCase *Case,
   1337                                             bool &FoundCase,
   1338                               SmallVectorImpl<const Stmt*> &ResultStmts) {
   1339   // If this is a null statement, just succeed.
   1340   if (!S)
   1341     return Case ? CSFC_Success : CSFC_FallThrough;
   1342 
   1343   // If this is the switchcase (case 4: or default) that we're looking for, then
   1344   // we're in business.  Just add the substatement.
   1345   if (const SwitchCase *SC = dyn_cast<SwitchCase>(S)) {
   1346     if (S == Case) {
   1347       FoundCase = true;
   1348       return CollectStatementsForCase(SC->getSubStmt(), nullptr, FoundCase,
   1349                                       ResultStmts);
   1350     }
   1351 
   1352     // Otherwise, this is some other case or default statement, just ignore it.
   1353     return CollectStatementsForCase(SC->getSubStmt(), Case, FoundCase,
   1354                                     ResultStmts);
   1355   }
   1356 
   1357   // If we are in the live part of the code and we found our break statement,
   1358   // return a success!
   1359   if (!Case && isa<BreakStmt>(S))
   1360     return CSFC_Success;
   1361 
   1362   // If this is a switch statement, then it might contain the SwitchCase, the
   1363   // break, or neither.
   1364   if (const CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
   1365     // Handle this as two cases: we might be looking for the SwitchCase (if so
   1366     // the skipped statements must be skippable) or we might already have it.
   1367     CompoundStmt::const_body_iterator I = CS->body_begin(), E = CS->body_end();
   1368     if (Case) {
   1369       // Keep track of whether we see a skipped declaration.  The code could be
   1370       // using the declaration even if it is skipped, so we can't optimize out
   1371       // the decl if the kept statements might refer to it.
   1372       bool HadSkippedDecl = false;
   1373 
   1374       // If we're looking for the case, just see if we can skip each of the
   1375       // substatements.
   1376       for (; Case && I != E; ++I) {
   1377         HadSkippedDecl |= isa<DeclStmt>(*I);
   1378 
   1379         switch (CollectStatementsForCase(*I, Case, FoundCase, ResultStmts)) {
   1380         case CSFC_Failure: return CSFC_Failure;
   1381         case CSFC_Success:
   1382           // A successful result means that either 1) that the statement doesn't
   1383           // have the case and is skippable, or 2) does contain the case value
   1384           // and also contains the break to exit the switch.  In the later case,
   1385           // we just verify the rest of the statements are elidable.
   1386           if (FoundCase) {
   1387             // If we found the case and skipped declarations, we can't do the
   1388             // optimization.
   1389             if (HadSkippedDecl)
   1390               return CSFC_Failure;
   1391 
   1392             for (++I; I != E; ++I)
   1393               if (CodeGenFunction::ContainsLabel(*I, true))
   1394                 return CSFC_Failure;
   1395             return CSFC_Success;
   1396           }
   1397           break;
   1398         case CSFC_FallThrough:
   1399           // If we have a fallthrough condition, then we must have found the
   1400           // case started to include statements.  Consider the rest of the
   1401           // statements in the compound statement as candidates for inclusion.
   1402           assert(FoundCase && "Didn't find case but returned fallthrough?");
   1403           // We recursively found Case, so we're not looking for it anymore.
   1404           Case = nullptr;
   1405 
   1406           // If we found the case and skipped declarations, we can't do the
   1407           // optimization.
   1408           if (HadSkippedDecl)
   1409             return CSFC_Failure;
   1410           break;
   1411         }
   1412       }
   1413     }
   1414 
   1415     // If we have statements in our range, then we know that the statements are
   1416     // live and need to be added to the set of statements we're tracking.
   1417     for (; I != E; ++I) {
   1418       switch (CollectStatementsForCase(*I, nullptr, FoundCase, ResultStmts)) {
   1419       case CSFC_Failure: return CSFC_Failure;
   1420       case CSFC_FallThrough:
   1421         // A fallthrough result means that the statement was simple and just
   1422         // included in ResultStmt, keep adding them afterwards.
   1423         break;
   1424       case CSFC_Success:
   1425         // A successful result means that we found the break statement and
   1426         // stopped statement inclusion.  We just ensure that any leftover stmts
   1427         // are skippable and return success ourselves.
   1428         for (++I; I != E; ++I)
   1429           if (CodeGenFunction::ContainsLabel(*I, true))
   1430             return CSFC_Failure;
   1431         return CSFC_Success;
   1432       }
   1433     }
   1434 
   1435     return Case ? CSFC_Success : CSFC_FallThrough;
   1436   }
   1437 
   1438   // Okay, this is some other statement that we don't handle explicitly, like a
   1439   // for statement or increment etc.  If we are skipping over this statement,
   1440   // just verify it doesn't have labels, which would make it invalid to elide.
   1441   if (Case) {
   1442     if (CodeGenFunction::ContainsLabel(S, true))
   1443       return CSFC_Failure;
   1444     return CSFC_Success;
   1445   }
   1446 
   1447   // Otherwise, we want to include this statement.  Everything is cool with that
   1448   // so long as it doesn't contain a break out of the switch we're in.
   1449   if (CodeGenFunction::containsBreak(S)) return CSFC_Failure;
   1450 
   1451   // Otherwise, everything is great.  Include the statement and tell the caller
   1452   // that we fall through and include the next statement as well.
   1453   ResultStmts.push_back(S);
   1454   return CSFC_FallThrough;
   1455 }
   1456 
   1457 /// FindCaseStatementsForValue - Find the case statement being jumped to and
   1458 /// then invoke CollectStatementsForCase to find the list of statements to emit
   1459 /// for a switch on constant.  See the comment above CollectStatementsForCase
   1460 /// for more details.
   1461 static bool FindCaseStatementsForValue(const SwitchStmt &S,
   1462                                        const llvm::APSInt &ConstantCondValue,
   1463                                 SmallVectorImpl<const Stmt*> &ResultStmts,
   1464                                        ASTContext &C,
   1465                                        const SwitchCase *&ResultCase) {
   1466   // First step, find the switch case that is being branched to.  We can do this
   1467   // efficiently by scanning the SwitchCase list.
   1468   const SwitchCase *Case = S.getSwitchCaseList();
   1469   const DefaultStmt *DefaultCase = nullptr;
   1470 
   1471   for (; Case; Case = Case->getNextSwitchCase()) {
   1472     // It's either a default or case.  Just remember the default statement in
   1473     // case we're not jumping to any numbered cases.
   1474     if (const DefaultStmt *DS = dyn_cast<DefaultStmt>(Case)) {
   1475       DefaultCase = DS;
   1476       continue;
   1477     }
   1478 
   1479     // Check to see if this case is the one we're looking for.
   1480     const CaseStmt *CS = cast<CaseStmt>(Case);
   1481     // Don't handle case ranges yet.
   1482     if (CS->getRHS()) return false;
   1483 
   1484     // If we found our case, remember it as 'case'.
   1485     if (CS->getLHS()->EvaluateKnownConstInt(C) == ConstantCondValue)
   1486       break;
   1487   }
   1488 
   1489   // If we didn't find a matching case, we use a default if it exists, or we
   1490   // elide the whole switch body!
   1491   if (!Case) {
   1492     // It is safe to elide the body of the switch if it doesn't contain labels
   1493     // etc.  If it is safe, return successfully with an empty ResultStmts list.
   1494     if (!DefaultCase)
   1495       return !CodeGenFunction::ContainsLabel(&S);
   1496     Case = DefaultCase;
   1497   }
   1498 
   1499   // Ok, we know which case is being jumped to, try to collect all the
   1500   // statements that follow it.  This can fail for a variety of reasons.  Also,
   1501   // check to see that the recursive walk actually found our case statement.
   1502   // Insane cases like this can fail to find it in the recursive walk since we
   1503   // don't handle every stmt kind:
   1504   // switch (4) {
   1505   //   while (1) {
   1506   //     case 4: ...
   1507   bool FoundCase = false;
   1508   ResultCase = Case;
   1509   return CollectStatementsForCase(S.getBody(), Case, FoundCase,
   1510                                   ResultStmts) != CSFC_Failure &&
   1511          FoundCase;
   1512 }
   1513 
   1514 void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
   1515   // Handle nested switch statements.
   1516   llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
   1517   SmallVector<uint64_t, 16> *SavedSwitchWeights = SwitchWeights;
   1518   llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
   1519 
   1520   // See if we can constant fold the condition of the switch and therefore only
   1521   // emit the live case statement (if any) of the switch.
   1522   llvm::APSInt ConstantCondValue;
   1523   if (ConstantFoldsToSimpleInteger(S.getCond(), ConstantCondValue)) {
   1524     SmallVector<const Stmt*, 4> CaseStmts;
   1525     const SwitchCase *Case = nullptr;
   1526     if (FindCaseStatementsForValue(S, ConstantCondValue, CaseStmts,
   1527                                    getContext(), Case)) {
   1528       if (Case) {
   1529         RegionCounter CaseCnt = getPGORegionCounter(Case);
   1530         CaseCnt.beginRegion(Builder);
   1531       }
   1532       RunCleanupsScope ExecutedScope(*this);
   1533 
   1534       // Emit the condition variable if needed inside the entire cleanup scope
   1535       // used by this special case for constant folded switches.
   1536       if (S.getConditionVariable())
   1537         EmitAutoVarDecl(*S.getConditionVariable());
   1538 
   1539       // At this point, we are no longer "within" a switch instance, so
   1540       // we can temporarily enforce this to ensure that any embedded case
   1541       // statements are not emitted.
   1542       SwitchInsn = nullptr;
   1543 
   1544       // Okay, we can dead code eliminate everything except this case.  Emit the
   1545       // specified series of statements and we're good.
   1546       for (unsigned i = 0, e = CaseStmts.size(); i != e; ++i)
   1547         EmitStmt(CaseStmts[i]);
   1548       RegionCounter ExitCnt = getPGORegionCounter(&S);
   1549       ExitCnt.beginRegion(Builder);
   1550 
   1551       // Now we want to restore the saved switch instance so that nested
   1552       // switches continue to function properly
   1553       SwitchInsn = SavedSwitchInsn;
   1554 
   1555       return;
   1556     }
   1557   }
   1558 
   1559   JumpDest SwitchExit = getJumpDestInCurrentScope("sw.epilog");
   1560 
   1561   RunCleanupsScope ConditionScope(*this);
   1562   if (S.getConditionVariable())
   1563     EmitAutoVarDecl(*S.getConditionVariable());
   1564   llvm::Value *CondV = EmitScalarExpr(S.getCond());
   1565 
   1566   // Create basic block to hold stuff that comes after switch
   1567   // statement. We also need to create a default block now so that
   1568   // explicit case ranges tests can have a place to jump to on
   1569   // failure.
   1570   llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
   1571   SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
   1572   if (PGO.haveRegionCounts()) {
   1573     // Walk the SwitchCase list to find how many there are.
   1574     uint64_t DefaultCount = 0;
   1575     unsigned NumCases = 0;
   1576     for (const SwitchCase *Case = S.getSwitchCaseList();
   1577          Case;
   1578          Case = Case->getNextSwitchCase()) {
   1579       if (isa<DefaultStmt>(Case))
   1580         DefaultCount = getPGORegionCounter(Case).getCount();
   1581       NumCases += 1;
   1582     }
   1583     SwitchWeights = new SmallVector<uint64_t, 16>();
   1584     SwitchWeights->reserve(NumCases);
   1585     // The default needs to be first. We store the edge count, so we already
   1586     // know the right weight.
   1587     SwitchWeights->push_back(DefaultCount);
   1588   }
   1589   CaseRangeBlock = DefaultBlock;
   1590 
   1591   // Clear the insertion point to indicate we are in unreachable code.
   1592   Builder.ClearInsertionPoint();
   1593 
   1594   // All break statements jump to NextBlock. If BreakContinueStack is non-empty
   1595   // then reuse last ContinueBlock.
   1596   JumpDest OuterContinue;
   1597   if (!BreakContinueStack.empty())
   1598     OuterContinue = BreakContinueStack.back().ContinueBlock;
   1599 
   1600   BreakContinueStack.push_back(BreakContinue(SwitchExit, OuterContinue));
   1601 
   1602   // Emit switch body.
   1603   EmitStmt(S.getBody());
   1604 
   1605   BreakContinueStack.pop_back();
   1606 
   1607   // Update the default block in case explicit case range tests have
   1608   // been chained on top.
   1609   SwitchInsn->setDefaultDest(CaseRangeBlock);
   1610 
   1611   // If a default was never emitted:
   1612   if (!DefaultBlock->getParent()) {
   1613     // If we have cleanups, emit the default block so that there's a
   1614     // place to jump through the cleanups from.
   1615     if (ConditionScope.requiresCleanups()) {
   1616       EmitBlock(DefaultBlock);
   1617 
   1618     // Otherwise, just forward the default block to the switch end.
   1619     } else {
   1620       DefaultBlock->replaceAllUsesWith(SwitchExit.getBlock());
   1621       delete DefaultBlock;
   1622     }
   1623   }
   1624 
   1625   ConditionScope.ForceCleanup();
   1626 
   1627   // Emit continuation.
   1628   EmitBlock(SwitchExit.getBlock(), true);
   1629   RegionCounter ExitCnt = getPGORegionCounter(&S);
   1630   ExitCnt.beginRegion(Builder);
   1631 
   1632   if (SwitchWeights) {
   1633     assert(SwitchWeights->size() == 1 + SwitchInsn->getNumCases() &&
   1634            "switch weights do not match switch cases");
   1635     // If there's only one jump destination there's no sense weighting it.
   1636     if (SwitchWeights->size() > 1)
   1637       SwitchInsn->setMetadata(llvm::LLVMContext::MD_prof,
   1638                               PGO.createBranchWeights(*SwitchWeights));
   1639     delete SwitchWeights;
   1640   }
   1641   SwitchInsn = SavedSwitchInsn;
   1642   SwitchWeights = SavedSwitchWeights;
   1643   CaseRangeBlock = SavedCRBlock;
   1644 }
   1645 
   1646 static std::string
   1647 SimplifyConstraint(const char *Constraint, const TargetInfo &Target,
   1648                  SmallVectorImpl<TargetInfo::ConstraintInfo> *OutCons=nullptr) {
   1649   std::string Result;
   1650 
   1651   while (*Constraint) {
   1652     switch (*Constraint) {
   1653     default:
   1654       Result += Target.convertConstraint(Constraint);
   1655       break;
   1656     // Ignore these
   1657     case '*':
   1658     case '?':
   1659     case '!':
   1660     case '=': // Will see this and the following in mult-alt constraints.
   1661     case '+':
   1662       break;
   1663     case '#': // Ignore the rest of the constraint alternative.
   1664       while (Constraint[1] && Constraint[1] != ',')
   1665         Constraint++;
   1666       break;
   1667     case '&':
   1668     case '%':
   1669       Result += *Constraint;
   1670       while (Constraint[1] && Constraint[1] == *Constraint)
   1671         Constraint++;
   1672       break;
   1673     case ',':
   1674       Result += "|";
   1675       break;
   1676     case 'g':
   1677       Result += "imr";
   1678       break;
   1679     case '[': {
   1680       assert(OutCons &&
   1681              "Must pass output names to constraints with a symbolic name");
   1682       unsigned Index;
   1683       bool result = Target.resolveSymbolicName(Constraint,
   1684                                                &(*OutCons)[0],
   1685                                                OutCons->size(), Index);
   1686       assert(result && "Could not resolve symbolic name"); (void)result;
   1687       Result += llvm::utostr(Index);
   1688       break;
   1689     }
   1690     }
   1691 
   1692     Constraint++;
   1693   }
   1694 
   1695   return Result;
   1696 }
   1697 
   1698 /// AddVariableConstraints - Look at AsmExpr and if it is a variable declared
   1699 /// as using a particular register add that as a constraint that will be used
   1700 /// in this asm stmt.
   1701 static std::string
   1702 AddVariableConstraints(const std::string &Constraint, const Expr &AsmExpr,
   1703                        const TargetInfo &Target, CodeGenModule &CGM,
   1704                        const AsmStmt &Stmt, const bool EarlyClobber) {
   1705   const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(&AsmExpr);
   1706   if (!AsmDeclRef)
   1707     return Constraint;
   1708   const ValueDecl &Value = *AsmDeclRef->getDecl();
   1709   const VarDecl *Variable = dyn_cast<VarDecl>(&Value);
   1710   if (!Variable)
   1711     return Constraint;
   1712   if (Variable->getStorageClass() != SC_Register)
   1713     return Constraint;
   1714   AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>();
   1715   if (!Attr)
   1716     return Constraint;
   1717   StringRef Register = Attr->getLabel();
   1718   assert(Target.isValidGCCRegisterName(Register));
   1719   // We're using validateOutputConstraint here because we only care if
   1720   // this is a register constraint.
   1721   TargetInfo::ConstraintInfo Info(Constraint, "");
   1722   if (Target.validateOutputConstraint(Info) &&
   1723       !Info.allowsRegister()) {
   1724     CGM.ErrorUnsupported(&Stmt, "__asm__");
   1725     return Constraint;
   1726   }
   1727   // Canonicalize the register here before returning it.
   1728   Register = Target.getNormalizedGCCRegisterName(Register);
   1729   return (EarlyClobber ? "&{" : "{") + Register.str() + "}";
   1730 }
   1731 
   1732 llvm::Value*
   1733 CodeGenFunction::EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info,
   1734                                     LValue InputValue, QualType InputType,
   1735                                     std::string &ConstraintStr,
   1736                                     SourceLocation Loc) {
   1737   llvm::Value *Arg;
   1738   if (Info.allowsRegister() || !Info.allowsMemory()) {
   1739     if (CodeGenFunction::hasScalarEvaluationKind(InputType)) {
   1740       Arg = EmitLoadOfLValue(InputValue, Loc).getScalarVal();
   1741     } else {
   1742       llvm::Type *Ty = ConvertType(InputType);
   1743       uint64_t Size = CGM.getDataLayout().getTypeSizeInBits(Ty);
   1744       if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
   1745         Ty = llvm::IntegerType::get(getLLVMContext(), Size);
   1746         Ty = llvm::PointerType::getUnqual(Ty);
   1747 
   1748         Arg = Builder.CreateLoad(Builder.CreateBitCast(InputValue.getAddress(),
   1749                                                        Ty));
   1750       } else {
   1751         Arg = InputValue.getAddress();
   1752         ConstraintStr += '*';
   1753       }
   1754     }
   1755   } else {
   1756     Arg = InputValue.getAddress();
   1757     ConstraintStr += '*';
   1758   }
   1759 
   1760   return Arg;
   1761 }
   1762 
   1763 llvm::Value* CodeGenFunction::EmitAsmInput(
   1764                                          const TargetInfo::ConstraintInfo &Info,
   1765                                            const Expr *InputExpr,
   1766                                            std::string &ConstraintStr) {
   1767   if (Info.allowsRegister() || !Info.allowsMemory())
   1768     if (CodeGenFunction::hasScalarEvaluationKind(InputExpr->getType()))
   1769       return EmitScalarExpr(InputExpr);
   1770 
   1771   InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
   1772   LValue Dest = EmitLValue(InputExpr);
   1773   return EmitAsmInputLValue(Info, Dest, InputExpr->getType(), ConstraintStr,
   1774                             InputExpr->getExprLoc());
   1775 }
   1776 
   1777 /// getAsmSrcLocInfo - Return the !srcloc metadata node to attach to an inline
   1778 /// asm call instruction.  The !srcloc MDNode contains a list of constant
   1779 /// integers which are the source locations of the start of each line in the
   1780 /// asm.
   1781 static llvm::MDNode *getAsmSrcLocInfo(const StringLiteral *Str,
   1782                                       CodeGenFunction &CGF) {
   1783   SmallVector<llvm::Metadata *, 8> Locs;
   1784   // Add the location of the first line to the MDNode.
   1785   Locs.push_back(llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
   1786       CGF.Int32Ty, Str->getLocStart().getRawEncoding())));
   1787   StringRef StrVal = Str->getString();
   1788   if (!StrVal.empty()) {
   1789     const SourceManager &SM = CGF.CGM.getContext().getSourceManager();
   1790     const LangOptions &LangOpts = CGF.CGM.getLangOpts();
   1791 
   1792     // Add the location of the start of each subsequent line of the asm to the
   1793     // MDNode.
   1794     for (unsigned i = 0, e = StrVal.size()-1; i != e; ++i) {
   1795       if (StrVal[i] != '\n') continue;
   1796       SourceLocation LineLoc = Str->getLocationOfByte(i+1, SM, LangOpts,
   1797                                                       CGF.getTarget());
   1798       Locs.push_back(llvm::ConstantAsMetadata::get(
   1799           llvm::ConstantInt::get(CGF.Int32Ty, LineLoc.getRawEncoding())));
   1800     }
   1801   }
   1802 
   1803   return llvm::MDNode::get(CGF.getLLVMContext(), Locs);
   1804 }
   1805 
   1806 void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
   1807   // Assemble the final asm string.
   1808   std::string AsmString = S.generateAsmString(getContext());
   1809 
   1810   // Get all the output and input constraints together.
   1811   SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
   1812   SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
   1813 
   1814   for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
   1815     StringRef Name;
   1816     if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
   1817       Name = GAS->getOutputName(i);
   1818     TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i), Name);
   1819     bool IsValid = getTarget().validateOutputConstraint(Info); (void)IsValid;
   1820     assert(IsValid && "Failed to parse output constraint");
   1821     OutputConstraintInfos.push_back(Info);
   1822   }
   1823 
   1824   for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
   1825     StringRef Name;
   1826     if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
   1827       Name = GAS->getInputName(i);
   1828     TargetInfo::ConstraintInfo Info(S.getInputConstraint(i), Name);
   1829     bool IsValid =
   1830       getTarget().validateInputConstraint(OutputConstraintInfos.data(),
   1831                                           S.getNumOutputs(), Info);
   1832     assert(IsValid && "Failed to parse input constraint"); (void)IsValid;
   1833     InputConstraintInfos.push_back(Info);
   1834   }
   1835 
   1836   std::string Constraints;
   1837 
   1838   std::vector<LValue> ResultRegDests;
   1839   std::vector<QualType> ResultRegQualTys;
   1840   std::vector<llvm::Type *> ResultRegTypes;
   1841   std::vector<llvm::Type *> ResultTruncRegTypes;
   1842   std::vector<llvm::Type *> ArgTypes;
   1843   std::vector<llvm::Value*> Args;
   1844 
   1845   // Keep track of inout constraints.
   1846   std::string InOutConstraints;
   1847   std::vector<llvm::Value*> InOutArgs;
   1848   std::vector<llvm::Type*> InOutArgTypes;
   1849 
   1850   for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
   1851     TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
   1852 
   1853     // Simplify the output constraint.
   1854     std::string OutputConstraint(S.getOutputConstraint(i));
   1855     OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1,
   1856                                           getTarget());
   1857 
   1858     const Expr *OutExpr = S.getOutputExpr(i);
   1859     OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
   1860 
   1861     OutputConstraint = AddVariableConstraints(OutputConstraint, *OutExpr,
   1862                                               getTarget(), CGM, S,
   1863                                               Info.earlyClobber());
   1864 
   1865     LValue Dest = EmitLValue(OutExpr);
   1866     if (!Constraints.empty())
   1867       Constraints += ',';
   1868 
   1869     // If this is a register output, then make the inline asm return it
   1870     // by-value.  If this is a memory result, return the value by-reference.
   1871     if (!Info.allowsMemory() && hasScalarEvaluationKind(OutExpr->getType())) {
   1872       Constraints += "=" + OutputConstraint;
   1873       ResultRegQualTys.push_back(OutExpr->getType());
   1874       ResultRegDests.push_back(Dest);
   1875       ResultRegTypes.push_back(ConvertTypeForMem(OutExpr->getType()));
   1876       ResultTruncRegTypes.push_back(ResultRegTypes.back());
   1877 
   1878       // If this output is tied to an input, and if the input is larger, then
   1879       // we need to set the actual result type of the inline asm node to be the
   1880       // same as the input type.
   1881       if (Info.hasMatchingInput()) {
   1882         unsigned InputNo;
   1883         for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) {
   1884           TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo];
   1885           if (Input.hasTiedOperand() && Input.getTiedOperand() == i)
   1886             break;
   1887         }
   1888         assert(InputNo != S.getNumInputs() && "Didn't find matching input!");
   1889 
   1890         QualType InputTy = S.getInputExpr(InputNo)->getType();
   1891         QualType OutputType = OutExpr->getType();
   1892 
   1893         uint64_t InputSize = getContext().getTypeSize(InputTy);
   1894         if (getContext().getTypeSize(OutputType) < InputSize) {
   1895           // Form the asm to return the value as a larger integer or fp type.
   1896           ResultRegTypes.back() = ConvertType(InputTy);
   1897         }
   1898       }
   1899       if (llvm::Type* AdjTy =
   1900             getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
   1901                                                  ResultRegTypes.back()))
   1902         ResultRegTypes.back() = AdjTy;
   1903       else {
   1904         CGM.getDiags().Report(S.getAsmLoc(),
   1905                               diag::err_asm_invalid_type_in_input)
   1906             << OutExpr->getType() << OutputConstraint;
   1907       }
   1908     } else {
   1909       ArgTypes.push_back(Dest.getAddress()->getType());
   1910       Args.push_back(Dest.getAddress());
   1911       Constraints += "=*";
   1912       Constraints += OutputConstraint;
   1913     }
   1914 
   1915     if (Info.isReadWrite()) {
   1916       InOutConstraints += ',';
   1917 
   1918       const Expr *InputExpr = S.getOutputExpr(i);
   1919       llvm::Value *Arg = EmitAsmInputLValue(Info, Dest, InputExpr->getType(),
   1920                                             InOutConstraints,
   1921                                             InputExpr->getExprLoc());
   1922 
   1923       if (llvm::Type* AdjTy =
   1924           getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
   1925                                                Arg->getType()))
   1926         Arg = Builder.CreateBitCast(Arg, AdjTy);
   1927 
   1928       if (Info.allowsRegister())
   1929         InOutConstraints += llvm::utostr(i);
   1930       else
   1931         InOutConstraints += OutputConstraint;
   1932 
   1933       InOutArgTypes.push_back(Arg->getType());
   1934       InOutArgs.push_back(Arg);
   1935     }
   1936   }
   1937 
   1938   // If this is a Microsoft-style asm blob, store the return registers (EAX:EDX)
   1939   // to the return value slot. Only do this when returning in registers.
   1940   if (isa<MSAsmStmt>(&S)) {
   1941     const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
   1942     if (RetAI.isDirect() || RetAI.isExtend()) {
   1943       // Make a fake lvalue for the return value slot.
   1944       LValue ReturnSlot = MakeAddrLValue(ReturnValue, FnRetTy);
   1945       CGM.getTargetCodeGenInfo().addReturnRegisterOutputs(
   1946           *this, ReturnSlot, Constraints, ResultRegTypes, ResultTruncRegTypes,
   1947           ResultRegDests, AsmString, S.getNumOutputs());
   1948       SawAsmBlock = true;
   1949     }
   1950   }
   1951 
   1952   for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
   1953     const Expr *InputExpr = S.getInputExpr(i);
   1954 
   1955     TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
   1956 
   1957     if (!Constraints.empty())
   1958       Constraints += ',';
   1959 
   1960     // Simplify the input constraint.
   1961     std::string InputConstraint(S.getInputConstraint(i));
   1962     InputConstraint = SimplifyConstraint(InputConstraint.c_str(), getTarget(),
   1963                                          &OutputConstraintInfos);
   1964 
   1965     InputConstraint = AddVariableConstraints(
   1966         InputConstraint, *InputExpr->IgnoreParenNoopCasts(getContext()),
   1967         getTarget(), CGM, S, false /* No EarlyClobber */);
   1968 
   1969     llvm::Value *Arg = EmitAsmInput(Info, InputExpr, Constraints);
   1970 
   1971     // If this input argument is tied to a larger output result, extend the
   1972     // input to be the same size as the output.  The LLVM backend wants to see
   1973     // the input and output of a matching constraint be the same size.  Note
   1974     // that GCC does not define what the top bits are here.  We use zext because
   1975     // that is usually cheaper, but LLVM IR should really get an anyext someday.
   1976     if (Info.hasTiedOperand()) {
   1977       unsigned Output = Info.getTiedOperand();
   1978       QualType OutputType = S.getOutputExpr(Output)->getType();
   1979       QualType InputTy = InputExpr->getType();
   1980 
   1981       if (getContext().getTypeSize(OutputType) >
   1982           getContext().getTypeSize(InputTy)) {
   1983         // Use ptrtoint as appropriate so that we can do our extension.
   1984         if (isa<llvm::PointerType>(Arg->getType()))
   1985           Arg = Builder.CreatePtrToInt(Arg, IntPtrTy);
   1986         llvm::Type *OutputTy = ConvertType(OutputType);
   1987         if (isa<llvm::IntegerType>(OutputTy))
   1988           Arg = Builder.CreateZExt(Arg, OutputTy);
   1989         else if (isa<llvm::PointerType>(OutputTy))
   1990           Arg = Builder.CreateZExt(Arg, IntPtrTy);
   1991         else {
   1992           assert(OutputTy->isFloatingPointTy() && "Unexpected output type");
   1993           Arg = Builder.CreateFPExt(Arg, OutputTy);
   1994         }
   1995       }
   1996     }
   1997     if (llvm::Type* AdjTy =
   1998               getTargetHooks().adjustInlineAsmType(*this, InputConstraint,
   1999                                                    Arg->getType()))
   2000       Arg = Builder.CreateBitCast(Arg, AdjTy);
   2001     else
   2002       CGM.getDiags().Report(S.getAsmLoc(), diag::err_asm_invalid_type_in_input)
   2003           << InputExpr->getType() << InputConstraint;
   2004 
   2005     ArgTypes.push_back(Arg->getType());
   2006     Args.push_back(Arg);
   2007     Constraints += InputConstraint;
   2008   }
   2009 
   2010   // Append the "input" part of inout constraints last.
   2011   for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
   2012     ArgTypes.push_back(InOutArgTypes[i]);
   2013     Args.push_back(InOutArgs[i]);
   2014   }
   2015   Constraints += InOutConstraints;
   2016 
   2017   // Clobbers
   2018   for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
   2019     StringRef Clobber = S.getClobber(i);
   2020 
   2021     if (Clobber != "memory" && Clobber != "cc")
   2022       Clobber = getTarget().getNormalizedGCCRegisterName(Clobber);
   2023 
   2024     if (!Constraints.empty())
   2025       Constraints += ',';
   2026 
   2027     Constraints += "~{";
   2028     Constraints += Clobber;
   2029     Constraints += '}';
   2030   }
   2031 
   2032   // Add machine specific clobbers
   2033   std::string MachineClobbers = getTarget().getClobbers();
   2034   if (!MachineClobbers.empty()) {
   2035     if (!Constraints.empty())
   2036       Constraints += ',';
   2037     Constraints += MachineClobbers;
   2038   }
   2039 
   2040   llvm::Type *ResultType;
   2041   if (ResultRegTypes.empty())
   2042     ResultType = VoidTy;
   2043   else if (ResultRegTypes.size() == 1)
   2044     ResultType = ResultRegTypes[0];
   2045   else
   2046     ResultType = llvm::StructType::get(getLLVMContext(), ResultRegTypes);
   2047 
   2048   llvm::FunctionType *FTy =
   2049     llvm::FunctionType::get(ResultType, ArgTypes, false);
   2050 
   2051   bool HasSideEffect = S.isVolatile() || S.getNumOutputs() == 0;
   2052   llvm::InlineAsm::AsmDialect AsmDialect = isa<MSAsmStmt>(&S) ?
   2053     llvm::InlineAsm::AD_Intel : llvm::InlineAsm::AD_ATT;
   2054   llvm::InlineAsm *IA =
   2055     llvm::InlineAsm::get(FTy, AsmString, Constraints, HasSideEffect,
   2056                          /* IsAlignStack */ false, AsmDialect);
   2057   llvm::CallInst *Result = Builder.CreateCall(IA, Args);
   2058   Result->addAttribute(llvm::AttributeSet::FunctionIndex,
   2059                        llvm::Attribute::NoUnwind);
   2060 
   2061   // Slap the source location of the inline asm into a !srcloc metadata on the
   2062   // call.
   2063   if (const GCCAsmStmt *gccAsmStmt = dyn_cast<GCCAsmStmt>(&S)) {
   2064     Result->setMetadata("srcloc", getAsmSrcLocInfo(gccAsmStmt->getAsmString(),
   2065                                                    *this));
   2066   } else {
   2067     // At least put the line number on MS inline asm blobs.
   2068     auto Loc = llvm::ConstantInt::get(Int32Ty, S.getAsmLoc().getRawEncoding());
   2069     Result->setMetadata("srcloc",
   2070                         llvm::MDNode::get(getLLVMContext(),
   2071                                           llvm::ConstantAsMetadata::get(Loc)));
   2072   }
   2073 
   2074   // Extract all of the register value results from the asm.
   2075   std::vector<llvm::Value*> RegResults;
   2076   if (ResultRegTypes.size() == 1) {
   2077     RegResults.push_back(Result);
   2078   } else {
   2079     for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) {
   2080       llvm::Value *Tmp = Builder.CreateExtractValue(Result, i, "asmresult");
   2081       RegResults.push_back(Tmp);
   2082     }
   2083   }
   2084 
   2085   assert(RegResults.size() == ResultRegTypes.size());
   2086   assert(RegResults.size() == ResultTruncRegTypes.size());
   2087   assert(RegResults.size() == ResultRegDests.size());
   2088   for (unsigned i = 0, e = RegResults.size(); i != e; ++i) {
   2089     llvm::Value *Tmp = RegResults[i];
   2090 
   2091     // If the result type of the LLVM IR asm doesn't match the result type of
   2092     // the expression, do the conversion.
   2093     if (ResultRegTypes[i] != ResultTruncRegTypes[i]) {
   2094       llvm::Type *TruncTy = ResultTruncRegTypes[i];
   2095 
   2096       // Truncate the integer result to the right size, note that TruncTy can be
   2097       // a pointer.
   2098       if (TruncTy->isFloatingPointTy())
   2099         Tmp = Builder.CreateFPTrunc(Tmp, TruncTy);
   2100       else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) {
   2101         uint64_t ResSize = CGM.getDataLayout().getTypeSizeInBits(TruncTy);
   2102         Tmp = Builder.CreateTrunc(Tmp,
   2103                    llvm::IntegerType::get(getLLVMContext(), (unsigned)ResSize));
   2104         Tmp = Builder.CreateIntToPtr(Tmp, TruncTy);
   2105       } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) {
   2106         uint64_t TmpSize =CGM.getDataLayout().getTypeSizeInBits(Tmp->getType());
   2107         Tmp = Builder.CreatePtrToInt(Tmp,
   2108                    llvm::IntegerType::get(getLLVMContext(), (unsigned)TmpSize));
   2109         Tmp = Builder.CreateTrunc(Tmp, TruncTy);
   2110       } else if (TruncTy->isIntegerTy()) {
   2111         Tmp = Builder.CreateTrunc(Tmp, TruncTy);
   2112       } else if (TruncTy->isVectorTy()) {
   2113         Tmp = Builder.CreateBitCast(Tmp, TruncTy);
   2114       }
   2115     }
   2116 
   2117     EmitStoreThroughLValue(RValue::get(Tmp), ResultRegDests[i]);
   2118   }
   2119 }
   2120 
   2121 LValue CodeGenFunction::InitCapturedStruct(const CapturedStmt &S) {
   2122   const RecordDecl *RD = S.getCapturedRecordDecl();
   2123   QualType RecordTy = getContext().getRecordType(RD);
   2124 
   2125   // Initialize the captured struct.
   2126   LValue SlotLV = MakeNaturalAlignAddrLValue(
   2127       CreateMemTemp(RecordTy, "agg.captured"), RecordTy);
   2128 
   2129   RecordDecl::field_iterator CurField = RD->field_begin();
   2130   for (CapturedStmt::capture_init_iterator I = S.capture_init_begin(),
   2131                                            E = S.capture_init_end();
   2132        I != E; ++I, ++CurField) {
   2133     LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
   2134     if (CurField->hasCapturedVLAType()) {
   2135       auto VAT = CurField->getCapturedVLAType();
   2136       EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
   2137     } else {
   2138       EmitInitializerForField(*CurField, LV, *I, None);
   2139     }
   2140   }
   2141 
   2142   return SlotLV;
   2143 }
   2144 
   2145 /// Generate an outlined function for the body of a CapturedStmt, store any
   2146 /// captured variables into the captured struct, and call the outlined function.
   2147 llvm::Function *
   2148 CodeGenFunction::EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K) {
   2149   LValue CapStruct = InitCapturedStruct(S);
   2150 
   2151   // Emit the CapturedDecl
   2152   CodeGenFunction CGF(CGM, true);
   2153   CGF.CapturedStmtInfo = new CGCapturedStmtInfo(S, K);
   2154   llvm::Function *F = CGF.GenerateCapturedStmtFunction(S);
   2155   delete CGF.CapturedStmtInfo;
   2156 
   2157   // Emit call to the helper function.
   2158   EmitCallOrInvoke(F, CapStruct.getAddress());
   2159 
   2160   return F;
   2161 }
   2162 
   2163 llvm::Value *
   2164 CodeGenFunction::GenerateCapturedStmtArgument(const CapturedStmt &S) {
   2165   LValue CapStruct = InitCapturedStruct(S);
   2166   return CapStruct.getAddress();
   2167 }
   2168 
   2169 /// Creates the outlined function for a CapturedStmt.
   2170 llvm::Function *
   2171 CodeGenFunction::GenerateCapturedStmtFunction(const CapturedStmt &S) {
   2172   assert(CapturedStmtInfo &&
   2173     "CapturedStmtInfo should be set when generating the captured function");
   2174   const CapturedDecl *CD = S.getCapturedDecl();
   2175   const RecordDecl *RD = S.getCapturedRecordDecl();
   2176   SourceLocation Loc = S.getLocStart();
   2177   assert(CD->hasBody() && "missing CapturedDecl body");
   2178 
   2179   // Build the argument list.
   2180   ASTContext &Ctx = CGM.getContext();
   2181   FunctionArgList Args;
   2182   Args.append(CD->param_begin(), CD->param_end());
   2183 
   2184   // Create the function declaration.
   2185   FunctionType::ExtInfo ExtInfo;
   2186   const CGFunctionInfo &FuncInfo =
   2187       CGM.getTypes().arrangeFreeFunctionDeclaration(Ctx.VoidTy, Args, ExtInfo,
   2188                                                     /*IsVariadic=*/false);
   2189   llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
   2190 
   2191   llvm::Function *F =
   2192     llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
   2193                            CapturedStmtInfo->getHelperName(), &CGM.getModule());
   2194   CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
   2195   if (CD->isNothrow())
   2196     F->addFnAttr(llvm::Attribute::NoUnwind);
   2197 
   2198   // Generate the function.
   2199   StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args,
   2200                 CD->getLocation(),
   2201                 CD->getBody()->getLocStart());
   2202   // Set the context parameter in CapturedStmtInfo.
   2203   llvm::Value *DeclPtr = LocalDeclMap[CD->getContextParam()];
   2204   assert(DeclPtr && "missing context parameter for CapturedStmt");
   2205   CapturedStmtInfo->setContextValue(Builder.CreateLoad(DeclPtr));
   2206 
   2207   // Initialize variable-length arrays.
   2208   LValue Base = MakeNaturalAlignAddrLValue(CapturedStmtInfo->getContextValue(),
   2209                                            Ctx.getTagDeclType(RD));
   2210   for (auto *FD : RD->fields()) {
   2211     if (FD->hasCapturedVLAType()) {
   2212       auto *ExprArg = EmitLoadOfLValue(EmitLValueForField(Base, FD),
   2213                                        S.getLocStart()).getScalarVal();
   2214       auto VAT = FD->getCapturedVLAType();
   2215       VLASizeMap[VAT->getSizeExpr()] = ExprArg;
   2216     }
   2217   }
   2218 
   2219   // If 'this' is captured, load it into CXXThisValue.
   2220   if (CapturedStmtInfo->isCXXThisExprCaptured()) {
   2221     FieldDecl *FD = CapturedStmtInfo->getThisFieldDecl();
   2222     LValue ThisLValue = EmitLValueForField(Base, FD);
   2223     CXXThisValue = EmitLoadOfLValue(ThisLValue, Loc).getScalarVal();
   2224   }
   2225 
   2226   PGO.assignRegionCounters(CD, F);
   2227   CapturedStmtInfo->EmitBody(*this, CD->getBody());
   2228   FinishFunction(CD->getBodyRBrace());
   2229 
   2230   return F;
   2231 }
   2232