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