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