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