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