CGStmt.cpp revision 91d723da7b68be5245c3ac58aa2a36d04658cfb8
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/AST.h"
18#include "clang/Basic/TargetInfo.h"
19#include "llvm/Constants.h"
20#include "llvm/DerivedTypes.h"
21#include "llvm/Function.h"
22#include "llvm/InlineAsm.h"
23#include "llvm/ADT/StringExtras.h"
24using namespace clang;
25using namespace CodeGen;
26
27//===----------------------------------------------------------------------===//
28//                              Statement Emission
29//===----------------------------------------------------------------------===//
30
31void CodeGenFunction::EmitStmt(const Stmt *S) {
32  assert(S && "Null statement?");
33
34  // Generate stoppoints if we are emitting debug info.
35  // Beginning of a Compound Statement (e.g. an opening '{') does not produce
36  // executable code. So do not generate a stoppoint for that.
37  CGDebugInfo *DI = CGM.getDebugInfo();
38  if (DI && S->getStmtClass() != Stmt::CompoundStmtClass) {
39    if (S->getLocStart().isValid()) {
40        DI->setLocation(S->getLocStart());
41    }
42
43    DI->EmitStopPoint(CurFn, Builder);
44  }
45
46  switch (S->getStmtClass()) {
47  default:
48    // Must be an expression in a stmt context.  Emit the value (to get
49    // side-effects) and ignore the result.
50    if (const Expr *E = dyn_cast<Expr>(S)) {
51      if (!hasAggregateLLVMType(E->getType()))
52        EmitScalarExpr(E);
53      else if (E->getType()->isAnyComplexType())
54        EmitComplexExpr(E);
55      else
56        EmitAggExpr(E, 0, false);
57    } else {
58      WarnUnsupported(S, "statement");
59    }
60    break;
61  case Stmt::NullStmtClass: break;
62  case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
63  case Stmt::LabelStmtClass:    EmitLabelStmt(cast<LabelStmt>(*S));       break;
64  case Stmt::GotoStmtClass:     EmitGotoStmt(cast<GotoStmt>(*S));         break;
65
66  case Stmt::IfStmtClass:       EmitIfStmt(cast<IfStmt>(*S));             break;
67  case Stmt::WhileStmtClass:    EmitWhileStmt(cast<WhileStmt>(*S));       break;
68  case Stmt::DoStmtClass:       EmitDoStmt(cast<DoStmt>(*S));             break;
69  case Stmt::ForStmtClass:      EmitForStmt(cast<ForStmt>(*S));           break;
70
71  case Stmt::ReturnStmtClass:   EmitReturnStmt(cast<ReturnStmt>(*S));     break;
72  case Stmt::DeclStmtClass:     EmitDeclStmt(cast<DeclStmt>(*S));         break;
73
74  case Stmt::BreakStmtClass:    EmitBreakStmt();                          break;
75  case Stmt::ContinueStmtClass: EmitContinueStmt();                       break;
76  case Stmt::SwitchStmtClass:   EmitSwitchStmt(cast<SwitchStmt>(*S));     break;
77  case Stmt::DefaultStmtClass:  EmitDefaultStmt(cast<DefaultStmt>(*S));   break;
78  case Stmt::CaseStmtClass:     EmitCaseStmt(cast<CaseStmt>(*S));         break;
79  case Stmt::AsmStmtClass:      EmitAsmStmt(cast<AsmStmt>(*S));           break;
80  }
81}
82
83/// EmitCompoundStmt - Emit a compound statement {..} node.  If GetLast is true,
84/// this captures the expression result of the last sub-statement and returns it
85/// (for use by the statement expression extension).
86RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
87                                         llvm::Value *AggLoc, bool isAggVol) {
88  // FIXME: handle vla's etc.
89  CGDebugInfo *DI = CGM.getDebugInfo();
90  if (DI) {
91    if (S.getLBracLoc().isValid())
92      DI->setLocation(S.getLBracLoc());
93    DI->EmitRegionStart(CurFn, Builder);
94  }
95
96  for (CompoundStmt::const_body_iterator I = S.body_begin(),
97       E = S.body_end()-GetLast; I != E; ++I)
98    EmitStmt(*I);
99
100  if (DI) {
101    if (S.getRBracLoc().isValid())
102      DI->setLocation(S.getRBracLoc());
103    DI->EmitRegionEnd(CurFn, Builder);
104  }
105
106  if (!GetLast)
107    return RValue::get(0);
108
109  // We have to special case labels here.  They are statements, but when put at
110  // the end of a statement expression, they yield the value of their
111  // subexpression.  Handle this by walking through all labels we encounter,
112  // emitting them before we evaluate the subexpr.
113  const Stmt *LastStmt = S.body_back();
114  while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
115    EmitLabel(*LS);
116    LastStmt = LS->getSubStmt();
117  }
118
119  return EmitAnyExpr(cast<Expr>(LastStmt), AggLoc);
120}
121
122void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB) {
123  // Emit a branch from this block to the next one if this was a real block.  If
124  // this was just a fall-through block after a terminator, don't emit it.
125  llvm::BasicBlock *LastBB = Builder.GetInsertBlock();
126
127  if (LastBB->getTerminator()) {
128    // If the previous block is already terminated, don't touch it.
129  } else if (LastBB->empty() && isDummyBlock(LastBB)) {
130    // If the last block was an empty placeholder, remove it now.
131    // TODO: cache and reuse these.
132    LastBB->eraseFromParent();
133  } else {
134    // Otherwise, create a fall-through branch.
135    Builder.CreateBr(BB);
136  }
137  CurFn->getBasicBlockList().push_back(BB);
138  Builder.SetInsertPoint(BB);
139}
140
141void CodeGenFunction::EmitLabel(const LabelStmt &S) {
142  llvm::BasicBlock *NextBB = getBasicBlockForLabel(&S);
143  EmitBlock(NextBB);
144}
145
146
147void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
148  EmitLabel(S);
149  EmitStmt(S.getSubStmt());
150}
151
152void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
153  Builder.CreateBr(getBasicBlockForLabel(S.getLabel()));
154
155  // Emit a block after the branch so that dead code after a goto has some place
156  // to go.
157  Builder.SetInsertPoint(llvm::BasicBlock::Create("", CurFn));
158}
159
160void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
161  // C99 6.8.4.1: The first substatement is executed if the expression compares
162  // unequal to 0.  The condition must be a scalar type.
163  llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
164
165  llvm::BasicBlock *ContBlock = llvm::BasicBlock::Create("ifend");
166  llvm::BasicBlock *ThenBlock = llvm::BasicBlock::Create("ifthen");
167  llvm::BasicBlock *ElseBlock = ContBlock;
168
169  if (S.getElse())
170    ElseBlock = llvm::BasicBlock::Create("ifelse");
171
172  // Insert the conditional branch.
173  Builder.CreateCondBr(BoolCondVal, ThenBlock, ElseBlock);
174
175  // Emit the 'then' code.
176  EmitBlock(ThenBlock);
177  EmitStmt(S.getThen());
178  llvm::BasicBlock *BB = Builder.GetInsertBlock();
179  if (isDummyBlock(BB)) {
180    BB->eraseFromParent();
181    Builder.SetInsertPoint(ThenBlock);
182  } else {
183    Builder.CreateBr(ContBlock);
184  }
185
186  // Emit the 'else' code if present.
187  if (const Stmt *Else = S.getElse()) {
188    EmitBlock(ElseBlock);
189    EmitStmt(Else);
190    llvm::BasicBlock *BB = Builder.GetInsertBlock();
191    if (isDummyBlock(BB)) {
192      BB->eraseFromParent();
193      Builder.SetInsertPoint(ElseBlock);
194    } else {
195      Builder.CreateBr(ContBlock);
196    }
197  }
198
199  // Emit the continuation block for code after the if.
200  EmitBlock(ContBlock);
201}
202
203void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
204  // Emit the header for the loop, insert it, which will create an uncond br to
205  // it.
206  llvm::BasicBlock *LoopHeader = llvm::BasicBlock::Create("whilecond");
207  EmitBlock(LoopHeader);
208
209  // Evaluate the conditional in the while header.  C99 6.8.5.1: The evaluation
210  // of the controlling expression takes place before each execution of the loop
211  // body.
212  llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
213
214  // while(1) is common, avoid extra exit blocks.  Be sure
215  // to correctly handle break/continue though.
216  bool EmitBoolCondBranch = true;
217  if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
218    if (C->isOne())
219      EmitBoolCondBranch = false;
220
221  // Create an exit block for when the condition fails, create a block for the
222  // body of the loop.
223  llvm::BasicBlock *ExitBlock = llvm::BasicBlock::Create("whileexit");
224  llvm::BasicBlock *LoopBody  = llvm::BasicBlock::Create("whilebody");
225
226  // As long as the condition is true, go to the loop body.
227  if (EmitBoolCondBranch)
228    Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
229
230  // Store the blocks to use for break and continue.
231  BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader));
232
233  // Emit the loop body.
234  EmitBlock(LoopBody);
235  EmitStmt(S.getBody());
236
237  BreakContinueStack.pop_back();
238
239  // Cycle to the condition.
240  Builder.CreateBr(LoopHeader);
241
242  // Emit the exit block.
243  EmitBlock(ExitBlock);
244
245  // If LoopHeader is a simple forwarding block then eliminate it.
246  if (!EmitBoolCondBranch
247      && &LoopHeader->front() == LoopHeader->getTerminator()) {
248    LoopHeader->replaceAllUsesWith(LoopBody);
249    LoopHeader->getTerminator()->eraseFromParent();
250    LoopHeader->eraseFromParent();
251  }
252}
253
254void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
255  // Emit the body for the loop, insert it, which will create an uncond br to
256  // it.
257  llvm::BasicBlock *LoopBody = llvm::BasicBlock::Create("dobody");
258  llvm::BasicBlock *AfterDo = llvm::BasicBlock::Create("afterdo");
259  EmitBlock(LoopBody);
260
261  llvm::BasicBlock *DoCond = llvm::BasicBlock::Create("docond");
262
263  // Store the blocks to use for break and continue.
264  BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond));
265
266  // Emit the body of the loop into the block.
267  EmitStmt(S.getBody());
268
269  BreakContinueStack.pop_back();
270
271  EmitBlock(DoCond);
272
273  // C99 6.8.5.2: "The evaluation of the controlling expression takes place
274  // after each execution of the loop body."
275
276  // Evaluate the conditional in the while header.
277  // C99 6.8.5p2/p4: The first substatement is executed if the expression
278  // compares unequal to 0.  The condition must be a scalar type.
279  llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
280
281  // "do {} while (0)" is common in macros, avoid extra blocks.  Be sure
282  // to correctly handle break/continue though.
283  bool EmitBoolCondBranch = true;
284  if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
285    if (C->isZero())
286      EmitBoolCondBranch = false;
287
288  // As long as the condition is true, iterate the loop.
289  if (EmitBoolCondBranch)
290    Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
291
292  // Emit the exit block.
293  EmitBlock(AfterDo);
294
295  // If DoCond is a simple forwarding block then eliminate it.
296  if (!EmitBoolCondBranch && &DoCond->front() == DoCond->getTerminator()) {
297    DoCond->replaceAllUsesWith(AfterDo);
298    DoCond->getTerminator()->eraseFromParent();
299    DoCond->eraseFromParent();
300  }
301}
302
303void CodeGenFunction::EmitForStmt(const ForStmt &S) {
304  // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
305  // which contains a continue/break?
306  // TODO: We could keep track of whether the loop body contains any
307  // break/continue statements and not create unnecessary blocks (like
308  // "afterfor" for a condless loop) if it doesn't.
309
310  // Evaluate the first part before the loop.
311  if (S.getInit())
312    EmitStmt(S.getInit());
313
314  // Start the loop with a block that tests the condition.
315  llvm::BasicBlock *CondBlock = llvm::BasicBlock::Create("forcond");
316  llvm::BasicBlock *AfterFor = llvm::BasicBlock::Create("afterfor");
317
318  EmitBlock(CondBlock);
319
320  // Evaluate the condition if present.  If not, treat it as a non-zero-constant
321  // according to 6.8.5.3p2, aka, true.
322  if (S.getCond()) {
323    // C99 6.8.5p2/p4: The first substatement is executed if the expression
324    // compares unequal to 0.  The condition must be a scalar type.
325    llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
326
327    // As long as the condition is true, iterate the loop.
328    llvm::BasicBlock *ForBody = llvm::BasicBlock::Create("forbody");
329    Builder.CreateCondBr(BoolCondVal, ForBody, AfterFor);
330    EmitBlock(ForBody);
331  } else {
332    // Treat it as a non-zero constant.  Don't even create a new block for the
333    // body, just fall into it.
334  }
335
336  // If the for loop doesn't have an increment we can just use the
337  // condition as the continue block.
338  llvm::BasicBlock *ContinueBlock;
339  if (S.getInc())
340    ContinueBlock = llvm::BasicBlock::Create("forinc");
341  else
342    ContinueBlock = CondBlock;
343
344  // Store the blocks to use for break and continue.
345  BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock));
346
347  // If the condition is true, execute the body of the for stmt.
348  EmitStmt(S.getBody());
349
350  BreakContinueStack.pop_back();
351
352  if (S.getInc())
353    EmitBlock(ContinueBlock);
354
355  // If there is an increment, emit it next.
356  if (S.getInc())
357    EmitStmt(S.getInc());
358
359  // Finally, branch back up to the condition for the next iteration.
360  Builder.CreateBr(CondBlock);
361
362  // Emit the fall-through block.
363  EmitBlock(AfterFor);
364}
365
366/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
367/// if the function returns void, or may be missing one if the function returns
368/// non-void.  Fun stuff :).
369void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
370  // Emit the result value, even if unused, to evalute the side effects.
371  const Expr *RV = S.getRetValue();
372
373  llvm::Value* RetValue = 0;
374  if (FnRetTy->isVoidType()) {
375    // Make sure not to return anything
376    if (RV) {
377      // Evaluate the expression for side effects
378      EmitAnyExpr(RV);
379    }
380  } else if (RV == 0) {
381    const llvm::Type *RetTy = CurFn->getFunctionType()->getReturnType();
382    if (RetTy != llvm::Type::VoidTy) {
383      // Handle "return;" in a function that returns a value.
384      RetValue = llvm::UndefValue::get(RetTy);
385    }
386  } else if (!hasAggregateLLVMType(RV->getType())) {
387    RetValue = EmitScalarExpr(RV);
388  } else if (RV->getType()->isAnyComplexType()) {
389    EmitComplexExprIntoAddr(RV, CurFn->arg_begin(), false);
390  } else {
391    EmitAggExpr(RV, CurFn->arg_begin(), false);
392  }
393
394  if (RetValue) {
395    Builder.CreateRet(RetValue);
396  } else {
397    Builder.CreateRetVoid();
398  }
399
400  // Emit a block after the branch so that dead code after a return has some
401  // place to go.
402  EmitBlock(llvm::BasicBlock::Create());
403}
404
405void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
406  for (const ScopedDecl *Decl = S.getDecl(); Decl;
407       Decl = Decl->getNextDeclarator())
408    EmitDecl(*Decl);
409}
410
411void CodeGenFunction::EmitBreakStmt() {
412  assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
413
414  llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
415  Builder.CreateBr(Block);
416  EmitBlock(llvm::BasicBlock::Create());
417}
418
419void CodeGenFunction::EmitContinueStmt() {
420  assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
421
422  llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
423  Builder.CreateBr(Block);
424  EmitBlock(llvm::BasicBlock::Create());
425}
426
427/// EmitCaseStmtRange - If case statement range is not too big then
428/// add multiple cases to switch instruction, one for each value within
429/// the range. If range is too big then emit "if" condition check.
430void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
431  // XXX kill me with param - ddunbar
432  assert(S.getRHS() && "Expected RHS value in CaseStmt");
433
434  llvm::APSInt LHS = S.getLHS()->getIntegerConstantExprValue(getContext());
435  llvm::APSInt RHS = S.getRHS()->getIntegerConstantExprValue(getContext());
436
437  // Emit the code for this case. We do this first to make sure it is
438  // properly chained from our predecessor before generating the
439  // switch machinery to enter this block.
440  StartBlock("sw.bb");
441  llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
442  EmitStmt(S.getSubStmt());
443
444  // If range is empty, do nothing.
445  if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
446    return;
447
448  llvm::APInt Range = RHS - LHS;
449  // FIXME: parameters such as this should not be hardcoded.
450  if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
451    // Range is small enough to add multiple switch instruction cases.
452    for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
453      SwitchInsn->addCase(llvm::ConstantInt::get(LHS), CaseDest);
454      LHS++;
455    }
456    return;
457  }
458
459  // The range is too big. Emit "if" condition into a new block,
460  // making sure to save and restore the current insertion point.
461  llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
462
463  // Push this test onto the chain of range checks (which terminates
464  // in the default basic block). The switch's default will be changed
465  // to the top of this chain after switch emission is complete.
466  llvm::BasicBlock *FalseDest = CaseRangeBlock;
467  CaseRangeBlock = llvm::BasicBlock::Create("sw.caserange");
468
469  CurFn->getBasicBlockList().push_back(CaseRangeBlock);
470  Builder.SetInsertPoint(CaseRangeBlock);
471
472  // Emit range check.
473  llvm::Value *Diff =
474    Builder.CreateSub(SwitchInsn->getCondition(), llvm::ConstantInt::get(LHS),
475                      "tmp");
476  llvm::Value *Cond =
477    Builder.CreateICmpULE(Diff, llvm::ConstantInt::get(Range), "tmp");
478  Builder.CreateCondBr(Cond, CaseDest, FalseDest);
479
480  // Restore the appropriate insertion point.
481  Builder.SetInsertPoint(RestoreBB);
482}
483
484void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
485  if (S.getRHS()) {
486    EmitCaseStmtRange(S);
487    return;
488  }
489
490  StartBlock("sw.bb");
491  llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
492  llvm::APSInt CaseVal = S.getLHS()->getIntegerConstantExprValue(getContext());
493  SwitchInsn->addCase(llvm::ConstantInt::get(CaseVal),
494                      CaseDest);
495  EmitStmt(S.getSubStmt());
496}
497
498void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
499  llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
500  assert(DefaultBlock->empty() && "EmitDefaultStmt: Default block already defined?");
501  EmitBlock(DefaultBlock);
502  EmitStmt(S.getSubStmt());
503}
504
505void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
506  llvm::Value *CondV = EmitScalarExpr(S.getCond());
507
508  // Handle nested switch statements.
509  llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
510  llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
511
512  // Create basic block to hold stuff that comes after switch
513  // statement. We also need to create a default block now so that
514  // explicit case ranges tests can have a place to jump to on
515  // failure.
516  llvm::BasicBlock *NextBlock = llvm::BasicBlock::Create("sw.epilog");
517  llvm::BasicBlock *DefaultBlock = llvm::BasicBlock::Create("sw.default");
518  SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
519  CaseRangeBlock = DefaultBlock;
520
521  // Create basic block for body of switch
522  StartBlock("sw.body");
523
524  // All break statements jump to NextBlock. If BreakContinueStack is non empty
525  // then reuse last ContinueBlock.
526  llvm::BasicBlock *ContinueBlock = NULL;
527  if (!BreakContinueStack.empty())
528    ContinueBlock = BreakContinueStack.back().ContinueBlock;
529  BreakContinueStack.push_back(BreakContinue(NextBlock, ContinueBlock));
530
531  // Emit switch body.
532  EmitStmt(S.getBody());
533  BreakContinueStack.pop_back();
534
535  // Update the default block in case explicit case range tests have
536  // been chained on top.
537  SwitchInsn->setSuccessor(0, CaseRangeBlock);
538
539  // If a default was never emitted then reroute any jumps to it and
540  // discard.
541  if (!DefaultBlock->getParent()) {
542    DefaultBlock->replaceAllUsesWith(NextBlock);
543    delete DefaultBlock;
544  }
545
546  // Emit continuation.
547  EmitBlock(NextBlock);
548
549  SwitchInsn = SavedSwitchInsn;
550  CaseRangeBlock = SavedCRBlock;
551}
552
553static std::string ConvertAsmString(const char *Start, unsigned NumOperands,
554                                    bool IsSimple) {
555  static unsigned AsmCounter = 0;
556  AsmCounter++;
557  std::string Result;
558  if (IsSimple) {
559    while (*Start) {
560      switch (*Start) {
561      default:
562        Result += *Start;
563        break;
564      case '$':
565        Result += "$$";
566        break;
567      }
568      Start++;
569    }
570
571    return Result;
572  }
573
574  while (*Start) {
575    switch (*Start) {
576    default:
577      Result += *Start;
578      break;
579    case '$':
580      Result += "$$";
581      break;
582    case '%':
583      // Escaped character
584      Start++;
585      if (!*Start) {
586        // FIXME: This should be caught during Sema.
587        assert(0 && "Trailing '%' in asm string.");
588      }
589
590      char EscapedChar = *Start;
591      if (EscapedChar == '%') {
592        // Escaped percentage sign.
593        Result += '%';
594      } else if (EscapedChar == '=') {
595        // Generate an unique ID.
596        Result += llvm::utostr(AsmCounter);
597      } else if (isdigit(EscapedChar)) {
598        // %n - Assembler operand n
599        char *End;
600        unsigned long n = strtoul(Start, &End, 10);
601        if (Start == End) {
602          // FIXME: This should be caught during Sema.
603          assert(0 && "Missing operand!");
604        } else if (n >= NumOperands) {
605          // FIXME: This should be caught during Sema.
606          assert(0 && "Operand number out of range!");
607        }
608
609        Result += '$' + llvm::utostr(n);
610        Start = End - 1;
611      } else if (isalpha(EscapedChar)) {
612        char *End;
613
614        unsigned long n = strtoul(Start + 1, &End, 10);
615        if (Start == End) {
616          // FIXME: This should be caught during Sema.
617          assert(0 && "Missing operand!");
618        } else if (n >= NumOperands) {
619          // FIXME: This should be caught during Sema.
620          assert(0 && "Operand number out of range!");
621        }
622
623        Result += "${" + llvm::utostr(n) + ':' + EscapedChar + '}';
624        Start = End - 1;
625      } else {
626        assert(0 && "Unhandled asm escaped character!");
627      }
628    }
629    Start++;
630  }
631
632  return Result;
633}
634
635static std::string SimplifyConstraint(const char* Constraint,
636                                      TargetInfo &Target) {
637  std::string Result;
638
639  while (*Constraint) {
640    switch (*Constraint) {
641    default:
642      Result += Target.convertConstraint(*Constraint);
643      break;
644    // Ignore these
645    case '*':
646    case '?':
647    case '!':
648      break;
649    case 'g':
650      Result += "imr";
651      break;
652    }
653
654    Constraint++;
655  }
656
657  return Result;
658}
659
660void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
661  std::string AsmString =
662    ConvertAsmString(std::string(S.getAsmString()->getStrData(),
663                                 S.getAsmString()->getByteLength()).c_str(),
664                     S.getNumOutputs() + S.getNumInputs(), S.isSimple());
665
666  std::string Constraints;
667
668  llvm::Value *ResultAddr = 0;
669  const llvm::Type *ResultType = llvm::Type::VoidTy;
670
671  std::vector<const llvm::Type*> ArgTypes;
672  std::vector<llvm::Value*> Args;
673
674  // Keep track of inout constraints.
675  std::string InOutConstraints;
676  std::vector<llvm::Value*> InOutArgs;
677  std::vector<const llvm::Type*> InOutArgTypes;
678
679  for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
680    std::string OutputConstraint(S.getOutputConstraint(i)->getStrData(),
681                                 S.getOutputConstraint(i)->getByteLength());
682
683    TargetInfo::ConstraintInfo Info;
684    bool result = Target.validateOutputConstraint(OutputConstraint.c_str(),
685                                                  Info);
686    assert(result && "Failed to parse output constraint");
687
688    // Simplify the output constraint.
689    OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
690
691    LValue Dest = EmitLValue(S.getOutputExpr(i));
692    const llvm::Type *DestValueType =
693      cast<llvm::PointerType>(Dest.getAddress()->getType())->getElementType();
694
695    // If the first output operand is not a memory dest, we'll
696    // make it the return value.
697    if (i == 0 && !(Info & TargetInfo::CI_AllowsMemory) &&
698        DestValueType->isSingleValueType()) {
699      ResultAddr = Dest.getAddress();
700      ResultType = DestValueType;
701      Constraints += "=" + OutputConstraint;
702    } else {
703      ArgTypes.push_back(Dest.getAddress()->getType());
704      Args.push_back(Dest.getAddress());
705      if (i != 0)
706        Constraints += ',';
707      Constraints += "=*";
708      Constraints += OutputConstraint;
709    }
710
711    if (Info & TargetInfo::CI_ReadWrite) {
712      // FIXME: This code should be shared with the code that handles inputs.
713      InOutConstraints += ',';
714
715      const Expr *InputExpr = S.getOutputExpr(i);
716      llvm::Value *Arg;
717      if ((Info & TargetInfo::CI_AllowsRegister) ||
718          !(Info & TargetInfo::CI_AllowsMemory)) {
719        if (ConvertType(InputExpr->getType())->isSingleValueType()) {
720          Arg = EmitScalarExpr(InputExpr);
721        } else {
722          assert(0 && "FIXME: Implement passing multiple-value types as inputs");
723        }
724      } else {
725        LValue Dest = EmitLValue(InputExpr);
726        Arg = Dest.getAddress();
727        InOutConstraints += '*';
728      }
729
730      InOutArgTypes.push_back(Arg->getType());
731      InOutArgs.push_back(Arg);
732      InOutConstraints += OutputConstraint;
733    }
734  }
735
736  unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
737
738  for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
739    const Expr *InputExpr = S.getInputExpr(i);
740
741    std::string InputConstraint(S.getInputConstraint(i)->getStrData(),
742                                S.getInputConstraint(i)->getByteLength());
743
744    TargetInfo::ConstraintInfo Info;
745    bool result = Target.validateInputConstraint(InputConstraint.c_str(),
746                                                 NumConstraints,
747                                                 Info);
748    assert(result && "Failed to parse input constraint");
749
750    if (i != 0 || S.getNumOutputs() > 0)
751      Constraints += ',';
752
753    // Simplify the input constraint.
754    InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target);
755
756    llvm::Value *Arg;
757
758    if ((Info & TargetInfo::CI_AllowsRegister) ||
759        !(Info & TargetInfo::CI_AllowsMemory)) {
760      if (ConvertType(InputExpr->getType())->isSingleValueType()) {
761        Arg = EmitScalarExpr(InputExpr);
762      } else {
763        assert(0 && "FIXME: Implement passing multiple-value types as inputs");
764      }
765    } else {
766      LValue Dest = EmitLValue(InputExpr);
767      Arg = Dest.getAddress();
768      Constraints += '*';
769    }
770
771    ArgTypes.push_back(Arg->getType());
772    Args.push_back(Arg);
773    Constraints += InputConstraint;
774  }
775
776  // Append the "input" part of inout constraints last.
777  for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
778    ArgTypes.push_back(InOutArgTypes[i]);
779    Args.push_back(InOutArgs[i]);
780  }
781  Constraints += InOutConstraints;
782
783  // Clobbers
784  for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
785    std::string Clobber(S.getClobber(i)->getStrData(),
786                        S.getClobber(i)->getByteLength());
787
788    Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str());
789
790    if (i != 0 || NumConstraints != 0)
791      Constraints += ',';
792
793    Constraints += "~{";
794    Constraints += Clobber;
795    Constraints += '}';
796  }
797
798  // Add machine specific clobbers
799  if (const char *C = Target.getClobbers()) {
800    if (!Constraints.empty())
801      Constraints += ',';
802    Constraints += C;
803  }
804
805  const llvm::FunctionType *FTy =
806    llvm::FunctionType::get(ResultType, ArgTypes, false);
807
808  llvm::InlineAsm *IA =
809    llvm::InlineAsm::get(FTy, AsmString, Constraints,
810                         S.isVolatile() || S.getNumOutputs() == 0);
811  llvm::Value *Result = Builder.CreateCall(IA, Args.begin(), Args.end(), "");
812  if (ResultAddr) // FIXME: volatility
813    Builder.CreateStore(Result, ResultAddr);
814}
815