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