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