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