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