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