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   // Branch to the loop header again.
734   EmitBranch(LoopHeader.getBlock());
735 
736   LoopStack.pop();
737 
738   // Emit the exit block.
739   EmitBlock(LoopExit.getBlock(), true);
740 
741   // The LoopHeader typically is just a branch if we skipped emitting
742   // a branch, try to erase it.
743   if (!EmitBoolCondBranch)
744     SimplifyForwardingBlocks(LoopHeader.getBlock());
745 }
746 
747 void CodeGenFunction::EmitDoStmt(const DoStmt &S,
748                                  const ArrayRef<const Attr *> &DoAttrs) {
749   JumpDest LoopExit = getJumpDestInCurrentScope("do.end");
750   JumpDest LoopCond = getJumpDestInCurrentScope("do.cond");
751 
752   RegionCounter Cnt = getPGORegionCounter(&S);
753 
754   // Store the blocks to use for break and continue.
755   BreakContinueStack.push_back(BreakContinue(LoopExit, LoopCond));
756 
757   // Emit the body of the loop.
758   llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
759 
760   LoopStack.push(LoopBody);
761 
762   EmitBlockWithFallThrough(LoopBody, Cnt);
763   {
764     RunCleanupsScope BodyScope(*this);
765     EmitStmt(S.getBody());
766   }
767 
768   EmitBlock(LoopCond.getBlock());
769 
770   // C99 6.8.5.2: "The evaluation of the controlling expression takes place
771   // after each execution of the loop body."
772 
773   // Evaluate the conditional in the while header.
774   // C99 6.8.5p2/p4: The first substatement is executed if the expression
775   // compares unequal to 0.  The condition must be a scalar type.
776   llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
777 
778   BreakContinueStack.pop_back();
779 
780   // "do {} while (0)" is common in macros, avoid extra blocks.  Be sure
781   // to correctly handle break/continue though.
782   bool EmitBoolCondBranch = true;
783   if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
784     if (C->isZero())
785       EmitBoolCondBranch = false;
786 
787   // As long as the condition is true, iterate the loop.
788   if (EmitBoolCondBranch) {
789     llvm::BranchInst *CondBr =
790         Builder.CreateCondBr(BoolCondVal, LoopBody, LoopExit.getBlock(),
791                              PGO.createLoopWeights(S.getCond(), Cnt));
792 
793     // Attach metadata to loop body conditional branch.
794     EmitCondBrHints(LoopBody->getContext(), CondBr, DoAttrs);
795   }
796 
797   LoopStack.pop();
798 
799   // Emit the exit block.
800   EmitBlock(LoopExit.getBlock());
801 
802   // The DoCond block typically is just a branch if we skipped
803   // emitting a branch, try to erase it.
804   if (!EmitBoolCondBranch)
805     SimplifyForwardingBlocks(LoopCond.getBlock());
806 }
807 
808 void CodeGenFunction::EmitForStmt(const ForStmt &S,
809                                   const ArrayRef<const Attr *> &ForAttrs) {
810   JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
811 
812   RunCleanupsScope ForScope(*this);
813 
814   CGDebugInfo *DI = getDebugInfo();
815   if (DI)
816     DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
817 
818   // Evaluate the first part before the loop.
819   if (S.getInit())
820     EmitStmt(S.getInit());
821 
822   RegionCounter Cnt = getPGORegionCounter(&S);
823 
824   // Start the loop with a block that tests the condition.
825   // If there's an increment, the continue scope will be overwritten
826   // later.
827   JumpDest Continue = getJumpDestInCurrentScope("for.cond");
828   llvm::BasicBlock *CondBlock = Continue.getBlock();
829   EmitBlock(CondBlock);
830 
831   LoopStack.push(CondBlock);
832 
833   // If the for loop doesn't have an increment we can just use the
834   // condition as the continue block.  Otherwise we'll need to create
835   // a block for it (in the current scope, i.e. in the scope of the
836   // condition), and that we will become our continue block.
837   if (S.getInc())
838     Continue = getJumpDestInCurrentScope("for.inc");
839 
840   // Store the blocks to use for break and continue.
841   BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
842 
843   // Create a cleanup scope for the condition variable cleanups.
844   RunCleanupsScope ConditionScope(*this);
845 
846   if (S.getCond()) {
847     // If the for statement has a condition scope, emit the local variable
848     // declaration.
849     if (S.getConditionVariable()) {
850       EmitAutoVarDecl(*S.getConditionVariable());
851     }
852 
853     llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
854     // If there are any cleanups between here and the loop-exit scope,
855     // create a block to stage a loop exit along.
856     if (ForScope.requiresCleanups())
857       ExitBlock = createBasicBlock("for.cond.cleanup");
858 
859     // As long as the condition is true, iterate the loop.
860     llvm::BasicBlock *ForBody = createBasicBlock("for.body");
861 
862     // C99 6.8.5p2/p4: The first substatement is executed if the expression
863     // compares unequal to 0.  The condition must be a scalar type.
864     llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
865     llvm::BranchInst *CondBr =
866         Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock,
867                              PGO.createLoopWeights(S.getCond(), Cnt));
868 
869     // Attach metadata to loop body conditional branch.
870     EmitCondBrHints(ForBody->getContext(), CondBr, ForAttrs);
871 
872     if (ExitBlock != LoopExit.getBlock()) {
873       EmitBlock(ExitBlock);
874       EmitBranchThroughCleanup(LoopExit);
875     }
876 
877     EmitBlock(ForBody);
878   } else {
879     // Treat it as a non-zero constant.  Don't even create a new block for the
880     // body, just fall into it.
881   }
882   Cnt.beginRegion(Builder);
883 
884   {
885     // Create a separate cleanup scope for the body, in case it is not
886     // a compound statement.
887     RunCleanupsScope BodyScope(*this);
888     EmitStmt(S.getBody());
889   }
890 
891   // If there is an increment, emit it next.
892   if (S.getInc()) {
893     EmitBlock(Continue.getBlock());
894     EmitStmt(S.getInc());
895   }
896 
897   BreakContinueStack.pop_back();
898 
899   ConditionScope.ForceCleanup();
900   EmitBranch(CondBlock);
901 
902   ForScope.ForceCleanup();
903 
904   if (DI)
905     DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
906 
907   LoopStack.pop();
908 
909   // Emit the fall-through block.
910   EmitBlock(LoopExit.getBlock(), true);
911 }
912 
913 void
914 CodeGenFunction::EmitCXXForRangeStmt(const CXXForRangeStmt &S,
915                                      const ArrayRef<const Attr *> &ForAttrs) {
916   JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
917 
918   RunCleanupsScope ForScope(*this);
919 
920   CGDebugInfo *DI = getDebugInfo();
921   if (DI)
922     DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
923 
924   // Evaluate the first pieces before the loop.
925   EmitStmt(S.getRangeStmt());
926   EmitStmt(S.getBeginEndStmt());
927 
928   RegionCounter Cnt = getPGORegionCounter(&S);
929 
930   // Start the loop with a block that tests the condition.
931   // If there's an increment, the continue scope will be overwritten
932   // later.
933   llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
934   EmitBlock(CondBlock);
935 
936   LoopStack.push(CondBlock);
937 
938   // If there are any cleanups between here and the loop-exit scope,
939   // create a block to stage a loop exit along.
940   llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
941   if (ForScope.requiresCleanups())
942     ExitBlock = createBasicBlock("for.cond.cleanup");
943 
944   // The loop body, consisting of the specified body and the loop variable.
945   llvm::BasicBlock *ForBody = createBasicBlock("for.body");
946 
947   // The body is executed if the expression, contextually converted
948   // to bool, is true.
949   llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
950   llvm::BranchInst *CondBr = Builder.CreateCondBr(
951       BoolCondVal, ForBody, ExitBlock, PGO.createLoopWeights(S.getCond(), Cnt));
952 
953   // Attach metadata to loop body conditional branch.
954   EmitCondBrHints(ForBody->getContext(), CondBr, ForAttrs);
955 
956   if (ExitBlock != LoopExit.getBlock()) {
957     EmitBlock(ExitBlock);
958     EmitBranchThroughCleanup(LoopExit);
959   }
960 
961   EmitBlock(ForBody);
962   Cnt.beginRegion(Builder);
963 
964   // Create a block for the increment. In case of a 'continue', we jump there.
965   JumpDest Continue = getJumpDestInCurrentScope("for.inc");
966 
967   // Store the blocks to use for break and continue.
968   BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
969 
970   {
971     // Create a separate cleanup scope for the loop variable and body.
972     RunCleanupsScope BodyScope(*this);
973     EmitStmt(S.getLoopVarStmt());
974     EmitStmt(S.getBody());
975   }
976 
977   // If there is an increment, emit it next.
978   EmitBlock(Continue.getBlock());
979   EmitStmt(S.getInc());
980 
981   BreakContinueStack.pop_back();
982 
983   EmitBranch(CondBlock);
984 
985   ForScope.ForceCleanup();
986 
987   if (DI)
988     DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
989 
990   LoopStack.pop();
991 
992   // Emit the fall-through block.
993   EmitBlock(LoopExit.getBlock(), true);
994 }
995 
996 void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
997   if (RV.isScalar()) {
998     Builder.CreateStore(RV.getScalarVal(), ReturnValue);
999   } else if (RV.isAggregate()) {
1000     EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
1001   } else {
1002     EmitStoreOfComplex(RV.getComplexVal(),
1003                        MakeNaturalAlignAddrLValue(ReturnValue, Ty),
1004                        /*init*/ true);
1005   }
1006   EmitBranchThroughCleanup(ReturnBlock);
1007 }
1008 
1009 /// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
1010 /// if the function returns void, or may be missing one if the function returns
1011 /// non-void.  Fun stuff :).
1012 void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
1013   // Emit the result value, even if unused, to evalute the side effects.
1014   const Expr *RV = S.getRetValue();
1015 
1016   // Treat block literals in a return expression as if they appeared
1017   // in their own scope.  This permits a small, easily-implemented
1018   // exception to our over-conservative rules about not jumping to
1019   // statements following block literals with non-trivial cleanups.
1020   RunCleanupsScope cleanupScope(*this);
1021   if (const ExprWithCleanups *cleanups =
1022         dyn_cast_or_null<ExprWithCleanups>(RV)) {
1023     enterFullExpression(cleanups);
1024     RV = cleanups->getSubExpr();
1025   }
1026 
1027   // FIXME: Clean this up by using an LValue for ReturnTemp,
1028   // EmitStoreThroughLValue, and EmitAnyExpr.
1029   if (getLangOpts().ElideConstructors &&
1030       S.getNRVOCandidate() && S.getNRVOCandidate()->isNRVOVariable()) {
1031     // Apply the named return value optimization for this return statement,
1032     // which means doing nothing: the appropriate result has already been
1033     // constructed into the NRVO variable.
1034 
1035     // If there is an NRVO flag for this variable, set it to 1 into indicate
1036     // that the cleanup code should not destroy the variable.
1037     if (llvm::Value *NRVOFlag = NRVOFlags[S.getNRVOCandidate()])
1038       Builder.CreateStore(Builder.getTrue(), NRVOFlag);
1039   } else if (!ReturnValue || (RV && RV->getType()->isVoidType())) {
1040     // Make sure not to return anything, but evaluate the expression
1041     // for side effects.
1042     if (RV)
1043       EmitAnyExpr(RV);
1044   } else if (!RV) {
1045     // Do nothing (return value is left uninitialized)
1046   } else if (FnRetTy->isReferenceType()) {
1047     // If this function returns a reference, take the address of the expression
1048     // rather than the value.
1049     RValue Result = EmitReferenceBindingToExpr(RV);
1050     Builder.CreateStore(Result.getScalarVal(), ReturnValue);
1051   } else {
1052     switch (getEvaluationKind(RV->getType())) {
1053     case TEK_Scalar:
1054       Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
1055       break;
1056     case TEK_Complex:
1057       EmitComplexExprIntoLValue(RV,
1058                      MakeNaturalAlignAddrLValue(ReturnValue, RV->getType()),
1059                                 /*isInit*/ true);
1060       break;
1061     case TEK_Aggregate: {
1062       CharUnits Alignment = getContext().getTypeAlignInChars(RV->getType());
1063       EmitAggExpr(RV, AggValueSlot::forAddr(ReturnValue, Alignment,
1064                                             Qualifiers(),
1065                                             AggValueSlot::IsDestructed,
1066                                             AggValueSlot::DoesNotNeedGCBarriers,
1067                                             AggValueSlot::IsNotAliased));
1068       break;
1069     }
1070     }
1071   }
1072 
1073   ++NumReturnExprs;
1074   if (!RV || RV->isEvaluatable(getContext()))
1075     ++NumSimpleReturnExprs;
1076 
1077   cleanupScope.ForceCleanup();
1078   EmitBranchThroughCleanup(ReturnBlock);
1079 }
1080 
1081 void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
1082   // As long as debug info is modeled with instructions, we have to ensure we
1083   // have a place to insert here and write the stop point here.
1084   if (HaveInsertPoint())
1085     EmitStopPoint(&S);
1086 
1087   for (const auto *I : S.decls())
1088     EmitDecl(*I);
1089 }
1090 
1091 void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
1092   assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
1093 
1094   // If this code is reachable then emit a stop point (if generating
1095   // debug info). We have to do this ourselves because we are on the
1096   // "simple" statement path.
1097   if (HaveInsertPoint())
1098     EmitStopPoint(&S);
1099 
1100   EmitBranchThroughCleanup(BreakContinueStack.back().BreakBlock);
1101 }
1102 
1103 void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
1104   assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
1105 
1106   // If this code is reachable then emit a stop point (if generating
1107   // debug info). We have to do this ourselves because we are on the
1108   // "simple" statement path.
1109   if (HaveInsertPoint())
1110     EmitStopPoint(&S);
1111 
1112   EmitBranchThroughCleanup(BreakContinueStack.back().ContinueBlock);
1113 }
1114 
1115 /// EmitCaseStmtRange - If case statement range is not too big then
1116 /// add multiple cases to switch instruction, one for each value within
1117 /// the range. If range is too big then emit "if" condition check.
1118 void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
1119   assert(S.getRHS() && "Expected RHS value in CaseStmt");
1120 
1121   llvm::APSInt LHS = S.getLHS()->EvaluateKnownConstInt(getContext());
1122   llvm::APSInt RHS = S.getRHS()->EvaluateKnownConstInt(getContext());
1123 
1124   RegionCounter CaseCnt = getPGORegionCounter(&S);
1125 
1126   // Emit the code for this case. We do this first to make sure it is
1127   // properly chained from our predecessor before generating the
1128   // switch machinery to enter this block.
1129   llvm::BasicBlock *CaseDest = createBasicBlock("sw.bb");
1130   EmitBlockWithFallThrough(CaseDest, CaseCnt);
1131   EmitStmt(S.getSubStmt());
1132 
1133   // If range is empty, do nothing.
1134   if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
1135     return;
1136 
1137   llvm::APInt Range = RHS - LHS;
1138   // FIXME: parameters such as this should not be hardcoded.
1139   if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
1140     // Range is small enough to add multiple switch instruction cases.
1141     uint64_t Total = CaseCnt.getCount();
1142     unsigned NCases = Range.getZExtValue() + 1;
1143     // We only have one region counter for the entire set of cases here, so we
1144     // need to divide the weights evenly between the generated cases, ensuring
1145     // that the total weight is preserved. E.g., a weight of 5 over three cases
1146     // will be distributed as weights of 2, 2, and 1.
1147     uint64_t Weight = Total / NCases, Rem = Total % NCases;
1148     for (unsigned I = 0; I != NCases; ++I) {
1149       if (SwitchWeights)
1150         SwitchWeights->push_back(Weight + (Rem ? 1 : 0));
1151       if (Rem)
1152         Rem--;
1153       SwitchInsn->addCase(Builder.getInt(LHS), CaseDest);
1154       LHS++;
1155     }
1156     return;
1157   }
1158 
1159   // The range is too big. Emit "if" condition into a new block,
1160   // making sure to save and restore the current insertion point.
1161   llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
1162 
1163   // Push this test onto the chain of range checks (which terminates
1164   // in the default basic block). The switch's default will be changed
1165   // to the top of this chain after switch emission is complete.
1166   llvm::BasicBlock *FalseDest = CaseRangeBlock;
1167   CaseRangeBlock = createBasicBlock("sw.caserange");
1168 
1169   CurFn->getBasicBlockList().push_back(CaseRangeBlock);
1170   Builder.SetInsertPoint(CaseRangeBlock);
1171 
1172   // Emit range check.
1173   llvm::Value *Diff =
1174     Builder.CreateSub(SwitchInsn->getCondition(), Builder.getInt(LHS));
1175   llvm::Value *Cond =
1176     Builder.CreateICmpULE(Diff, Builder.getInt(Range), "inbounds");
1177 
1178   llvm::MDNode *Weights = nullptr;
1179   if (SwitchWeights) {
1180     uint64_t ThisCount = CaseCnt.getCount();
1181     uint64_t DefaultCount = (*SwitchWeights)[0];
1182     Weights = PGO.createBranchWeights(ThisCount, DefaultCount);
1183 
1184     // Since we're chaining the switch default through each large case range, we
1185     // need to update the weight for the default, ie, the first case, to include
1186     // this case.
1187     (*SwitchWeights)[0] += ThisCount;
1188   }
1189   Builder.CreateCondBr(Cond, CaseDest, FalseDest, Weights);
1190 
1191   // Restore the appropriate insertion point.
1192   if (RestoreBB)
1193     Builder.SetInsertPoint(RestoreBB);
1194   else
1195     Builder.ClearInsertionPoint();
1196 }
1197 
1198 void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
1199   // If there is no enclosing switch instance that we're aware of, then this
1200   // case statement and its block can be elided.  This situation only happens
1201   // when we've constant-folded the switch, are emitting the constant case,
1202   // and part of the constant case includes another case statement.  For
1203   // instance: switch (4) { case 4: do { case 5: } while (1); }
1204   if (!SwitchInsn) {
1205     EmitStmt(S.getSubStmt());
1206     return;
1207   }
1208 
1209   // Handle case ranges.
1210   if (S.getRHS()) {
1211     EmitCaseStmtRange(S);
1212     return;
1213   }
1214 
1215   RegionCounter CaseCnt = getPGORegionCounter(&S);
1216   llvm::ConstantInt *CaseVal =
1217     Builder.getInt(S.getLHS()->EvaluateKnownConstInt(getContext()));
1218 
1219   // If the body of the case is just a 'break', try to not emit an empty block.
1220   // If we're profiling or we're not optimizing, leave the block in for better
1221   // debug and coverage analysis.
1222   if (!CGM.getCodeGenOpts().ProfileInstrGenerate &&
1223       CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1224       isa<BreakStmt>(S.getSubStmt())) {
1225     JumpDest Block = BreakContinueStack.back().BreakBlock;
1226 
1227     // Only do this optimization if there are no cleanups that need emitting.
1228     if (isObviouslyBranchWithoutCleanups(Block)) {
1229       if (SwitchWeights)
1230         SwitchWeights->push_back(CaseCnt.getCount());
1231       SwitchInsn->addCase(CaseVal, Block.getBlock());
1232 
1233       // If there was a fallthrough into this case, make sure to redirect it to
1234       // the end of the switch as well.
1235       if (Builder.GetInsertBlock()) {
1236         Builder.CreateBr(Block.getBlock());
1237         Builder.ClearInsertionPoint();
1238       }
1239       return;
1240     }
1241   }
1242 
1243   llvm::BasicBlock *CaseDest = createBasicBlock("sw.bb");
1244   EmitBlockWithFallThrough(CaseDest, CaseCnt);
1245   if (SwitchWeights)
1246     SwitchWeights->push_back(CaseCnt.getCount());
1247   SwitchInsn->addCase(CaseVal, CaseDest);
1248 
1249   // Recursively emitting the statement is acceptable, but is not wonderful for
1250   // code where we have many case statements nested together, i.e.:
1251   //  case 1:
1252   //    case 2:
1253   //      case 3: etc.
1254   // Handling this recursively will create a new block for each case statement
1255   // that falls through to the next case which is IR intensive.  It also causes
1256   // deep recursion which can run into stack depth limitations.  Handle
1257   // sequential non-range case statements specially.
1258   const CaseStmt *CurCase = &S;
1259   const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
1260 
1261   // Otherwise, iteratively add consecutive cases to this switch stmt.
1262   while (NextCase && NextCase->getRHS() == nullptr) {
1263     CurCase = NextCase;
1264     llvm::ConstantInt *CaseVal =
1265       Builder.getInt(CurCase->getLHS()->EvaluateKnownConstInt(getContext()));
1266 
1267     CaseCnt = getPGORegionCounter(NextCase);
1268     if (SwitchWeights)
1269       SwitchWeights->push_back(CaseCnt.getCount());
1270     if (CGM.getCodeGenOpts().ProfileInstrGenerate) {
1271       CaseDest = createBasicBlock("sw.bb");
1272       EmitBlockWithFallThrough(CaseDest, CaseCnt);
1273     }
1274 
1275     SwitchInsn->addCase(CaseVal, CaseDest);
1276     NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt());
1277   }
1278 
1279   // Normal default recursion for non-cases.
1280   EmitStmt(CurCase->getSubStmt());
1281 }
1282 
1283 void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
1284   llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
1285   assert(DefaultBlock->empty() &&
1286          "EmitDefaultStmt: Default block already defined?");
1287 
1288   RegionCounter Cnt = getPGORegionCounter(&S);
1289   EmitBlockWithFallThrough(DefaultBlock, Cnt);
1290 
1291   EmitStmt(S.getSubStmt());
1292 }
1293 
1294 /// CollectStatementsForCase - Given the body of a 'switch' statement and a
1295 /// constant value that is being switched on, see if we can dead code eliminate
1296 /// the body of the switch to a simple series of statements to emit.  Basically,
1297 /// on a switch (5) we want to find these statements:
1298 ///    case 5:
1299 ///      printf(...);    <--
1300 ///      ++i;            <--
1301 ///      break;
1302 ///
1303 /// and add them to the ResultStmts vector.  If it is unsafe to do this
1304 /// transformation (for example, one of the elided statements contains a label
1305 /// that might be jumped to), return CSFC_Failure.  If we handled it and 'S'
1306 /// should include statements after it (e.g. the printf() line is a substmt of
1307 /// the case) then return CSFC_FallThrough.  If we handled it and found a break
1308 /// statement, then return CSFC_Success.
1309 ///
1310 /// If Case is non-null, then we are looking for the specified case, checking
1311 /// that nothing we jump over contains labels.  If Case is null, then we found
1312 /// the case and are looking for the break.
1313 ///
1314 /// If the recursive walk actually finds our Case, then we set FoundCase to
1315 /// true.
1316 ///
1317 enum CSFC_Result { CSFC_Failure, CSFC_FallThrough, CSFC_Success };
1318 static CSFC_Result CollectStatementsForCase(const Stmt *S,
1319                                             const SwitchCase *Case,
1320                                             bool &FoundCase,
1321                               SmallVectorImpl<const Stmt*> &ResultStmts) {
1322   // If this is a null statement, just succeed.
1323   if (!S)
1324     return Case ? CSFC_Success : CSFC_FallThrough;
1325 
1326   // If this is the switchcase (case 4: or default) that we're looking for, then
1327   // we're in business.  Just add the substatement.
1328   if (const SwitchCase *SC = dyn_cast<SwitchCase>(S)) {
1329     if (S == Case) {
1330       FoundCase = true;
1331       return CollectStatementsForCase(SC->getSubStmt(), nullptr, FoundCase,
1332                                       ResultStmts);
1333     }
1334 
1335     // Otherwise, this is some other case or default statement, just ignore it.
1336     return CollectStatementsForCase(SC->getSubStmt(), Case, FoundCase,
1337                                     ResultStmts);
1338   }
1339 
1340   // If we are in the live part of the code and we found our break statement,
1341   // return a success!
1342   if (!Case && isa<BreakStmt>(S))
1343     return CSFC_Success;
1344 
1345   // If this is a switch statement, then it might contain the SwitchCase, the
1346   // break, or neither.
1347   if (const CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
1348     // Handle this as two cases: we might be looking for the SwitchCase (if so
1349     // the skipped statements must be skippable) or we might already have it.
1350     CompoundStmt::const_body_iterator I = CS->body_begin(), E = CS->body_end();
1351     if (Case) {
1352       // Keep track of whether we see a skipped declaration.  The code could be
1353       // using the declaration even if it is skipped, so we can't optimize out
1354       // the decl if the kept statements might refer to it.
1355       bool HadSkippedDecl = false;
1356 
1357       // If we're looking for the case, just see if we can skip each of the
1358       // substatements.
1359       for (; Case && I != E; ++I) {
1360         HadSkippedDecl |= isa<DeclStmt>(*I);
1361 
1362         switch (CollectStatementsForCase(*I, Case, FoundCase, ResultStmts)) {
1363         case CSFC_Failure: return CSFC_Failure;
1364         case CSFC_Success:
1365           // A successful result means that either 1) that the statement doesn't
1366           // have the case and is skippable, or 2) does contain the case value
1367           // and also contains the break to exit the switch.  In the later case,
1368           // we just verify the rest of the statements are elidable.
1369           if (FoundCase) {
1370             // If we found the case and skipped declarations, we can't do the
1371             // optimization.
1372             if (HadSkippedDecl)
1373               return CSFC_Failure;
1374 
1375             for (++I; I != E; ++I)
1376               if (CodeGenFunction::ContainsLabel(*I, true))
1377                 return CSFC_Failure;
1378             return CSFC_Success;
1379           }
1380           break;
1381         case CSFC_FallThrough:
1382           // If we have a fallthrough condition, then we must have found the
1383           // case started to include statements.  Consider the rest of the
1384           // statements in the compound statement as candidates for inclusion.
1385           assert(FoundCase && "Didn't find case but returned fallthrough?");
1386           // We recursively found Case, so we're not looking for it anymore.
1387           Case = nullptr;
1388 
1389           // If we found the case and skipped declarations, we can't do the
1390           // optimization.
1391           if (HadSkippedDecl)
1392             return CSFC_Failure;
1393           break;
1394         }
1395       }
1396     }
1397 
1398     // If we have statements in our range, then we know that the statements are
1399     // live and need to be added to the set of statements we're tracking.
1400     for (; I != E; ++I) {
1401       switch (CollectStatementsForCase(*I, nullptr, FoundCase, ResultStmts)) {
1402       case CSFC_Failure: return CSFC_Failure;
1403       case CSFC_FallThrough:
1404         // A fallthrough result means that the statement was simple and just
1405         // included in ResultStmt, keep adding them afterwards.
1406         break;
1407       case CSFC_Success:
1408         // A successful result means that we found the break statement and
1409         // stopped statement inclusion.  We just ensure that any leftover stmts
1410         // are skippable and return success ourselves.
1411         for (++I; I != E; ++I)
1412           if (CodeGenFunction::ContainsLabel(*I, true))
1413             return CSFC_Failure;
1414         return CSFC_Success;
1415       }
1416     }
1417 
1418     return Case ? CSFC_Success : CSFC_FallThrough;
1419   }
1420 
1421   // Okay, this is some other statement that we don't handle explicitly, like a
1422   // for statement or increment etc.  If we are skipping over this statement,
1423   // just verify it doesn't have labels, which would make it invalid to elide.
1424   if (Case) {
1425     if (CodeGenFunction::ContainsLabel(S, true))
1426       return CSFC_Failure;
1427     return CSFC_Success;
1428   }
1429 
1430   // Otherwise, we want to include this statement.  Everything is cool with that
1431   // so long as it doesn't contain a break out of the switch we're in.
1432   if (CodeGenFunction::containsBreak(S)) return CSFC_Failure;
1433 
1434   // Otherwise, everything is great.  Include the statement and tell the caller
1435   // that we fall through and include the next statement as well.
1436   ResultStmts.push_back(S);
1437   return CSFC_FallThrough;
1438 }
1439 
1440 /// FindCaseStatementsForValue - Find the case statement being jumped to and
1441 /// then invoke CollectStatementsForCase to find the list of statements to emit
1442 /// for a switch on constant.  See the comment above CollectStatementsForCase
1443 /// for more details.
1444 static bool FindCaseStatementsForValue(const SwitchStmt &S,
1445                                        const llvm::APSInt &ConstantCondValue,
1446                                 SmallVectorImpl<const Stmt*> &ResultStmts,
1447                                        ASTContext &C,
1448                                        const SwitchCase *&ResultCase) {
1449   // First step, find the switch case that is being branched to.  We can do this
1450   // efficiently by scanning the SwitchCase list.
1451   const SwitchCase *Case = S.getSwitchCaseList();
1452   const DefaultStmt *DefaultCase = nullptr;
1453 
1454   for (; Case; Case = Case->getNextSwitchCase()) {
1455     // It's either a default or case.  Just remember the default statement in
1456     // case we're not jumping to any numbered cases.
1457     if (const DefaultStmt *DS = dyn_cast<DefaultStmt>(Case)) {
1458       DefaultCase = DS;
1459       continue;
1460     }
1461 
1462     // Check to see if this case is the one we're looking for.
1463     const CaseStmt *CS = cast<CaseStmt>(Case);
1464     // Don't handle case ranges yet.
1465     if (CS->getRHS()) return false;
1466 
1467     // If we found our case, remember it as 'case'.
1468     if (CS->getLHS()->EvaluateKnownConstInt(C) == ConstantCondValue)
1469       break;
1470   }
1471 
1472   // If we didn't find a matching case, we use a default if it exists, or we
1473   // elide the whole switch body!
1474   if (!Case) {
1475     // It is safe to elide the body of the switch if it doesn't contain labels
1476     // etc.  If it is safe, return successfully with an empty ResultStmts list.
1477     if (!DefaultCase)
1478       return !CodeGenFunction::ContainsLabel(&S);
1479     Case = DefaultCase;
1480   }
1481 
1482   // Ok, we know which case is being jumped to, try to collect all the
1483   // statements that follow it.  This can fail for a variety of reasons.  Also,
1484   // check to see that the recursive walk actually found our case statement.
1485   // Insane cases like this can fail to find it in the recursive walk since we
1486   // don't handle every stmt kind:
1487   // switch (4) {
1488   //   while (1) {
1489   //     case 4: ...
1490   bool FoundCase = false;
1491   ResultCase = Case;
1492   return CollectStatementsForCase(S.getBody(), Case, FoundCase,
1493                                   ResultStmts) != CSFC_Failure &&
1494          FoundCase;
1495 }
1496 
1497 void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
1498   // Handle nested switch statements.
1499   llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
1500   SmallVector<uint64_t, 16> *SavedSwitchWeights = SwitchWeights;
1501   llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
1502 
1503   // See if we can constant fold the condition of the switch and therefore only
1504   // emit the live case statement (if any) of the switch.
1505   llvm::APSInt ConstantCondValue;
1506   if (ConstantFoldsToSimpleInteger(S.getCond(), ConstantCondValue)) {
1507     SmallVector<const Stmt*, 4> CaseStmts;
1508     const SwitchCase *Case = nullptr;
1509     if (FindCaseStatementsForValue(S, ConstantCondValue, CaseStmts,
1510                                    getContext(), Case)) {
1511       if (Case) {
1512         RegionCounter CaseCnt = getPGORegionCounter(Case);
1513         CaseCnt.beginRegion(Builder);
1514       }
1515       RunCleanupsScope ExecutedScope(*this);
1516 
1517       // Emit the condition variable if needed inside the entire cleanup scope
1518       // used by this special case for constant folded switches.
1519       if (S.getConditionVariable())
1520         EmitAutoVarDecl(*S.getConditionVariable());
1521 
1522       // At this point, we are no longer "within" a switch instance, so
1523       // we can temporarily enforce this to ensure that any embedded case
1524       // statements are not emitted.
1525       SwitchInsn = nullptr;
1526 
1527       // Okay, we can dead code eliminate everything except this case.  Emit the
1528       // specified series of statements and we're good.
1529       for (unsigned i = 0, e = CaseStmts.size(); i != e; ++i)
1530         EmitStmt(CaseStmts[i]);
1531       RegionCounter ExitCnt = getPGORegionCounter(&S);
1532       ExitCnt.beginRegion(Builder);
1533 
1534       // Now we want to restore the saved switch instance so that nested
1535       // switches continue to function properly
1536       SwitchInsn = SavedSwitchInsn;
1537 
1538       return;
1539     }
1540   }
1541 
1542   JumpDest SwitchExit = getJumpDestInCurrentScope("sw.epilog");
1543 
1544   RunCleanupsScope ConditionScope(*this);
1545   if (S.getConditionVariable())
1546     EmitAutoVarDecl(*S.getConditionVariable());
1547   llvm::Value *CondV = EmitScalarExpr(S.getCond());
1548 
1549   // Create basic block to hold stuff that comes after switch
1550   // statement. We also need to create a default block now so that
1551   // explicit case ranges tests can have a place to jump to on
1552   // failure.
1553   llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
1554   SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
1555   if (PGO.haveRegionCounts()) {
1556     // Walk the SwitchCase list to find how many there are.
1557     uint64_t DefaultCount = 0;
1558     unsigned NumCases = 0;
1559     for (const SwitchCase *Case = S.getSwitchCaseList();
1560          Case;
1561          Case = Case->getNextSwitchCase()) {
1562       if (isa<DefaultStmt>(Case))
1563         DefaultCount = getPGORegionCounter(Case).getCount();
1564       NumCases += 1;
1565     }
1566     SwitchWeights = new SmallVector<uint64_t, 16>();
1567     SwitchWeights->reserve(NumCases);
1568     // The default needs to be first. We store the edge count, so we already
1569     // know the right weight.
1570     SwitchWeights->push_back(DefaultCount);
1571   }
1572   CaseRangeBlock = DefaultBlock;
1573 
1574   // Clear the insertion point to indicate we are in unreachable code.
1575   Builder.ClearInsertionPoint();
1576 
1577   // All break statements jump to NextBlock. If BreakContinueStack is non-empty
1578   // then reuse last ContinueBlock.
1579   JumpDest OuterContinue;
1580   if (!BreakContinueStack.empty())
1581     OuterContinue = BreakContinueStack.back().ContinueBlock;
1582 
1583   BreakContinueStack.push_back(BreakContinue(SwitchExit, OuterContinue));
1584 
1585   // Emit switch body.
1586   EmitStmt(S.getBody());
1587 
1588   BreakContinueStack.pop_back();
1589 
1590   // Update the default block in case explicit case range tests have
1591   // been chained on top.
1592   SwitchInsn->setDefaultDest(CaseRangeBlock);
1593 
1594   // If a default was never emitted:
1595   if (!DefaultBlock->getParent()) {
1596     // If we have cleanups, emit the default block so that there's a
1597     // place to jump through the cleanups from.
1598     if (ConditionScope.requiresCleanups()) {
1599       EmitBlock(DefaultBlock);
1600 
1601     // Otherwise, just forward the default block to the switch end.
1602     } else {
1603       DefaultBlock->replaceAllUsesWith(SwitchExit.getBlock());
1604       delete DefaultBlock;
1605     }
1606   }
1607 
1608   ConditionScope.ForceCleanup();
1609 
1610   // Emit continuation.
1611   EmitBlock(SwitchExit.getBlock(), true);
1612   RegionCounter ExitCnt = getPGORegionCounter(&S);
1613   ExitCnt.beginRegion(Builder);
1614 
1615   if (SwitchWeights) {
1616     assert(SwitchWeights->size() == 1 + SwitchInsn->getNumCases() &&
1617            "switch weights do not match switch cases");
1618     // If there's only one jump destination there's no sense weighting it.
1619     if (SwitchWeights->size() > 1)
1620       SwitchInsn->setMetadata(llvm::LLVMContext::MD_prof,
1621                               PGO.createBranchWeights(*SwitchWeights));
1622     delete SwitchWeights;
1623   }
1624   SwitchInsn = SavedSwitchInsn;
1625   SwitchWeights = SavedSwitchWeights;
1626   CaseRangeBlock = SavedCRBlock;
1627 }
1628 
1629 static std::string
1630 SimplifyConstraint(const char *Constraint, const TargetInfo &Target,
1631                  SmallVectorImpl<TargetInfo::ConstraintInfo> *OutCons=nullptr) {
1632   std::string Result;
1633 
1634   while (*Constraint) {
1635     switch (*Constraint) {
1636     default:
1637       Result += Target.convertConstraint(Constraint);
1638       break;
1639     // Ignore these
1640     case '*':
1641     case '?':
1642     case '!':
1643     case '=': // Will see this and the following in mult-alt constraints.
1644     case '+':
1645       break;
1646     case '#': // Ignore the rest of the constraint alternative.
1647       while (Constraint[1] && Constraint[1] != ',')
1648         Constraint++;
1649       break;
1650     case ',':
1651       Result += "|";
1652       break;
1653     case 'g':
1654       Result += "imr";
1655       break;
1656     case '[': {
1657       assert(OutCons &&
1658              "Must pass output names to constraints with a symbolic name");
1659       unsigned Index;
1660       bool result = Target.resolveSymbolicName(Constraint,
1661                                                &(*OutCons)[0],
1662                                                OutCons->size(), Index);
1663       assert(result && "Could not resolve symbolic name"); (void)result;
1664       Result += llvm::utostr(Index);
1665       break;
1666     }
1667     }
1668 
1669     Constraint++;
1670   }
1671 
1672   return Result;
1673 }
1674 
1675 /// AddVariableConstraints - Look at AsmExpr and if it is a variable declared
1676 /// as using a particular register add that as a constraint that will be used
1677 /// in this asm stmt.
1678 static std::string
1679 AddVariableConstraints(const std::string &Constraint, const Expr &AsmExpr,
1680                        const TargetInfo &Target, CodeGenModule &CGM,
1681                        const AsmStmt &Stmt) {
1682   const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(&AsmExpr);
1683   if (!AsmDeclRef)
1684     return Constraint;
1685   const ValueDecl &Value = *AsmDeclRef->getDecl();
1686   const VarDecl *Variable = dyn_cast<VarDecl>(&Value);
1687   if (!Variable)
1688     return Constraint;
1689   if (Variable->getStorageClass() != SC_Register)
1690     return Constraint;
1691   AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>();
1692   if (!Attr)
1693     return Constraint;
1694   StringRef Register = Attr->getLabel();
1695   assert(Target.isValidGCCRegisterName(Register));
1696   // We're using validateOutputConstraint here because we only care if
1697   // this is a register constraint.
1698   TargetInfo::ConstraintInfo Info(Constraint, "");
1699   if (Target.validateOutputConstraint(Info) &&
1700       !Info.allowsRegister()) {
1701     CGM.ErrorUnsupported(&Stmt, "__asm__");
1702     return Constraint;
1703   }
1704   // Canonicalize the register here before returning it.
1705   Register = Target.getNormalizedGCCRegisterName(Register);
1706   return "{" + Register.str() + "}";
1707 }
1708 
1709 llvm::Value*
1710 CodeGenFunction::EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info,
1711                                     LValue InputValue, QualType InputType,
1712                                     std::string &ConstraintStr,
1713                                     SourceLocation Loc) {
1714   llvm::Value *Arg;
1715   if (Info.allowsRegister() || !Info.allowsMemory()) {
1716     if (CodeGenFunction::hasScalarEvaluationKind(InputType)) {
1717       Arg = EmitLoadOfLValue(InputValue, Loc).getScalarVal();
1718     } else {
1719       llvm::Type *Ty = ConvertType(InputType);
1720       uint64_t Size = CGM.getDataLayout().getTypeSizeInBits(Ty);
1721       if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
1722         Ty = llvm::IntegerType::get(getLLVMContext(), Size);
1723         Ty = llvm::PointerType::getUnqual(Ty);
1724 
1725         Arg = Builder.CreateLoad(Builder.CreateBitCast(InputValue.getAddress(),
1726                                                        Ty));
1727       } else {
1728         Arg = InputValue.getAddress();
1729         ConstraintStr += '*';
1730       }
1731     }
1732   } else {
1733     Arg = InputValue.getAddress();
1734     ConstraintStr += '*';
1735   }
1736 
1737   return Arg;
1738 }
1739 
1740 llvm::Value* CodeGenFunction::EmitAsmInput(
1741                                          const TargetInfo::ConstraintInfo &Info,
1742                                            const Expr *InputExpr,
1743                                            std::string &ConstraintStr) {
1744   if (Info.allowsRegister() || !Info.allowsMemory())
1745     if (CodeGenFunction::hasScalarEvaluationKind(InputExpr->getType()))
1746       return EmitScalarExpr(InputExpr);
1747 
1748   InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
1749   LValue Dest = EmitLValue(InputExpr);
1750   return EmitAsmInputLValue(Info, Dest, InputExpr->getType(), ConstraintStr,
1751                             InputExpr->getExprLoc());
1752 }
1753 
1754 /// getAsmSrcLocInfo - Return the !srcloc metadata node to attach to an inline
1755 /// asm call instruction.  The !srcloc MDNode contains a list of constant
1756 /// integers which are the source locations of the start of each line in the
1757 /// asm.
1758 static llvm::MDNode *getAsmSrcLocInfo(const StringLiteral *Str,
1759                                       CodeGenFunction &CGF) {
1760   SmallVector<llvm::Value *, 8> Locs;
1761   // Add the location of the first line to the MDNode.
1762   Locs.push_back(llvm::ConstantInt::get(CGF.Int32Ty,
1763                                         Str->getLocStart().getRawEncoding()));
1764   StringRef StrVal = Str->getString();
1765   if (!StrVal.empty()) {
1766     const SourceManager &SM = CGF.CGM.getContext().getSourceManager();
1767     const LangOptions &LangOpts = CGF.CGM.getLangOpts();
1768 
1769     // Add the location of the start of each subsequent line of the asm to the
1770     // MDNode.
1771     for (unsigned i = 0, e = StrVal.size()-1; i != e; ++i) {
1772       if (StrVal[i] != '\n') continue;
1773       SourceLocation LineLoc = Str->getLocationOfByte(i+1, SM, LangOpts,
1774                                                       CGF.getTarget());
1775       Locs.push_back(llvm::ConstantInt::get(CGF.Int32Ty,
1776                                             LineLoc.getRawEncoding()));
1777     }
1778   }
1779 
1780   return llvm::MDNode::get(CGF.getLLVMContext(), Locs);
1781 }
1782 
1783 void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
1784   // Assemble the final asm string.
1785   std::string AsmString = S.generateAsmString(getContext());
1786 
1787   // Get all the output and input constraints together.
1788   SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
1789   SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
1790 
1791   for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
1792     StringRef Name;
1793     if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
1794       Name = GAS->getOutputName(i);
1795     TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i), Name);
1796     bool IsValid = getTarget().validateOutputConstraint(Info); (void)IsValid;
1797     assert(IsValid && "Failed to parse output constraint");
1798     OutputConstraintInfos.push_back(Info);
1799   }
1800 
1801   for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1802     StringRef Name;
1803     if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
1804       Name = GAS->getInputName(i);
1805     TargetInfo::ConstraintInfo Info(S.getInputConstraint(i), Name);
1806     bool IsValid =
1807       getTarget().validateInputConstraint(OutputConstraintInfos.data(),
1808                                           S.getNumOutputs(), Info);
1809     assert(IsValid && "Failed to parse input constraint"); (void)IsValid;
1810     InputConstraintInfos.push_back(Info);
1811   }
1812 
1813   std::string Constraints;
1814 
1815   std::vector<LValue> ResultRegDests;
1816   std::vector<QualType> ResultRegQualTys;
1817   std::vector<llvm::Type *> ResultRegTypes;
1818   std::vector<llvm::Type *> ResultTruncRegTypes;
1819   std::vector<llvm::Type *> ArgTypes;
1820   std::vector<llvm::Value*> Args;
1821 
1822   // Keep track of inout constraints.
1823   std::string InOutConstraints;
1824   std::vector<llvm::Value*> InOutArgs;
1825   std::vector<llvm::Type*> InOutArgTypes;
1826 
1827   for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
1828     TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
1829 
1830     // Simplify the output constraint.
1831     std::string OutputConstraint(S.getOutputConstraint(i));
1832     OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1,
1833                                           getTarget());
1834 
1835     const Expr *OutExpr = S.getOutputExpr(i);
1836     OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
1837 
1838     OutputConstraint = AddVariableConstraints(OutputConstraint, *OutExpr,
1839                                               getTarget(), CGM, S);
1840 
1841     LValue Dest = EmitLValue(OutExpr);
1842     if (!Constraints.empty())
1843       Constraints += ',';
1844 
1845     // If this is a register output, then make the inline asm return it
1846     // by-value.  If this is a memory result, return the value by-reference.
1847     if (!Info.allowsMemory() && hasScalarEvaluationKind(OutExpr->getType())) {
1848       Constraints += "=" + OutputConstraint;
1849       ResultRegQualTys.push_back(OutExpr->getType());
1850       ResultRegDests.push_back(Dest);
1851       ResultRegTypes.push_back(ConvertTypeForMem(OutExpr->getType()));
1852       ResultTruncRegTypes.push_back(ResultRegTypes.back());
1853 
1854       // If this output is tied to an input, and if the input is larger, then
1855       // we need to set the actual result type of the inline asm node to be the
1856       // same as the input type.
1857       if (Info.hasMatchingInput()) {
1858         unsigned InputNo;
1859         for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) {
1860           TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo];
1861           if (Input.hasTiedOperand() && Input.getTiedOperand() == i)
1862             break;
1863         }
1864         assert(InputNo != S.getNumInputs() && "Didn't find matching input!");
1865 
1866         QualType InputTy = S.getInputExpr(InputNo)->getType();
1867         QualType OutputType = OutExpr->getType();
1868 
1869         uint64_t InputSize = getContext().getTypeSize(InputTy);
1870         if (getContext().getTypeSize(OutputType) < InputSize) {
1871           // Form the asm to return the value as a larger integer or fp type.
1872           ResultRegTypes.back() = ConvertType(InputTy);
1873         }
1874       }
1875       if (llvm::Type* AdjTy =
1876             getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
1877                                                  ResultRegTypes.back()))
1878         ResultRegTypes.back() = AdjTy;
1879       else {
1880         CGM.getDiags().Report(S.getAsmLoc(),
1881                               diag::err_asm_invalid_type_in_input)
1882             << OutExpr->getType() << OutputConstraint;
1883       }
1884     } else {
1885       ArgTypes.push_back(Dest.getAddress()->getType());
1886       Args.push_back(Dest.getAddress());
1887       Constraints += "=*";
1888       Constraints += OutputConstraint;
1889     }
1890 
1891     if (Info.isReadWrite()) {
1892       InOutConstraints += ',';
1893 
1894       const Expr *InputExpr = S.getOutputExpr(i);
1895       llvm::Value *Arg = EmitAsmInputLValue(Info, Dest, InputExpr->getType(),
1896                                             InOutConstraints,
1897                                             InputExpr->getExprLoc());
1898 
1899       if (llvm::Type* AdjTy =
1900           getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
1901                                                Arg->getType()))
1902         Arg = Builder.CreateBitCast(Arg, AdjTy);
1903 
1904       if (Info.allowsRegister())
1905         InOutConstraints += llvm::utostr(i);
1906       else
1907         InOutConstraints += OutputConstraint;
1908 
1909       InOutArgTypes.push_back(Arg->getType());
1910       InOutArgs.push_back(Arg);
1911     }
1912   }
1913 
1914   unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
1915 
1916   for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1917     const Expr *InputExpr = S.getInputExpr(i);
1918 
1919     TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
1920 
1921     if (!Constraints.empty())
1922       Constraints += ',';
1923 
1924     // Simplify the input constraint.
1925     std::string InputConstraint(S.getInputConstraint(i));
1926     InputConstraint = SimplifyConstraint(InputConstraint.c_str(), getTarget(),
1927                                          &OutputConstraintInfos);
1928 
1929     InputConstraint =
1930       AddVariableConstraints(InputConstraint,
1931                             *InputExpr->IgnoreParenNoopCasts(getContext()),
1932                             getTarget(), CGM, S);
1933 
1934     llvm::Value *Arg = EmitAsmInput(Info, InputExpr, Constraints);
1935 
1936     // If this input argument is tied to a larger output result, extend the
1937     // input to be the same size as the output.  The LLVM backend wants to see
1938     // the input and output of a matching constraint be the same size.  Note
1939     // that GCC does not define what the top bits are here.  We use zext because
1940     // that is usually cheaper, but LLVM IR should really get an anyext someday.
1941     if (Info.hasTiedOperand()) {
1942       unsigned Output = Info.getTiedOperand();
1943       QualType OutputType = S.getOutputExpr(Output)->getType();
1944       QualType InputTy = InputExpr->getType();
1945 
1946       if (getContext().getTypeSize(OutputType) >
1947           getContext().getTypeSize(InputTy)) {
1948         // Use ptrtoint as appropriate so that we can do our extension.
1949         if (isa<llvm::PointerType>(Arg->getType()))
1950           Arg = Builder.CreatePtrToInt(Arg, IntPtrTy);
1951         llvm::Type *OutputTy = ConvertType(OutputType);
1952         if (isa<llvm::IntegerType>(OutputTy))
1953           Arg = Builder.CreateZExt(Arg, OutputTy);
1954         else if (isa<llvm::PointerType>(OutputTy))
1955           Arg = Builder.CreateZExt(Arg, IntPtrTy);
1956         else {
1957           assert(OutputTy->isFloatingPointTy() && "Unexpected output type");
1958           Arg = Builder.CreateFPExt(Arg, OutputTy);
1959         }
1960       }
1961     }
1962     if (llvm::Type* AdjTy =
1963               getTargetHooks().adjustInlineAsmType(*this, InputConstraint,
1964                                                    Arg->getType()))
1965       Arg = Builder.CreateBitCast(Arg, AdjTy);
1966     else
1967       CGM.getDiags().Report(S.getAsmLoc(), diag::err_asm_invalid_type_in_input)
1968           << InputExpr->getType() << InputConstraint;
1969 
1970     ArgTypes.push_back(Arg->getType());
1971     Args.push_back(Arg);
1972     Constraints += InputConstraint;
1973   }
1974 
1975   // Append the "input" part of inout constraints last.
1976   for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
1977     ArgTypes.push_back(InOutArgTypes[i]);
1978     Args.push_back(InOutArgs[i]);
1979   }
1980   Constraints += InOutConstraints;
1981 
1982   // Clobbers
1983   for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
1984     StringRef Clobber = S.getClobber(i);
1985 
1986     if (Clobber != "memory" && Clobber != "cc")
1987     Clobber = getTarget().getNormalizedGCCRegisterName(Clobber);
1988 
1989     if (i != 0 || NumConstraints != 0)
1990       Constraints += ',';
1991 
1992     Constraints += "~{";
1993     Constraints += Clobber;
1994     Constraints += '}';
1995   }
1996 
1997   // Add machine specific clobbers
1998   std::string MachineClobbers = getTarget().getClobbers();
1999   if (!MachineClobbers.empty()) {
2000     if (!Constraints.empty())
2001       Constraints += ',';
2002     Constraints += MachineClobbers;
2003   }
2004 
2005   llvm::Type *ResultType;
2006   if (ResultRegTypes.empty())
2007     ResultType = VoidTy;
2008   else if (ResultRegTypes.size() == 1)
2009     ResultType = ResultRegTypes[0];
2010   else
2011     ResultType = llvm::StructType::get(getLLVMContext(), ResultRegTypes);
2012 
2013   llvm::FunctionType *FTy =
2014     llvm::FunctionType::get(ResultType, ArgTypes, false);
2015 
2016   bool HasSideEffect = S.isVolatile() || S.getNumOutputs() == 0;
2017   llvm::InlineAsm::AsmDialect AsmDialect = isa<MSAsmStmt>(&S) ?
2018     llvm::InlineAsm::AD_Intel : llvm::InlineAsm::AD_ATT;
2019   llvm::InlineAsm *IA =
2020     llvm::InlineAsm::get(FTy, AsmString, Constraints, HasSideEffect,
2021                          /* IsAlignStack */ false, AsmDialect);
2022   llvm::CallInst *Result = Builder.CreateCall(IA, Args);
2023   Result->addAttribute(llvm::AttributeSet::FunctionIndex,
2024                        llvm::Attribute::NoUnwind);
2025 
2026   // Slap the source location of the inline asm into a !srcloc metadata on the
2027   // call.
2028   if (const GCCAsmStmt *gccAsmStmt = dyn_cast<GCCAsmStmt>(&S)) {
2029     Result->setMetadata("srcloc", getAsmSrcLocInfo(gccAsmStmt->getAsmString(),
2030                                                    *this));
2031   } else {
2032     // At least put the line number on MS inline asm blobs.
2033     auto Loc = llvm::ConstantInt::get(Int32Ty, S.getAsmLoc().getRawEncoding());
2034     Result->setMetadata("srcloc", llvm::MDNode::get(getLLVMContext(), Loc));
2035   }
2036 
2037   // Extract all of the register value results from the asm.
2038   std::vector<llvm::Value*> RegResults;
2039   if (ResultRegTypes.size() == 1) {
2040     RegResults.push_back(Result);
2041   } else {
2042     for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) {
2043       llvm::Value *Tmp = Builder.CreateExtractValue(Result, i, "asmresult");
2044       RegResults.push_back(Tmp);
2045     }
2046   }
2047 
2048   for (unsigned i = 0, e = RegResults.size(); i != e; ++i) {
2049     llvm::Value *Tmp = RegResults[i];
2050 
2051     // If the result type of the LLVM IR asm doesn't match the result type of
2052     // the expression, do the conversion.
2053     if (ResultRegTypes[i] != ResultTruncRegTypes[i]) {
2054       llvm::Type *TruncTy = ResultTruncRegTypes[i];
2055 
2056       // Truncate the integer result to the right size, note that TruncTy can be
2057       // a pointer.
2058       if (TruncTy->isFloatingPointTy())
2059         Tmp = Builder.CreateFPTrunc(Tmp, TruncTy);
2060       else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) {
2061         uint64_t ResSize = CGM.getDataLayout().getTypeSizeInBits(TruncTy);
2062         Tmp = Builder.CreateTrunc(Tmp,
2063                    llvm::IntegerType::get(getLLVMContext(), (unsigned)ResSize));
2064         Tmp = Builder.CreateIntToPtr(Tmp, TruncTy);
2065       } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) {
2066         uint64_t TmpSize =CGM.getDataLayout().getTypeSizeInBits(Tmp->getType());
2067         Tmp = Builder.CreatePtrToInt(Tmp,
2068                    llvm::IntegerType::get(getLLVMContext(), (unsigned)TmpSize));
2069         Tmp = Builder.CreateTrunc(Tmp, TruncTy);
2070       } else if (TruncTy->isIntegerTy()) {
2071         Tmp = Builder.CreateTrunc(Tmp, TruncTy);
2072       } else if (TruncTy->isVectorTy()) {
2073         Tmp = Builder.CreateBitCast(Tmp, TruncTy);
2074       }
2075     }
2076 
2077     EmitStoreThroughLValue(RValue::get(Tmp), ResultRegDests[i]);
2078   }
2079 }
2080 
2081 static LValue InitCapturedStruct(CodeGenFunction &CGF, const CapturedStmt &S) {
2082   const RecordDecl *RD = S.getCapturedRecordDecl();
2083   QualType RecordTy = CGF.getContext().getRecordType(RD);
2084 
2085   // Initialize the captured struct.
2086   LValue SlotLV = CGF.MakeNaturalAlignAddrLValue(
2087                     CGF.CreateMemTemp(RecordTy, "agg.captured"), RecordTy);
2088 
2089   RecordDecl::field_iterator CurField = RD->field_begin();
2090   for (CapturedStmt::capture_init_iterator I = S.capture_init_begin(),
2091                                            E = S.capture_init_end();
2092        I != E; ++I, ++CurField) {
2093     LValue LV = CGF.EmitLValueForFieldInitialization(SlotLV, *CurField);
2094     CGF.EmitInitializerForField(*CurField, LV, *I, ArrayRef<VarDecl *>());
2095   }
2096 
2097   return SlotLV;
2098 }
2099 
2100 static void InitVLACaptures(CodeGenFunction &CGF, const CapturedStmt &S) {
2101   for (auto &C : S.captures()) {
2102     if (C.capturesVariable()) {
2103       QualType QTy;
2104       auto VD = C.getCapturedVar();
2105       if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
2106         QTy = PVD->getOriginalType();
2107       else
2108         QTy = VD->getType();
2109       if (QTy->isVariablyModifiedType()) {
2110         CGF.EmitVariablyModifiedType(QTy);
2111       }
2112     }
2113   }
2114 }
2115 
2116 /// Generate an outlined function for the body of a CapturedStmt, store any
2117 /// captured variables into the captured struct, and call the outlined function.
2118 llvm::Function *
2119 CodeGenFunction::EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K) {
2120   LValue CapStruct = InitCapturedStruct(*this, S);
2121 
2122   // Emit the CapturedDecl
2123   CodeGenFunction CGF(CGM, true);
2124   CGF.CapturedStmtInfo = new CGCapturedStmtInfo(S, K);
2125   llvm::Function *F = CGF.GenerateCapturedStmtFunction(S);
2126   delete CGF.CapturedStmtInfo;
2127 
2128   // Emit call to the helper function.
2129   EmitCallOrInvoke(F, CapStruct.getAddress());
2130 
2131   return F;
2132 }
2133 
2134 llvm::Value *
2135 CodeGenFunction::GenerateCapturedStmtArgument(const CapturedStmt &S) {
2136   LValue CapStruct = InitCapturedStruct(*this, S);
2137   return CapStruct.getAddress();
2138 }
2139 
2140 /// Creates the outlined function for a CapturedStmt.
2141 llvm::Function *
2142 CodeGenFunction::GenerateCapturedStmtFunction(const CapturedStmt &S) {
2143   assert(CapturedStmtInfo &&
2144     "CapturedStmtInfo should be set when generating the captured function");
2145   const CapturedDecl *CD = S.getCapturedDecl();
2146   const RecordDecl *RD = S.getCapturedRecordDecl();
2147   SourceLocation Loc = S.getLocStart();
2148   assert(CD->hasBody() && "missing CapturedDecl body");
2149 
2150   // Build the argument list.
2151   ASTContext &Ctx = CGM.getContext();
2152   FunctionArgList Args;
2153   Args.append(CD->param_begin(), CD->param_end());
2154 
2155   // Create the function declaration.
2156   FunctionType::ExtInfo ExtInfo;
2157   const CGFunctionInfo &FuncInfo =
2158       CGM.getTypes().arrangeFreeFunctionDeclaration(Ctx.VoidTy, Args, ExtInfo,
2159                                                     /*IsVariadic=*/false);
2160   llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
2161 
2162   llvm::Function *F =
2163     llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
2164                            CapturedStmtInfo->getHelperName(), &CGM.getModule());
2165   CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
2166 
2167   // Generate the function.
2168   StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args,
2169                 CD->getLocation(),
2170                 CD->getBody()->getLocStart());
2171   // Set the context parameter in CapturedStmtInfo.
2172   llvm::Value *DeclPtr = LocalDeclMap[CD->getContextParam()];
2173   assert(DeclPtr && "missing context parameter for CapturedStmt");
2174   CapturedStmtInfo->setContextValue(Builder.CreateLoad(DeclPtr));
2175 
2176   // Initialize variable-length arrays.
2177   InitVLACaptures(*this, S);
2178 
2179   // If 'this' is captured, load it into CXXThisValue.
2180   if (CapturedStmtInfo->isCXXThisExprCaptured()) {
2181     FieldDecl *FD = CapturedStmtInfo->getThisFieldDecl();
2182     LValue LV = MakeNaturalAlignAddrLValue(CapturedStmtInfo->getContextValue(),
2183                                            Ctx.getTagDeclType(RD));
2184     LValue ThisLValue = EmitLValueForField(LV, FD);
2185     CXXThisValue = EmitLoadOfLValue(ThisLValue, Loc).getScalarVal();
2186   }
2187 
2188   PGO.assignRegionCounters(CD, F);
2189   CapturedStmtInfo->EmitBody(*this, CD->getBody());
2190   FinishFunction(CD->getBodyRBrace());
2191   PGO.emitInstrumentationData();
2192   PGO.destroyRegionCounters();
2193 
2194   return F;
2195 }
2196