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