1 //===--- CGStmt.cpp - Emit LLVM Code from Statements ----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This contains code to emit Stmt nodes as LLVM code.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "CGDebugInfo.h"
14 #include "CGOpenMPRuntime.h"
15 #include "CodeGenFunction.h"
16 #include "CodeGenModule.h"
17 #include "TargetInfo.h"
18 #include "clang/AST/Attr.h"
19 #include "clang/AST/StmtVisitor.h"
20 #include "clang/Basic/Builtins.h"
21 #include "clang/Basic/DiagnosticSema.h"
22 #include "clang/Basic/PrettyStackTrace.h"
23 #include "clang/Basic/SourceManager.h"
24 #include "clang/Basic/TargetInfo.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/InlineAsm.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/MDBuilder.h"
31 #include "llvm/Support/SaveAndRestore.h"
32 
33 using namespace clang;
34 using namespace CodeGen;
35 
36 //===----------------------------------------------------------------------===//
37 //                              Statement Emission
38 //===----------------------------------------------------------------------===//
39 
40 void CodeGenFunction::EmitStopPoint(const Stmt *S) {
41   if (CGDebugInfo *DI = getDebugInfo()) {
42     SourceLocation Loc;
43     Loc = S->getBeginLoc();
44     DI->EmitLocation(Builder, Loc);
45 
46     LastStopPoint = Loc;
47   }
48 }
49 
50 void CodeGenFunction::EmitStmt(const Stmt *S, ArrayRef<const Attr *> Attrs) {
51   assert(S && "Null statement?");
52   PGO.setCurrentStmt(S);
53 
54   // These statements have their own debug info handling.
55   if (EmitSimpleStmt(S, Attrs))
56     return;
57 
58   // Check if we are generating unreachable code.
59   if (!HaveInsertPoint()) {
60     // If so, and the statement doesn't contain a label, then we do not need to
61     // generate actual code. This is safe because (1) the current point is
62     // unreachable, so we don't need to execute the code, and (2) we've already
63     // handled the statements which update internal data structures (like the
64     // local variable map) which could be used by subsequent statements.
65     if (!ContainsLabel(S)) {
66       // Verify that any decl statements were handled as simple, they may be in
67       // scope of subsequent reachable statements.
68       assert(!isa<DeclStmt>(*S) && "Unexpected DeclStmt!");
69       return;
70     }
71 
72     // Otherwise, make a new block to hold the code.
73     EnsureInsertPoint();
74   }
75 
76   // Generate a stoppoint if we are emitting debug info.
77   EmitStopPoint(S);
78 
79   // Ignore all OpenMP directives except for simd if OpenMP with Simd is
80   // enabled.
81   if (getLangOpts().OpenMP && getLangOpts().OpenMPSimd) {
82     if (const auto *D = dyn_cast<OMPExecutableDirective>(S)) {
83       EmitSimpleOMPExecutableDirective(*D);
84       return;
85     }
86   }
87 
88   switch (S->getStmtClass()) {
89   case Stmt::NoStmtClass:
90   case Stmt::CXXCatchStmtClass:
91   case Stmt::SEHExceptStmtClass:
92   case Stmt::SEHFinallyStmtClass:
93   case Stmt::MSDependentExistsStmtClass:
94     llvm_unreachable("invalid statement class to emit generically");
95   case Stmt::NullStmtClass:
96   case Stmt::CompoundStmtClass:
97   case Stmt::DeclStmtClass:
98   case Stmt::LabelStmtClass:
99   case Stmt::AttributedStmtClass:
100   case Stmt::GotoStmtClass:
101   case Stmt::BreakStmtClass:
102   case Stmt::ContinueStmtClass:
103   case Stmt::DefaultStmtClass:
104   case Stmt::CaseStmtClass:
105   case Stmt::SEHLeaveStmtClass:
106     llvm_unreachable("should have emitted these statements as simple");
107 
108 #define STMT(Type, Base)
109 #define ABSTRACT_STMT(Op)
110 #define EXPR(Type, Base) \
111   case Stmt::Type##Class:
112 #include "clang/AST/StmtNodes.inc"
113   {
114     // Remember the block we came in on.
115     llvm::BasicBlock *incoming = Builder.GetInsertBlock();
116     assert(incoming && "expression emission must have an insertion point");
117 
118     EmitIgnoredExpr(cast<Expr>(S));
119 
120     llvm::BasicBlock *outgoing = Builder.GetInsertBlock();
121     assert(outgoing && "expression emission cleared block!");
122 
123     // The expression emitters assume (reasonably!) that the insertion
124     // point is always set.  To maintain that, the call-emission code
125     // for noreturn functions has to enter a new block with no
126     // predecessors.  We want to kill that block and mark the current
127     // insertion point unreachable in the common case of a call like
128     // "exit();".  Since expression emission doesn't otherwise create
129     // blocks with no predecessors, we can just test for that.
130     // However, we must be careful not to do this to our incoming
131     // block, because *statement* emission does sometimes create
132     // reachable blocks which will have no predecessors until later in
133     // the function.  This occurs with, e.g., labels that are not
134     // reachable by fallthrough.
135     if (incoming != outgoing && outgoing->use_empty()) {
136       outgoing->eraseFromParent();
137       Builder.ClearInsertionPoint();
138     }
139     break;
140   }
141 
142   case Stmt::IndirectGotoStmtClass:
143     EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
144 
145   case Stmt::IfStmtClass:      EmitIfStmt(cast<IfStmt>(*S));              break;
146   case Stmt::WhileStmtClass:   EmitWhileStmt(cast<WhileStmt>(*S), Attrs); break;
147   case Stmt::DoStmtClass:      EmitDoStmt(cast<DoStmt>(*S), Attrs);       break;
148   case Stmt::ForStmtClass:     EmitForStmt(cast<ForStmt>(*S), Attrs);     break;
149 
150   case Stmt::ReturnStmtClass:  EmitReturnStmt(cast<ReturnStmt>(*S));      break;
151 
152   case Stmt::SwitchStmtClass:  EmitSwitchStmt(cast<SwitchStmt>(*S));      break;
153   case Stmt::GCCAsmStmtClass:  // Intentional fall-through.
154   case Stmt::MSAsmStmtClass:   EmitAsmStmt(cast<AsmStmt>(*S));            break;
155   case Stmt::CoroutineBodyStmtClass:
156     EmitCoroutineBody(cast<CoroutineBodyStmt>(*S));
157     break;
158   case Stmt::CoreturnStmtClass:
159     EmitCoreturnStmt(cast<CoreturnStmt>(*S));
160     break;
161   case Stmt::CapturedStmtClass: {
162     const CapturedStmt *CS = cast<CapturedStmt>(S);
163     EmitCapturedStmt(*CS, CS->getCapturedRegionKind());
164     }
165     break;
166   case Stmt::ObjCAtTryStmtClass:
167     EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
168     break;
169   case Stmt::ObjCAtCatchStmtClass:
170     llvm_unreachable(
171                     "@catch statements should be handled by EmitObjCAtTryStmt");
172   case Stmt::ObjCAtFinallyStmtClass:
173     llvm_unreachable(
174                   "@finally statements should be handled by EmitObjCAtTryStmt");
175   case Stmt::ObjCAtThrowStmtClass:
176     EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
177     break;
178   case Stmt::ObjCAtSynchronizedStmtClass:
179     EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
180     break;
181   case Stmt::ObjCForCollectionStmtClass:
182     EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
183     break;
184   case Stmt::ObjCAutoreleasePoolStmtClass:
185     EmitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(*S));
186     break;
187 
188   case Stmt::CXXTryStmtClass:
189     EmitCXXTryStmt(cast<CXXTryStmt>(*S));
190     break;
191   case Stmt::CXXForRangeStmtClass:
192     EmitCXXForRangeStmt(cast<CXXForRangeStmt>(*S), Attrs);
193     break;
194   case Stmt::SEHTryStmtClass:
195     EmitSEHTryStmt(cast<SEHTryStmt>(*S));
196     break;
197   case Stmt::OMPCanonicalLoopClass:
198     EmitOMPCanonicalLoop(cast<OMPCanonicalLoop>(S));
199     break;
200   case Stmt::OMPParallelDirectiveClass:
201     EmitOMPParallelDirective(cast<OMPParallelDirective>(*S));
202     break;
203   case Stmt::OMPSimdDirectiveClass:
204     EmitOMPSimdDirective(cast<OMPSimdDirective>(*S));
205     break;
206   case Stmt::OMPTileDirectiveClass:
207     EmitOMPTileDirective(cast<OMPTileDirective>(*S));
208     break;
209   case Stmt::OMPForDirectiveClass:
210     EmitOMPForDirective(cast<OMPForDirective>(*S));
211     break;
212   case Stmt::OMPForSimdDirectiveClass:
213     EmitOMPForSimdDirective(cast<OMPForSimdDirective>(*S));
214     break;
215   case Stmt::OMPSectionsDirectiveClass:
216     EmitOMPSectionsDirective(cast<OMPSectionsDirective>(*S));
217     break;
218   case Stmt::OMPSectionDirectiveClass:
219     EmitOMPSectionDirective(cast<OMPSectionDirective>(*S));
220     break;
221   case Stmt::OMPSingleDirectiveClass:
222     EmitOMPSingleDirective(cast<OMPSingleDirective>(*S));
223     break;
224   case Stmt::OMPMasterDirectiveClass:
225     EmitOMPMasterDirective(cast<OMPMasterDirective>(*S));
226     break;
227   case Stmt::OMPCriticalDirectiveClass:
228     EmitOMPCriticalDirective(cast<OMPCriticalDirective>(*S));
229     break;
230   case Stmt::OMPParallelForDirectiveClass:
231     EmitOMPParallelForDirective(cast<OMPParallelForDirective>(*S));
232     break;
233   case Stmt::OMPParallelForSimdDirectiveClass:
234     EmitOMPParallelForSimdDirective(cast<OMPParallelForSimdDirective>(*S));
235     break;
236   case Stmt::OMPParallelMasterDirectiveClass:
237     EmitOMPParallelMasterDirective(cast<OMPParallelMasterDirective>(*S));
238     break;
239   case Stmt::OMPParallelSectionsDirectiveClass:
240     EmitOMPParallelSectionsDirective(cast<OMPParallelSectionsDirective>(*S));
241     break;
242   case Stmt::OMPTaskDirectiveClass:
243     EmitOMPTaskDirective(cast<OMPTaskDirective>(*S));
244     break;
245   case Stmt::OMPTaskyieldDirectiveClass:
246     EmitOMPTaskyieldDirective(cast<OMPTaskyieldDirective>(*S));
247     break;
248   case Stmt::OMPBarrierDirectiveClass:
249     EmitOMPBarrierDirective(cast<OMPBarrierDirective>(*S));
250     break;
251   case Stmt::OMPTaskwaitDirectiveClass:
252     EmitOMPTaskwaitDirective(cast<OMPTaskwaitDirective>(*S));
253     break;
254   case Stmt::OMPTaskgroupDirectiveClass:
255     EmitOMPTaskgroupDirective(cast<OMPTaskgroupDirective>(*S));
256     break;
257   case Stmt::OMPFlushDirectiveClass:
258     EmitOMPFlushDirective(cast<OMPFlushDirective>(*S));
259     break;
260   case Stmt::OMPDepobjDirectiveClass:
261     EmitOMPDepobjDirective(cast<OMPDepobjDirective>(*S));
262     break;
263   case Stmt::OMPScanDirectiveClass:
264     EmitOMPScanDirective(cast<OMPScanDirective>(*S));
265     break;
266   case Stmt::OMPOrderedDirectiveClass:
267     EmitOMPOrderedDirective(cast<OMPOrderedDirective>(*S));
268     break;
269   case Stmt::OMPAtomicDirectiveClass:
270     EmitOMPAtomicDirective(cast<OMPAtomicDirective>(*S));
271     break;
272   case Stmt::OMPTargetDirectiveClass:
273     EmitOMPTargetDirective(cast<OMPTargetDirective>(*S));
274     break;
275   case Stmt::OMPTeamsDirectiveClass:
276     EmitOMPTeamsDirective(cast<OMPTeamsDirective>(*S));
277     break;
278   case Stmt::OMPCancellationPointDirectiveClass:
279     EmitOMPCancellationPointDirective(cast<OMPCancellationPointDirective>(*S));
280     break;
281   case Stmt::OMPCancelDirectiveClass:
282     EmitOMPCancelDirective(cast<OMPCancelDirective>(*S));
283     break;
284   case Stmt::OMPTargetDataDirectiveClass:
285     EmitOMPTargetDataDirective(cast<OMPTargetDataDirective>(*S));
286     break;
287   case Stmt::OMPTargetEnterDataDirectiveClass:
288     EmitOMPTargetEnterDataDirective(cast<OMPTargetEnterDataDirective>(*S));
289     break;
290   case Stmt::OMPTargetExitDataDirectiveClass:
291     EmitOMPTargetExitDataDirective(cast<OMPTargetExitDataDirective>(*S));
292     break;
293   case Stmt::OMPTargetParallelDirectiveClass:
294     EmitOMPTargetParallelDirective(cast<OMPTargetParallelDirective>(*S));
295     break;
296   case Stmt::OMPTargetParallelForDirectiveClass:
297     EmitOMPTargetParallelForDirective(cast<OMPTargetParallelForDirective>(*S));
298     break;
299   case Stmt::OMPTaskLoopDirectiveClass:
300     EmitOMPTaskLoopDirective(cast<OMPTaskLoopDirective>(*S));
301     break;
302   case Stmt::OMPTaskLoopSimdDirectiveClass:
303     EmitOMPTaskLoopSimdDirective(cast<OMPTaskLoopSimdDirective>(*S));
304     break;
305   case Stmt::OMPMasterTaskLoopDirectiveClass:
306     EmitOMPMasterTaskLoopDirective(cast<OMPMasterTaskLoopDirective>(*S));
307     break;
308   case Stmt::OMPMasterTaskLoopSimdDirectiveClass:
309     EmitOMPMasterTaskLoopSimdDirective(
310         cast<OMPMasterTaskLoopSimdDirective>(*S));
311     break;
312   case Stmt::OMPParallelMasterTaskLoopDirectiveClass:
313     EmitOMPParallelMasterTaskLoopDirective(
314         cast<OMPParallelMasterTaskLoopDirective>(*S));
315     break;
316   case Stmt::OMPParallelMasterTaskLoopSimdDirectiveClass:
317     EmitOMPParallelMasterTaskLoopSimdDirective(
318         cast<OMPParallelMasterTaskLoopSimdDirective>(*S));
319     break;
320   case Stmt::OMPDistributeDirectiveClass:
321     EmitOMPDistributeDirective(cast<OMPDistributeDirective>(*S));
322     break;
323   case Stmt::OMPTargetUpdateDirectiveClass:
324     EmitOMPTargetUpdateDirective(cast<OMPTargetUpdateDirective>(*S));
325     break;
326   case Stmt::OMPDistributeParallelForDirectiveClass:
327     EmitOMPDistributeParallelForDirective(
328         cast<OMPDistributeParallelForDirective>(*S));
329     break;
330   case Stmt::OMPDistributeParallelForSimdDirectiveClass:
331     EmitOMPDistributeParallelForSimdDirective(
332         cast<OMPDistributeParallelForSimdDirective>(*S));
333     break;
334   case Stmt::OMPDistributeSimdDirectiveClass:
335     EmitOMPDistributeSimdDirective(cast<OMPDistributeSimdDirective>(*S));
336     break;
337   case Stmt::OMPTargetParallelForSimdDirectiveClass:
338     EmitOMPTargetParallelForSimdDirective(
339         cast<OMPTargetParallelForSimdDirective>(*S));
340     break;
341   case Stmt::OMPTargetSimdDirectiveClass:
342     EmitOMPTargetSimdDirective(cast<OMPTargetSimdDirective>(*S));
343     break;
344   case Stmt::OMPTeamsDistributeDirectiveClass:
345     EmitOMPTeamsDistributeDirective(cast<OMPTeamsDistributeDirective>(*S));
346     break;
347   case Stmt::OMPTeamsDistributeSimdDirectiveClass:
348     EmitOMPTeamsDistributeSimdDirective(
349         cast<OMPTeamsDistributeSimdDirective>(*S));
350     break;
351   case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass:
352     EmitOMPTeamsDistributeParallelForSimdDirective(
353         cast<OMPTeamsDistributeParallelForSimdDirective>(*S));
354     break;
355   case Stmt::OMPTeamsDistributeParallelForDirectiveClass:
356     EmitOMPTeamsDistributeParallelForDirective(
357         cast<OMPTeamsDistributeParallelForDirective>(*S));
358     break;
359   case Stmt::OMPTargetTeamsDirectiveClass:
360     EmitOMPTargetTeamsDirective(cast<OMPTargetTeamsDirective>(*S));
361     break;
362   case Stmt::OMPTargetTeamsDistributeDirectiveClass:
363     EmitOMPTargetTeamsDistributeDirective(
364         cast<OMPTargetTeamsDistributeDirective>(*S));
365     break;
366   case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass:
367     EmitOMPTargetTeamsDistributeParallelForDirective(
368         cast<OMPTargetTeamsDistributeParallelForDirective>(*S));
369     break;
370   case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass:
371     EmitOMPTargetTeamsDistributeParallelForSimdDirective(
372         cast<OMPTargetTeamsDistributeParallelForSimdDirective>(*S));
373     break;
374   case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass:
375     EmitOMPTargetTeamsDistributeSimdDirective(
376         cast<OMPTargetTeamsDistributeSimdDirective>(*S));
377     break;
378   case Stmt::OMPInteropDirectiveClass:
379     llvm_unreachable("Interop directive not supported yet.");
380     break;
381   }
382 }
383 
384 bool CodeGenFunction::EmitSimpleStmt(const Stmt *S,
385                                      ArrayRef<const Attr *> Attrs) {
386   switch (S->getStmtClass()) {
387   default:
388     return false;
389   case Stmt::NullStmtClass:
390     break;
391   case Stmt::CompoundStmtClass:
392     EmitCompoundStmt(cast<CompoundStmt>(*S));
393     break;
394   case Stmt::DeclStmtClass:
395     EmitDeclStmt(cast<DeclStmt>(*S));
396     break;
397   case Stmt::LabelStmtClass:
398     EmitLabelStmt(cast<LabelStmt>(*S));
399     break;
400   case Stmt::AttributedStmtClass:
401     EmitAttributedStmt(cast<AttributedStmt>(*S));
402     break;
403   case Stmt::GotoStmtClass:
404     EmitGotoStmt(cast<GotoStmt>(*S));
405     break;
406   case Stmt::BreakStmtClass:
407     EmitBreakStmt(cast<BreakStmt>(*S));
408     break;
409   case Stmt::ContinueStmtClass:
410     EmitContinueStmt(cast<ContinueStmt>(*S));
411     break;
412   case Stmt::DefaultStmtClass:
413     EmitDefaultStmt(cast<DefaultStmt>(*S), Attrs);
414     break;
415   case Stmt::CaseStmtClass:
416     EmitCaseStmt(cast<CaseStmt>(*S), Attrs);
417     break;
418   case Stmt::SEHLeaveStmtClass:
419     EmitSEHLeaveStmt(cast<SEHLeaveStmt>(*S));
420     break;
421   }
422   return true;
423 }
424 
425 /// EmitCompoundStmt - Emit a compound statement {..} node.  If GetLast is true,
426 /// this captures the expression result of the last sub-statement and returns it
427 /// (for use by the statement expression extension).
428 Address CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
429                                           AggValueSlot AggSlot) {
430   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(),
431                              "LLVM IR generation of compound statement ('{}')");
432 
433   // Keep track of the current cleanup stack depth, including debug scopes.
434   LexicalScope Scope(*this, S.getSourceRange());
435 
436   return EmitCompoundStmtWithoutScope(S, GetLast, AggSlot);
437 }
438 
439 Address
440 CodeGenFunction::EmitCompoundStmtWithoutScope(const CompoundStmt &S,
441                                               bool GetLast,
442                                               AggValueSlot AggSlot) {
443 
444   const Stmt *ExprResult = S.getStmtExprResult();
445   assert((!GetLast || (GetLast && ExprResult)) &&
446          "If GetLast is true then the CompoundStmt must have a StmtExprResult");
447 
448   Address RetAlloca = Address::invalid();
449 
450   for (auto *CurStmt : S.body()) {
451     if (GetLast && ExprResult == CurStmt) {
452       // We have to special case labels here.  They are statements, but when put
453       // at the end of a statement expression, they yield the value of their
454       // subexpression.  Handle this by walking through all labels we encounter,
455       // emitting them before we evaluate the subexpr.
456       // Similar issues arise for attributed statements.
457       while (!isa<Expr>(ExprResult)) {
458         if (const auto *LS = dyn_cast<LabelStmt>(ExprResult)) {
459           EmitLabel(LS->getDecl());
460           ExprResult = LS->getSubStmt();
461         } else if (const auto *AS = dyn_cast<AttributedStmt>(ExprResult)) {
462           // FIXME: Update this if we ever have attributes that affect the
463           // semantics of an expression.
464           ExprResult = AS->getSubStmt();
465         } else {
466           llvm_unreachable("unknown value statement");
467         }
468       }
469 
470       EnsureInsertPoint();
471 
472       const Expr *E = cast<Expr>(ExprResult);
473       QualType ExprTy = E->getType();
474       if (hasAggregateEvaluationKind(ExprTy)) {
475         EmitAggExpr(E, AggSlot);
476       } else {
477         // We can't return an RValue here because there might be cleanups at
478         // the end of the StmtExpr.  Because of that, we have to emit the result
479         // here into a temporary alloca.
480         RetAlloca = CreateMemTemp(ExprTy);
481         EmitAnyExprToMem(E, RetAlloca, Qualifiers(),
482                          /*IsInit*/ false);
483       }
484     } else {
485       EmitStmt(CurStmt);
486     }
487   }
488 
489   return RetAlloca;
490 }
491 
492 void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) {
493   llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(BB->getTerminator());
494 
495   // If there is a cleanup stack, then we it isn't worth trying to
496   // simplify this block (we would need to remove it from the scope map
497   // and cleanup entry).
498   if (!EHStack.empty())
499     return;
500 
501   // Can only simplify direct branches.
502   if (!BI || !BI->isUnconditional())
503     return;
504 
505   // Can only simplify empty blocks.
506   if (BI->getIterator() != BB->begin())
507     return;
508 
509   BB->replaceAllUsesWith(BI->getSuccessor(0));
510   BI->eraseFromParent();
511   BB->eraseFromParent();
512 }
513 
514 void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
515   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
516 
517   // Fall out of the current block (if necessary).
518   EmitBranch(BB);
519 
520   if (IsFinished && BB->use_empty()) {
521     delete BB;
522     return;
523   }
524 
525   // Place the block after the current block, if possible, or else at
526   // the end of the function.
527   if (CurBB && CurBB->getParent())
528     CurFn->getBasicBlockList().insertAfter(CurBB->getIterator(), BB);
529   else
530     CurFn->getBasicBlockList().push_back(BB);
531   Builder.SetInsertPoint(BB);
532 }
533 
534 void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
535   // Emit a branch from the current block to the target one if this
536   // was a real block.  If this was just a fall-through block after a
537   // terminator, don't emit it.
538   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
539 
540   if (!CurBB || CurBB->getTerminator()) {
541     // If there is no insert point or the previous block is already
542     // terminated, don't touch it.
543   } else {
544     // Otherwise, create a fall-through branch.
545     Builder.CreateBr(Target);
546   }
547 
548   Builder.ClearInsertionPoint();
549 }
550 
551 void CodeGenFunction::EmitBlockAfterUses(llvm::BasicBlock *block) {
552   bool inserted = false;
553   for (llvm::User *u : block->users()) {
554     if (llvm::Instruction *insn = dyn_cast<llvm::Instruction>(u)) {
555       CurFn->getBasicBlockList().insertAfter(insn->getParent()->getIterator(),
556                                              block);
557       inserted = true;
558       break;
559     }
560   }
561 
562   if (!inserted)
563     CurFn->getBasicBlockList().push_back(block);
564 
565   Builder.SetInsertPoint(block);
566 }
567 
568 CodeGenFunction::JumpDest
569 CodeGenFunction::getJumpDestForLabel(const LabelDecl *D) {
570   JumpDest &Dest = LabelMap[D];
571   if (Dest.isValid()) return Dest;
572 
573   // Create, but don't insert, the new block.
574   Dest = JumpDest(createBasicBlock(D->getName()),
575                   EHScopeStack::stable_iterator::invalid(),
576                   NextCleanupDestIndex++);
577   return Dest;
578 }
579 
580 void CodeGenFunction::EmitLabel(const LabelDecl *D) {
581   // Add this label to the current lexical scope if we're within any
582   // normal cleanups.  Jumps "in" to this label --- when permitted by
583   // the language --- may need to be routed around such cleanups.
584   if (EHStack.hasNormalCleanups() && CurLexicalScope)
585     CurLexicalScope->addLabel(D);
586 
587   JumpDest &Dest = LabelMap[D];
588 
589   // If we didn't need a forward reference to this label, just go
590   // ahead and create a destination at the current scope.
591   if (!Dest.isValid()) {
592     Dest = getJumpDestInCurrentScope(D->getName());
593 
594   // Otherwise, we need to give this label a target depth and remove
595   // it from the branch-fixups list.
596   } else {
597     assert(!Dest.getScopeDepth().isValid() && "already emitted label!");
598     Dest.setScopeDepth(EHStack.stable_begin());
599     ResolveBranchFixups(Dest.getBlock());
600   }
601 
602   EmitBlock(Dest.getBlock());
603 
604   // Emit debug info for labels.
605   if (CGDebugInfo *DI = getDebugInfo()) {
606     if (CGM.getCodeGenOpts().hasReducedDebugInfo()) {
607       DI->setLocation(D->getLocation());
608       DI->EmitLabel(D, Builder);
609     }
610   }
611 
612   incrementProfileCounter(D->getStmt());
613 }
614 
615 /// Change the cleanup scope of the labels in this lexical scope to
616 /// match the scope of the enclosing context.
617 void CodeGenFunction::LexicalScope::rescopeLabels() {
618   assert(!Labels.empty());
619   EHScopeStack::stable_iterator innermostScope
620     = CGF.EHStack.getInnermostNormalCleanup();
621 
622   // Change the scope depth of all the labels.
623   for (SmallVectorImpl<const LabelDecl*>::const_iterator
624          i = Labels.begin(), e = Labels.end(); i != e; ++i) {
625     assert(CGF.LabelMap.count(*i));
626     JumpDest &dest = CGF.LabelMap.find(*i)->second;
627     assert(dest.getScopeDepth().isValid());
628     assert(innermostScope.encloses(dest.getScopeDepth()));
629     dest.setScopeDepth(innermostScope);
630   }
631 
632   // Reparent the labels if the new scope also has cleanups.
633   if (innermostScope != EHScopeStack::stable_end() && ParentScope) {
634     ParentScope->Labels.append(Labels.begin(), Labels.end());
635   }
636 }
637 
638 
639 void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
640   EmitLabel(S.getDecl());
641   EmitStmt(S.getSubStmt());
642 }
643 
644 void CodeGenFunction::EmitAttributedStmt(const AttributedStmt &S) {
645   bool nomerge = false;
646   for (const auto *A : S.getAttrs())
647     if (A->getKind() == attr::NoMerge) {
648       nomerge = true;
649       break;
650     }
651   SaveAndRestore<bool> save_nomerge(InNoMergeAttributedStmt, nomerge);
652   EmitStmt(S.getSubStmt(), S.getAttrs());
653 }
654 
655 void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
656   // If this code is reachable then emit a stop point (if generating
657   // debug info). We have to do this ourselves because we are on the
658   // "simple" statement path.
659   if (HaveInsertPoint())
660     EmitStopPoint(&S);
661 
662   EmitBranchThroughCleanup(getJumpDestForLabel(S.getLabel()));
663 }
664 
665 
666 void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
667   if (const LabelDecl *Target = S.getConstantTarget()) {
668     EmitBranchThroughCleanup(getJumpDestForLabel(Target));
669     return;
670   }
671 
672   // Ensure that we have an i8* for our PHI node.
673   llvm::Value *V = Builder.CreateBitCast(EmitScalarExpr(S.getTarget()),
674                                          Int8PtrTy, "addr");
675   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
676 
677   // Get the basic block for the indirect goto.
678   llvm::BasicBlock *IndGotoBB = GetIndirectGotoBlock();
679 
680   // The first instruction in the block has to be the PHI for the switch dest,
681   // add an entry for this branch.
682   cast<llvm::PHINode>(IndGotoBB->begin())->addIncoming(V, CurBB);
683 
684   EmitBranch(IndGotoBB);
685 }
686 
687 void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
688   // C99 6.8.4.1: The first substatement is executed if the expression compares
689   // unequal to 0.  The condition must be a scalar type.
690   LexicalScope ConditionScope(*this, S.getCond()->getSourceRange());
691 
692   if (S.getInit())
693     EmitStmt(S.getInit());
694 
695   if (S.getConditionVariable())
696     EmitDecl(*S.getConditionVariable());
697 
698   // If the condition constant folds and can be elided, try to avoid emitting
699   // the condition and the dead arm of the if/else.
700   bool CondConstant;
701   if (ConstantFoldsToSimpleInteger(S.getCond(), CondConstant,
702                                    S.isConstexpr())) {
703     // Figure out which block (then or else) is executed.
704     const Stmt *Executed = S.getThen();
705     const Stmt *Skipped  = S.getElse();
706     if (!CondConstant)  // Condition false?
707       std::swap(Executed, Skipped);
708 
709     // If the skipped block has no labels in it, just emit the executed block.
710     // This avoids emitting dead code and simplifies the CFG substantially.
711     if (S.isConstexpr() || !ContainsLabel(Skipped)) {
712       if (CondConstant)
713         incrementProfileCounter(&S);
714       if (Executed) {
715         RunCleanupsScope ExecutedScope(*this);
716         EmitStmt(Executed);
717       }
718       return;
719     }
720   }
721 
722   // Otherwise, the condition did not fold, or we couldn't elide it.  Just emit
723   // the conditional branch.
724   llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
725   llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
726   llvm::BasicBlock *ElseBlock = ContBlock;
727   if (S.getElse())
728     ElseBlock = createBasicBlock("if.else");
729 
730   // Prefer the PGO based weights over the likelihood attribute.
731   // When the build isn't optimized the metadata isn't used, so don't generate
732   // it.
733   Stmt::Likelihood LH = Stmt::LH_None;
734   uint64_t Count = getProfileCount(S.getThen());
735   if (!Count && CGM.getCodeGenOpts().OptimizationLevel)
736     LH = Stmt::getLikelihood(S.getThen(), S.getElse());
737   EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock, Count, LH);
738 
739   // Emit the 'then' code.
740   EmitBlock(ThenBlock);
741   incrementProfileCounter(&S);
742   {
743     RunCleanupsScope ThenScope(*this);
744     EmitStmt(S.getThen());
745   }
746   EmitBranch(ContBlock);
747 
748   // Emit the 'else' code if present.
749   if (const Stmt *Else = S.getElse()) {
750     {
751       // There is no need to emit line number for an unconditional branch.
752       auto NL = ApplyDebugLocation::CreateEmpty(*this);
753       EmitBlock(ElseBlock);
754     }
755     {
756       RunCleanupsScope ElseScope(*this);
757       EmitStmt(Else);
758     }
759     {
760       // There is no need to emit line number for an unconditional branch.
761       auto NL = ApplyDebugLocation::CreateEmpty(*this);
762       EmitBranch(ContBlock);
763     }
764   }
765 
766   // Emit the continuation block for code after the if.
767   EmitBlock(ContBlock, true);
768 }
769 
770 void CodeGenFunction::EmitWhileStmt(const WhileStmt &S,
771                                     ArrayRef<const Attr *> WhileAttrs) {
772   // Emit the header for the loop, which will also become
773   // the continue target.
774   JumpDest LoopHeader = getJumpDestInCurrentScope("while.cond");
775   EmitBlock(LoopHeader.getBlock());
776 
777   // Create an exit block for when the condition fails, which will
778   // also become the break target.
779   JumpDest LoopExit = getJumpDestInCurrentScope("while.end");
780 
781   // Store the blocks to use for break and continue.
782   BreakContinueStack.push_back(BreakContinue(LoopExit, LoopHeader));
783 
784   // C++ [stmt.while]p2:
785   //   When the condition of a while statement is a declaration, the
786   //   scope of the variable that is declared extends from its point
787   //   of declaration (3.3.2) to the end of the while statement.
788   //   [...]
789   //   The object created in a condition is destroyed and created
790   //   with each iteration of the loop.
791   RunCleanupsScope ConditionScope(*this);
792 
793   if (S.getConditionVariable())
794     EmitDecl(*S.getConditionVariable());
795 
796   // Evaluate the conditional in the while header.  C99 6.8.5.1: The
797   // evaluation of the controlling expression takes place before each
798   // execution of the loop body.
799   llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
800 
801   // while(1) is common, avoid extra exit blocks.  Be sure
802   // to correctly handle break/continue though.
803   bool EmitBoolCondBranch = true;
804   bool LoopMustProgress = false;
805   if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal)) {
806     if (C->isOne()) {
807       EmitBoolCondBranch = false;
808       FnIsMustProgress = false;
809     }
810   } else if (LanguageRequiresProgress())
811     LoopMustProgress = true;
812 
813   const SourceRange &R = S.getSourceRange();
814   LoopStack.push(LoopHeader.getBlock(), CGM.getContext(), CGM.getCodeGenOpts(),
815                  WhileAttrs, SourceLocToDebugLoc(R.getBegin()),
816                  SourceLocToDebugLoc(R.getEnd()), LoopMustProgress);
817 
818   // As long as the condition is true, go to the loop body.
819   llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
820   if (EmitBoolCondBranch) {
821     llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
822     if (ConditionScope.requiresCleanups())
823       ExitBlock = createBasicBlock("while.exit");
824     llvm::MDNode *Weights =
825         createProfileWeightsForLoop(S.getCond(), getProfileCount(S.getBody()));
826     if (!Weights && CGM.getCodeGenOpts().OptimizationLevel)
827       BoolCondVal = emitCondLikelihoodViaExpectIntrinsic(
828           BoolCondVal, Stmt::getLikelihood(S.getBody()));
829     Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock, Weights);
830 
831     if (ExitBlock != LoopExit.getBlock()) {
832       EmitBlock(ExitBlock);
833       EmitBranchThroughCleanup(LoopExit);
834     }
835   } else if (const Attr *A = Stmt::getLikelihoodAttr(S.getBody())) {
836     CGM.getDiags().Report(A->getLocation(),
837                           diag::warn_attribute_has_no_effect_on_infinite_loop)
838         << A << A->getRange();
839     CGM.getDiags().Report(
840         S.getWhileLoc(),
841         diag::note_attribute_has_no_effect_on_infinite_loop_here)
842         << SourceRange(S.getWhileLoc(), S.getRParenLoc());
843   }
844 
845   // Emit the loop body.  We have to emit this in a cleanup scope
846   // because it might be a singleton DeclStmt.
847   {
848     RunCleanupsScope BodyScope(*this);
849     EmitBlock(LoopBody);
850     incrementProfileCounter(&S);
851     EmitStmt(S.getBody());
852   }
853 
854   BreakContinueStack.pop_back();
855 
856   // Immediately force cleanup.
857   ConditionScope.ForceCleanup();
858 
859   EmitStopPoint(&S);
860   // Branch to the loop header again.
861   EmitBranch(LoopHeader.getBlock());
862 
863   LoopStack.pop();
864 
865   // Emit the exit block.
866   EmitBlock(LoopExit.getBlock(), true);
867 
868   // The LoopHeader typically is just a branch if we skipped emitting
869   // a branch, try to erase it.
870   if (!EmitBoolCondBranch)
871     SimplifyForwardingBlocks(LoopHeader.getBlock());
872 }
873 
874 void CodeGenFunction::EmitDoStmt(const DoStmt &S,
875                                  ArrayRef<const Attr *> DoAttrs) {
876   JumpDest LoopExit = getJumpDestInCurrentScope("do.end");
877   JumpDest LoopCond = getJumpDestInCurrentScope("do.cond");
878 
879   uint64_t ParentCount = getCurrentProfileCount();
880 
881   // Store the blocks to use for break and continue.
882   BreakContinueStack.push_back(BreakContinue(LoopExit, LoopCond));
883 
884   // Emit the body of the loop.
885   llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
886 
887   EmitBlockWithFallThrough(LoopBody, &S);
888   {
889     RunCleanupsScope BodyScope(*this);
890     EmitStmt(S.getBody());
891   }
892 
893   EmitBlock(LoopCond.getBlock());
894 
895   // C99 6.8.5.2: "The evaluation of the controlling expression takes place
896   // after each execution of the loop body."
897 
898   // Evaluate the conditional in the while header.
899   // C99 6.8.5p2/p4: The first substatement is executed if the expression
900   // compares unequal to 0.  The condition must be a scalar type.
901   llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
902 
903   BreakContinueStack.pop_back();
904 
905   // "do {} while (0)" is common in macros, avoid extra blocks.  Be sure
906   // to correctly handle break/continue though.
907   bool EmitBoolCondBranch = true;
908   bool LoopMustProgress = false;
909   if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal)) {
910     if (C->isZero())
911       EmitBoolCondBranch = false;
912     else if (C->isOne())
913       FnIsMustProgress = false;
914   } else if (LanguageRequiresProgress())
915     LoopMustProgress = true;
916 
917   const SourceRange &R = S.getSourceRange();
918   LoopStack.push(LoopBody, CGM.getContext(), CGM.getCodeGenOpts(), DoAttrs,
919                  SourceLocToDebugLoc(R.getBegin()),
920                  SourceLocToDebugLoc(R.getEnd()), LoopMustProgress);
921 
922   // As long as the condition is true, iterate the loop.
923   if (EmitBoolCondBranch) {
924     uint64_t BackedgeCount = getProfileCount(S.getBody()) - ParentCount;
925     Builder.CreateCondBr(
926         BoolCondVal, LoopBody, LoopExit.getBlock(),
927         createProfileWeightsForLoop(S.getCond(), BackedgeCount));
928   }
929 
930   LoopStack.pop();
931 
932   // Emit the exit block.
933   EmitBlock(LoopExit.getBlock());
934 
935   // The DoCond block typically is just a branch if we skipped
936   // emitting a branch, try to erase it.
937   if (!EmitBoolCondBranch)
938     SimplifyForwardingBlocks(LoopCond.getBlock());
939 }
940 
941 void CodeGenFunction::EmitForStmt(const ForStmt &S,
942                                   ArrayRef<const Attr *> ForAttrs) {
943   JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
944 
945   LexicalScope ForScope(*this, S.getSourceRange());
946 
947   // Evaluate the first part before the loop.
948   if (S.getInit())
949     EmitStmt(S.getInit());
950 
951   // Start the loop with a block that tests the condition.
952   // If there's an increment, the continue scope will be overwritten
953   // later.
954   JumpDest CondDest = getJumpDestInCurrentScope("for.cond");
955   llvm::BasicBlock *CondBlock = CondDest.getBlock();
956   EmitBlock(CondBlock);
957 
958   bool LoopMustProgress = false;
959   Expr::EvalResult Result;
960   if (LanguageRequiresProgress()) {
961     if (!S.getCond()) {
962       FnIsMustProgress = false;
963     } else if (!S.getCond()->EvaluateAsInt(Result, getContext())) {
964       LoopMustProgress = true;
965     }
966   }
967 
968   const SourceRange &R = S.getSourceRange();
969   LoopStack.push(CondBlock, CGM.getContext(), CGM.getCodeGenOpts(), ForAttrs,
970                  SourceLocToDebugLoc(R.getBegin()),
971                  SourceLocToDebugLoc(R.getEnd()), LoopMustProgress);
972 
973   // Create a cleanup scope for the condition variable cleanups.
974   LexicalScope ConditionScope(*this, S.getSourceRange());
975 
976   // If the for loop doesn't have an increment we can just use the condition as
977   // the continue block. Otherwise, if there is no condition variable, we can
978   // form the continue block now. If there is a condition variable, we can't
979   // form the continue block until after we've emitted the condition, because
980   // the condition is in scope in the increment, but Sema's jump diagnostics
981   // ensure that there are no continues from the condition variable that jump
982   // to the loop increment.
983   JumpDest Continue;
984   if (!S.getInc())
985     Continue = CondDest;
986   else if (!S.getConditionVariable())
987     Continue = getJumpDestInCurrentScope("for.inc");
988   BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
989 
990   if (S.getCond()) {
991     // If the for statement has a condition scope, emit the local variable
992     // declaration.
993     if (S.getConditionVariable()) {
994       EmitDecl(*S.getConditionVariable());
995 
996       // We have entered the condition variable's scope, so we're now able to
997       // jump to the continue block.
998       Continue = S.getInc() ? getJumpDestInCurrentScope("for.inc") : CondDest;
999       BreakContinueStack.back().ContinueBlock = Continue;
1000     }
1001 
1002     llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
1003     // If there are any cleanups between here and the loop-exit scope,
1004     // create a block to stage a loop exit along.
1005     if (ForScope.requiresCleanups())
1006       ExitBlock = createBasicBlock("for.cond.cleanup");
1007 
1008     // As long as the condition is true, iterate the loop.
1009     llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1010 
1011     // C99 6.8.5p2/p4: The first substatement is executed if the expression
1012     // compares unequal to 0.  The condition must be a scalar type.
1013     llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
1014     llvm::MDNode *Weights =
1015         createProfileWeightsForLoop(S.getCond(), getProfileCount(S.getBody()));
1016     if (!Weights && CGM.getCodeGenOpts().OptimizationLevel)
1017       BoolCondVal = emitCondLikelihoodViaExpectIntrinsic(
1018           BoolCondVal, Stmt::getLikelihood(S.getBody()));
1019 
1020     if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
1021       if (C->isOne())
1022         FnIsMustProgress = false;
1023 
1024     Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock, Weights);
1025 
1026     if (ExitBlock != LoopExit.getBlock()) {
1027       EmitBlock(ExitBlock);
1028       EmitBranchThroughCleanup(LoopExit);
1029     }
1030 
1031     EmitBlock(ForBody);
1032   } else {
1033     // Treat it as a non-zero constant.  Don't even create a new block for the
1034     // body, just fall into it.
1035   }
1036   incrementProfileCounter(&S);
1037 
1038   {
1039     // Create a separate cleanup scope for the body, in case it is not
1040     // a compound statement.
1041     RunCleanupsScope BodyScope(*this);
1042     EmitStmt(S.getBody());
1043   }
1044 
1045   // If there is an increment, emit it next.
1046   if (S.getInc()) {
1047     EmitBlock(Continue.getBlock());
1048     EmitStmt(S.getInc());
1049   }
1050 
1051   BreakContinueStack.pop_back();
1052 
1053   ConditionScope.ForceCleanup();
1054 
1055   EmitStopPoint(&S);
1056   EmitBranch(CondBlock);
1057 
1058   ForScope.ForceCleanup();
1059 
1060   LoopStack.pop();
1061 
1062   // Emit the fall-through block.
1063   EmitBlock(LoopExit.getBlock(), true);
1064 }
1065 
1066 void
1067 CodeGenFunction::EmitCXXForRangeStmt(const CXXForRangeStmt &S,
1068                                      ArrayRef<const Attr *> ForAttrs) {
1069   JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
1070 
1071   LexicalScope ForScope(*this, S.getSourceRange());
1072 
1073   // Evaluate the first pieces before the loop.
1074   if (S.getInit())
1075     EmitStmt(S.getInit());
1076   EmitStmt(S.getRangeStmt());
1077   EmitStmt(S.getBeginStmt());
1078   EmitStmt(S.getEndStmt());
1079 
1080   // Start the loop with a block that tests the condition.
1081   // If there's an increment, the continue scope will be overwritten
1082   // later.
1083   llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1084   EmitBlock(CondBlock);
1085 
1086   const SourceRange &R = S.getSourceRange();
1087   LoopStack.push(CondBlock, CGM.getContext(), CGM.getCodeGenOpts(), ForAttrs,
1088                  SourceLocToDebugLoc(R.getBegin()),
1089                  SourceLocToDebugLoc(R.getEnd()));
1090 
1091   // If there are any cleanups between here and the loop-exit scope,
1092   // create a block to stage a loop exit along.
1093   llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
1094   if (ForScope.requiresCleanups())
1095     ExitBlock = createBasicBlock("for.cond.cleanup");
1096 
1097   // The loop body, consisting of the specified body and the loop variable.
1098   llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1099 
1100   // The body is executed if the expression, contextually converted
1101   // to bool, is true.
1102   llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
1103   llvm::MDNode *Weights =
1104       createProfileWeightsForLoop(S.getCond(), getProfileCount(S.getBody()));
1105   if (!Weights && CGM.getCodeGenOpts().OptimizationLevel)
1106     BoolCondVal = emitCondLikelihoodViaExpectIntrinsic(
1107         BoolCondVal, Stmt::getLikelihood(S.getBody()));
1108   Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock, Weights);
1109 
1110   if (ExitBlock != LoopExit.getBlock()) {
1111     EmitBlock(ExitBlock);
1112     EmitBranchThroughCleanup(LoopExit);
1113   }
1114 
1115   EmitBlock(ForBody);
1116   incrementProfileCounter(&S);
1117 
1118   // Create a block for the increment. In case of a 'continue', we jump there.
1119   JumpDest Continue = getJumpDestInCurrentScope("for.inc");
1120 
1121   // Store the blocks to use for break and continue.
1122   BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1123 
1124   {
1125     // Create a separate cleanup scope for the loop variable and body.
1126     LexicalScope BodyScope(*this, S.getSourceRange());
1127     EmitStmt(S.getLoopVarStmt());
1128     EmitStmt(S.getBody());
1129   }
1130 
1131   EmitStopPoint(&S);
1132   // If there is an increment, emit it next.
1133   EmitBlock(Continue.getBlock());
1134   EmitStmt(S.getInc());
1135 
1136   BreakContinueStack.pop_back();
1137 
1138   EmitBranch(CondBlock);
1139 
1140   ForScope.ForceCleanup();
1141 
1142   LoopStack.pop();
1143 
1144   // Emit the fall-through block.
1145   EmitBlock(LoopExit.getBlock(), true);
1146 }
1147 
1148 void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
1149   if (RV.isScalar()) {
1150     Builder.CreateStore(RV.getScalarVal(), ReturnValue);
1151   } else if (RV.isAggregate()) {
1152     LValue Dest = MakeAddrLValue(ReturnValue, Ty);
1153     LValue Src = MakeAddrLValue(RV.getAggregateAddress(), Ty);
1154     EmitAggregateCopy(Dest, Src, Ty, getOverlapForReturnValue());
1155   } else {
1156     EmitStoreOfComplex(RV.getComplexVal(), MakeAddrLValue(ReturnValue, Ty),
1157                        /*init*/ true);
1158   }
1159   EmitBranchThroughCleanup(ReturnBlock);
1160 }
1161 
1162 namespace {
1163 // RAII struct used to save and restore a return statment's result expression.
1164 struct SaveRetExprRAII {
1165   SaveRetExprRAII(const Expr *RetExpr, CodeGenFunction &CGF)
1166       : OldRetExpr(CGF.RetExpr), CGF(CGF) {
1167     CGF.RetExpr = RetExpr;
1168   }
1169   ~SaveRetExprRAII() { CGF.RetExpr = OldRetExpr; }
1170   const Expr *OldRetExpr;
1171   CodeGenFunction &CGF;
1172 };
1173 } // namespace
1174 
1175 /// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
1176 /// if the function returns void, or may be missing one if the function returns
1177 /// non-void.  Fun stuff :).
1178 void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
1179   if (requiresReturnValueCheck()) {
1180     llvm::Constant *SLoc = EmitCheckSourceLocation(S.getBeginLoc());
1181     auto *SLocPtr =
1182         new llvm::GlobalVariable(CGM.getModule(), SLoc->getType(), false,
1183                                  llvm::GlobalVariable::PrivateLinkage, SLoc);
1184     SLocPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1185     CGM.getSanitizerMetadata()->disableSanitizerForGlobal(SLocPtr);
1186     assert(ReturnLocation.isValid() && "No valid return location");
1187     Builder.CreateStore(Builder.CreateBitCast(SLocPtr, Int8PtrTy),
1188                         ReturnLocation);
1189   }
1190 
1191   // Returning from an outlined SEH helper is UB, and we already warn on it.
1192   if (IsOutlinedSEHHelper) {
1193     Builder.CreateUnreachable();
1194     Builder.ClearInsertionPoint();
1195   }
1196 
1197   // Emit the result value, even if unused, to evaluate the side effects.
1198   const Expr *RV = S.getRetValue();
1199 
1200   // Record the result expression of the return statement. The recorded
1201   // expression is used to determine whether a block capture's lifetime should
1202   // end at the end of the full expression as opposed to the end of the scope
1203   // enclosing the block expression.
1204   //
1205   // This permits a small, easily-implemented exception to our over-conservative
1206   // rules about not jumping to statements following block literals with
1207   // non-trivial cleanups.
1208   SaveRetExprRAII SaveRetExpr(RV, *this);
1209 
1210   RunCleanupsScope cleanupScope(*this);
1211   if (const auto *EWC = dyn_cast_or_null<ExprWithCleanups>(RV))
1212     RV = EWC->getSubExpr();
1213   // FIXME: Clean this up by using an LValue for ReturnTemp,
1214   // EmitStoreThroughLValue, and EmitAnyExpr.
1215   // Check if the NRVO candidate was not globalized in OpenMP mode.
1216   if (getLangOpts().ElideConstructors && S.getNRVOCandidate() &&
1217       S.getNRVOCandidate()->isNRVOVariable() &&
1218       (!getLangOpts().OpenMP ||
1219        !CGM.getOpenMPRuntime()
1220             .getAddressOfLocalVariable(*this, S.getNRVOCandidate())
1221             .isValid())) {
1222     // Apply the named return value optimization for this return statement,
1223     // which means doing nothing: the appropriate result has already been
1224     // constructed into the NRVO variable.
1225 
1226     // If there is an NRVO flag for this variable, set it to 1 into indicate
1227     // that the cleanup code should not destroy the variable.
1228     if (llvm::Value *NRVOFlag = NRVOFlags[S.getNRVOCandidate()])
1229       Builder.CreateFlagStore(Builder.getTrue(), NRVOFlag);
1230   } else if (!ReturnValue.isValid() || (RV && RV->getType()->isVoidType())) {
1231     // Make sure not to return anything, but evaluate the expression
1232     // for side effects.
1233     if (RV)
1234       EmitAnyExpr(RV);
1235   } else if (!RV) {
1236     // Do nothing (return value is left uninitialized)
1237   } else if (FnRetTy->isReferenceType()) {
1238     // If this function returns a reference, take the address of the expression
1239     // rather than the value.
1240     RValue Result = EmitReferenceBindingToExpr(RV);
1241     Builder.CreateStore(Result.getScalarVal(), ReturnValue);
1242   } else {
1243     switch (getEvaluationKind(RV->getType())) {
1244     case TEK_Scalar:
1245       Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
1246       break;
1247     case TEK_Complex:
1248       EmitComplexExprIntoLValue(RV, MakeAddrLValue(ReturnValue, RV->getType()),
1249                                 /*isInit*/ true);
1250       break;
1251     case TEK_Aggregate:
1252       EmitAggExpr(RV, AggValueSlot::forAddr(
1253                           ReturnValue, Qualifiers(),
1254                           AggValueSlot::IsDestructed,
1255                           AggValueSlot::DoesNotNeedGCBarriers,
1256                           AggValueSlot::IsNotAliased,
1257                           getOverlapForReturnValue()));
1258       break;
1259     }
1260   }
1261 
1262   ++NumReturnExprs;
1263   if (!RV || RV->isEvaluatable(getContext()))
1264     ++NumSimpleReturnExprs;
1265 
1266   cleanupScope.ForceCleanup();
1267   EmitBranchThroughCleanup(ReturnBlock);
1268 }
1269 
1270 void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
1271   // As long as debug info is modeled with instructions, we have to ensure we
1272   // have a place to insert here and write the stop point here.
1273   if (HaveInsertPoint())
1274     EmitStopPoint(&S);
1275 
1276   for (const auto *I : S.decls())
1277     EmitDecl(*I);
1278 }
1279 
1280 void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
1281   assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
1282 
1283   // If this code is reachable then emit a stop point (if generating
1284   // debug info). We have to do this ourselves because we are on the
1285   // "simple" statement path.
1286   if (HaveInsertPoint())
1287     EmitStopPoint(&S);
1288 
1289   EmitBranchThroughCleanup(BreakContinueStack.back().BreakBlock);
1290 }
1291 
1292 void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
1293   assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
1294 
1295   // If this code is reachable then emit a stop point (if generating
1296   // debug info). We have to do this ourselves because we are on the
1297   // "simple" statement path.
1298   if (HaveInsertPoint())
1299     EmitStopPoint(&S);
1300 
1301   EmitBranchThroughCleanup(BreakContinueStack.back().ContinueBlock);
1302 }
1303 
1304 /// EmitCaseStmtRange - If case statement range is not too big then
1305 /// add multiple cases to switch instruction, one for each value within
1306 /// the range. If range is too big then emit "if" condition check.
1307 void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S,
1308                                         ArrayRef<const Attr *> Attrs) {
1309   assert(S.getRHS() && "Expected RHS value in CaseStmt");
1310 
1311   llvm::APSInt LHS = S.getLHS()->EvaluateKnownConstInt(getContext());
1312   llvm::APSInt RHS = S.getRHS()->EvaluateKnownConstInt(getContext());
1313 
1314   // Emit the code for this case. We do this first to make sure it is
1315   // properly chained from our predecessor before generating the
1316   // switch machinery to enter this block.
1317   llvm::BasicBlock *CaseDest = createBasicBlock("sw.bb");
1318   EmitBlockWithFallThrough(CaseDest, &S);
1319   EmitStmt(S.getSubStmt());
1320 
1321   // If range is empty, do nothing.
1322   if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
1323     return;
1324 
1325   Stmt::Likelihood LH = Stmt::getLikelihood(Attrs);
1326   llvm::APInt Range = RHS - LHS;
1327   // FIXME: parameters such as this should not be hardcoded.
1328   if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
1329     // Range is small enough to add multiple switch instruction cases.
1330     uint64_t Total = getProfileCount(&S);
1331     unsigned NCases = Range.getZExtValue() + 1;
1332     // We only have one region counter for the entire set of cases here, so we
1333     // need to divide the weights evenly between the generated cases, ensuring
1334     // that the total weight is preserved. E.g., a weight of 5 over three cases
1335     // will be distributed as weights of 2, 2, and 1.
1336     uint64_t Weight = Total / NCases, Rem = Total % NCases;
1337     for (unsigned I = 0; I != NCases; ++I) {
1338       if (SwitchWeights)
1339         SwitchWeights->push_back(Weight + (Rem ? 1 : 0));
1340       else if (SwitchLikelihood)
1341         SwitchLikelihood->push_back(LH);
1342 
1343       if (Rem)
1344         Rem--;
1345       SwitchInsn->addCase(Builder.getInt(LHS), CaseDest);
1346       ++LHS;
1347     }
1348     return;
1349   }
1350 
1351   // The range is too big. Emit "if" condition into a new block,
1352   // making sure to save and restore the current insertion point.
1353   llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
1354 
1355   // Push this test onto the chain of range checks (which terminates
1356   // in the default basic block). The switch's default will be changed
1357   // to the top of this chain after switch emission is complete.
1358   llvm::BasicBlock *FalseDest = CaseRangeBlock;
1359   CaseRangeBlock = createBasicBlock("sw.caserange");
1360 
1361   CurFn->getBasicBlockList().push_back(CaseRangeBlock);
1362   Builder.SetInsertPoint(CaseRangeBlock);
1363 
1364   // Emit range check.
1365   llvm::Value *Diff =
1366     Builder.CreateSub(SwitchInsn->getCondition(), Builder.getInt(LHS));
1367   llvm::Value *Cond =
1368     Builder.CreateICmpULE(Diff, Builder.getInt(Range), "inbounds");
1369 
1370   llvm::MDNode *Weights = nullptr;
1371   if (SwitchWeights) {
1372     uint64_t ThisCount = getProfileCount(&S);
1373     uint64_t DefaultCount = (*SwitchWeights)[0];
1374     Weights = createProfileWeights(ThisCount, DefaultCount);
1375 
1376     // Since we're chaining the switch default through each large case range, we
1377     // need to update the weight for the default, ie, the first case, to include
1378     // this case.
1379     (*SwitchWeights)[0] += ThisCount;
1380   } else if (SwitchLikelihood)
1381     Cond = emitCondLikelihoodViaExpectIntrinsic(Cond, LH);
1382 
1383   Builder.CreateCondBr(Cond, CaseDest, FalseDest, Weights);
1384 
1385   // Restore the appropriate insertion point.
1386   if (RestoreBB)
1387     Builder.SetInsertPoint(RestoreBB);
1388   else
1389     Builder.ClearInsertionPoint();
1390 }
1391 
1392 void CodeGenFunction::EmitCaseStmt(const CaseStmt &S,
1393                                    ArrayRef<const Attr *> Attrs) {
1394   // If there is no enclosing switch instance that we're aware of, then this
1395   // case statement and its block can be elided.  This situation only happens
1396   // when we've constant-folded the switch, are emitting the constant case,
1397   // and part of the constant case includes another case statement.  For
1398   // instance: switch (4) { case 4: do { case 5: } while (1); }
1399   if (!SwitchInsn) {
1400     EmitStmt(S.getSubStmt());
1401     return;
1402   }
1403 
1404   // Handle case ranges.
1405   if (S.getRHS()) {
1406     EmitCaseStmtRange(S, Attrs);
1407     return;
1408   }
1409 
1410   llvm::ConstantInt *CaseVal =
1411     Builder.getInt(S.getLHS()->EvaluateKnownConstInt(getContext()));
1412   if (SwitchLikelihood)
1413     SwitchLikelihood->push_back(Stmt::getLikelihood(Attrs));
1414 
1415   // If the body of the case is just a 'break', try to not emit an empty block.
1416   // If we're profiling or we're not optimizing, leave the block in for better
1417   // debug and coverage analysis.
1418   if (!CGM.getCodeGenOpts().hasProfileClangInstr() &&
1419       CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1420       isa<BreakStmt>(S.getSubStmt())) {
1421     JumpDest Block = BreakContinueStack.back().BreakBlock;
1422 
1423     // Only do this optimization if there are no cleanups that need emitting.
1424     if (isObviouslyBranchWithoutCleanups(Block)) {
1425       if (SwitchWeights)
1426         SwitchWeights->push_back(getProfileCount(&S));
1427       SwitchInsn->addCase(CaseVal, Block.getBlock());
1428 
1429       // If there was a fallthrough into this case, make sure to redirect it to
1430       // the end of the switch as well.
1431       if (Builder.GetInsertBlock()) {
1432         Builder.CreateBr(Block.getBlock());
1433         Builder.ClearInsertionPoint();
1434       }
1435       return;
1436     }
1437   }
1438 
1439   llvm::BasicBlock *CaseDest = createBasicBlock("sw.bb");
1440   EmitBlockWithFallThrough(CaseDest, &S);
1441   if (SwitchWeights)
1442     SwitchWeights->push_back(getProfileCount(&S));
1443   SwitchInsn->addCase(CaseVal, CaseDest);
1444 
1445   // Recursively emitting the statement is acceptable, but is not wonderful for
1446   // code where we have many case statements nested together, i.e.:
1447   //  case 1:
1448   //    case 2:
1449   //      case 3: etc.
1450   // Handling this recursively will create a new block for each case statement
1451   // that falls through to the next case which is IR intensive.  It also causes
1452   // deep recursion which can run into stack depth limitations.  Handle
1453   // sequential non-range case statements specially.
1454   //
1455   // TODO When the next case has a likelihood attribute the code returns to the
1456   // recursive algorithm. Maybe improve this case if it becomes common practice
1457   // to use a lot of attributes.
1458   const CaseStmt *CurCase = &S;
1459   const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
1460 
1461   // Otherwise, iteratively add consecutive cases to this switch stmt.
1462   while (NextCase && NextCase->getRHS() == nullptr) {
1463     CurCase = NextCase;
1464     llvm::ConstantInt *CaseVal =
1465       Builder.getInt(CurCase->getLHS()->EvaluateKnownConstInt(getContext()));
1466 
1467     if (SwitchWeights)
1468       SwitchWeights->push_back(getProfileCount(NextCase));
1469     if (CGM.getCodeGenOpts().hasProfileClangInstr()) {
1470       CaseDest = createBasicBlock("sw.bb");
1471       EmitBlockWithFallThrough(CaseDest, CurCase);
1472     }
1473     // Since this loop is only executed when the CaseStmt has no attributes
1474     // use a hard-coded value.
1475     if (SwitchLikelihood)
1476       SwitchLikelihood->push_back(Stmt::LH_None);
1477 
1478     SwitchInsn->addCase(CaseVal, CaseDest);
1479     NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt());
1480   }
1481 
1482   // Normal default recursion for non-cases.
1483   EmitStmt(CurCase->getSubStmt());
1484 }
1485 
1486 void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S,
1487                                       ArrayRef<const Attr *> Attrs) {
1488   // If there is no enclosing switch instance that we're aware of, then this
1489   // default statement can be elided. This situation only happens when we've
1490   // constant-folded the switch.
1491   if (!SwitchInsn) {
1492     EmitStmt(S.getSubStmt());
1493     return;
1494   }
1495 
1496   llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
1497   assert(DefaultBlock->empty() &&
1498          "EmitDefaultStmt: Default block already defined?");
1499 
1500   if (SwitchLikelihood)
1501     SwitchLikelihood->front() = Stmt::getLikelihood(Attrs);
1502 
1503   EmitBlockWithFallThrough(DefaultBlock, &S);
1504 
1505   EmitStmt(S.getSubStmt());
1506 }
1507 
1508 /// CollectStatementsForCase - Given the body of a 'switch' statement and a
1509 /// constant value that is being switched on, see if we can dead code eliminate
1510 /// the body of the switch to a simple series of statements to emit.  Basically,
1511 /// on a switch (5) we want to find these statements:
1512 ///    case 5:
1513 ///      printf(...);    <--
1514 ///      ++i;            <--
1515 ///      break;
1516 ///
1517 /// and add them to the ResultStmts vector.  If it is unsafe to do this
1518 /// transformation (for example, one of the elided statements contains a label
1519 /// that might be jumped to), return CSFC_Failure.  If we handled it and 'S'
1520 /// should include statements after it (e.g. the printf() line is a substmt of
1521 /// the case) then return CSFC_FallThrough.  If we handled it and found a break
1522 /// statement, then return CSFC_Success.
1523 ///
1524 /// If Case is non-null, then we are looking for the specified case, checking
1525 /// that nothing we jump over contains labels.  If Case is null, then we found
1526 /// the case and are looking for the break.
1527 ///
1528 /// If the recursive walk actually finds our Case, then we set FoundCase to
1529 /// true.
1530 ///
1531 enum CSFC_Result { CSFC_Failure, CSFC_FallThrough, CSFC_Success };
1532 static CSFC_Result CollectStatementsForCase(const Stmt *S,
1533                                             const SwitchCase *Case,
1534                                             bool &FoundCase,
1535                               SmallVectorImpl<const Stmt*> &ResultStmts) {
1536   // If this is a null statement, just succeed.
1537   if (!S)
1538     return Case ? CSFC_Success : CSFC_FallThrough;
1539 
1540   // If this is the switchcase (case 4: or default) that we're looking for, then
1541   // we're in business.  Just add the substatement.
1542   if (const SwitchCase *SC = dyn_cast<SwitchCase>(S)) {
1543     if (S == Case) {
1544       FoundCase = true;
1545       return CollectStatementsForCase(SC->getSubStmt(), nullptr, FoundCase,
1546                                       ResultStmts);
1547     }
1548 
1549     // Otherwise, this is some other case or default statement, just ignore it.
1550     return CollectStatementsForCase(SC->getSubStmt(), Case, FoundCase,
1551                                     ResultStmts);
1552   }
1553 
1554   // If we are in the live part of the code and we found our break statement,
1555   // return a success!
1556   if (!Case && isa<BreakStmt>(S))
1557     return CSFC_Success;
1558 
1559   // If this is a switch statement, then it might contain the SwitchCase, the
1560   // break, or neither.
1561   if (const CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
1562     // Handle this as two cases: we might be looking for the SwitchCase (if so
1563     // the skipped statements must be skippable) or we might already have it.
1564     CompoundStmt::const_body_iterator I = CS->body_begin(), E = CS->body_end();
1565     bool StartedInLiveCode = FoundCase;
1566     unsigned StartSize = ResultStmts.size();
1567 
1568     // If we've not found the case yet, scan through looking for it.
1569     if (Case) {
1570       // Keep track of whether we see a skipped declaration.  The code could be
1571       // using the declaration even if it is skipped, so we can't optimize out
1572       // the decl if the kept statements might refer to it.
1573       bool HadSkippedDecl = false;
1574 
1575       // If we're looking for the case, just see if we can skip each of the
1576       // substatements.
1577       for (; Case && I != E; ++I) {
1578         HadSkippedDecl |= CodeGenFunction::mightAddDeclToScope(*I);
1579 
1580         switch (CollectStatementsForCase(*I, Case, FoundCase, ResultStmts)) {
1581         case CSFC_Failure: return CSFC_Failure;
1582         case CSFC_Success:
1583           // A successful result means that either 1) that the statement doesn't
1584           // have the case and is skippable, or 2) does contain the case value
1585           // and also contains the break to exit the switch.  In the later case,
1586           // we just verify the rest of the statements are elidable.
1587           if (FoundCase) {
1588             // If we found the case and skipped declarations, we can't do the
1589             // optimization.
1590             if (HadSkippedDecl)
1591               return CSFC_Failure;
1592 
1593             for (++I; I != E; ++I)
1594               if (CodeGenFunction::ContainsLabel(*I, true))
1595                 return CSFC_Failure;
1596             return CSFC_Success;
1597           }
1598           break;
1599         case CSFC_FallThrough:
1600           // If we have a fallthrough condition, then we must have found the
1601           // case started to include statements.  Consider the rest of the
1602           // statements in the compound statement as candidates for inclusion.
1603           assert(FoundCase && "Didn't find case but returned fallthrough?");
1604           // We recursively found Case, so we're not looking for it anymore.
1605           Case = nullptr;
1606 
1607           // If we found the case and skipped declarations, we can't do the
1608           // optimization.
1609           if (HadSkippedDecl)
1610             return CSFC_Failure;
1611           break;
1612         }
1613       }
1614 
1615       if (!FoundCase)
1616         return CSFC_Success;
1617 
1618       assert(!HadSkippedDecl && "fallthrough after skipping decl");
1619     }
1620 
1621     // If we have statements in our range, then we know that the statements are
1622     // live and need to be added to the set of statements we're tracking.
1623     bool AnyDecls = false;
1624     for (; I != E; ++I) {
1625       AnyDecls |= CodeGenFunction::mightAddDeclToScope(*I);
1626 
1627       switch (CollectStatementsForCase(*I, nullptr, FoundCase, ResultStmts)) {
1628       case CSFC_Failure: return CSFC_Failure;
1629       case CSFC_FallThrough:
1630         // A fallthrough result means that the statement was simple and just
1631         // included in ResultStmt, keep adding them afterwards.
1632         break;
1633       case CSFC_Success:
1634         // A successful result means that we found the break statement and
1635         // stopped statement inclusion.  We just ensure that any leftover stmts
1636         // are skippable and return success ourselves.
1637         for (++I; I != E; ++I)
1638           if (CodeGenFunction::ContainsLabel(*I, true))
1639             return CSFC_Failure;
1640         return CSFC_Success;
1641       }
1642     }
1643 
1644     // If we're about to fall out of a scope without hitting a 'break;', we
1645     // can't perform the optimization if there were any decls in that scope
1646     // (we'd lose their end-of-lifetime).
1647     if (AnyDecls) {
1648       // If the entire compound statement was live, there's one more thing we
1649       // can try before giving up: emit the whole thing as a single statement.
1650       // We can do that unless the statement contains a 'break;'.
1651       // FIXME: Such a break must be at the end of a construct within this one.
1652       // We could emit this by just ignoring the BreakStmts entirely.
1653       if (StartedInLiveCode && !CodeGenFunction::containsBreak(S)) {
1654         ResultStmts.resize(StartSize);
1655         ResultStmts.push_back(S);
1656       } else {
1657         return CSFC_Failure;
1658       }
1659     }
1660 
1661     return CSFC_FallThrough;
1662   }
1663 
1664   // Okay, this is some other statement that we don't handle explicitly, like a
1665   // for statement or increment etc.  If we are skipping over this statement,
1666   // just verify it doesn't have labels, which would make it invalid to elide.
1667   if (Case) {
1668     if (CodeGenFunction::ContainsLabel(S, true))
1669       return CSFC_Failure;
1670     return CSFC_Success;
1671   }
1672 
1673   // Otherwise, we want to include this statement.  Everything is cool with that
1674   // so long as it doesn't contain a break out of the switch we're in.
1675   if (CodeGenFunction::containsBreak(S)) return CSFC_Failure;
1676 
1677   // Otherwise, everything is great.  Include the statement and tell the caller
1678   // that we fall through and include the next statement as well.
1679   ResultStmts.push_back(S);
1680   return CSFC_FallThrough;
1681 }
1682 
1683 /// FindCaseStatementsForValue - Find the case statement being jumped to and
1684 /// then invoke CollectStatementsForCase to find the list of statements to emit
1685 /// for a switch on constant.  See the comment above CollectStatementsForCase
1686 /// for more details.
1687 static bool FindCaseStatementsForValue(const SwitchStmt &S,
1688                                        const llvm::APSInt &ConstantCondValue,
1689                                 SmallVectorImpl<const Stmt*> &ResultStmts,
1690                                        ASTContext &C,
1691                                        const SwitchCase *&ResultCase) {
1692   // First step, find the switch case that is being branched to.  We can do this
1693   // efficiently by scanning the SwitchCase list.
1694   const SwitchCase *Case = S.getSwitchCaseList();
1695   const DefaultStmt *DefaultCase = nullptr;
1696 
1697   for (; Case; Case = Case->getNextSwitchCase()) {
1698     // It's either a default or case.  Just remember the default statement in
1699     // case we're not jumping to any numbered cases.
1700     if (const DefaultStmt *DS = dyn_cast<DefaultStmt>(Case)) {
1701       DefaultCase = DS;
1702       continue;
1703     }
1704 
1705     // Check to see if this case is the one we're looking for.
1706     const CaseStmt *CS = cast<CaseStmt>(Case);
1707     // Don't handle case ranges yet.
1708     if (CS->getRHS()) return false;
1709 
1710     // If we found our case, remember it as 'case'.
1711     if (CS->getLHS()->EvaluateKnownConstInt(C) == ConstantCondValue)
1712       break;
1713   }
1714 
1715   // If we didn't find a matching case, we use a default if it exists, or we
1716   // elide the whole switch body!
1717   if (!Case) {
1718     // It is safe to elide the body of the switch if it doesn't contain labels
1719     // etc.  If it is safe, return successfully with an empty ResultStmts list.
1720     if (!DefaultCase)
1721       return !CodeGenFunction::ContainsLabel(&S);
1722     Case = DefaultCase;
1723   }
1724 
1725   // Ok, we know which case is being jumped to, try to collect all the
1726   // statements that follow it.  This can fail for a variety of reasons.  Also,
1727   // check to see that the recursive walk actually found our case statement.
1728   // Insane cases like this can fail to find it in the recursive walk since we
1729   // don't handle every stmt kind:
1730   // switch (4) {
1731   //   while (1) {
1732   //     case 4: ...
1733   bool FoundCase = false;
1734   ResultCase = Case;
1735   return CollectStatementsForCase(S.getBody(), Case, FoundCase,
1736                                   ResultStmts) != CSFC_Failure &&
1737          FoundCase;
1738 }
1739 
1740 static Optional<SmallVector<uint64_t, 16>>
1741 getLikelihoodWeights(ArrayRef<Stmt::Likelihood> Likelihoods) {
1742   // Are there enough branches to weight them?
1743   if (Likelihoods.size() <= 1)
1744     return None;
1745 
1746   uint64_t NumUnlikely = 0;
1747   uint64_t NumNone = 0;
1748   uint64_t NumLikely = 0;
1749   for (const auto LH : Likelihoods) {
1750     switch (LH) {
1751     case Stmt::LH_Unlikely:
1752       ++NumUnlikely;
1753       break;
1754     case Stmt::LH_None:
1755       ++NumNone;
1756       break;
1757     case Stmt::LH_Likely:
1758       ++NumLikely;
1759       break;
1760     }
1761   }
1762 
1763   // Is there a likelihood attribute used?
1764   if (NumUnlikely == 0 && NumLikely == 0)
1765     return None;
1766 
1767   // When multiple cases share the same code they can be combined during
1768   // optimization. In that case the weights of the branch will be the sum of
1769   // the individual weights. Make sure the combined sum of all neutral cases
1770   // doesn't exceed the value of a single likely attribute.
1771   // The additions both avoid divisions by 0 and make sure the weights of None
1772   // don't exceed the weight of Likely.
1773   const uint64_t Likely = INT32_MAX / (NumLikely + 2);
1774   const uint64_t None = Likely / (NumNone + 1);
1775   const uint64_t Unlikely = 0;
1776 
1777   SmallVector<uint64_t, 16> Result;
1778   Result.reserve(Likelihoods.size());
1779   for (const auto LH : Likelihoods) {
1780     switch (LH) {
1781     case Stmt::LH_Unlikely:
1782       Result.push_back(Unlikely);
1783       break;
1784     case Stmt::LH_None:
1785       Result.push_back(None);
1786       break;
1787     case Stmt::LH_Likely:
1788       Result.push_back(Likely);
1789       break;
1790     }
1791   }
1792 
1793   return Result;
1794 }
1795 
1796 void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
1797   // Handle nested switch statements.
1798   llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
1799   SmallVector<uint64_t, 16> *SavedSwitchWeights = SwitchWeights;
1800   SmallVector<Stmt::Likelihood, 16> *SavedSwitchLikelihood = SwitchLikelihood;
1801   llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
1802 
1803   // See if we can constant fold the condition of the switch and therefore only
1804   // emit the live case statement (if any) of the switch.
1805   llvm::APSInt ConstantCondValue;
1806   if (ConstantFoldsToSimpleInteger(S.getCond(), ConstantCondValue)) {
1807     SmallVector<const Stmt*, 4> CaseStmts;
1808     const SwitchCase *Case = nullptr;
1809     if (FindCaseStatementsForValue(S, ConstantCondValue, CaseStmts,
1810                                    getContext(), Case)) {
1811       if (Case)
1812         incrementProfileCounter(Case);
1813       RunCleanupsScope ExecutedScope(*this);
1814 
1815       if (S.getInit())
1816         EmitStmt(S.getInit());
1817 
1818       // Emit the condition variable if needed inside the entire cleanup scope
1819       // used by this special case for constant folded switches.
1820       if (S.getConditionVariable())
1821         EmitDecl(*S.getConditionVariable());
1822 
1823       // At this point, we are no longer "within" a switch instance, so
1824       // we can temporarily enforce this to ensure that any embedded case
1825       // statements are not emitted.
1826       SwitchInsn = nullptr;
1827 
1828       // Okay, we can dead code eliminate everything except this case.  Emit the
1829       // specified series of statements and we're good.
1830       for (unsigned i = 0, e = CaseStmts.size(); i != e; ++i)
1831         EmitStmt(CaseStmts[i]);
1832       incrementProfileCounter(&S);
1833 
1834       // Now we want to restore the saved switch instance so that nested
1835       // switches continue to function properly
1836       SwitchInsn = SavedSwitchInsn;
1837 
1838       return;
1839     }
1840   }
1841 
1842   JumpDest SwitchExit = getJumpDestInCurrentScope("sw.epilog");
1843 
1844   RunCleanupsScope ConditionScope(*this);
1845 
1846   if (S.getInit())
1847     EmitStmt(S.getInit());
1848 
1849   if (S.getConditionVariable())
1850     EmitDecl(*S.getConditionVariable());
1851   llvm::Value *CondV = EmitScalarExpr(S.getCond());
1852 
1853   // Create basic block to hold stuff that comes after switch
1854   // statement. We also need to create a default block now so that
1855   // explicit case ranges tests can have a place to jump to on
1856   // failure.
1857   llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
1858   SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
1859   if (PGO.haveRegionCounts()) {
1860     // Walk the SwitchCase list to find how many there are.
1861     uint64_t DefaultCount = 0;
1862     unsigned NumCases = 0;
1863     for (const SwitchCase *Case = S.getSwitchCaseList();
1864          Case;
1865          Case = Case->getNextSwitchCase()) {
1866       if (isa<DefaultStmt>(Case))
1867         DefaultCount = getProfileCount(Case);
1868       NumCases += 1;
1869     }
1870     SwitchWeights = new SmallVector<uint64_t, 16>();
1871     SwitchWeights->reserve(NumCases);
1872     // The default needs to be first. We store the edge count, so we already
1873     // know the right weight.
1874     SwitchWeights->push_back(DefaultCount);
1875   } else if (CGM.getCodeGenOpts().OptimizationLevel) {
1876     SwitchLikelihood = new SmallVector<Stmt::Likelihood, 16>();
1877     // Initialize the default case.
1878     SwitchLikelihood->push_back(Stmt::LH_None);
1879   }
1880 
1881   CaseRangeBlock = DefaultBlock;
1882 
1883   // Clear the insertion point to indicate we are in unreachable code.
1884   Builder.ClearInsertionPoint();
1885 
1886   // All break statements jump to NextBlock. If BreakContinueStack is non-empty
1887   // then reuse last ContinueBlock.
1888   JumpDest OuterContinue;
1889   if (!BreakContinueStack.empty())
1890     OuterContinue = BreakContinueStack.back().ContinueBlock;
1891 
1892   BreakContinueStack.push_back(BreakContinue(SwitchExit, OuterContinue));
1893 
1894   // Emit switch body.
1895   EmitStmt(S.getBody());
1896 
1897   BreakContinueStack.pop_back();
1898 
1899   // Update the default block in case explicit case range tests have
1900   // been chained on top.
1901   SwitchInsn->setDefaultDest(CaseRangeBlock);
1902 
1903   // If a default was never emitted:
1904   if (!DefaultBlock->getParent()) {
1905     // If we have cleanups, emit the default block so that there's a
1906     // place to jump through the cleanups from.
1907     if (ConditionScope.requiresCleanups()) {
1908       EmitBlock(DefaultBlock);
1909 
1910     // Otherwise, just forward the default block to the switch end.
1911     } else {
1912       DefaultBlock->replaceAllUsesWith(SwitchExit.getBlock());
1913       delete DefaultBlock;
1914     }
1915   }
1916 
1917   ConditionScope.ForceCleanup();
1918 
1919   // Emit continuation.
1920   EmitBlock(SwitchExit.getBlock(), true);
1921   incrementProfileCounter(&S);
1922 
1923   // If the switch has a condition wrapped by __builtin_unpredictable,
1924   // create metadata that specifies that the switch is unpredictable.
1925   // Don't bother if not optimizing because that metadata would not be used.
1926   auto *Call = dyn_cast<CallExpr>(S.getCond());
1927   if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
1928     auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
1929     if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
1930       llvm::MDBuilder MDHelper(getLLVMContext());
1931       SwitchInsn->setMetadata(llvm::LLVMContext::MD_unpredictable,
1932                               MDHelper.createUnpredictable());
1933     }
1934   }
1935 
1936   if (SwitchWeights) {
1937     assert(SwitchWeights->size() == 1 + SwitchInsn->getNumCases() &&
1938            "switch weights do not match switch cases");
1939     // If there's only one jump destination there's no sense weighting it.
1940     if (SwitchWeights->size() > 1)
1941       SwitchInsn->setMetadata(llvm::LLVMContext::MD_prof,
1942                               createProfileWeights(*SwitchWeights));
1943     delete SwitchWeights;
1944   } else if (SwitchLikelihood) {
1945     assert(SwitchLikelihood->size() == 1 + SwitchInsn->getNumCases() &&
1946            "switch likelihoods do not match switch cases");
1947     Optional<SmallVector<uint64_t, 16>> LHW =
1948         getLikelihoodWeights(*SwitchLikelihood);
1949     if (LHW) {
1950       llvm::MDBuilder MDHelper(CGM.getLLVMContext());
1951       SwitchInsn->setMetadata(llvm::LLVMContext::MD_prof,
1952                               createProfileWeights(*LHW));
1953     }
1954     delete SwitchLikelihood;
1955   }
1956   SwitchInsn = SavedSwitchInsn;
1957   SwitchWeights = SavedSwitchWeights;
1958   SwitchLikelihood = SavedSwitchLikelihood;
1959   CaseRangeBlock = SavedCRBlock;
1960 }
1961 
1962 static std::string
1963 SimplifyConstraint(const char *Constraint, const TargetInfo &Target,
1964                  SmallVectorImpl<TargetInfo::ConstraintInfo> *OutCons=nullptr) {
1965   std::string Result;
1966 
1967   while (*Constraint) {
1968     switch (*Constraint) {
1969     default:
1970       Result += Target.convertConstraint(Constraint);
1971       break;
1972     // Ignore these
1973     case '*':
1974     case '?':
1975     case '!':
1976     case '=': // Will see this and the following in mult-alt constraints.
1977     case '+':
1978       break;
1979     case '#': // Ignore the rest of the constraint alternative.
1980       while (Constraint[1] && Constraint[1] != ',')
1981         Constraint++;
1982       break;
1983     case '&':
1984     case '%':
1985       Result += *Constraint;
1986       while (Constraint[1] && Constraint[1] == *Constraint)
1987         Constraint++;
1988       break;
1989     case ',':
1990       Result += "|";
1991       break;
1992     case 'g':
1993       Result += "imr";
1994       break;
1995     case '[': {
1996       assert(OutCons &&
1997              "Must pass output names to constraints with a symbolic name");
1998       unsigned Index;
1999       bool result = Target.resolveSymbolicName(Constraint, *OutCons, Index);
2000       assert(result && "Could not resolve symbolic name"); (void)result;
2001       Result += llvm::utostr(Index);
2002       break;
2003     }
2004     }
2005 
2006     Constraint++;
2007   }
2008 
2009   return Result;
2010 }
2011 
2012 /// AddVariableConstraints - Look at AsmExpr and if it is a variable declared
2013 /// as using a particular register add that as a constraint that will be used
2014 /// in this asm stmt.
2015 static std::string
2016 AddVariableConstraints(const std::string &Constraint, const Expr &AsmExpr,
2017                        const TargetInfo &Target, CodeGenModule &CGM,
2018                        const AsmStmt &Stmt, const bool EarlyClobber,
2019                        std::string *GCCReg = nullptr) {
2020   const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(&AsmExpr);
2021   if (!AsmDeclRef)
2022     return Constraint;
2023   const ValueDecl &Value = *AsmDeclRef->getDecl();
2024   const VarDecl *Variable = dyn_cast<VarDecl>(&Value);
2025   if (!Variable)
2026     return Constraint;
2027   if (Variable->getStorageClass() != SC_Register)
2028     return Constraint;
2029   AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>();
2030   if (!Attr)
2031     return Constraint;
2032   StringRef Register = Attr->getLabel();
2033   assert(Target.isValidGCCRegisterName(Register));
2034   // We're using validateOutputConstraint here because we only care if
2035   // this is a register constraint.
2036   TargetInfo::ConstraintInfo Info(Constraint, "");
2037   if (Target.validateOutputConstraint(Info) &&
2038       !Info.allowsRegister()) {
2039     CGM.ErrorUnsupported(&Stmt, "__asm__");
2040     return Constraint;
2041   }
2042   // Canonicalize the register here before returning it.
2043   Register = Target.getNormalizedGCCRegisterName(Register);
2044   if (GCCReg != nullptr)
2045     *GCCReg = Register.str();
2046   return (EarlyClobber ? "&{" : "{") + Register.str() + "}";
2047 }
2048 
2049 llvm::Value*
2050 CodeGenFunction::EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info,
2051                                     LValue InputValue, QualType InputType,
2052                                     std::string &ConstraintStr,
2053                                     SourceLocation Loc) {
2054   llvm::Value *Arg;
2055   if (Info.allowsRegister() || !Info.allowsMemory()) {
2056     if (CodeGenFunction::hasScalarEvaluationKind(InputType)) {
2057       Arg = EmitLoadOfLValue(InputValue, Loc).getScalarVal();
2058     } else {
2059       llvm::Type *Ty = ConvertType(InputType);
2060       uint64_t Size = CGM.getDataLayout().getTypeSizeInBits(Ty);
2061       if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
2062         Ty = llvm::IntegerType::get(getLLVMContext(), Size);
2063         Ty = llvm::PointerType::getUnqual(Ty);
2064 
2065         Arg = Builder.CreateLoad(
2066             Builder.CreateBitCast(InputValue.getAddress(*this), Ty));
2067       } else {
2068         Arg = InputValue.getPointer(*this);
2069         ConstraintStr += '*';
2070       }
2071     }
2072   } else {
2073     Arg = InputValue.getPointer(*this);
2074     ConstraintStr += '*';
2075   }
2076 
2077   return Arg;
2078 }
2079 
2080 llvm::Value* CodeGenFunction::EmitAsmInput(
2081                                          const TargetInfo::ConstraintInfo &Info,
2082                                            const Expr *InputExpr,
2083                                            std::string &ConstraintStr) {
2084   // If this can't be a register or memory, i.e., has to be a constant
2085   // (immediate or symbolic), try to emit it as such.
2086   if (!Info.allowsRegister() && !Info.allowsMemory()) {
2087     if (Info.requiresImmediateConstant()) {
2088       Expr::EvalResult EVResult;
2089       InputExpr->EvaluateAsRValue(EVResult, getContext(), true);
2090 
2091       llvm::APSInt IntResult;
2092       if (EVResult.Val.toIntegralConstant(IntResult, InputExpr->getType(),
2093                                           getContext()))
2094         return llvm::ConstantInt::get(getLLVMContext(), IntResult);
2095     }
2096 
2097     Expr::EvalResult Result;
2098     if (InputExpr->EvaluateAsInt(Result, getContext()))
2099       return llvm::ConstantInt::get(getLLVMContext(), Result.Val.getInt());
2100   }
2101 
2102   if (Info.allowsRegister() || !Info.allowsMemory())
2103     if (CodeGenFunction::hasScalarEvaluationKind(InputExpr->getType()))
2104       return EmitScalarExpr(InputExpr);
2105   if (InputExpr->getStmtClass() == Expr::CXXThisExprClass)
2106     return EmitScalarExpr(InputExpr);
2107   InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
2108   LValue Dest = EmitLValue(InputExpr);
2109   return EmitAsmInputLValue(Info, Dest, InputExpr->getType(), ConstraintStr,
2110                             InputExpr->getExprLoc());
2111 }
2112 
2113 /// getAsmSrcLocInfo - Return the !srcloc metadata node to attach to an inline
2114 /// asm call instruction.  The !srcloc MDNode contains a list of constant
2115 /// integers which are the source locations of the start of each line in the
2116 /// asm.
2117 static llvm::MDNode *getAsmSrcLocInfo(const StringLiteral *Str,
2118                                       CodeGenFunction &CGF) {
2119   SmallVector<llvm::Metadata *, 8> Locs;
2120   // Add the location of the first line to the MDNode.
2121   Locs.push_back(llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
2122       CGF.Int32Ty, Str->getBeginLoc().getRawEncoding())));
2123   StringRef StrVal = Str->getString();
2124   if (!StrVal.empty()) {
2125     const SourceManager &SM = CGF.CGM.getContext().getSourceManager();
2126     const LangOptions &LangOpts = CGF.CGM.getLangOpts();
2127     unsigned StartToken = 0;
2128     unsigned ByteOffset = 0;
2129 
2130     // Add the location of the start of each subsequent line of the asm to the
2131     // MDNode.
2132     for (unsigned i = 0, e = StrVal.size() - 1; i != e; ++i) {
2133       if (StrVal[i] != '\n') continue;
2134       SourceLocation LineLoc = Str->getLocationOfByte(
2135           i + 1, SM, LangOpts, CGF.getTarget(), &StartToken, &ByteOffset);
2136       Locs.push_back(llvm::ConstantAsMetadata::get(
2137           llvm::ConstantInt::get(CGF.Int32Ty, LineLoc.getRawEncoding())));
2138     }
2139   }
2140 
2141   return llvm::MDNode::get(CGF.getLLVMContext(), Locs);
2142 }
2143 
2144 static void UpdateAsmCallInst(llvm::CallBase &Result, bool HasSideEffect,
2145                               bool ReadOnly, bool ReadNone, bool NoMerge,
2146                               const AsmStmt &S,
2147                               const std::vector<llvm::Type *> &ResultRegTypes,
2148                               CodeGenFunction &CGF,
2149                               std::vector<llvm::Value *> &RegResults) {
2150   Result.addAttribute(llvm::AttributeList::FunctionIndex,
2151                       llvm::Attribute::NoUnwind);
2152   if (NoMerge)
2153     Result.addAttribute(llvm::AttributeList::FunctionIndex,
2154                         llvm::Attribute::NoMerge);
2155   // Attach readnone and readonly attributes.
2156   if (!HasSideEffect) {
2157     if (ReadNone)
2158       Result.addAttribute(llvm::AttributeList::FunctionIndex,
2159                           llvm::Attribute::ReadNone);
2160     else if (ReadOnly)
2161       Result.addAttribute(llvm::AttributeList::FunctionIndex,
2162                           llvm::Attribute::ReadOnly);
2163   }
2164 
2165   // Slap the source location of the inline asm into a !srcloc metadata on the
2166   // call.
2167   if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(&S))
2168     Result.setMetadata("srcloc",
2169                        getAsmSrcLocInfo(gccAsmStmt->getAsmString(), CGF));
2170   else {
2171     // At least put the line number on MS inline asm blobs.
2172     llvm::Constant *Loc = llvm::ConstantInt::get(CGF.Int32Ty,
2173                                         S.getAsmLoc().getRawEncoding());
2174     Result.setMetadata("srcloc",
2175                        llvm::MDNode::get(CGF.getLLVMContext(),
2176                                          llvm::ConstantAsMetadata::get(Loc)));
2177   }
2178 
2179   if (CGF.getLangOpts().assumeFunctionsAreConvergent())
2180     // Conservatively, mark all inline asm blocks in CUDA or OpenCL as
2181     // convergent (meaning, they may call an intrinsically convergent op, such
2182     // as bar.sync, and so can't have certain optimizations applied around
2183     // them).
2184     Result.addAttribute(llvm::AttributeList::FunctionIndex,
2185                         llvm::Attribute::Convergent);
2186   // Extract all of the register value results from the asm.
2187   if (ResultRegTypes.size() == 1) {
2188     RegResults.push_back(&Result);
2189   } else {
2190     for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) {
2191       llvm::Value *Tmp = CGF.Builder.CreateExtractValue(&Result, i, "asmresult");
2192       RegResults.push_back(Tmp);
2193     }
2194   }
2195 }
2196 
2197 void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
2198   // Assemble the final asm string.
2199   std::string AsmString = S.generateAsmString(getContext());
2200 
2201   // Get all the output and input constraints together.
2202   SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
2203   SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
2204 
2205   for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
2206     StringRef Name;
2207     if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
2208       Name = GAS->getOutputName(i);
2209     TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i), Name);
2210     bool IsValid = getTarget().validateOutputConstraint(Info); (void)IsValid;
2211     assert(IsValid && "Failed to parse output constraint");
2212     OutputConstraintInfos.push_back(Info);
2213   }
2214 
2215   for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
2216     StringRef Name;
2217     if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
2218       Name = GAS->getInputName(i);
2219     TargetInfo::ConstraintInfo Info(S.getInputConstraint(i), Name);
2220     bool IsValid =
2221       getTarget().validateInputConstraint(OutputConstraintInfos, Info);
2222     assert(IsValid && "Failed to parse input constraint"); (void)IsValid;
2223     InputConstraintInfos.push_back(Info);
2224   }
2225 
2226   std::string Constraints;
2227 
2228   std::vector<LValue> ResultRegDests;
2229   std::vector<QualType> ResultRegQualTys;
2230   std::vector<llvm::Type *> ResultRegTypes;
2231   std::vector<llvm::Type *> ResultTruncRegTypes;
2232   std::vector<llvm::Type *> ArgTypes;
2233   std::vector<llvm::Value*> Args;
2234   llvm::BitVector ResultTypeRequiresCast;
2235 
2236   // Keep track of inout constraints.
2237   std::string InOutConstraints;
2238   std::vector<llvm::Value*> InOutArgs;
2239   std::vector<llvm::Type*> InOutArgTypes;
2240 
2241   // Keep track of out constraints for tied input operand.
2242   std::vector<std::string> OutputConstraints;
2243 
2244   // Keep track of defined physregs.
2245   llvm::SmallSet<std::string, 8> PhysRegOutputs;
2246 
2247   // An inline asm can be marked readonly if it meets the following conditions:
2248   //  - it doesn't have any sideeffects
2249   //  - it doesn't clobber memory
2250   //  - it doesn't return a value by-reference
2251   // It can be marked readnone if it doesn't have any input memory constraints
2252   // in addition to meeting the conditions listed above.
2253   bool ReadOnly = true, ReadNone = true;
2254 
2255   for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
2256     TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
2257 
2258     // Simplify the output constraint.
2259     std::string OutputConstraint(S.getOutputConstraint(i));
2260     OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1,
2261                                           getTarget(), &OutputConstraintInfos);
2262 
2263     const Expr *OutExpr = S.getOutputExpr(i);
2264     OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
2265 
2266     std::string GCCReg;
2267     OutputConstraint = AddVariableConstraints(OutputConstraint, *OutExpr,
2268                                               getTarget(), CGM, S,
2269                                               Info.earlyClobber(),
2270                                               &GCCReg);
2271     // Give an error on multiple outputs to same physreg.
2272     if (!GCCReg.empty() && !PhysRegOutputs.insert(GCCReg).second)
2273       CGM.Error(S.getAsmLoc(), "multiple outputs to hard register: " + GCCReg);
2274 
2275     OutputConstraints.push_back(OutputConstraint);
2276     LValue Dest = EmitLValue(OutExpr);
2277     if (!Constraints.empty())
2278       Constraints += ',';
2279 
2280     // If this is a register output, then make the inline asm return it
2281     // by-value.  If this is a memory result, return the value by-reference.
2282     bool isScalarizableAggregate =
2283         hasAggregateEvaluationKind(OutExpr->getType());
2284     if (!Info.allowsMemory() && (hasScalarEvaluationKind(OutExpr->getType()) ||
2285                                  isScalarizableAggregate)) {
2286       Constraints += "=" + OutputConstraint;
2287       ResultRegQualTys.push_back(OutExpr->getType());
2288       ResultRegDests.push_back(Dest);
2289       ResultTruncRegTypes.push_back(ConvertTypeForMem(OutExpr->getType()));
2290       if (Info.allowsRegister() && isScalarizableAggregate) {
2291         ResultTypeRequiresCast.push_back(true);
2292         unsigned Size = getContext().getTypeSize(OutExpr->getType());
2293         llvm::Type *ConvTy = llvm::IntegerType::get(getLLVMContext(), Size);
2294         ResultRegTypes.push_back(ConvTy);
2295       } else {
2296         ResultTypeRequiresCast.push_back(false);
2297         ResultRegTypes.push_back(ResultTruncRegTypes.back());
2298       }
2299       // If this output is tied to an input, and if the input is larger, then
2300       // we need to set the actual result type of the inline asm node to be the
2301       // same as the input type.
2302       if (Info.hasMatchingInput()) {
2303         unsigned InputNo;
2304         for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) {
2305           TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo];
2306           if (Input.hasTiedOperand() && Input.getTiedOperand() == i)
2307             break;
2308         }
2309         assert(InputNo != S.getNumInputs() && "Didn't find matching input!");
2310 
2311         QualType InputTy = S.getInputExpr(InputNo)->getType();
2312         QualType OutputType = OutExpr->getType();
2313 
2314         uint64_t InputSize = getContext().getTypeSize(InputTy);
2315         if (getContext().getTypeSize(OutputType) < InputSize) {
2316           // Form the asm to return the value as a larger integer or fp type.
2317           ResultRegTypes.back() = ConvertType(InputTy);
2318         }
2319       }
2320       if (llvm::Type* AdjTy =
2321             getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
2322                                                  ResultRegTypes.back()))
2323         ResultRegTypes.back() = AdjTy;
2324       else {
2325         CGM.getDiags().Report(S.getAsmLoc(),
2326                               diag::err_asm_invalid_type_in_input)
2327             << OutExpr->getType() << OutputConstraint;
2328       }
2329 
2330       // Update largest vector width for any vector types.
2331       if (auto *VT = dyn_cast<llvm::VectorType>(ResultRegTypes.back()))
2332         LargestVectorWidth =
2333             std::max((uint64_t)LargestVectorWidth,
2334                      VT->getPrimitiveSizeInBits().getKnownMinSize());
2335     } else {
2336       llvm::Type *DestAddrTy = Dest.getAddress(*this).getType();
2337       llvm::Value *DestPtr = Dest.getPointer(*this);
2338       // Matrix types in memory are represented by arrays, but accessed through
2339       // vector pointers, with the alignment specified on the access operation.
2340       // For inline assembly, update pointer arguments to use vector pointers.
2341       // Otherwise there will be a mis-match if the matrix is also an
2342       // input-argument which is represented as vector.
2343       if (isa<MatrixType>(OutExpr->getType().getCanonicalType())) {
2344         DestAddrTy = llvm::PointerType::get(
2345             ConvertType(OutExpr->getType()),
2346             cast<llvm::PointerType>(DestAddrTy)->getAddressSpace());
2347         DestPtr = Builder.CreateBitCast(DestPtr, DestAddrTy);
2348       }
2349       ArgTypes.push_back(DestAddrTy);
2350       Args.push_back(DestPtr);
2351       Constraints += "=*";
2352       Constraints += OutputConstraint;
2353       ReadOnly = ReadNone = false;
2354     }
2355 
2356     if (Info.isReadWrite()) {
2357       InOutConstraints += ',';
2358 
2359       const Expr *InputExpr = S.getOutputExpr(i);
2360       llvm::Value *Arg = EmitAsmInputLValue(Info, Dest, InputExpr->getType(),
2361                                             InOutConstraints,
2362                                             InputExpr->getExprLoc());
2363 
2364       if (llvm::Type* AdjTy =
2365           getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
2366                                                Arg->getType()))
2367         Arg = Builder.CreateBitCast(Arg, AdjTy);
2368 
2369       // Update largest vector width for any vector types.
2370       if (auto *VT = dyn_cast<llvm::VectorType>(Arg->getType()))
2371         LargestVectorWidth =
2372             std::max((uint64_t)LargestVectorWidth,
2373                      VT->getPrimitiveSizeInBits().getKnownMinSize());
2374       // Only tie earlyclobber physregs.
2375       if (Info.allowsRegister() && (GCCReg.empty() || Info.earlyClobber()))
2376         InOutConstraints += llvm::utostr(i);
2377       else
2378         InOutConstraints += OutputConstraint;
2379 
2380       InOutArgTypes.push_back(Arg->getType());
2381       InOutArgs.push_back(Arg);
2382     }
2383   }
2384 
2385   // If this is a Microsoft-style asm blob, store the return registers (EAX:EDX)
2386   // to the return value slot. Only do this when returning in registers.
2387   if (isa<MSAsmStmt>(&S)) {
2388     const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
2389     if (RetAI.isDirect() || RetAI.isExtend()) {
2390       // Make a fake lvalue for the return value slot.
2391       LValue ReturnSlot = MakeAddrLValue(ReturnValue, FnRetTy);
2392       CGM.getTargetCodeGenInfo().addReturnRegisterOutputs(
2393           *this, ReturnSlot, Constraints, ResultRegTypes, ResultTruncRegTypes,
2394           ResultRegDests, AsmString, S.getNumOutputs());
2395       SawAsmBlock = true;
2396     }
2397   }
2398 
2399   for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
2400     const Expr *InputExpr = S.getInputExpr(i);
2401 
2402     TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
2403 
2404     if (Info.allowsMemory())
2405       ReadNone = false;
2406 
2407     if (!Constraints.empty())
2408       Constraints += ',';
2409 
2410     // Simplify the input constraint.
2411     std::string InputConstraint(S.getInputConstraint(i));
2412     InputConstraint = SimplifyConstraint(InputConstraint.c_str(), getTarget(),
2413                                          &OutputConstraintInfos);
2414 
2415     InputConstraint = AddVariableConstraints(
2416         InputConstraint, *InputExpr->IgnoreParenNoopCasts(getContext()),
2417         getTarget(), CGM, S, false /* No EarlyClobber */);
2418 
2419     std::string ReplaceConstraint (InputConstraint);
2420     llvm::Value *Arg = EmitAsmInput(Info, InputExpr, Constraints);
2421 
2422     // If this input argument is tied to a larger output result, extend the
2423     // input to be the same size as the output.  The LLVM backend wants to see
2424     // the input and output of a matching constraint be the same size.  Note
2425     // that GCC does not define what the top bits are here.  We use zext because
2426     // that is usually cheaper, but LLVM IR should really get an anyext someday.
2427     if (Info.hasTiedOperand()) {
2428       unsigned Output = Info.getTiedOperand();
2429       QualType OutputType = S.getOutputExpr(Output)->getType();
2430       QualType InputTy = InputExpr->getType();
2431 
2432       if (getContext().getTypeSize(OutputType) >
2433           getContext().getTypeSize(InputTy)) {
2434         // Use ptrtoint as appropriate so that we can do our extension.
2435         if (isa<llvm::PointerType>(Arg->getType()))
2436           Arg = Builder.CreatePtrToInt(Arg, IntPtrTy);
2437         llvm::Type *OutputTy = ConvertType(OutputType);
2438         if (isa<llvm::IntegerType>(OutputTy))
2439           Arg = Builder.CreateZExt(Arg, OutputTy);
2440         else if (isa<llvm::PointerType>(OutputTy))
2441           Arg = Builder.CreateZExt(Arg, IntPtrTy);
2442         else {
2443           assert(OutputTy->isFloatingPointTy() && "Unexpected output type");
2444           Arg = Builder.CreateFPExt(Arg, OutputTy);
2445         }
2446       }
2447       // Deal with the tied operands' constraint code in adjustInlineAsmType.
2448       ReplaceConstraint = OutputConstraints[Output];
2449     }
2450     if (llvm::Type* AdjTy =
2451           getTargetHooks().adjustInlineAsmType(*this, ReplaceConstraint,
2452                                                    Arg->getType()))
2453       Arg = Builder.CreateBitCast(Arg, AdjTy);
2454     else
2455       CGM.getDiags().Report(S.getAsmLoc(), diag::err_asm_invalid_type_in_input)
2456           << InputExpr->getType() << InputConstraint;
2457 
2458     // Update largest vector width for any vector types.
2459     if (auto *VT = dyn_cast<llvm::VectorType>(Arg->getType()))
2460       LargestVectorWidth =
2461           std::max((uint64_t)LargestVectorWidth,
2462                    VT->getPrimitiveSizeInBits().getKnownMinSize());
2463 
2464     ArgTypes.push_back(Arg->getType());
2465     Args.push_back(Arg);
2466     Constraints += InputConstraint;
2467   }
2468 
2469   // Labels
2470   SmallVector<llvm::BasicBlock *, 16> Transfer;
2471   llvm::BasicBlock *Fallthrough = nullptr;
2472   bool IsGCCAsmGoto = false;
2473   if (const auto *GS =  dyn_cast<GCCAsmStmt>(&S)) {
2474     IsGCCAsmGoto = GS->isAsmGoto();
2475     if (IsGCCAsmGoto) {
2476       for (const auto *E : GS->labels()) {
2477         JumpDest Dest = getJumpDestForLabel(E->getLabel());
2478         Transfer.push_back(Dest.getBlock());
2479         llvm::BlockAddress *BA =
2480             llvm::BlockAddress::get(CurFn, Dest.getBlock());
2481         Args.push_back(BA);
2482         ArgTypes.push_back(BA->getType());
2483         if (!Constraints.empty())
2484           Constraints += ',';
2485         Constraints += 'X';
2486       }
2487       Fallthrough = createBasicBlock("asm.fallthrough");
2488     }
2489   }
2490 
2491   // Append the "input" part of inout constraints last.
2492   for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
2493     ArgTypes.push_back(InOutArgTypes[i]);
2494     Args.push_back(InOutArgs[i]);
2495   }
2496   Constraints += InOutConstraints;
2497 
2498   // Clobbers
2499   for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
2500     StringRef Clobber = S.getClobber(i);
2501 
2502     if (Clobber == "memory")
2503       ReadOnly = ReadNone = false;
2504     else if (Clobber != "cc") {
2505       Clobber = getTarget().getNormalizedGCCRegisterName(Clobber);
2506       if (CGM.getCodeGenOpts().StackClashProtector &&
2507           getTarget().isSPRegName(Clobber)) {
2508         CGM.getDiags().Report(S.getAsmLoc(),
2509                               diag::warn_stack_clash_protection_inline_asm);
2510       }
2511     }
2512 
2513     if (isa<MSAsmStmt>(&S)) {
2514       if (Clobber == "eax" || Clobber == "edx") {
2515         if (Constraints.find("=&A") != std::string::npos)
2516           continue;
2517         std::string::size_type position1 =
2518             Constraints.find("={" + Clobber.str() + "}");
2519         if (position1 != std::string::npos) {
2520           Constraints.insert(position1 + 1, "&");
2521           continue;
2522         }
2523         std::string::size_type position2 = Constraints.find("=A");
2524         if (position2 != std::string::npos) {
2525           Constraints.insert(position2 + 1, "&");
2526           continue;
2527         }
2528       }
2529     }
2530     if (!Constraints.empty())
2531       Constraints += ',';
2532 
2533     Constraints += "~{";
2534     Constraints += Clobber;
2535     Constraints += '}';
2536   }
2537 
2538   // Add machine specific clobbers
2539   std::string MachineClobbers = getTarget().getClobbers();
2540   if (!MachineClobbers.empty()) {
2541     if (!Constraints.empty())
2542       Constraints += ',';
2543     Constraints += MachineClobbers;
2544   }
2545 
2546   llvm::Type *ResultType;
2547   if (ResultRegTypes.empty())
2548     ResultType = VoidTy;
2549   else if (ResultRegTypes.size() == 1)
2550     ResultType = ResultRegTypes[0];
2551   else
2552     ResultType = llvm::StructType::get(getLLVMContext(), ResultRegTypes);
2553 
2554   llvm::FunctionType *FTy =
2555     llvm::FunctionType::get(ResultType, ArgTypes, false);
2556 
2557   bool HasSideEffect = S.isVolatile() || S.getNumOutputs() == 0;
2558   llvm::InlineAsm::AsmDialect AsmDialect = isa<MSAsmStmt>(&S) ?
2559     llvm::InlineAsm::AD_Intel : llvm::InlineAsm::AD_ATT;
2560   llvm::InlineAsm *IA =
2561     llvm::InlineAsm::get(FTy, AsmString, Constraints, HasSideEffect,
2562                          /* IsAlignStack */ false, AsmDialect);
2563   std::vector<llvm::Value*> RegResults;
2564   if (IsGCCAsmGoto) {
2565     llvm::CallBrInst *Result =
2566         Builder.CreateCallBr(IA, Fallthrough, Transfer, Args);
2567     EmitBlock(Fallthrough);
2568     UpdateAsmCallInst(cast<llvm::CallBase>(*Result), HasSideEffect, ReadOnly,
2569                       ReadNone, InNoMergeAttributedStmt, S, ResultRegTypes,
2570                       *this, RegResults);
2571   } else {
2572     llvm::CallInst *Result =
2573         Builder.CreateCall(IA, Args, getBundlesForFunclet(IA));
2574     UpdateAsmCallInst(cast<llvm::CallBase>(*Result), HasSideEffect, ReadOnly,
2575                       ReadNone, InNoMergeAttributedStmt, S, ResultRegTypes,
2576                       *this, RegResults);
2577   }
2578 
2579   assert(RegResults.size() == ResultRegTypes.size());
2580   assert(RegResults.size() == ResultTruncRegTypes.size());
2581   assert(RegResults.size() == ResultRegDests.size());
2582   // ResultRegDests can be also populated by addReturnRegisterOutputs() above,
2583   // in which case its size may grow.
2584   assert(ResultTypeRequiresCast.size() <= ResultRegDests.size());
2585   for (unsigned i = 0, e = RegResults.size(); i != e; ++i) {
2586     llvm::Value *Tmp = RegResults[i];
2587 
2588     // If the result type of the LLVM IR asm doesn't match the result type of
2589     // the expression, do the conversion.
2590     if (ResultRegTypes[i] != ResultTruncRegTypes[i]) {
2591       llvm::Type *TruncTy = ResultTruncRegTypes[i];
2592 
2593       // Truncate the integer result to the right size, note that TruncTy can be
2594       // a pointer.
2595       if (TruncTy->isFloatingPointTy())
2596         Tmp = Builder.CreateFPTrunc(Tmp, TruncTy);
2597       else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) {
2598         uint64_t ResSize = CGM.getDataLayout().getTypeSizeInBits(TruncTy);
2599         Tmp = Builder.CreateTrunc(Tmp,
2600                    llvm::IntegerType::get(getLLVMContext(), (unsigned)ResSize));
2601         Tmp = Builder.CreateIntToPtr(Tmp, TruncTy);
2602       } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) {
2603         uint64_t TmpSize =CGM.getDataLayout().getTypeSizeInBits(Tmp->getType());
2604         Tmp = Builder.CreatePtrToInt(Tmp,
2605                    llvm::IntegerType::get(getLLVMContext(), (unsigned)TmpSize));
2606         Tmp = Builder.CreateTrunc(Tmp, TruncTy);
2607       } else if (TruncTy->isIntegerTy()) {
2608         Tmp = Builder.CreateZExtOrTrunc(Tmp, TruncTy);
2609       } else if (TruncTy->isVectorTy()) {
2610         Tmp = Builder.CreateBitCast(Tmp, TruncTy);
2611       }
2612     }
2613 
2614     LValue Dest = ResultRegDests[i];
2615     // ResultTypeRequiresCast elements correspond to the first
2616     // ResultTypeRequiresCast.size() elements of RegResults.
2617     if ((i < ResultTypeRequiresCast.size()) && ResultTypeRequiresCast[i]) {
2618       unsigned Size = getContext().getTypeSize(ResultRegQualTys[i]);
2619       Address A = Builder.CreateBitCast(Dest.getAddress(*this),
2620                                         ResultRegTypes[i]->getPointerTo());
2621       QualType Ty = getContext().getIntTypeForBitwidth(Size, /*Signed*/ false);
2622       if (Ty.isNull()) {
2623         const Expr *OutExpr = S.getOutputExpr(i);
2624         CGM.Error(
2625             OutExpr->getExprLoc(),
2626             "impossible constraint in asm: can't store value into a register");
2627         return;
2628       }
2629       Dest = MakeAddrLValue(A, Ty);
2630     }
2631     EmitStoreThroughLValue(RValue::get(Tmp), Dest);
2632   }
2633 }
2634 
2635 LValue CodeGenFunction::InitCapturedStruct(const CapturedStmt &S) {
2636   const RecordDecl *RD = S.getCapturedRecordDecl();
2637   QualType RecordTy = getContext().getRecordType(RD);
2638 
2639   // Initialize the captured struct.
2640   LValue SlotLV =
2641     MakeAddrLValue(CreateMemTemp(RecordTy, "agg.captured"), RecordTy);
2642 
2643   RecordDecl::field_iterator CurField = RD->field_begin();
2644   for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
2645                                                  E = S.capture_init_end();
2646        I != E; ++I, ++CurField) {
2647     LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
2648     if (CurField->hasCapturedVLAType()) {
2649       EmitLambdaVLACapture(CurField->getCapturedVLAType(), LV);
2650     } else {
2651       EmitInitializerForField(*CurField, LV, *I);
2652     }
2653   }
2654 
2655   return SlotLV;
2656 }
2657 
2658 /// Generate an outlined function for the body of a CapturedStmt, store any
2659 /// captured variables into the captured struct, and call the outlined function.
2660 llvm::Function *
2661 CodeGenFunction::EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K) {
2662   LValue CapStruct = InitCapturedStruct(S);
2663 
2664   // Emit the CapturedDecl
2665   CodeGenFunction CGF(CGM, true);
2666   CGCapturedStmtRAII CapInfoRAII(CGF, new CGCapturedStmtInfo(S, K));
2667   llvm::Function *F = CGF.GenerateCapturedStmtFunction(S);
2668   delete CGF.CapturedStmtInfo;
2669 
2670   // Emit call to the helper function.
2671   EmitCallOrInvoke(F, CapStruct.getPointer(*this));
2672 
2673   return F;
2674 }
2675 
2676 Address CodeGenFunction::GenerateCapturedStmtArgument(const CapturedStmt &S) {
2677   LValue CapStruct = InitCapturedStruct(S);
2678   return CapStruct.getAddress(*this);
2679 }
2680 
2681 /// Creates the outlined function for a CapturedStmt.
2682 llvm::Function *
2683 CodeGenFunction::GenerateCapturedStmtFunction(const CapturedStmt &S) {
2684   assert(CapturedStmtInfo &&
2685     "CapturedStmtInfo should be set when generating the captured function");
2686   const CapturedDecl *CD = S.getCapturedDecl();
2687   const RecordDecl *RD = S.getCapturedRecordDecl();
2688   SourceLocation Loc = S.getBeginLoc();
2689   assert(CD->hasBody() && "missing CapturedDecl body");
2690 
2691   // Build the argument list.
2692   ASTContext &Ctx = CGM.getContext();
2693   FunctionArgList Args;
2694   Args.append(CD->param_begin(), CD->param_end());
2695 
2696   // Create the function declaration.
2697   const CGFunctionInfo &FuncInfo =
2698     CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Args);
2699   llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
2700 
2701   llvm::Function *F =
2702     llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
2703                            CapturedStmtInfo->getHelperName(), &CGM.getModule());
2704   CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
2705   if (CD->isNothrow())
2706     F->addFnAttr(llvm::Attribute::NoUnwind);
2707 
2708   // Generate the function.
2709   StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args, CD->getLocation(),
2710                 CD->getBody()->getBeginLoc());
2711   // Set the context parameter in CapturedStmtInfo.
2712   Address DeclPtr = GetAddrOfLocalVar(CD->getContextParam());
2713   CapturedStmtInfo->setContextValue(Builder.CreateLoad(DeclPtr));
2714 
2715   // Initialize variable-length arrays.
2716   LValue Base = MakeNaturalAlignAddrLValue(CapturedStmtInfo->getContextValue(),
2717                                            Ctx.getTagDeclType(RD));
2718   for (auto *FD : RD->fields()) {
2719     if (FD->hasCapturedVLAType()) {
2720       auto *ExprArg =
2721           EmitLoadOfLValue(EmitLValueForField(Base, FD), S.getBeginLoc())
2722               .getScalarVal();
2723       auto VAT = FD->getCapturedVLAType();
2724       VLASizeMap[VAT->getSizeExpr()] = ExprArg;
2725     }
2726   }
2727 
2728   // If 'this' is captured, load it into CXXThisValue.
2729   if (CapturedStmtInfo->isCXXThisExprCaptured()) {
2730     FieldDecl *FD = CapturedStmtInfo->getThisFieldDecl();
2731     LValue ThisLValue = EmitLValueForField(Base, FD);
2732     CXXThisValue = EmitLoadOfLValue(ThisLValue, Loc).getScalarVal();
2733   }
2734 
2735   PGO.assignRegionCounters(GlobalDecl(CD), F);
2736   CapturedStmtInfo->EmitBody(*this, CD->getBody());
2737   FinishFunction(CD->getBodyRBrace());
2738 
2739   return F;
2740 }
2741