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