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