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