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