CGStmt.cpp revision eb91f0ecb420f481811f8812ac4d39087e8dd754
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 "clang/AST/StmtVisitor.h"
18#include "clang/Basic/TargetInfo.h"
19#include "llvm/ADT/StringExtras.h"
20#include "llvm/InlineAsm.h"
21#include "llvm/Intrinsics.h"
22using namespace clang;
23using namespace CodeGen;
24
25//===----------------------------------------------------------------------===//
26//                              Statement Emission
27//===----------------------------------------------------------------------===//
28
29void CodeGenFunction::EmitStopPoint(const Stmt *S) {
30  if (CGDebugInfo *DI = CGM.getDebugInfo()) {
31    DI->setLocation(S->getLocStart());
32    DI->EmitStopPoint(CurFn, Builder);
33  }
34}
35
36void CodeGenFunction::EmitStmt(const Stmt *S) {
37  assert(S && "Null statement?");
38
39  // Check if we can handle this without bothering to generate an
40  // insert point or debug info.
41  if (EmitSimpleStmt(S))
42    return;
43
44  // If we happen to be at an unreachable point just create a dummy
45  // basic block to hold the code. We could change parts of irgen to
46  // simply not generate this code, but this situation is rare and
47  // probably not worth the effort.
48  // FIXME: Verify previous performance/effort claim.
49  EnsureInsertPoint();
50
51  // Generate a stoppoint if we are emitting debug info.
52  EmitStopPoint(S);
53
54  switch (S->getStmtClass()) {
55  default:
56    // Must be an expression in a stmt context.  Emit the value (to get
57    // side-effects) and ignore the result.
58    if (const Expr *E = dyn_cast<Expr>(S)) {
59      if (!hasAggregateLLVMType(E->getType()))
60        EmitScalarExpr(E);
61      else if (E->getType()->isAnyComplexType())
62        EmitComplexExpr(E);
63      else
64        EmitAggExpr(E, 0, false);
65    } else {
66      ErrorUnsupported(S, "statement");
67    }
68    break;
69  case Stmt::IndirectGotoStmtClass:
70    EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
71
72  case Stmt::IfStmtClass:       EmitIfStmt(cast<IfStmt>(*S));             break;
73  case Stmt::WhileStmtClass:    EmitWhileStmt(cast<WhileStmt>(*S));       break;
74  case Stmt::DoStmtClass:       EmitDoStmt(cast<DoStmt>(*S));             break;
75  case Stmt::ForStmtClass:      EmitForStmt(cast<ForStmt>(*S));           break;
76
77  case Stmt::ReturnStmtClass:   EmitReturnStmt(cast<ReturnStmt>(*S));     break;
78  case Stmt::DeclStmtClass:     EmitDeclStmt(cast<DeclStmt>(*S));         break;
79
80  case Stmt::SwitchStmtClass:   EmitSwitchStmt(cast<SwitchStmt>(*S));     break;
81  case Stmt::AsmStmtClass:      EmitAsmStmt(cast<AsmStmt>(*S));           break;
82
83  case Stmt::ObjCAtTryStmtClass:
84    EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
85    break;
86  case Stmt::ObjCAtCatchStmtClass:
87    assert(0 && "@catch statements should be handled by EmitObjCAtTryStmt");
88    break;
89  case Stmt::ObjCAtFinallyStmtClass:
90    assert(0 && "@finally statements should be handled by EmitObjCAtTryStmt");
91    break;
92  case Stmt::ObjCAtThrowStmtClass:
93    EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
94    break;
95  case Stmt::ObjCAtSynchronizedStmtClass:
96    EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
97    break;
98  case Stmt::ObjCForCollectionStmtClass:
99    EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
100    break;
101  }
102}
103
104bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
105  switch (S->getStmtClass()) {
106  default: return false;
107  case Stmt::NullStmtClass: break;
108  case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
109  case Stmt::LabelStmtClass:    EmitLabelStmt(cast<LabelStmt>(*S));       break;
110  case Stmt::GotoStmtClass:     EmitGotoStmt(cast<GotoStmt>(*S));         break;
111  case Stmt::BreakStmtClass:    EmitBreakStmt(cast<BreakStmt>(*S));       break;
112  case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
113  case Stmt::DefaultStmtClass:  EmitDefaultStmt(cast<DefaultStmt>(*S));   break;
114  case Stmt::CaseStmtClass:     EmitCaseStmt(cast<CaseStmt>(*S));         break;
115  }
116
117  return true;
118}
119
120/// EmitCompoundStmt - Emit a compound statement {..} node.  If GetLast is true,
121/// this captures the expression result of the last sub-statement and returns it
122/// (for use by the statement expression extension).
123RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
124                                         llvm::Value *AggLoc, bool isAggVol) {
125  // FIXME: handle vla's etc.
126  CGDebugInfo *DI = CGM.getDebugInfo();
127  if (DI) {
128    EnsureInsertPoint();
129    DI->setLocation(S.getLBracLoc());
130    DI->EmitRegionStart(CurFn, Builder);
131  }
132
133  // Push a null stack save value.
134  StackSaveValues.push_back(0);
135
136  for (CompoundStmt::const_body_iterator I = S.body_begin(),
137       E = S.body_end()-GetLast; I != E; ++I)
138    EmitStmt(*I);
139
140  if (DI) {
141    EnsureInsertPoint();
142    DI->setLocation(S.getRBracLoc());
143    DI->EmitRegionEnd(CurFn, Builder);
144  }
145
146  RValue RV;
147  if (!GetLast)
148    RV = RValue::get(0);
149  else {
150    // We have to special case labels here.  They are statements, but when put
151    // at the end of a statement expression, they yield the value of their
152    // subexpression.  Handle this by walking through all labels we encounter,
153    // emitting them before we evaluate the subexpr.
154    const Stmt *LastStmt = S.body_back();
155    while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
156      EmitLabel(*LS);
157      LastStmt = LS->getSubStmt();
158    }
159
160    EnsureInsertPoint();
161
162    RV = EmitAnyExpr(cast<Expr>(LastStmt), AggLoc);
163  }
164
165  if (llvm::Value *V = StackSaveValues.pop_back_val()) {
166    V = Builder.CreateLoad(V, "tmp");
167
168    llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
169    Builder.CreateCall(F, V);
170  }
171
172  return RV;
173}
174
175void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
176  // Fall out of the current block (if necessary).
177  EmitBranch(BB);
178
179  if (IsFinished && BB->use_empty()) {
180    delete BB;
181    return;
182  }
183
184  CurFn->getBasicBlockList().push_back(BB);
185  Builder.SetInsertPoint(BB);
186}
187
188void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
189  // Emit a branch from the current block to the target one if this
190  // was a real block.  If this was just a fall-through block after a
191  // terminator, don't emit it.
192  llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
193
194  if (!CurBB || CurBB->getTerminator()) {
195    // If there is no insert point or the previous block is already
196    // terminated, don't touch it.
197  } else {
198    // Otherwise, create a fall-through branch.
199    Builder.CreateBr(Target);
200  }
201
202  Builder.ClearInsertionPoint();
203}
204
205void CodeGenFunction::EmitLabel(const LabelStmt &S) {
206  llvm::BasicBlock *NextBB = getBasicBlockForLabel(&S);
207  EmitBlock(NextBB);
208}
209
210
211void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
212  EmitLabel(S);
213  EmitStmt(S.getSubStmt());
214}
215
216void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
217  // FIXME: Implement goto out in @try or @catch blocks.
218  if (!ObjCEHStack.empty()) {
219    CGM.ErrorUnsupported(&S, "goto inside an Obj-C exception block");
220    return;
221  }
222
223  if (StackSaveValues.back()) {
224    CGM.ErrorUnsupported(&S, "goto inside scope with VLA");
225    return;
226  }
227
228  // If this code is reachable then emit a stop point (if generating
229  // debug info). We have to do this ourselves because we are on the
230  // "simple" statement path.
231  if (HaveInsertPoint())
232    EmitStopPoint(&S);
233  EmitBranch(getBasicBlockForLabel(S.getLabel()));
234}
235
236void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
237  // FIXME: Implement indirect goto in @try or @catch blocks.
238  if (!ObjCEHStack.empty()) {
239    CGM.ErrorUnsupported(&S, "goto inside an Obj-C exception block");
240    return;
241  }
242
243  // Emit initial switch which will be patched up later by
244  // EmitIndirectSwitches(). We need a default dest, so we use the
245  // current BB, but this is overwritten.
246  llvm::Value *V = Builder.CreatePtrToInt(EmitScalarExpr(S.getTarget()),
247                                          llvm::Type::Int32Ty,
248                                          "addr");
249  llvm::SwitchInst *I = Builder.CreateSwitch(V, Builder.GetInsertBlock());
250  IndirectSwitches.push_back(I);
251
252  // Clear the insertion point to indicate we are in unreachable code.
253  Builder.ClearInsertionPoint();
254}
255
256void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
257  // C99 6.8.4.1: The first substatement is executed if the expression compares
258  // unequal to 0.  The condition must be a scalar type.
259
260  // If the condition constant folds and can be elided, try to avoid emitting
261  // the condition and the dead arm of the if/else.
262  if (int Cond = ConstantFoldsToSimpleInteger(S.getCond())) {
263    // Figure out which block (then or else) is executed.
264    const Stmt *Executed = S.getThen(), *Skipped  = S.getElse();
265    if (Cond == -1)  // Condition false?
266      std::swap(Executed, Skipped);
267
268    // If the skipped block has no labels in it, just emit the executed block.
269    // This avoids emitting dead code and simplifies the CFG substantially.
270    if (!ContainsLabel(Skipped)) {
271      if (Executed)
272        EmitStmt(Executed);
273      return;
274    }
275  }
276
277  // Otherwise, the condition did not fold, or we couldn't elide it.  Just emit
278  // the conditional branch.
279  llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
280  llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
281  llvm::BasicBlock *ElseBlock = ContBlock;
282  if (S.getElse())
283    ElseBlock = createBasicBlock("if.else");
284  EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
285
286  // Emit the 'then' code.
287  EmitBlock(ThenBlock);
288  EmitStmt(S.getThen());
289  EmitBranch(ContBlock);
290
291  // Emit the 'else' code if present.
292  if (const Stmt *Else = S.getElse()) {
293    EmitBlock(ElseBlock);
294    EmitStmt(Else);
295    EmitBranch(ContBlock);
296  }
297
298  // Emit the continuation block for code after the if.
299  EmitBlock(ContBlock, true);
300}
301
302void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
303  // Emit the header for the loop, insert it, which will create an uncond br to
304  // it.
305  llvm::BasicBlock *LoopHeader = createBasicBlock("while.cond");
306  EmitBlock(LoopHeader);
307
308  // Evaluate the conditional in the while header.  C99 6.8.5.1: The evaluation
309  // of the controlling expression takes place before each execution of the loop
310  // body.
311  llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
312
313  // while(1) is common, avoid extra exit blocks.  Be sure
314  // to correctly handle break/continue though.
315  bool EmitBoolCondBranch = true;
316  if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
317    if (C->isOne())
318      EmitBoolCondBranch = false;
319
320  // Create an exit block for when the condition fails, create a block for the
321  // body of the loop.
322  llvm::BasicBlock *ExitBlock = createBasicBlock("while.end");
323  llvm::BasicBlock *LoopBody  = createBasicBlock("while.body");
324
325  // As long as the condition is true, go to the loop body.
326  if (EmitBoolCondBranch)
327    Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
328
329  // Store the blocks to use for break and continue.
330  BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader,
331                                             ObjCEHStack.size()));
332
333  // Emit the loop body.
334  EmitBlock(LoopBody);
335  EmitStmt(S.getBody());
336
337  BreakContinueStack.pop_back();
338
339  // Cycle to the condition.
340  EmitBranch(LoopHeader);
341
342  // Emit the exit block.
343  EmitBlock(ExitBlock, true);
344
345  // If LoopHeader is a simple forwarding block then eliminate it.
346  if (!EmitBoolCondBranch
347      && &LoopHeader->front() == LoopHeader->getTerminator()) {
348    LoopHeader->replaceAllUsesWith(LoopBody);
349    LoopHeader->getTerminator()->eraseFromParent();
350    LoopHeader->eraseFromParent();
351  }
352}
353
354void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
355  // Emit the body for the loop, insert it, which will create an uncond br to
356  // it.
357  llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
358  llvm::BasicBlock *AfterDo = createBasicBlock("do.end");
359  EmitBlock(LoopBody);
360
361  llvm::BasicBlock *DoCond = createBasicBlock("do.cond");
362
363  // Store the blocks to use for break and continue.
364  BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond,
365                                             ObjCEHStack.size()));
366
367  // Emit the body of the loop into the block.
368  EmitStmt(S.getBody());
369
370  BreakContinueStack.pop_back();
371
372  EmitBlock(DoCond);
373
374  // C99 6.8.5.2: "The evaluation of the controlling expression takes place
375  // after each execution of the loop body."
376
377  // Evaluate the conditional in the while header.
378  // C99 6.8.5p2/p4: The first substatement is executed if the expression
379  // compares unequal to 0.  The condition must be a scalar type.
380  llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
381
382  // "do {} while (0)" is common in macros, avoid extra blocks.  Be sure
383  // to correctly handle break/continue though.
384  bool EmitBoolCondBranch = true;
385  if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
386    if (C->isZero())
387      EmitBoolCondBranch = false;
388
389  // As long as the condition is true, iterate the loop.
390  if (EmitBoolCondBranch)
391    Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
392
393  // Emit the exit block.
394  EmitBlock(AfterDo, true);
395
396  // If DoCond is a simple forwarding block then eliminate it.
397  if (!EmitBoolCondBranch && &DoCond->front() == DoCond->getTerminator()) {
398    DoCond->replaceAllUsesWith(AfterDo);
399    DoCond->getTerminator()->eraseFromParent();
400    DoCond->eraseFromParent();
401  }
402}
403
404void CodeGenFunction::EmitForStmt(const ForStmt &S) {
405  // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
406  // which contains a continue/break?
407
408  // Evaluate the first part before the loop.
409  if (S.getInit())
410    EmitStmt(S.getInit());
411
412  // Start the loop with a block that tests the condition.
413  llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
414  llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
415
416  EmitBlock(CondBlock);
417
418  // Evaluate the condition if present.  If not, treat it as a non-zero-constant
419  // according to 6.8.5.3p2, aka, true.
420  if (S.getCond()) {
421    // As long as the condition is true, iterate the loop.
422    llvm::BasicBlock *ForBody = createBasicBlock("for.body");
423
424    // C99 6.8.5p2/p4: The first substatement is executed if the expression
425    // compares unequal to 0.  The condition must be a scalar type.
426    EmitBranchOnBoolExpr(S.getCond(), ForBody, AfterFor);
427
428    EmitBlock(ForBody);
429  } else {
430    // Treat it as a non-zero constant.  Don't even create a new block for the
431    // body, just fall into it.
432  }
433
434  // If the for loop doesn't have an increment we can just use the
435  // condition as the continue block.
436  llvm::BasicBlock *ContinueBlock;
437  if (S.getInc())
438    ContinueBlock = createBasicBlock("for.inc");
439  else
440    ContinueBlock = CondBlock;
441
442  // Store the blocks to use for break and continue.
443  BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock,
444                                             ObjCEHStack.size()));
445
446  // If the condition is true, execute the body of the for stmt.
447  EmitStmt(S.getBody());
448
449  BreakContinueStack.pop_back();
450
451  // If there is an increment, emit it next.
452  if (S.getInc()) {
453    EmitBlock(ContinueBlock);
454    EmitStmt(S.getInc());
455  }
456
457  // Finally, branch back up to the condition for the next iteration.
458  EmitBranch(CondBlock);
459
460  // Emit the fall-through block.
461  EmitBlock(AfterFor, true);
462}
463
464void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
465  if (RV.isScalar()) {
466    Builder.CreateStore(RV.getScalarVal(), ReturnValue);
467  } else if (RV.isAggregate()) {
468    EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
469  } else {
470    StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
471  }
472  EmitBranch(ReturnBlock);
473}
474
475/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
476/// if the function returns void, or may be missing one if the function returns
477/// non-void.  Fun stuff :).
478void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
479  if (StackSaveValues.back()) {
480    CGM.ErrorUnsupported(&S, "return inside scope with VLA");
481    return;
482  }
483
484  // Emit the result value, even if unused, to evalute the side effects.
485  const Expr *RV = S.getRetValue();
486
487  // FIXME: Clean this up by using an LValue for ReturnTemp,
488  // EmitStoreThroughLValue, and EmitAnyExpr.
489  if (!ReturnValue) {
490    // Make sure not to return anything, but evaluate the expression
491    // for side effects.
492    if (RV)
493      EmitAnyExpr(RV);
494  } else if (RV == 0) {
495    // Do nothing (return value is left uninitialized)
496  } else if (!hasAggregateLLVMType(RV->getType())) {
497    Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
498  } else if (RV->getType()->isAnyComplexType()) {
499    EmitComplexExprIntoAddr(RV, ReturnValue, false);
500  } else {
501    EmitAggExpr(RV, ReturnValue, false);
502  }
503
504  if (!ObjCEHStack.empty()) {
505    for (ObjCEHStackType::reverse_iterator i = ObjCEHStack.rbegin(),
506           e = ObjCEHStack.rend(); i != e; ++i) {
507      llvm::BasicBlock *ReturnPad = createBasicBlock("return.pad");
508      EmitJumpThroughFinally(*i, ReturnPad);
509      EmitBlock(ReturnPad);
510    }
511  }
512
513  EmitBranch(ReturnBlock);
514}
515
516void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
517  for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
518       I != E; ++I)
519    EmitDecl(**I);
520}
521
522void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
523  assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
524
525  // FIXME: Implement break in @try or @catch blocks.
526  if (ObjCEHStack.size() != BreakContinueStack.back().EHStackSize) {
527    CGM.ErrorUnsupported(&S, "break inside an Obj-C exception block");
528    return;
529  }
530
531  if (StackSaveValues.back()) {
532    CGM.ErrorUnsupported(&S, "break inside scope with VLA");
533    return;
534  }
535
536  // If this code is reachable then emit a stop point (if generating
537  // debug info). We have to do this ourselves because we are on the
538  // "simple" statement path.
539  if (HaveInsertPoint())
540    EmitStopPoint(&S);
541  llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
542  EmitBranch(Block);
543}
544
545void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
546  assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
547
548  // FIXME: Implement continue in @try or @catch blocks.
549  if (ObjCEHStack.size() != BreakContinueStack.back().EHStackSize) {
550    CGM.ErrorUnsupported(&S, "continue inside an Obj-C exception block");
551    return;
552  }
553
554  if (StackSaveValues.back()) {
555    CGM.ErrorUnsupported(&S, "continue inside scope with VLA");
556    return;
557  }
558
559  // If this code is reachable then emit a stop point (if generating
560  // debug info). We have to do this ourselves because we are on the
561  // "simple" statement path.
562  if (HaveInsertPoint())
563    EmitStopPoint(&S);
564  llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
565  EmitBranch(Block);
566}
567
568/// EmitCaseStmtRange - If case statement range is not too big then
569/// add multiple cases to switch instruction, one for each value within
570/// the range. If range is too big then emit "if" condition check.
571void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
572  assert(S.getRHS() && "Expected RHS value in CaseStmt");
573
574  llvm::APSInt LHS = S.getLHS()->EvaluateAsInt(getContext());
575  llvm::APSInt RHS = S.getRHS()->EvaluateAsInt(getContext());
576
577  // Emit the code for this case. We do this first to make sure it is
578  // properly chained from our predecessor before generating the
579  // switch machinery to enter this block.
580  EmitBlock(createBasicBlock("sw.bb"));
581  llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
582  EmitStmt(S.getSubStmt());
583
584  // If range is empty, do nothing.
585  if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
586    return;
587
588  llvm::APInt Range = RHS - LHS;
589  // FIXME: parameters such as this should not be hardcoded.
590  if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
591    // Range is small enough to add multiple switch instruction cases.
592    for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
593      SwitchInsn->addCase(llvm::ConstantInt::get(LHS), CaseDest);
594      LHS++;
595    }
596    return;
597  }
598
599  // The range is too big. Emit "if" condition into a new block,
600  // making sure to save and restore the current insertion point.
601  llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
602
603  // Push this test onto the chain of range checks (which terminates
604  // in the default basic block). The switch's default will be changed
605  // to the top of this chain after switch emission is complete.
606  llvm::BasicBlock *FalseDest = CaseRangeBlock;
607  CaseRangeBlock = createBasicBlock("sw.caserange");
608
609  CurFn->getBasicBlockList().push_back(CaseRangeBlock);
610  Builder.SetInsertPoint(CaseRangeBlock);
611
612  // Emit range check.
613  llvm::Value *Diff =
614    Builder.CreateSub(SwitchInsn->getCondition(), llvm::ConstantInt::get(LHS),
615                      "tmp");
616  llvm::Value *Cond =
617    Builder.CreateICmpULE(Diff, llvm::ConstantInt::get(Range), "tmp");
618  Builder.CreateCondBr(Cond, CaseDest, FalseDest);
619
620  // Restore the appropriate insertion point.
621  if (RestoreBB)
622    Builder.SetInsertPoint(RestoreBB);
623  else
624    Builder.ClearInsertionPoint();
625}
626
627void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
628  if (S.getRHS()) {
629    EmitCaseStmtRange(S);
630    return;
631  }
632
633  EmitBlock(createBasicBlock("sw.bb"));
634  llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
635  llvm::APSInt CaseVal = S.getLHS()->EvaluateAsInt(getContext());
636  SwitchInsn->addCase(llvm::ConstantInt::get(CaseVal), CaseDest);
637  EmitStmt(S.getSubStmt());
638}
639
640void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
641  llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
642  assert(DefaultBlock->empty() &&
643         "EmitDefaultStmt: Default block already defined?");
644  EmitBlock(DefaultBlock);
645  EmitStmt(S.getSubStmt());
646}
647
648void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
649  llvm::Value *CondV = EmitScalarExpr(S.getCond());
650
651  // Handle nested switch statements.
652  llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
653  llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
654
655  // Create basic block to hold stuff that comes after switch
656  // statement. We also need to create a default block now so that
657  // explicit case ranges tests can have a place to jump to on
658  // failure.
659  llvm::BasicBlock *NextBlock = createBasicBlock("sw.epilog");
660  llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
661  SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
662  CaseRangeBlock = DefaultBlock;
663
664  // Clear the insertion point to indicate we are in unreachable code.
665  Builder.ClearInsertionPoint();
666
667  // All break statements jump to NextBlock. If BreakContinueStack is non empty
668  // then reuse last ContinueBlock.
669  llvm::BasicBlock *ContinueBlock = NULL;
670  if (!BreakContinueStack.empty())
671    ContinueBlock = BreakContinueStack.back().ContinueBlock;
672  BreakContinueStack.push_back(BreakContinue(NextBlock, ContinueBlock,
673                                             ObjCEHStack.size()));
674
675  // Emit switch body.
676  EmitStmt(S.getBody());
677  BreakContinueStack.pop_back();
678
679  // Update the default block in case explicit case range tests have
680  // been chained on top.
681  SwitchInsn->setSuccessor(0, CaseRangeBlock);
682
683  // If a default was never emitted then reroute any jumps to it and
684  // discard.
685  if (!DefaultBlock->getParent()) {
686    DefaultBlock->replaceAllUsesWith(NextBlock);
687    delete DefaultBlock;
688  }
689
690  // Emit continuation.
691  EmitBlock(NextBlock, true);
692
693  SwitchInsn = SavedSwitchInsn;
694  CaseRangeBlock = SavedCRBlock;
695}
696
697static std::string ConvertAsmString(const AsmStmt& S, bool &Failed)
698{
699  // FIXME: No need to create new std::string here, we could just make sure
700  // that we don't read past the end of the string data.
701  std::string str(S.getAsmString()->getStrData(),
702                  S.getAsmString()->getByteLength());
703  const char *Start = str.c_str();
704
705  unsigned NumOperands = S.getNumOutputs() + S.getNumInputs();
706  bool IsSimple = S.isSimple();
707  Failed = false;
708
709  static unsigned AsmCounter = 0;
710  AsmCounter++;
711  std::string Result;
712  if (IsSimple) {
713    while (*Start) {
714      switch (*Start) {
715      default:
716        Result += *Start;
717        break;
718      case '$':
719        Result += "$$";
720        break;
721      }
722      Start++;
723    }
724
725    return Result;
726  }
727
728  while (*Start) {
729    switch (*Start) {
730    default:
731      Result += *Start;
732      break;
733    case '$':
734      Result += "$$";
735      break;
736    case '%':
737      // Escaped character
738      Start++;
739      if (!*Start) {
740        // FIXME: This should be caught during Sema.
741        assert(0 && "Trailing '%' in asm string.");
742      }
743
744      char EscapedChar = *Start;
745      if (EscapedChar == '%') {
746        // Escaped percentage sign.
747        Result += '%';
748      } else if (EscapedChar == '=') {
749        // Generate an unique ID.
750        Result += llvm::utostr(AsmCounter);
751      } else if (isdigit(EscapedChar)) {
752        // %n - Assembler operand n
753        char *End;
754        unsigned long n = strtoul(Start, &End, 10);
755        if (Start == End) {
756          // FIXME: This should be caught during Sema.
757          assert(0 && "Missing operand!");
758        } else if (n >= NumOperands) {
759          // FIXME: This should be caught during Sema.
760          assert(0 && "Operand number out of range!");
761        }
762
763        Result += '$' + llvm::utostr(n);
764        Start = End - 1;
765      } else if (isalpha(EscapedChar)) {
766        char *End;
767
768        unsigned long n = strtoul(Start + 1, &End, 10);
769        if (Start == End) {
770          // FIXME: This should be caught during Sema.
771          assert(0 && "Missing operand!");
772        } else if (n >= NumOperands) {
773          // FIXME: This should be caught during Sema.
774          assert(0 && "Operand number out of range!");
775        }
776
777        Result += "${" + llvm::utostr(n) + ':' + EscapedChar + '}';
778        Start = End - 1;
779      } else if (EscapedChar == '[') {
780        std::string SymbolicName;
781
782        Start++;
783
784        while (*Start && *Start != ']') {
785          SymbolicName += *Start;
786
787          Start++;
788        }
789
790        if (!Start) {
791          // FIXME: Should be caught by sema.
792          assert(0 && "Could not parse symbolic name");
793        }
794
795        assert(*Start == ']' && "Error parsing symbolic name");
796
797        int Index = -1;
798
799        // Check if this is an output operand.
800        for (unsigned i = 0; i < S.getNumOutputs(); i++) {
801          if (S.getOutputName(i) == SymbolicName) {
802            Index = i;
803            break;
804          }
805        }
806
807        if (Index == -1) {
808          for (unsigned i = 0; i < S.getNumInputs(); i++) {
809            if (S.getInputName(i) == SymbolicName) {
810              Index = S.getNumOutputs() + i;
811            }
812          }
813        }
814
815        assert(Index != -1 && "Did not find right operand!");
816
817        Result += '$' + llvm::utostr(Index);
818
819      } else {
820        Failed = true;
821        return "";
822      }
823    }
824    Start++;
825  }
826
827  return Result;
828}
829
830static std::string SimplifyConstraint(const char* Constraint,
831                                      TargetInfo &Target) {
832  std::string Result;
833
834  while (*Constraint) {
835    switch (*Constraint) {
836    default:
837      Result += Target.convertConstraint(*Constraint);
838      break;
839    // Ignore these
840    case '*':
841    case '?':
842    case '!':
843      break;
844    case 'g':
845      Result += "imr";
846      break;
847    }
848
849    Constraint++;
850  }
851
852  return Result;
853}
854
855void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
856  bool Failed;
857  std::string AsmString =
858    ConvertAsmString(S, Failed);
859
860  if (Failed) {
861    ErrorUnsupported(&S, "asm string");
862    return;
863  }
864
865  std::string Constraints;
866
867  llvm::Value *ResultAddr = 0;
868  const llvm::Type *ResultType = llvm::Type::VoidTy;
869
870  std::vector<const llvm::Type*> ArgTypes;
871  std::vector<llvm::Value*> Args;
872
873  // Keep track of inout constraints.
874  std::string InOutConstraints;
875  std::vector<llvm::Value*> InOutArgs;
876  std::vector<const llvm::Type*> InOutArgTypes;
877
878  for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
879    std::string OutputConstraint(S.getOutputConstraint(i)->getStrData(),
880                                 S.getOutputConstraint(i)->getByteLength());
881
882    TargetInfo::ConstraintInfo Info;
883    bool result = Target.validateOutputConstraint(OutputConstraint.c_str(),
884                                                  Info);
885    assert(result && "Failed to parse output constraint"); result=result;
886
887    // Simplify the output constraint.
888    OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
889
890    LValue Dest = EmitLValue(S.getOutputExpr(i));
891    const llvm::Type *DestValueType =
892      cast<llvm::PointerType>(Dest.getAddress()->getType())->getElementType();
893
894    // If the first output operand is not a memory dest, we'll
895    // make it the return value.
896    if (i == 0 && !(Info & TargetInfo::CI_AllowsMemory) &&
897        DestValueType->isSingleValueType()) {
898      ResultAddr = Dest.getAddress();
899      ResultType = DestValueType;
900      Constraints += "=" + OutputConstraint;
901    } else {
902      ArgTypes.push_back(Dest.getAddress()->getType());
903      Args.push_back(Dest.getAddress());
904      if (i != 0)
905        Constraints += ',';
906      Constraints += "=*";
907      Constraints += OutputConstraint;
908    }
909
910    if (Info & TargetInfo::CI_ReadWrite) {
911      // FIXME: This code should be shared with the code that handles inputs.
912      InOutConstraints += ',';
913
914      const Expr *InputExpr = S.getOutputExpr(i);
915      llvm::Value *Arg;
916      if ((Info & TargetInfo::CI_AllowsRegister) ||
917          !(Info & TargetInfo::CI_AllowsMemory)) {
918        if (ConvertType(InputExpr->getType())->isSingleValueType()) {
919          Arg = EmitScalarExpr(InputExpr);
920        } else {
921          ErrorUnsupported(&S,
922                      "asm statement passing multiple-value types as inputs");
923        }
924      } else {
925        LValue Dest = EmitLValue(InputExpr);
926        Arg = Dest.getAddress();
927        InOutConstraints += '*';
928      }
929
930      InOutArgTypes.push_back(Arg->getType());
931      InOutArgs.push_back(Arg);
932      InOutConstraints += OutputConstraint;
933    }
934  }
935
936  unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
937
938  for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
939    const Expr *InputExpr = S.getInputExpr(i);
940
941    std::string InputConstraint(S.getInputConstraint(i)->getStrData(),
942                                S.getInputConstraint(i)->getByteLength());
943
944    TargetInfo::ConstraintInfo Info;
945    bool result = Target.validateInputConstraint(InputConstraint.c_str(),
946                                                 NumConstraints,  Info);
947    assert(result && "Failed to parse input constraint"); result=result;
948
949    if (i != 0 || S.getNumOutputs() > 0)
950      Constraints += ',';
951
952    // Simplify the input constraint.
953    InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target);
954
955    llvm::Value *Arg;
956
957    if ((Info & TargetInfo::CI_AllowsRegister) ||
958        !(Info & TargetInfo::CI_AllowsMemory)) {
959      if (ConvertType(InputExpr->getType())->isSingleValueType()) {
960        Arg = EmitScalarExpr(InputExpr);
961      } else {
962        ErrorUnsupported(&S,
963                        "asm statement passing multiple-value types as inputs");
964      }
965    } else {
966      LValue Dest = EmitLValue(InputExpr);
967      Arg = Dest.getAddress();
968      Constraints += '*';
969    }
970
971    ArgTypes.push_back(Arg->getType());
972    Args.push_back(Arg);
973    Constraints += InputConstraint;
974  }
975
976  // Append the "input" part of inout constraints last.
977  for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
978    ArgTypes.push_back(InOutArgTypes[i]);
979    Args.push_back(InOutArgs[i]);
980  }
981  Constraints += InOutConstraints;
982
983  // Clobbers
984  for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
985    std::string Clobber(S.getClobber(i)->getStrData(),
986                        S.getClobber(i)->getByteLength());
987
988    Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str());
989
990    if (i != 0 || NumConstraints != 0)
991      Constraints += ',';
992
993    Constraints += "~{";
994    Constraints += Clobber;
995    Constraints += '}';
996  }
997
998  // Add machine specific clobbers
999  if (const char *C = Target.getClobbers()) {
1000    if (!Constraints.empty())
1001      Constraints += ',';
1002    Constraints += C;
1003  }
1004
1005  const llvm::FunctionType *FTy =
1006    llvm::FunctionType::get(ResultType, ArgTypes, false);
1007
1008  llvm::InlineAsm *IA =
1009    llvm::InlineAsm::get(FTy, AsmString, Constraints,
1010                         S.isVolatile() || S.getNumOutputs() == 0);
1011  llvm::Value *Result = Builder.CreateCall(IA, Args.begin(), Args.end(), "");
1012  if (ResultAddr) // FIXME: volatility
1013    Builder.CreateStore(Result, ResultAddr);
1014}
1015