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