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