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