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