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