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 /// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
1074 /// if the function returns void, or may be missing one if the function returns
1075 /// non-void.  Fun stuff :).
1076 void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
1077   if (requiresReturnValueCheck()) {
1078     llvm::Constant *SLoc = EmitCheckSourceLocation(S.getBeginLoc());
1079     auto *SLocPtr =
1080         new llvm::GlobalVariable(CGM.getModule(), SLoc->getType(), false,
1081                                  llvm::GlobalVariable::PrivateLinkage, SLoc);
1082     SLocPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1083     CGM.getSanitizerMetadata()->disableSanitizerForGlobal(SLocPtr);
1084     assert(ReturnLocation.isValid() && "No valid return location");
1085     Builder.CreateStore(Builder.CreateBitCast(SLocPtr, Int8PtrTy),
1086                         ReturnLocation);
1087   }
1088 
1089   // Returning from an outlined SEH helper is UB, and we already warn on it.
1090   if (IsOutlinedSEHHelper) {
1091     Builder.CreateUnreachable();
1092     Builder.ClearInsertionPoint();
1093   }
1094 
1095   // Emit the result value, even if unused, to evaluate the side effects.
1096   const Expr *RV = S.getRetValue();
1097 
1098   // Treat block literals in a return expression as if they appeared
1099   // in their own scope.  This permits a small, easily-implemented
1100   // exception to our over-conservative rules about not jumping to
1101   // statements following block literals with non-trivial cleanups.
1102   RunCleanupsScope cleanupScope(*this);
1103   if (const FullExpr *fe = dyn_cast_or_null<FullExpr>(RV)) {
1104     enterFullExpression(fe);
1105     RV = fe->getSubExpr();
1106   }
1107 
1108   // FIXME: Clean this up by using an LValue for ReturnTemp,
1109   // EmitStoreThroughLValue, and EmitAnyExpr.
1110   // Check if the NRVO candidate was not globalized in OpenMP mode.
1111   if (getLangOpts().ElideConstructors && S.getNRVOCandidate() &&
1112       S.getNRVOCandidate()->isNRVOVariable() &&
1113       (!getLangOpts().OpenMP ||
1114        !CGM.getOpenMPRuntime()
1115             .getAddressOfLocalVariable(*this, S.getNRVOCandidate())
1116             .isValid())) {
1117     // Apply the named return value optimization for this return statement,
1118     // which means doing nothing: the appropriate result has already been
1119     // constructed into the NRVO variable.
1120 
1121     // If there is an NRVO flag for this variable, set it to 1 into indicate
1122     // that the cleanup code should not destroy the variable.
1123     if (llvm::Value *NRVOFlag = NRVOFlags[S.getNRVOCandidate()])
1124       Builder.CreateFlagStore(Builder.getTrue(), NRVOFlag);
1125   } else if (!ReturnValue.isValid() || (RV && RV->getType()->isVoidType())) {
1126     // Make sure not to return anything, but evaluate the expression
1127     // for side effects.
1128     if (RV)
1129       EmitAnyExpr(RV);
1130   } else if (!RV) {
1131     // Do nothing (return value is left uninitialized)
1132   } else if (FnRetTy->isReferenceType()) {
1133     // If this function returns a reference, take the address of the expression
1134     // rather than the value.
1135     RValue Result = EmitReferenceBindingToExpr(RV);
1136     Builder.CreateStore(Result.getScalarVal(), ReturnValue);
1137   } else {
1138     switch (getEvaluationKind(RV->getType())) {
1139     case TEK_Scalar:
1140       Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
1141       break;
1142     case TEK_Complex:
1143       EmitComplexExprIntoLValue(RV, MakeAddrLValue(ReturnValue, RV->getType()),
1144                                 /*isInit*/ true);
1145       break;
1146     case TEK_Aggregate:
1147       EmitAggExpr(RV, AggValueSlot::forAddr(
1148                           ReturnValue, Qualifiers(),
1149                           AggValueSlot::IsDestructed,
1150                           AggValueSlot::DoesNotNeedGCBarriers,
1151                           AggValueSlot::IsNotAliased,
1152                           getOverlapForReturnValue()));
1153       break;
1154     }
1155   }
1156 
1157   ++NumReturnExprs;
1158   if (!RV || RV->isEvaluatable(getContext()))
1159     ++NumSimpleReturnExprs;
1160 
1161   cleanupScope.ForceCleanup();
1162   EmitBranchThroughCleanup(ReturnBlock);
1163 }
1164 
1165 void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
1166   // As long as debug info is modeled with instructions, we have to ensure we
1167   // have a place to insert here and write the stop point here.
1168   if (HaveInsertPoint())
1169     EmitStopPoint(&S);
1170 
1171   for (const auto *I : S.decls())
1172     EmitDecl(*I);
1173 }
1174 
1175 void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
1176   assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
1177 
1178   // If this code is reachable then emit a stop point (if generating
1179   // debug info). We have to do this ourselves because we are on the
1180   // "simple" statement path.
1181   if (HaveInsertPoint())
1182     EmitStopPoint(&S);
1183 
1184   EmitBranchThroughCleanup(BreakContinueStack.back().BreakBlock);
1185 }
1186 
1187 void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
1188   assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
1189 
1190   // If this code is reachable then emit a stop point (if generating
1191   // debug info). We have to do this ourselves because we are on the
1192   // "simple" statement path.
1193   if (HaveInsertPoint())
1194     EmitStopPoint(&S);
1195 
1196   EmitBranchThroughCleanup(BreakContinueStack.back().ContinueBlock);
1197 }
1198 
1199 /// EmitCaseStmtRange - If case statement range is not too big then
1200 /// add multiple cases to switch instruction, one for each value within
1201 /// the range. If range is too big then emit "if" condition check.
1202 void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
1203   assert(S.getRHS() && "Expected RHS value in CaseStmt");
1204 
1205   llvm::APSInt LHS = S.getLHS()->EvaluateKnownConstInt(getContext());
1206   llvm::APSInt RHS = S.getRHS()->EvaluateKnownConstInt(getContext());
1207 
1208   // Emit the code for this case. We do this first to make sure it is
1209   // properly chained from our predecessor before generating the
1210   // switch machinery to enter this block.
1211   llvm::BasicBlock *CaseDest = createBasicBlock("sw.bb");
1212   EmitBlockWithFallThrough(CaseDest, &S);
1213   EmitStmt(S.getSubStmt());
1214 
1215   // If range is empty, do nothing.
1216   if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
1217     return;
1218 
1219   llvm::APInt Range = RHS - LHS;
1220   // FIXME: parameters such as this should not be hardcoded.
1221   if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
1222     // Range is small enough to add multiple switch instruction cases.
1223     uint64_t Total = getProfileCount(&S);
1224     unsigned NCases = Range.getZExtValue() + 1;
1225     // We only have one region counter for the entire set of cases here, so we
1226     // need to divide the weights evenly between the generated cases, ensuring
1227     // that the total weight is preserved. E.g., a weight of 5 over three cases
1228     // will be distributed as weights of 2, 2, and 1.
1229     uint64_t Weight = Total / NCases, Rem = Total % NCases;
1230     for (unsigned I = 0; I != NCases; ++I) {
1231       if (SwitchWeights)
1232         SwitchWeights->push_back(Weight + (Rem ? 1 : 0));
1233       if (Rem)
1234         Rem--;
1235       SwitchInsn->addCase(Builder.getInt(LHS), CaseDest);
1236       ++LHS;
1237     }
1238     return;
1239   }
1240 
1241   // The range is too big. Emit "if" condition into a new block,
1242   // making sure to save and restore the current insertion point.
1243   llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
1244 
1245   // Push this test onto the chain of range checks (which terminates
1246   // in the default basic block). The switch's default will be changed
1247   // to the top of this chain after switch emission is complete.
1248   llvm::BasicBlock *FalseDest = CaseRangeBlock;
1249   CaseRangeBlock = createBasicBlock("sw.caserange");
1250 
1251   CurFn->getBasicBlockList().push_back(CaseRangeBlock);
1252   Builder.SetInsertPoint(CaseRangeBlock);
1253 
1254   // Emit range check.
1255   llvm::Value *Diff =
1256     Builder.CreateSub(SwitchInsn->getCondition(), Builder.getInt(LHS));
1257   llvm::Value *Cond =
1258     Builder.CreateICmpULE(Diff, Builder.getInt(Range), "inbounds");
1259 
1260   llvm::MDNode *Weights = nullptr;
1261   if (SwitchWeights) {
1262     uint64_t ThisCount = getProfileCount(&S);
1263     uint64_t DefaultCount = (*SwitchWeights)[0];
1264     Weights = createProfileWeights(ThisCount, DefaultCount);
1265 
1266     // Since we're chaining the switch default through each large case range, we
1267     // need to update the weight for the default, ie, the first case, to include
1268     // this case.
1269     (*SwitchWeights)[0] += ThisCount;
1270   }
1271   Builder.CreateCondBr(Cond, CaseDest, FalseDest, Weights);
1272 
1273   // Restore the appropriate insertion point.
1274   if (RestoreBB)
1275     Builder.SetInsertPoint(RestoreBB);
1276   else
1277     Builder.ClearInsertionPoint();
1278 }
1279 
1280 void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
1281   // If there is no enclosing switch instance that we're aware of, then this
1282   // case statement and its block can be elided.  This situation only happens
1283   // when we've constant-folded the switch, are emitting the constant case,
1284   // and part of the constant case includes another case statement.  For
1285   // instance: switch (4) { case 4: do { case 5: } while (1); }
1286   if (!SwitchInsn) {
1287     EmitStmt(S.getSubStmt());
1288     return;
1289   }
1290 
1291   // Handle case ranges.
1292   if (S.getRHS()) {
1293     EmitCaseStmtRange(S);
1294     return;
1295   }
1296 
1297   llvm::ConstantInt *CaseVal =
1298     Builder.getInt(S.getLHS()->EvaluateKnownConstInt(getContext()));
1299 
1300   // If the body of the case is just a 'break', try to not emit an empty block.
1301   // If we're profiling or we're not optimizing, leave the block in for better
1302   // debug and coverage analysis.
1303   if (!CGM.getCodeGenOpts().hasProfileClangInstr() &&
1304       CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1305       isa<BreakStmt>(S.getSubStmt())) {
1306     JumpDest Block = BreakContinueStack.back().BreakBlock;
1307 
1308     // Only do this optimization if there are no cleanups that need emitting.
1309     if (isObviouslyBranchWithoutCleanups(Block)) {
1310       if (SwitchWeights)
1311         SwitchWeights->push_back(getProfileCount(&S));
1312       SwitchInsn->addCase(CaseVal, Block.getBlock());
1313 
1314       // If there was a fallthrough into this case, make sure to redirect it to
1315       // the end of the switch as well.
1316       if (Builder.GetInsertBlock()) {
1317         Builder.CreateBr(Block.getBlock());
1318         Builder.ClearInsertionPoint();
1319       }
1320       return;
1321     }
1322   }
1323 
1324   llvm::BasicBlock *CaseDest = createBasicBlock("sw.bb");
1325   EmitBlockWithFallThrough(CaseDest, &S);
1326   if (SwitchWeights)
1327     SwitchWeights->push_back(getProfileCount(&S));
1328   SwitchInsn->addCase(CaseVal, CaseDest);
1329 
1330   // Recursively emitting the statement is acceptable, but is not wonderful for
1331   // code where we have many case statements nested together, i.e.:
1332   //  case 1:
1333   //    case 2:
1334   //      case 3: etc.
1335   // Handling this recursively will create a new block for each case statement
1336   // that falls through to the next case which is IR intensive.  It also causes
1337   // deep recursion which can run into stack depth limitations.  Handle
1338   // sequential non-range case statements specially.
1339   const CaseStmt *CurCase = &S;
1340   const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
1341 
1342   // Otherwise, iteratively add consecutive cases to this switch stmt.
1343   while (NextCase && NextCase->getRHS() == nullptr) {
1344     CurCase = NextCase;
1345     llvm::ConstantInt *CaseVal =
1346       Builder.getInt(CurCase->getLHS()->EvaluateKnownConstInt(getContext()));
1347 
1348     if (SwitchWeights)
1349       SwitchWeights->push_back(getProfileCount(NextCase));
1350     if (CGM.getCodeGenOpts().hasProfileClangInstr()) {
1351       CaseDest = createBasicBlock("sw.bb");
1352       EmitBlockWithFallThrough(CaseDest, &S);
1353     }
1354 
1355     SwitchInsn->addCase(CaseVal, CaseDest);
1356     NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt());
1357   }
1358 
1359   // Normal default recursion for non-cases.
1360   EmitStmt(CurCase->getSubStmt());
1361 }
1362 
1363 void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
1364   // If there is no enclosing switch instance that we're aware of, then this
1365   // default statement can be elided. This situation only happens when we've
1366   // constant-folded the switch.
1367   if (!SwitchInsn) {
1368     EmitStmt(S.getSubStmt());
1369     return;
1370   }
1371 
1372   llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
1373   assert(DefaultBlock->empty() &&
1374          "EmitDefaultStmt: Default block already defined?");
1375 
1376   EmitBlockWithFallThrough(DefaultBlock, &S);
1377 
1378   EmitStmt(S.getSubStmt());
1379 }
1380 
1381 /// CollectStatementsForCase - Given the body of a 'switch' statement and a
1382 /// constant value that is being switched on, see if we can dead code eliminate
1383 /// the body of the switch to a simple series of statements to emit.  Basically,
1384 /// on a switch (5) we want to find these statements:
1385 ///    case 5:
1386 ///      printf(...);    <--
1387 ///      ++i;            <--
1388 ///      break;
1389 ///
1390 /// and add them to the ResultStmts vector.  If it is unsafe to do this
1391 /// transformation (for example, one of the elided statements contains a label
1392 /// that might be jumped to), return CSFC_Failure.  If we handled it and 'S'
1393 /// should include statements after it (e.g. the printf() line is a substmt of
1394 /// the case) then return CSFC_FallThrough.  If we handled it and found a break
1395 /// statement, then return CSFC_Success.
1396 ///
1397 /// If Case is non-null, then we are looking for the specified case, checking
1398 /// that nothing we jump over contains labels.  If Case is null, then we found
1399 /// the case and are looking for the break.
1400 ///
1401 /// If the recursive walk actually finds our Case, then we set FoundCase to
1402 /// true.
1403 ///
1404 enum CSFC_Result { CSFC_Failure, CSFC_FallThrough, CSFC_Success };
1405 static CSFC_Result CollectStatementsForCase(const Stmt *S,
1406                                             const SwitchCase *Case,
1407                                             bool &FoundCase,
1408                               SmallVectorImpl<const Stmt*> &ResultStmts) {
1409   // If this is a null statement, just succeed.
1410   if (!S)
1411     return Case ? CSFC_Success : CSFC_FallThrough;
1412 
1413   // If this is the switchcase (case 4: or default) that we're looking for, then
1414   // we're in business.  Just add the substatement.
1415   if (const SwitchCase *SC = dyn_cast<SwitchCase>(S)) {
1416     if (S == Case) {
1417       FoundCase = true;
1418       return CollectStatementsForCase(SC->getSubStmt(), nullptr, FoundCase,
1419                                       ResultStmts);
1420     }
1421 
1422     // Otherwise, this is some other case or default statement, just ignore it.
1423     return CollectStatementsForCase(SC->getSubStmt(), Case, FoundCase,
1424                                     ResultStmts);
1425   }
1426 
1427   // If we are in the live part of the code and we found our break statement,
1428   // return a success!
1429   if (!Case && isa<BreakStmt>(S))
1430     return CSFC_Success;
1431 
1432   // If this is a switch statement, then it might contain the SwitchCase, the
1433   // break, or neither.
1434   if (const CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
1435     // Handle this as two cases: we might be looking for the SwitchCase (if so
1436     // the skipped statements must be skippable) or we might already have it.
1437     CompoundStmt::const_body_iterator I = CS->body_begin(), E = CS->body_end();
1438     bool StartedInLiveCode = FoundCase;
1439     unsigned StartSize = ResultStmts.size();
1440 
1441     // If we've not found the case yet, scan through looking for it.
1442     if (Case) {
1443       // Keep track of whether we see a skipped declaration.  The code could be
1444       // using the declaration even if it is skipped, so we can't optimize out
1445       // the decl if the kept statements might refer to it.
1446       bool HadSkippedDecl = false;
1447 
1448       // If we're looking for the case, just see if we can skip each of the
1449       // substatements.
1450       for (; Case && I != E; ++I) {
1451         HadSkippedDecl |= CodeGenFunction::mightAddDeclToScope(*I);
1452 
1453         switch (CollectStatementsForCase(*I, Case, FoundCase, ResultStmts)) {
1454         case CSFC_Failure: return CSFC_Failure;
1455         case CSFC_Success:
1456           // A successful result means that either 1) that the statement doesn't
1457           // have the case and is skippable, or 2) does contain the case value
1458           // and also contains the break to exit the switch.  In the later case,
1459           // we just verify the rest of the statements are elidable.
1460           if (FoundCase) {
1461             // If we found the case and skipped declarations, we can't do the
1462             // optimization.
1463             if (HadSkippedDecl)
1464               return CSFC_Failure;
1465 
1466             for (++I; I != E; ++I)
1467               if (CodeGenFunction::ContainsLabel(*I, true))
1468                 return CSFC_Failure;
1469             return CSFC_Success;
1470           }
1471           break;
1472         case CSFC_FallThrough:
1473           // If we have a fallthrough condition, then we must have found the
1474           // case started to include statements.  Consider the rest of the
1475           // statements in the compound statement as candidates for inclusion.
1476           assert(FoundCase && "Didn't find case but returned fallthrough?");
1477           // We recursively found Case, so we're not looking for it anymore.
1478           Case = nullptr;
1479 
1480           // If we found the case and skipped declarations, we can't do the
1481           // optimization.
1482           if (HadSkippedDecl)
1483             return CSFC_Failure;
1484           break;
1485         }
1486       }
1487 
1488       if (!FoundCase)
1489         return CSFC_Success;
1490 
1491       assert(!HadSkippedDecl && "fallthrough after skipping decl");
1492     }
1493 
1494     // If we have statements in our range, then we know that the statements are
1495     // live and need to be added to the set of statements we're tracking.
1496     bool AnyDecls = false;
1497     for (; I != E; ++I) {
1498       AnyDecls |= CodeGenFunction::mightAddDeclToScope(*I);
1499 
1500       switch (CollectStatementsForCase(*I, nullptr, FoundCase, ResultStmts)) {
1501       case CSFC_Failure: return CSFC_Failure;
1502       case CSFC_FallThrough:
1503         // A fallthrough result means that the statement was simple and just
1504         // included in ResultStmt, keep adding them afterwards.
1505         break;
1506       case CSFC_Success:
1507         // A successful result means that we found the break statement and
1508         // stopped statement inclusion.  We just ensure that any leftover stmts
1509         // are skippable and return success ourselves.
1510         for (++I; I != E; ++I)
1511           if (CodeGenFunction::ContainsLabel(*I, true))
1512             return CSFC_Failure;
1513         return CSFC_Success;
1514       }
1515     }
1516 
1517     // If we're about to fall out of a scope without hitting a 'break;', we
1518     // can't perform the optimization if there were any decls in that scope
1519     // (we'd lose their end-of-lifetime).
1520     if (AnyDecls) {
1521       // If the entire compound statement was live, there's one more thing we
1522       // can try before giving up: emit the whole thing as a single statement.
1523       // We can do that unless the statement contains a 'break;'.
1524       // FIXME: Such a break must be at the end of a construct within this one.
1525       // We could emit this by just ignoring the BreakStmts entirely.
1526       if (StartedInLiveCode && !CodeGenFunction::containsBreak(S)) {
1527         ResultStmts.resize(StartSize);
1528         ResultStmts.push_back(S);
1529       } else {
1530         return CSFC_Failure;
1531       }
1532     }
1533 
1534     return CSFC_FallThrough;
1535   }
1536 
1537   // Okay, this is some other statement that we don't handle explicitly, like a
1538   // for statement or increment etc.  If we are skipping over this statement,
1539   // just verify it doesn't have labels, which would make it invalid to elide.
1540   if (Case) {
1541     if (CodeGenFunction::ContainsLabel(S, true))
1542       return CSFC_Failure;
1543     return CSFC_Success;
1544   }
1545 
1546   // Otherwise, we want to include this statement.  Everything is cool with that
1547   // so long as it doesn't contain a break out of the switch we're in.
1548   if (CodeGenFunction::containsBreak(S)) return CSFC_Failure;
1549 
1550   // Otherwise, everything is great.  Include the statement and tell the caller
1551   // that we fall through and include the next statement as well.
1552   ResultStmts.push_back(S);
1553   return CSFC_FallThrough;
1554 }
1555 
1556 /// FindCaseStatementsForValue - Find the case statement being jumped to and
1557 /// then invoke CollectStatementsForCase to find the list of statements to emit
1558 /// for a switch on constant.  See the comment above CollectStatementsForCase
1559 /// for more details.
1560 static bool FindCaseStatementsForValue(const SwitchStmt &S,
1561                                        const llvm::APSInt &ConstantCondValue,
1562                                 SmallVectorImpl<const Stmt*> &ResultStmts,
1563                                        ASTContext &C,
1564                                        const SwitchCase *&ResultCase) {
1565   // First step, find the switch case that is being branched to.  We can do this
1566   // efficiently by scanning the SwitchCase list.
1567   const SwitchCase *Case = S.getSwitchCaseList();
1568   const DefaultStmt *DefaultCase = nullptr;
1569 
1570   for (; Case; Case = Case->getNextSwitchCase()) {
1571     // It's either a default or case.  Just remember the default statement in
1572     // case we're not jumping to any numbered cases.
1573     if (const DefaultStmt *DS = dyn_cast<DefaultStmt>(Case)) {
1574       DefaultCase = DS;
1575       continue;
1576     }
1577 
1578     // Check to see if this case is the one we're looking for.
1579     const CaseStmt *CS = cast<CaseStmt>(Case);
1580     // Don't handle case ranges yet.
1581     if (CS->getRHS()) return false;
1582 
1583     // If we found our case, remember it as 'case'.
1584     if (CS->getLHS()->EvaluateKnownConstInt(C) == ConstantCondValue)
1585       break;
1586   }
1587 
1588   // If we didn't find a matching case, we use a default if it exists, or we
1589   // elide the whole switch body!
1590   if (!Case) {
1591     // It is safe to elide the body of the switch if it doesn't contain labels
1592     // etc.  If it is safe, return successfully with an empty ResultStmts list.
1593     if (!DefaultCase)
1594       return !CodeGenFunction::ContainsLabel(&S);
1595     Case = DefaultCase;
1596   }
1597 
1598   // Ok, we know which case is being jumped to, try to collect all the
1599   // statements that follow it.  This can fail for a variety of reasons.  Also,
1600   // check to see that the recursive walk actually found our case statement.
1601   // Insane cases like this can fail to find it in the recursive walk since we
1602   // don't handle every stmt kind:
1603   // switch (4) {
1604   //   while (1) {
1605   //     case 4: ...
1606   bool FoundCase = false;
1607   ResultCase = Case;
1608   return CollectStatementsForCase(S.getBody(), Case, FoundCase,
1609                                   ResultStmts) != CSFC_Failure &&
1610          FoundCase;
1611 }
1612 
1613 void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
1614   // Handle nested switch statements.
1615   llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
1616   SmallVector<uint64_t, 16> *SavedSwitchWeights = SwitchWeights;
1617   llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
1618 
1619   // See if we can constant fold the condition of the switch and therefore only
1620   // emit the live case statement (if any) of the switch.
1621   llvm::APSInt ConstantCondValue;
1622   if (ConstantFoldsToSimpleInteger(S.getCond(), ConstantCondValue)) {
1623     SmallVector<const Stmt*, 4> CaseStmts;
1624     const SwitchCase *Case = nullptr;
1625     if (FindCaseStatementsForValue(S, ConstantCondValue, CaseStmts,
1626                                    getContext(), Case)) {
1627       if (Case)
1628         incrementProfileCounter(Case);
1629       RunCleanupsScope ExecutedScope(*this);
1630 
1631       if (S.getInit())
1632         EmitStmt(S.getInit());
1633 
1634       // Emit the condition variable if needed inside the entire cleanup scope
1635       // used by this special case for constant folded switches.
1636       if (S.getConditionVariable())
1637         EmitDecl(*S.getConditionVariable());
1638 
1639       // At this point, we are no longer "within" a switch instance, so
1640       // we can temporarily enforce this to ensure that any embedded case
1641       // statements are not emitted.
1642       SwitchInsn = nullptr;
1643 
1644       // Okay, we can dead code eliminate everything except this case.  Emit the
1645       // specified series of statements and we're good.
1646       for (unsigned i = 0, e = CaseStmts.size(); i != e; ++i)
1647         EmitStmt(CaseStmts[i]);
1648       incrementProfileCounter(&S);
1649 
1650       // Now we want to restore the saved switch instance so that nested
1651       // switches continue to function properly
1652       SwitchInsn = SavedSwitchInsn;
1653 
1654       return;
1655     }
1656   }
1657 
1658   JumpDest SwitchExit = getJumpDestInCurrentScope("sw.epilog");
1659 
1660   RunCleanupsScope ConditionScope(*this);
1661 
1662   if (S.getInit())
1663     EmitStmt(S.getInit());
1664 
1665   if (S.getConditionVariable())
1666     EmitDecl(*S.getConditionVariable());
1667   llvm::Value *CondV = EmitScalarExpr(S.getCond());
1668 
1669   // Create basic block to hold stuff that comes after switch
1670   // statement. We also need to create a default block now so that
1671   // explicit case ranges tests can have a place to jump to on
1672   // failure.
1673   llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
1674   SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
1675   if (PGO.haveRegionCounts()) {
1676     // Walk the SwitchCase list to find how many there are.
1677     uint64_t DefaultCount = 0;
1678     unsigned NumCases = 0;
1679     for (const SwitchCase *Case = S.getSwitchCaseList();
1680          Case;
1681          Case = Case->getNextSwitchCase()) {
1682       if (isa<DefaultStmt>(Case))
1683         DefaultCount = getProfileCount(Case);
1684       NumCases += 1;
1685     }
1686     SwitchWeights = new SmallVector<uint64_t, 16>();
1687     SwitchWeights->reserve(NumCases);
1688     // The default needs to be first. We store the edge count, so we already
1689     // know the right weight.
1690     SwitchWeights->push_back(DefaultCount);
1691   }
1692   CaseRangeBlock = DefaultBlock;
1693 
1694   // Clear the insertion point to indicate we are in unreachable code.
1695   Builder.ClearInsertionPoint();
1696 
1697   // All break statements jump to NextBlock. If BreakContinueStack is non-empty
1698   // then reuse last ContinueBlock.
1699   JumpDest OuterContinue;
1700   if (!BreakContinueStack.empty())
1701     OuterContinue = BreakContinueStack.back().ContinueBlock;
1702 
1703   BreakContinueStack.push_back(BreakContinue(SwitchExit, OuterContinue));
1704 
1705   // Emit switch body.
1706   EmitStmt(S.getBody());
1707 
1708   BreakContinueStack.pop_back();
1709 
1710   // Update the default block in case explicit case range tests have
1711   // been chained on top.
1712   SwitchInsn->setDefaultDest(CaseRangeBlock);
1713 
1714   // If a default was never emitted:
1715   if (!DefaultBlock->getParent()) {
1716     // If we have cleanups, emit the default block so that there's a
1717     // place to jump through the cleanups from.
1718     if (ConditionScope.requiresCleanups()) {
1719       EmitBlock(DefaultBlock);
1720 
1721     // Otherwise, just forward the default block to the switch end.
1722     } else {
1723       DefaultBlock->replaceAllUsesWith(SwitchExit.getBlock());
1724       delete DefaultBlock;
1725     }
1726   }
1727 
1728   ConditionScope.ForceCleanup();
1729 
1730   // Emit continuation.
1731   EmitBlock(SwitchExit.getBlock(), true);
1732   incrementProfileCounter(&S);
1733 
1734   // If the switch has a condition wrapped by __builtin_unpredictable,
1735   // create metadata that specifies that the switch is unpredictable.
1736   // Don't bother if not optimizing because that metadata would not be used.
1737   auto *Call = dyn_cast<CallExpr>(S.getCond());
1738   if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
1739     auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
1740     if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
1741       llvm::MDBuilder MDHelper(getLLVMContext());
1742       SwitchInsn->setMetadata(llvm::LLVMContext::MD_unpredictable,
1743                               MDHelper.createUnpredictable());
1744     }
1745   }
1746 
1747   if (SwitchWeights) {
1748     assert(SwitchWeights->size() == 1 + SwitchInsn->getNumCases() &&
1749            "switch weights do not match switch cases");
1750     // If there's only one jump destination there's no sense weighting it.
1751     if (SwitchWeights->size() > 1)
1752       SwitchInsn->setMetadata(llvm::LLVMContext::MD_prof,
1753                               createProfileWeights(*SwitchWeights));
1754     delete SwitchWeights;
1755   }
1756   SwitchInsn = SavedSwitchInsn;
1757   SwitchWeights = SavedSwitchWeights;
1758   CaseRangeBlock = SavedCRBlock;
1759 }
1760 
1761 static std::string
1762 SimplifyConstraint(const char *Constraint, const TargetInfo &Target,
1763                  SmallVectorImpl<TargetInfo::ConstraintInfo> *OutCons=nullptr) {
1764   std::string Result;
1765 
1766   while (*Constraint) {
1767     switch (*Constraint) {
1768     default:
1769       Result += Target.convertConstraint(Constraint);
1770       break;
1771     // Ignore these
1772     case '*':
1773     case '?':
1774     case '!':
1775     case '=': // Will see this and the following in mult-alt constraints.
1776     case '+':
1777       break;
1778     case '#': // Ignore the rest of the constraint alternative.
1779       while (Constraint[1] && Constraint[1] != ',')
1780         Constraint++;
1781       break;
1782     case '&':
1783     case '%':
1784       Result += *Constraint;
1785       while (Constraint[1] && Constraint[1] == *Constraint)
1786         Constraint++;
1787       break;
1788     case ',':
1789       Result += "|";
1790       break;
1791     case 'g':
1792       Result += "imr";
1793       break;
1794     case '[': {
1795       assert(OutCons &&
1796              "Must pass output names to constraints with a symbolic name");
1797       unsigned Index;
1798       bool result = Target.resolveSymbolicName(Constraint, *OutCons, Index);
1799       assert(result && "Could not resolve symbolic name"); (void)result;
1800       Result += llvm::utostr(Index);
1801       break;
1802     }
1803     }
1804 
1805     Constraint++;
1806   }
1807 
1808   return Result;
1809 }
1810 
1811 /// AddVariableConstraints - Look at AsmExpr and if it is a variable declared
1812 /// as using a particular register add that as a constraint that will be used
1813 /// in this asm stmt.
1814 static std::string
1815 AddVariableConstraints(const std::string &Constraint, const Expr &AsmExpr,
1816                        const TargetInfo &Target, CodeGenModule &CGM,
1817                        const AsmStmt &Stmt, const bool EarlyClobber) {
1818   const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(&AsmExpr);
1819   if (!AsmDeclRef)
1820     return Constraint;
1821   const ValueDecl &Value = *AsmDeclRef->getDecl();
1822   const VarDecl *Variable = dyn_cast<VarDecl>(&Value);
1823   if (!Variable)
1824     return Constraint;
1825   if (Variable->getStorageClass() != SC_Register)
1826     return Constraint;
1827   AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>();
1828   if (!Attr)
1829     return Constraint;
1830   StringRef Register = Attr->getLabel();
1831   assert(Target.isValidGCCRegisterName(Register));
1832   // We're using validateOutputConstraint here because we only care if
1833   // this is a register constraint.
1834   TargetInfo::ConstraintInfo Info(Constraint, "");
1835   if (Target.validateOutputConstraint(Info) &&
1836       !Info.allowsRegister()) {
1837     CGM.ErrorUnsupported(&Stmt, "__asm__");
1838     return Constraint;
1839   }
1840   // Canonicalize the register here before returning it.
1841   Register = Target.getNormalizedGCCRegisterName(Register);
1842   return (EarlyClobber ? "&{" : "{") + Register.str() + "}";
1843 }
1844 
1845 llvm::Value*
1846 CodeGenFunction::EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info,
1847                                     LValue InputValue, QualType InputType,
1848                                     std::string &ConstraintStr,
1849                                     SourceLocation Loc) {
1850   llvm::Value *Arg;
1851   if (Info.allowsRegister() || !Info.allowsMemory()) {
1852     if (CodeGenFunction::hasScalarEvaluationKind(InputType)) {
1853       Arg = EmitLoadOfLValue(InputValue, Loc).getScalarVal();
1854     } else {
1855       llvm::Type *Ty = ConvertType(InputType);
1856       uint64_t Size = CGM.getDataLayout().getTypeSizeInBits(Ty);
1857       if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
1858         Ty = llvm::IntegerType::get(getLLVMContext(), Size);
1859         Ty = llvm::PointerType::getUnqual(Ty);
1860 
1861         Arg = Builder.CreateLoad(
1862             Builder.CreateBitCast(InputValue.getAddress(*this), Ty));
1863       } else {
1864         Arg = InputValue.getPointer(*this);
1865         ConstraintStr += '*';
1866       }
1867     }
1868   } else {
1869     Arg = InputValue.getPointer(*this);
1870     ConstraintStr += '*';
1871   }
1872 
1873   return Arg;
1874 }
1875 
1876 llvm::Value* CodeGenFunction::EmitAsmInput(
1877                                          const TargetInfo::ConstraintInfo &Info,
1878                                            const Expr *InputExpr,
1879                                            std::string &ConstraintStr) {
1880   // If this can't be a register or memory, i.e., has to be a constant
1881   // (immediate or symbolic), try to emit it as such.
1882   if (!Info.allowsRegister() && !Info.allowsMemory()) {
1883     if (Info.requiresImmediateConstant()) {
1884       Expr::EvalResult EVResult;
1885       InputExpr->EvaluateAsRValue(EVResult, getContext(), true);
1886 
1887       llvm::APSInt IntResult;
1888       if (EVResult.Val.toIntegralConstant(IntResult, InputExpr->getType(),
1889                                           getContext()))
1890         return llvm::ConstantInt::get(getLLVMContext(), IntResult);
1891     }
1892 
1893     Expr::EvalResult Result;
1894     if (InputExpr->EvaluateAsInt(Result, getContext()))
1895       return llvm::ConstantInt::get(getLLVMContext(), Result.Val.getInt());
1896   }
1897 
1898   if (Info.allowsRegister() || !Info.allowsMemory())
1899     if (CodeGenFunction::hasScalarEvaluationKind(InputExpr->getType()))
1900       return EmitScalarExpr(InputExpr);
1901   if (InputExpr->getStmtClass() == Expr::CXXThisExprClass)
1902     return EmitScalarExpr(InputExpr);
1903   InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
1904   LValue Dest = EmitLValue(InputExpr);
1905   return EmitAsmInputLValue(Info, Dest, InputExpr->getType(), ConstraintStr,
1906                             InputExpr->getExprLoc());
1907 }
1908 
1909 /// getAsmSrcLocInfo - Return the !srcloc metadata node to attach to an inline
1910 /// asm call instruction.  The !srcloc MDNode contains a list of constant
1911 /// integers which are the source locations of the start of each line in the
1912 /// asm.
1913 static llvm::MDNode *getAsmSrcLocInfo(const StringLiteral *Str,
1914                                       CodeGenFunction &CGF) {
1915   SmallVector<llvm::Metadata *, 8> Locs;
1916   // Add the location of the first line to the MDNode.
1917   Locs.push_back(llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1918       CGF.Int32Ty, Str->getBeginLoc().getRawEncoding())));
1919   StringRef StrVal = Str->getString();
1920   if (!StrVal.empty()) {
1921     const SourceManager &SM = CGF.CGM.getContext().getSourceManager();
1922     const LangOptions &LangOpts = CGF.CGM.getLangOpts();
1923     unsigned StartToken = 0;
1924     unsigned ByteOffset = 0;
1925 
1926     // Add the location of the start of each subsequent line of the asm to the
1927     // MDNode.
1928     for (unsigned i = 0, e = StrVal.size() - 1; i != e; ++i) {
1929       if (StrVal[i] != '\n') continue;
1930       SourceLocation LineLoc = Str->getLocationOfByte(
1931           i + 1, SM, LangOpts, CGF.getTarget(), &StartToken, &ByteOffset);
1932       Locs.push_back(llvm::ConstantAsMetadata::get(
1933           llvm::ConstantInt::get(CGF.Int32Ty, LineLoc.getRawEncoding())));
1934     }
1935   }
1936 
1937   return llvm::MDNode::get(CGF.getLLVMContext(), Locs);
1938 }
1939 
1940 static void UpdateAsmCallInst(llvm::CallBase &Result, bool HasSideEffect,
1941                               bool ReadOnly, bool ReadNone, const AsmStmt &S,
1942                               const std::vector<llvm::Type *> &ResultRegTypes,
1943                               CodeGenFunction &CGF,
1944                               std::vector<llvm::Value *> &RegResults) {
1945   Result.addAttribute(llvm::AttributeList::FunctionIndex,
1946                       llvm::Attribute::NoUnwind);
1947   // Attach readnone and readonly attributes.
1948   if (!HasSideEffect) {
1949     if (ReadNone)
1950       Result.addAttribute(llvm::AttributeList::FunctionIndex,
1951                           llvm::Attribute::ReadNone);
1952     else if (ReadOnly)
1953       Result.addAttribute(llvm::AttributeList::FunctionIndex,
1954                           llvm::Attribute::ReadOnly);
1955   }
1956 
1957   // Slap the source location of the inline asm into a !srcloc metadata on the
1958   // call.
1959   if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(&S))
1960     Result.setMetadata("srcloc",
1961                        getAsmSrcLocInfo(gccAsmStmt->getAsmString(), CGF));
1962   else {
1963     // At least put the line number on MS inline asm blobs.
1964     llvm::Constant *Loc = llvm::ConstantInt::get(CGF.Int32Ty,
1965                                         S.getAsmLoc().getRawEncoding());
1966     Result.setMetadata("srcloc",
1967                        llvm::MDNode::get(CGF.getLLVMContext(),
1968                                          llvm::ConstantAsMetadata::get(Loc)));
1969   }
1970 
1971   if (CGF.getLangOpts().assumeFunctionsAreConvergent())
1972     // Conservatively, mark all inline asm blocks in CUDA or OpenCL as
1973     // convergent (meaning, they may call an intrinsically convergent op, such
1974     // as bar.sync, and so can't have certain optimizations applied around
1975     // them).
1976     Result.addAttribute(llvm::AttributeList::FunctionIndex,
1977                         llvm::Attribute::Convergent);
1978   // Extract all of the register value results from the asm.
1979   if (ResultRegTypes.size() == 1) {
1980     RegResults.push_back(&Result);
1981   } else {
1982     for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) {
1983       llvm::Value *Tmp = CGF.Builder.CreateExtractValue(&Result, i, "asmresult");
1984       RegResults.push_back(Tmp);
1985     }
1986   }
1987 }
1988 
1989 void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
1990   // Assemble the final asm string.
1991   std::string AsmString = S.generateAsmString(getContext());
1992 
1993   // Get all the output and input constraints together.
1994   SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
1995   SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
1996 
1997   for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
1998     StringRef Name;
1999     if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
2000       Name = GAS->getOutputName(i);
2001     TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i), Name);
2002     bool IsValid = getTarget().validateOutputConstraint(Info); (void)IsValid;
2003     assert(IsValid && "Failed to parse output constraint");
2004     OutputConstraintInfos.push_back(Info);
2005   }
2006 
2007   for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
2008     StringRef Name;
2009     if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
2010       Name = GAS->getInputName(i);
2011     TargetInfo::ConstraintInfo Info(S.getInputConstraint(i), Name);
2012     bool IsValid =
2013       getTarget().validateInputConstraint(OutputConstraintInfos, Info);
2014     assert(IsValid && "Failed to parse input constraint"); (void)IsValid;
2015     InputConstraintInfos.push_back(Info);
2016   }
2017 
2018   std::string Constraints;
2019 
2020   std::vector<LValue> ResultRegDests;
2021   std::vector<QualType> ResultRegQualTys;
2022   std::vector<llvm::Type *> ResultRegTypes;
2023   std::vector<llvm::Type *> ResultTruncRegTypes;
2024   std::vector<llvm::Type *> ArgTypes;
2025   std::vector<llvm::Value*> Args;
2026   llvm::BitVector ResultTypeRequiresCast;
2027 
2028   // Keep track of inout constraints.
2029   std::string InOutConstraints;
2030   std::vector<llvm::Value*> InOutArgs;
2031   std::vector<llvm::Type*> InOutArgTypes;
2032 
2033   // Keep track of out constraints for tied input operand.
2034   std::vector<std::string> OutputConstraints;
2035 
2036   // An inline asm can be marked readonly if it meets the following conditions:
2037   //  - it doesn't have any sideeffects
2038   //  - it doesn't clobber memory
2039   //  - it doesn't return a value by-reference
2040   // It can be marked readnone if it doesn't have any input memory constraints
2041   // in addition to meeting the conditions listed above.
2042   bool ReadOnly = true, ReadNone = true;
2043 
2044   for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
2045     TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
2046 
2047     // Simplify the output constraint.
2048     std::string OutputConstraint(S.getOutputConstraint(i));
2049     OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1,
2050                                           getTarget(), &OutputConstraintInfos);
2051 
2052     const Expr *OutExpr = S.getOutputExpr(i);
2053     OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
2054 
2055     OutputConstraint = AddVariableConstraints(OutputConstraint, *OutExpr,
2056                                               getTarget(), CGM, S,
2057                                               Info.earlyClobber());
2058     OutputConstraints.push_back(OutputConstraint);
2059     LValue Dest = EmitLValue(OutExpr);
2060     if (!Constraints.empty())
2061       Constraints += ',';
2062 
2063     // If this is a register output, then make the inline asm return it
2064     // by-value.  If this is a memory result, return the value by-reference.
2065     bool isScalarizableAggregate =
2066         hasAggregateEvaluationKind(OutExpr->getType());
2067     if (!Info.allowsMemory() && (hasScalarEvaluationKind(OutExpr->getType()) ||
2068                                  isScalarizableAggregate)) {
2069       Constraints += "=" + OutputConstraint;
2070       ResultRegQualTys.push_back(OutExpr->getType());
2071       ResultRegDests.push_back(Dest);
2072       ResultTruncRegTypes.push_back(ConvertTypeForMem(OutExpr->getType()));
2073       if (Info.allowsRegister() && isScalarizableAggregate) {
2074         ResultTypeRequiresCast.push_back(true);
2075         unsigned Size = getContext().getTypeSize(OutExpr->getType());
2076         llvm::Type *ConvTy = llvm::IntegerType::get(getLLVMContext(), Size);
2077         ResultRegTypes.push_back(ConvTy);
2078       } else {
2079         ResultTypeRequiresCast.push_back(false);
2080         ResultRegTypes.push_back(ResultTruncRegTypes.back());
2081       }
2082       // If this output is tied to an input, and if the input is larger, then
2083       // we need to set the actual result type of the inline asm node to be the
2084       // same as the input type.
2085       if (Info.hasMatchingInput()) {
2086         unsigned InputNo;
2087         for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) {
2088           TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo];
2089           if (Input.hasTiedOperand() && Input.getTiedOperand() == i)
2090             break;
2091         }
2092         assert(InputNo != S.getNumInputs() && "Didn't find matching input!");
2093 
2094         QualType InputTy = S.getInputExpr(InputNo)->getType();
2095         QualType OutputType = OutExpr->getType();
2096 
2097         uint64_t InputSize = getContext().getTypeSize(InputTy);
2098         if (getContext().getTypeSize(OutputType) < InputSize) {
2099           // Form the asm to return the value as a larger integer or fp type.
2100           ResultRegTypes.back() = ConvertType(InputTy);
2101         }
2102       }
2103       if (llvm::Type* AdjTy =
2104             getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
2105                                                  ResultRegTypes.back()))
2106         ResultRegTypes.back() = AdjTy;
2107       else {
2108         CGM.getDiags().Report(S.getAsmLoc(),
2109                               diag::err_asm_invalid_type_in_input)
2110             << OutExpr->getType() << OutputConstraint;
2111       }
2112 
2113       // Update largest vector width for any vector types.
2114       if (auto *VT = dyn_cast<llvm::VectorType>(ResultRegTypes.back()))
2115         LargestVectorWidth =
2116             std::max((uint64_t)LargestVectorWidth,
2117                      VT->getPrimitiveSizeInBits().getKnownMinSize());
2118     } else {
2119       ArgTypes.push_back(Dest.getAddress(*this).getType());
2120       Args.push_back(Dest.getPointer(*this));
2121       Constraints += "=*";
2122       Constraints += OutputConstraint;
2123       ReadOnly = ReadNone = false;
2124     }
2125 
2126     if (Info.isReadWrite()) {
2127       InOutConstraints += ',';
2128 
2129       const Expr *InputExpr = S.getOutputExpr(i);
2130       llvm::Value *Arg = EmitAsmInputLValue(Info, Dest, InputExpr->getType(),
2131                                             InOutConstraints,
2132                                             InputExpr->getExprLoc());
2133 
2134       if (llvm::Type* AdjTy =
2135           getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
2136                                                Arg->getType()))
2137         Arg = Builder.CreateBitCast(Arg, AdjTy);
2138 
2139       // Update largest vector width for any vector types.
2140       if (auto *VT = dyn_cast<llvm::VectorType>(Arg->getType()))
2141         LargestVectorWidth =
2142             std::max((uint64_t)LargestVectorWidth,
2143                      VT->getPrimitiveSizeInBits().getKnownMinSize());
2144       if (Info.allowsRegister())
2145         InOutConstraints += llvm::utostr(i);
2146       else
2147         InOutConstraints += OutputConstraint;
2148 
2149       InOutArgTypes.push_back(Arg->getType());
2150       InOutArgs.push_back(Arg);
2151     }
2152   }
2153 
2154   // If this is a Microsoft-style asm blob, store the return registers (EAX:EDX)
2155   // to the return value slot. Only do this when returning in registers.
2156   if (isa<MSAsmStmt>(&S)) {
2157     const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
2158     if (RetAI.isDirect() || RetAI.isExtend()) {
2159       // Make a fake lvalue for the return value slot.
2160       LValue ReturnSlot = MakeAddrLValue(ReturnValue, FnRetTy);
2161       CGM.getTargetCodeGenInfo().addReturnRegisterOutputs(
2162           *this, ReturnSlot, Constraints, ResultRegTypes, ResultTruncRegTypes,
2163           ResultRegDests, AsmString, S.getNumOutputs());
2164       SawAsmBlock = true;
2165     }
2166   }
2167 
2168   for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
2169     const Expr *InputExpr = S.getInputExpr(i);
2170 
2171     TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
2172 
2173     if (Info.allowsMemory())
2174       ReadNone = false;
2175 
2176     if (!Constraints.empty())
2177       Constraints += ',';
2178 
2179     // Simplify the input constraint.
2180     std::string InputConstraint(S.getInputConstraint(i));
2181     InputConstraint = SimplifyConstraint(InputConstraint.c_str(), getTarget(),
2182                                          &OutputConstraintInfos);
2183 
2184     InputConstraint = AddVariableConstraints(
2185         InputConstraint, *InputExpr->IgnoreParenNoopCasts(getContext()),
2186         getTarget(), CGM, S, false /* No EarlyClobber */);
2187 
2188     std::string ReplaceConstraint (InputConstraint);
2189     llvm::Value *Arg = EmitAsmInput(Info, InputExpr, Constraints);
2190 
2191     // If this input argument is tied to a larger output result, extend the
2192     // input to be the same size as the output.  The LLVM backend wants to see
2193     // the input and output of a matching constraint be the same size.  Note
2194     // that GCC does not define what the top bits are here.  We use zext because
2195     // that is usually cheaper, but LLVM IR should really get an anyext someday.
2196     if (Info.hasTiedOperand()) {
2197       unsigned Output = Info.getTiedOperand();
2198       QualType OutputType = S.getOutputExpr(Output)->getType();
2199       QualType InputTy = InputExpr->getType();
2200 
2201       if (getContext().getTypeSize(OutputType) >
2202           getContext().getTypeSize(InputTy)) {
2203         // Use ptrtoint as appropriate so that we can do our extension.
2204         if (isa<llvm::PointerType>(Arg->getType()))
2205           Arg = Builder.CreatePtrToInt(Arg, IntPtrTy);
2206         llvm::Type *OutputTy = ConvertType(OutputType);
2207         if (isa<llvm::IntegerType>(OutputTy))
2208           Arg = Builder.CreateZExt(Arg, OutputTy);
2209         else if (isa<llvm::PointerType>(OutputTy))
2210           Arg = Builder.CreateZExt(Arg, IntPtrTy);
2211         else {
2212           assert(OutputTy->isFloatingPointTy() && "Unexpected output type");
2213           Arg = Builder.CreateFPExt(Arg, OutputTy);
2214         }
2215       }
2216       // Deal with the tied operands' constraint code in adjustInlineAsmType.
2217       ReplaceConstraint = OutputConstraints[Output];
2218     }
2219     if (llvm::Type* AdjTy =
2220           getTargetHooks().adjustInlineAsmType(*this, ReplaceConstraint,
2221                                                    Arg->getType()))
2222       Arg = Builder.CreateBitCast(Arg, AdjTy);
2223     else
2224       CGM.getDiags().Report(S.getAsmLoc(), diag::err_asm_invalid_type_in_input)
2225           << InputExpr->getType() << InputConstraint;
2226 
2227     // Update largest vector width for any vector types.
2228     if (auto *VT = dyn_cast<llvm::VectorType>(Arg->getType()))
2229       LargestVectorWidth =
2230           std::max((uint64_t)LargestVectorWidth,
2231                    VT->getPrimitiveSizeInBits().getKnownMinSize());
2232 
2233     ArgTypes.push_back(Arg->getType());
2234     Args.push_back(Arg);
2235     Constraints += InputConstraint;
2236   }
2237 
2238   // Labels
2239   SmallVector<llvm::BasicBlock *, 16> Transfer;
2240   llvm::BasicBlock *Fallthrough = nullptr;
2241   bool IsGCCAsmGoto = false;
2242   if (const auto *GS =  dyn_cast<GCCAsmStmt>(&S)) {
2243     IsGCCAsmGoto = GS->isAsmGoto();
2244     if (IsGCCAsmGoto) {
2245       for (const auto *E : GS->labels()) {
2246         JumpDest Dest = getJumpDestForLabel(E->getLabel());
2247         Transfer.push_back(Dest.getBlock());
2248         llvm::BlockAddress *BA =
2249             llvm::BlockAddress::get(CurFn, Dest.getBlock());
2250         Args.push_back(BA);
2251         ArgTypes.push_back(BA->getType());
2252         if (!Constraints.empty())
2253           Constraints += ',';
2254         Constraints += 'X';
2255       }
2256       Fallthrough = createBasicBlock("asm.fallthrough");
2257     }
2258   }
2259 
2260   // Append the "input" part of inout constraints last.
2261   for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
2262     ArgTypes.push_back(InOutArgTypes[i]);
2263     Args.push_back(InOutArgs[i]);
2264   }
2265   Constraints += InOutConstraints;
2266 
2267   // Clobbers
2268   for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
2269     StringRef Clobber = S.getClobber(i);
2270 
2271     if (Clobber == "memory")
2272       ReadOnly = ReadNone = false;
2273     else if (Clobber != "cc") {
2274       Clobber = getTarget().getNormalizedGCCRegisterName(Clobber);
2275       if (CGM.getCodeGenOpts().StackClashProtector &&
2276           getTarget().isSPRegName(Clobber)) {
2277         CGM.getDiags().Report(S.getAsmLoc(),
2278                               diag::warn_stack_clash_protection_inline_asm);
2279       }
2280     }
2281 
2282     if (!Constraints.empty())
2283       Constraints += ',';
2284 
2285     Constraints += "~{";
2286     Constraints += Clobber;
2287     Constraints += '}';
2288   }
2289 
2290   // Add machine specific clobbers
2291   std::string MachineClobbers = getTarget().getClobbers();
2292   if (!MachineClobbers.empty()) {
2293     if (!Constraints.empty())
2294       Constraints += ',';
2295     Constraints += MachineClobbers;
2296   }
2297 
2298   llvm::Type *ResultType;
2299   if (ResultRegTypes.empty())
2300     ResultType = VoidTy;
2301   else if (ResultRegTypes.size() == 1)
2302     ResultType = ResultRegTypes[0];
2303   else
2304     ResultType = llvm::StructType::get(getLLVMContext(), ResultRegTypes);
2305 
2306   llvm::FunctionType *FTy =
2307     llvm::FunctionType::get(ResultType, ArgTypes, false);
2308 
2309   bool HasSideEffect = S.isVolatile() || S.getNumOutputs() == 0;
2310   llvm::InlineAsm::AsmDialect AsmDialect = isa<MSAsmStmt>(&S) ?
2311     llvm::InlineAsm::AD_Intel : llvm::InlineAsm::AD_ATT;
2312   llvm::InlineAsm *IA =
2313     llvm::InlineAsm::get(FTy, AsmString, Constraints, HasSideEffect,
2314                          /* IsAlignStack */ false, AsmDialect);
2315   std::vector<llvm::Value*> RegResults;
2316   if (IsGCCAsmGoto) {
2317     llvm::CallBrInst *Result =
2318         Builder.CreateCallBr(IA, Fallthrough, Transfer, Args);
2319     EmitBlock(Fallthrough);
2320     UpdateAsmCallInst(cast<llvm::CallBase>(*Result), HasSideEffect, ReadOnly,
2321                       ReadNone, S, ResultRegTypes, *this, RegResults);
2322   } else {
2323     llvm::CallInst *Result =
2324         Builder.CreateCall(IA, Args, getBundlesForFunclet(IA));
2325     UpdateAsmCallInst(cast<llvm::CallBase>(*Result), HasSideEffect, ReadOnly,
2326                       ReadNone, S, ResultRegTypes, *this, RegResults);
2327   }
2328 
2329   assert(RegResults.size() == ResultRegTypes.size());
2330   assert(RegResults.size() == ResultTruncRegTypes.size());
2331   assert(RegResults.size() == ResultRegDests.size());
2332   // ResultRegDests can be also populated by addReturnRegisterOutputs() above,
2333   // in which case its size may grow.
2334   assert(ResultTypeRequiresCast.size() <= ResultRegDests.size());
2335   for (unsigned i = 0, e = RegResults.size(); i != e; ++i) {
2336     llvm::Value *Tmp = RegResults[i];
2337 
2338     // If the result type of the LLVM IR asm doesn't match the result type of
2339     // the expression, do the conversion.
2340     if (ResultRegTypes[i] != ResultTruncRegTypes[i]) {
2341       llvm::Type *TruncTy = ResultTruncRegTypes[i];
2342 
2343       // Truncate the integer result to the right size, note that TruncTy can be
2344       // a pointer.
2345       if (TruncTy->isFloatingPointTy())
2346         Tmp = Builder.CreateFPTrunc(Tmp, TruncTy);
2347       else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) {
2348         uint64_t ResSize = CGM.getDataLayout().getTypeSizeInBits(TruncTy);
2349         Tmp = Builder.CreateTrunc(Tmp,
2350                    llvm::IntegerType::get(getLLVMContext(), (unsigned)ResSize));
2351         Tmp = Builder.CreateIntToPtr(Tmp, TruncTy);
2352       } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) {
2353         uint64_t TmpSize =CGM.getDataLayout().getTypeSizeInBits(Tmp->getType());
2354         Tmp = Builder.CreatePtrToInt(Tmp,
2355                    llvm::IntegerType::get(getLLVMContext(), (unsigned)TmpSize));
2356         Tmp = Builder.CreateTrunc(Tmp, TruncTy);
2357       } else if (TruncTy->isIntegerTy()) {
2358         Tmp = Builder.CreateZExtOrTrunc(Tmp, TruncTy);
2359       } else if (TruncTy->isVectorTy()) {
2360         Tmp = Builder.CreateBitCast(Tmp, TruncTy);
2361       }
2362     }
2363 
2364     LValue Dest = ResultRegDests[i];
2365     // ResultTypeRequiresCast elements correspond to the first
2366     // ResultTypeRequiresCast.size() elements of RegResults.
2367     if ((i < ResultTypeRequiresCast.size()) && ResultTypeRequiresCast[i]) {
2368       unsigned Size = getContext().getTypeSize(ResultRegQualTys[i]);
2369       Address A = Builder.CreateBitCast(Dest.getAddress(*this),
2370                                         ResultRegTypes[i]->getPointerTo());
2371       QualType Ty = getContext().getIntTypeForBitwidth(Size, /*Signed*/ false);
2372       if (Ty.isNull()) {
2373         const Expr *OutExpr = S.getOutputExpr(i);
2374         CGM.Error(
2375             OutExpr->getExprLoc(),
2376             "impossible constraint in asm: can't store value into a register");
2377         return;
2378       }
2379       Dest = MakeAddrLValue(A, Ty);
2380     }
2381     EmitStoreThroughLValue(RValue::get(Tmp), Dest);
2382   }
2383 }
2384 
2385 LValue CodeGenFunction::InitCapturedStruct(const CapturedStmt &S) {
2386   const RecordDecl *RD = S.getCapturedRecordDecl();
2387   QualType RecordTy = getContext().getRecordType(RD);
2388 
2389   // Initialize the captured struct.
2390   LValue SlotLV =
2391     MakeAddrLValue(CreateMemTemp(RecordTy, "agg.captured"), RecordTy);
2392 
2393   RecordDecl::field_iterator CurField = RD->field_begin();
2394   for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
2395                                                  E = S.capture_init_end();
2396        I != E; ++I, ++CurField) {
2397     LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
2398     if (CurField->hasCapturedVLAType()) {
2399       auto VAT = CurField->getCapturedVLAType();
2400       EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
2401     } else {
2402       EmitInitializerForField(*CurField, LV, *I);
2403     }
2404   }
2405 
2406   return SlotLV;
2407 }
2408 
2409 /// Generate an outlined function for the body of a CapturedStmt, store any
2410 /// captured variables into the captured struct, and call the outlined function.
2411 llvm::Function *
2412 CodeGenFunction::EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K) {
2413   LValue CapStruct = InitCapturedStruct(S);
2414 
2415   // Emit the CapturedDecl
2416   CodeGenFunction CGF(CGM, true);
2417   CGCapturedStmtRAII CapInfoRAII(CGF, new CGCapturedStmtInfo(S, K));
2418   llvm::Function *F = CGF.GenerateCapturedStmtFunction(S);
2419   delete CGF.CapturedStmtInfo;
2420 
2421   // Emit call to the helper function.
2422   EmitCallOrInvoke(F, CapStruct.getPointer(*this));
2423 
2424   return F;
2425 }
2426 
2427 Address CodeGenFunction::GenerateCapturedStmtArgument(const CapturedStmt &S) {
2428   LValue CapStruct = InitCapturedStruct(S);
2429   return CapStruct.getAddress(*this);
2430 }
2431 
2432 /// Creates the outlined function for a CapturedStmt.
2433 llvm::Function *
2434 CodeGenFunction::GenerateCapturedStmtFunction(const CapturedStmt &S) {
2435   assert(CapturedStmtInfo &&
2436     "CapturedStmtInfo should be set when generating the captured function");
2437   const CapturedDecl *CD = S.getCapturedDecl();
2438   const RecordDecl *RD = S.getCapturedRecordDecl();
2439   SourceLocation Loc = S.getBeginLoc();
2440   assert(CD->hasBody() && "missing CapturedDecl body");
2441 
2442   // Build the argument list.
2443   ASTContext &Ctx = CGM.getContext();
2444   FunctionArgList Args;
2445   Args.append(CD->param_begin(), CD->param_end());
2446 
2447   // Create the function declaration.
2448   const CGFunctionInfo &FuncInfo =
2449     CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Args);
2450   llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
2451 
2452   llvm::Function *F =
2453     llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
2454                            CapturedStmtInfo->getHelperName(), &CGM.getModule());
2455   CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
2456   if (CD->isNothrow())
2457     F->addFnAttr(llvm::Attribute::NoUnwind);
2458 
2459   // Generate the function.
2460   StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args, CD->getLocation(),
2461                 CD->getBody()->getBeginLoc());
2462   // Set the context parameter in CapturedStmtInfo.
2463   Address DeclPtr = GetAddrOfLocalVar(CD->getContextParam());
2464   CapturedStmtInfo->setContextValue(Builder.CreateLoad(DeclPtr));
2465 
2466   // Initialize variable-length arrays.
2467   LValue Base = MakeNaturalAlignAddrLValue(CapturedStmtInfo->getContextValue(),
2468                                            Ctx.getTagDeclType(RD));
2469   for (auto *FD : RD->fields()) {
2470     if (FD->hasCapturedVLAType()) {
2471       auto *ExprArg =
2472           EmitLoadOfLValue(EmitLValueForField(Base, FD), S.getBeginLoc())
2473               .getScalarVal();
2474       auto VAT = FD->getCapturedVLAType();
2475       VLASizeMap[VAT->getSizeExpr()] = ExprArg;
2476     }
2477   }
2478 
2479   // If 'this' is captured, load it into CXXThisValue.
2480   if (CapturedStmtInfo->isCXXThisExprCaptured()) {
2481     FieldDecl *FD = CapturedStmtInfo->getThisFieldDecl();
2482     LValue ThisLValue = EmitLValueForField(Base, FD);
2483     CXXThisValue = EmitLoadOfLValue(ThisLValue, Loc).getScalarVal();
2484   }
2485 
2486   PGO.assignRegionCounters(GlobalDecl(CD), F);
2487   CapturedStmtInfo->EmitBody(*this, CD->getBody());
2488   FinishFunction(CD->getBodyRBrace());
2489 
2490   return F;
2491 }
2492