clang API Documentation

CGStmt.cpp
Go to the documentation of this file.
00001 //===--- CGStmt.cpp - Emit LLVM Code from Statements ----------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This contains code to emit Stmt nodes as LLVM code.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "CGDebugInfo.h"
00015 #include "CodeGenModule.h"
00016 #include "CodeGenFunction.h"
00017 #include "TargetInfo.h"
00018 #include "clang/AST/StmtVisitor.h"
00019 #include "clang/Basic/PrettyStackTrace.h"
00020 #include "clang/Basic/TargetInfo.h"
00021 #include "llvm/ADT/StringExtras.h"
00022 #include "llvm/InlineAsm.h"
00023 #include "llvm/Intrinsics.h"
00024 #include "llvm/Target/TargetData.h"
00025 using namespace clang;
00026 using namespace CodeGen;
00027 
00028 //===----------------------------------------------------------------------===//
00029 //                              Statement Emission
00030 //===----------------------------------------------------------------------===//
00031 
00032 void CodeGenFunction::EmitStopPoint(const Stmt *S) {
00033   if (CGDebugInfo *DI = getDebugInfo()) {
00034     SourceLocation Loc;
00035     if (isa<DeclStmt>(S))
00036       Loc = S->getLocEnd();
00037     else
00038       Loc = S->getLocStart();
00039     DI->EmitLocation(Builder, Loc);
00040   }
00041 }
00042 
00043 void CodeGenFunction::EmitStmt(const Stmt *S) {
00044   assert(S && "Null statement?");
00045 
00046   // These statements have their own debug info handling.
00047   if (EmitSimpleStmt(S))
00048     return;
00049 
00050   // Check if we are generating unreachable code.
00051   if (!HaveInsertPoint()) {
00052     // If so, and the statement doesn't contain a label, then we do not need to
00053     // generate actual code. This is safe because (1) the current point is
00054     // unreachable, so we don't need to execute the code, and (2) we've already
00055     // handled the statements which update internal data structures (like the
00056     // local variable map) which could be used by subsequent statements.
00057     if (!ContainsLabel(S)) {
00058       // Verify that any decl statements were handled as simple, they may be in
00059       // scope of subsequent reachable statements.
00060       assert(!isa<DeclStmt>(*S) && "Unexpected DeclStmt!");
00061       return;
00062     }
00063 
00064     // Otherwise, make a new block to hold the code.
00065     EnsureInsertPoint();
00066   }
00067 
00068   // Generate a stoppoint if we are emitting debug info.
00069   EmitStopPoint(S);
00070 
00071   switch (S->getStmtClass()) {
00072   case Stmt::NoStmtClass:
00073   case Stmt::CXXCatchStmtClass:
00074   case Stmt::SEHExceptStmtClass:
00075   case Stmt::SEHFinallyStmtClass:
00076   case Stmt::MSDependentExistsStmtClass:
00077     llvm_unreachable("invalid statement class to emit generically");
00078   case Stmt::NullStmtClass:
00079   case Stmt::CompoundStmtClass:
00080   case Stmt::DeclStmtClass:
00081   case Stmt::LabelStmtClass:
00082   case Stmt::AttributedStmtClass:
00083   case Stmt::GotoStmtClass:
00084   case Stmt::BreakStmtClass:
00085   case Stmt::ContinueStmtClass:
00086   case Stmt::DefaultStmtClass:
00087   case Stmt::CaseStmtClass:
00088     llvm_unreachable("should have emitted these statements as simple");
00089 
00090 #define STMT(Type, Base)
00091 #define ABSTRACT_STMT(Op)
00092 #define EXPR(Type, Base) \
00093   case Stmt::Type##Class:
00094 #include "clang/AST/StmtNodes.inc"
00095   {
00096     // Remember the block we came in on.
00097     llvm::BasicBlock *incoming = Builder.GetInsertBlock();
00098     assert(incoming && "expression emission must have an insertion point");
00099 
00100     EmitIgnoredExpr(cast<Expr>(S));
00101 
00102     llvm::BasicBlock *outgoing = Builder.GetInsertBlock();
00103     assert(outgoing && "expression emission cleared block!");
00104 
00105     // The expression emitters assume (reasonably!) that the insertion
00106     // point is always set.  To maintain that, the call-emission code
00107     // for noreturn functions has to enter a new block with no
00108     // predecessors.  We want to kill that block and mark the current
00109     // insertion point unreachable in the common case of a call like
00110     // "exit();".  Since expression emission doesn't otherwise create
00111     // blocks with no predecessors, we can just test for that.
00112     // However, we must be careful not to do this to our incoming
00113     // block, because *statement* emission does sometimes create
00114     // reachable blocks which will have no predecessors until later in
00115     // the function.  This occurs with, e.g., labels that are not
00116     // reachable by fallthrough.
00117     if (incoming != outgoing && outgoing->use_empty()) {
00118       outgoing->eraseFromParent();
00119       Builder.ClearInsertionPoint();
00120     }
00121     break;
00122   }
00123 
00124   case Stmt::IndirectGotoStmtClass:
00125     EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
00126 
00127   case Stmt::IfStmtClass:       EmitIfStmt(cast<IfStmt>(*S));             break;
00128   case Stmt::WhileStmtClass:    EmitWhileStmt(cast<WhileStmt>(*S));       break;
00129   case Stmt::DoStmtClass:       EmitDoStmt(cast<DoStmt>(*S));             break;
00130   case Stmt::ForStmtClass:      EmitForStmt(cast<ForStmt>(*S));           break;
00131 
00132   case Stmt::ReturnStmtClass:   EmitReturnStmt(cast<ReturnStmt>(*S));     break;
00133 
00134   case Stmt::SwitchStmtClass:   EmitSwitchStmt(cast<SwitchStmt>(*S));     break;
00135   case Stmt::AsmStmtClass:      EmitAsmStmt(cast<AsmStmt>(*S));           break;
00136 
00137   case Stmt::ObjCAtTryStmtClass:
00138     EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
00139     break;
00140   case Stmt::ObjCAtCatchStmtClass:
00141     llvm_unreachable(
00142                     "@catch statements should be handled by EmitObjCAtTryStmt");
00143   case Stmt::ObjCAtFinallyStmtClass:
00144     llvm_unreachable(
00145                   "@finally statements should be handled by EmitObjCAtTryStmt");
00146   case Stmt::ObjCAtThrowStmtClass:
00147     EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
00148     break;
00149   case Stmt::ObjCAtSynchronizedStmtClass:
00150     EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
00151     break;
00152   case Stmt::ObjCForCollectionStmtClass:
00153     EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
00154     break;
00155   case Stmt::ObjCAutoreleasePoolStmtClass:
00156     EmitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(*S));
00157     break;
00158       
00159   case Stmt::CXXTryStmtClass:
00160     EmitCXXTryStmt(cast<CXXTryStmt>(*S));
00161     break;
00162   case Stmt::CXXForRangeStmtClass:
00163     EmitCXXForRangeStmt(cast<CXXForRangeStmt>(*S));
00164   case Stmt::SEHTryStmtClass:
00165     // FIXME Not yet implemented
00166     break;
00167   }
00168 }
00169 
00170 bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
00171   switch (S->getStmtClass()) {
00172   default: return false;
00173   case Stmt::NullStmtClass: break;
00174   case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
00175   case Stmt::DeclStmtClass:     EmitDeclStmt(cast<DeclStmt>(*S));         break;
00176   case Stmt::LabelStmtClass:    EmitLabelStmt(cast<LabelStmt>(*S));       break;
00177   case Stmt::AttributedStmtClass:
00178                             EmitAttributedStmt(cast<AttributedStmt>(*S)); break;
00179   case Stmt::GotoStmtClass:     EmitGotoStmt(cast<GotoStmt>(*S));         break;
00180   case Stmt::BreakStmtClass:    EmitBreakStmt(cast<BreakStmt>(*S));       break;
00181   case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
00182   case Stmt::DefaultStmtClass:  EmitDefaultStmt(cast<DefaultStmt>(*S));   break;
00183   case Stmt::CaseStmtClass:     EmitCaseStmt(cast<CaseStmt>(*S));         break;
00184   }
00185 
00186   return true;
00187 }
00188 
00189 /// EmitCompoundStmt - Emit a compound statement {..} node.  If GetLast is true,
00190 /// this captures the expression result of the last sub-statement and returns it
00191 /// (for use by the statement expression extension).
00192 RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
00193                                          AggValueSlot AggSlot) {
00194   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(),
00195                              "LLVM IR generation of compound statement ('{}')");
00196 
00197   // Keep track of the current cleanup stack depth, including debug scopes.
00198   LexicalScope Scope(*this, S.getSourceRange());
00199 
00200   for (CompoundStmt::const_body_iterator I = S.body_begin(),
00201        E = S.body_end()-GetLast; I != E; ++I)
00202     EmitStmt(*I);
00203 
00204   RValue RV;
00205   if (!GetLast)
00206     RV = RValue::get(0);
00207   else {
00208     // We have to special case labels here.  They are statements, but when put
00209     // at the end of a statement expression, they yield the value of their
00210     // subexpression.  Handle this by walking through all labels we encounter,
00211     // emitting them before we evaluate the subexpr.
00212     const Stmt *LastStmt = S.body_back();
00213     while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
00214       EmitLabel(LS->getDecl());
00215       LastStmt = LS->getSubStmt();
00216     }
00217 
00218     EnsureInsertPoint();
00219 
00220     RV = EmitAnyExpr(cast<Expr>(LastStmt), AggSlot);
00221   }
00222 
00223   return RV;
00224 }
00225 
00226 void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) {
00227   llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(BB->getTerminator());
00228 
00229   // If there is a cleanup stack, then we it isn't worth trying to
00230   // simplify this block (we would need to remove it from the scope map
00231   // and cleanup entry).
00232   if (!EHStack.empty())
00233     return;
00234 
00235   // Can only simplify direct branches.
00236   if (!BI || !BI->isUnconditional())
00237     return;
00238 
00239   BB->replaceAllUsesWith(BI->getSuccessor(0));
00240   BI->eraseFromParent();
00241   BB->eraseFromParent();
00242 }
00243 
00244 void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
00245   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
00246 
00247   // Fall out of the current block (if necessary).
00248   EmitBranch(BB);
00249 
00250   if (IsFinished && BB->use_empty()) {
00251     delete BB;
00252     return;
00253   }
00254 
00255   // Place the block after the current block, if possible, or else at
00256   // the end of the function.
00257   if (CurBB && CurBB->getParent())
00258     CurFn->getBasicBlockList().insertAfter(CurBB, BB);
00259   else
00260     CurFn->getBasicBlockList().push_back(BB);
00261   Builder.SetInsertPoint(BB);
00262 }
00263 
00264 void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
00265   // Emit a branch from the current block to the target one if this
00266   // was a real block.  If this was just a fall-through block after a
00267   // terminator, don't emit it.
00268   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
00269 
00270   if (!CurBB || CurBB->getTerminator()) {
00271     // If there is no insert point or the previous block is already
00272     // terminated, don't touch it.
00273   } else {
00274     // Otherwise, create a fall-through branch.
00275     Builder.CreateBr(Target);
00276   }
00277 
00278   Builder.ClearInsertionPoint();
00279 }
00280 
00281 void CodeGenFunction::EmitBlockAfterUses(llvm::BasicBlock *block) {
00282   bool inserted = false;
00283   for (llvm::BasicBlock::use_iterator
00284          i = block->use_begin(), e = block->use_end(); i != e; ++i) {
00285     if (llvm::Instruction *insn = dyn_cast<llvm::Instruction>(*i)) {
00286       CurFn->getBasicBlockList().insertAfter(insn->getParent(), block);
00287       inserted = true;
00288       break;
00289     }
00290   }
00291 
00292   if (!inserted)
00293     CurFn->getBasicBlockList().push_back(block);
00294 
00295   Builder.SetInsertPoint(block);
00296 }
00297 
00298 CodeGenFunction::JumpDest
00299 CodeGenFunction::getJumpDestForLabel(const LabelDecl *D) {
00300   JumpDest &Dest = LabelMap[D];
00301   if (Dest.isValid()) return Dest;
00302 
00303   // Create, but don't insert, the new block.
00304   Dest = JumpDest(createBasicBlock(D->getName()),
00305                   EHScopeStack::stable_iterator::invalid(),
00306                   NextCleanupDestIndex++);
00307   return Dest;
00308 }
00309 
00310 void CodeGenFunction::EmitLabel(const LabelDecl *D) {
00311   JumpDest &Dest = LabelMap[D];
00312 
00313   // If we didn't need a forward reference to this label, just go
00314   // ahead and create a destination at the current scope.
00315   if (!Dest.isValid()) {
00316     Dest = getJumpDestInCurrentScope(D->getName());
00317 
00318   // Otherwise, we need to give this label a target depth and remove
00319   // it from the branch-fixups list.
00320   } else {
00321     assert(!Dest.getScopeDepth().isValid() && "already emitted label!");
00322     Dest = JumpDest(Dest.getBlock(),
00323                     EHStack.stable_begin(),
00324                     Dest.getDestIndex());
00325 
00326     ResolveBranchFixups(Dest.getBlock());
00327   }
00328 
00329   EmitBlock(Dest.getBlock());
00330 }
00331 
00332 
00333 void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
00334   EmitLabel(S.getDecl());
00335   EmitStmt(S.getSubStmt());
00336 }
00337 
00338 void CodeGenFunction::EmitAttributedStmt(const AttributedStmt &S) {
00339   EmitStmt(S.getSubStmt());
00340 }
00341 
00342 void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
00343   // If this code is reachable then emit a stop point (if generating
00344   // debug info). We have to do this ourselves because we are on the
00345   // "simple" statement path.
00346   if (HaveInsertPoint())
00347     EmitStopPoint(&S);
00348 
00349   EmitBranchThroughCleanup(getJumpDestForLabel(S.getLabel()));
00350 }
00351 
00352 
00353 void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
00354   if (const LabelDecl *Target = S.getConstantTarget()) {
00355     EmitBranchThroughCleanup(getJumpDestForLabel(Target));
00356     return;
00357   }
00358 
00359   // Ensure that we have an i8* for our PHI node.
00360   llvm::Value *V = Builder.CreateBitCast(EmitScalarExpr(S.getTarget()),
00361                                          Int8PtrTy, "addr");
00362   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
00363   
00364 
00365   // Get the basic block for the indirect goto.
00366   llvm::BasicBlock *IndGotoBB = GetIndirectGotoBlock();
00367   
00368   // The first instruction in the block has to be the PHI for the switch dest,
00369   // add an entry for this branch.
00370   cast<llvm::PHINode>(IndGotoBB->begin())->addIncoming(V, CurBB);
00371   
00372   EmitBranch(IndGotoBB);
00373 }
00374 
00375 void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
00376   // C99 6.8.4.1: The first substatement is executed if the expression compares
00377   // unequal to 0.  The condition must be a scalar type.
00378   RunCleanupsScope ConditionScope(*this);
00379 
00380   if (S.getConditionVariable())
00381     EmitAutoVarDecl(*S.getConditionVariable());
00382 
00383   // If the condition constant folds and can be elided, try to avoid emitting
00384   // the condition and the dead arm of the if/else.
00385   bool CondConstant;
00386   if (ConstantFoldsToSimpleInteger(S.getCond(), CondConstant)) {
00387     // Figure out which block (then or else) is executed.
00388     const Stmt *Executed = S.getThen();
00389     const Stmt *Skipped  = S.getElse();
00390     if (!CondConstant)  // Condition false?
00391       std::swap(Executed, Skipped);
00392 
00393     // If the skipped block has no labels in it, just emit the executed block.
00394     // This avoids emitting dead code and simplifies the CFG substantially.
00395     if (!ContainsLabel(Skipped)) {
00396       if (Executed) {
00397         RunCleanupsScope ExecutedScope(*this);
00398         EmitStmt(Executed);
00399       }
00400       return;
00401     }
00402   }
00403 
00404   // Otherwise, the condition did not fold, or we couldn't elide it.  Just emit
00405   // the conditional branch.
00406   llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
00407   llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
00408   llvm::BasicBlock *ElseBlock = ContBlock;
00409   if (S.getElse())
00410     ElseBlock = createBasicBlock("if.else");
00411   EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
00412 
00413   // Emit the 'then' code.
00414   EmitBlock(ThenBlock); 
00415   {
00416     RunCleanupsScope ThenScope(*this);
00417     EmitStmt(S.getThen());
00418   }
00419   EmitBranch(ContBlock);
00420 
00421   // Emit the 'else' code if present.
00422   if (const Stmt *Else = S.getElse()) {
00423     // There is no need to emit line number for unconditional branch.
00424     if (getDebugInfo())
00425       Builder.SetCurrentDebugLocation(llvm::DebugLoc());
00426     EmitBlock(ElseBlock);
00427     {
00428       RunCleanupsScope ElseScope(*this);
00429       EmitStmt(Else);
00430     }
00431     // There is no need to emit line number for unconditional branch.
00432     if (getDebugInfo())
00433       Builder.SetCurrentDebugLocation(llvm::DebugLoc());
00434     EmitBranch(ContBlock);
00435   }
00436 
00437   // Emit the continuation block for code after the if.
00438   EmitBlock(ContBlock, true);
00439 }
00440 
00441 void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
00442   // Emit the header for the loop, which will also become
00443   // the continue target.
00444   JumpDest LoopHeader = getJumpDestInCurrentScope("while.cond");
00445   EmitBlock(LoopHeader.getBlock());
00446 
00447   // Create an exit block for when the condition fails, which will
00448   // also become the break target.
00449   JumpDest LoopExit = getJumpDestInCurrentScope("while.end");
00450 
00451   // Store the blocks to use for break and continue.
00452   BreakContinueStack.push_back(BreakContinue(LoopExit, LoopHeader));
00453 
00454   // C++ [stmt.while]p2:
00455   //   When the condition of a while statement is a declaration, the
00456   //   scope of the variable that is declared extends from its point
00457   //   of declaration (3.3.2) to the end of the while statement.
00458   //   [...]
00459   //   The object created in a condition is destroyed and created
00460   //   with each iteration of the loop.
00461   RunCleanupsScope ConditionScope(*this);
00462 
00463   if (S.getConditionVariable())
00464     EmitAutoVarDecl(*S.getConditionVariable());
00465   
00466   // Evaluate the conditional in the while header.  C99 6.8.5.1: The
00467   // evaluation of the controlling expression takes place before each
00468   // execution of the loop body.
00469   llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
00470    
00471   // while(1) is common, avoid extra exit blocks.  Be sure
00472   // to correctly handle break/continue though.
00473   bool EmitBoolCondBranch = true;
00474   if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
00475     if (C->isOne())
00476       EmitBoolCondBranch = false;
00477 
00478   // As long as the condition is true, go to the loop body.
00479   llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
00480   if (EmitBoolCondBranch) {
00481     llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
00482     if (ConditionScope.requiresCleanups())
00483       ExitBlock = createBasicBlock("while.exit");
00484 
00485     Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
00486 
00487     if (ExitBlock != LoopExit.getBlock()) {
00488       EmitBlock(ExitBlock);
00489       EmitBranchThroughCleanup(LoopExit);
00490     }
00491   }
00492  
00493   // Emit the loop body.  We have to emit this in a cleanup scope
00494   // because it might be a singleton DeclStmt.
00495   {
00496     RunCleanupsScope BodyScope(*this);
00497     EmitBlock(LoopBody);
00498     EmitStmt(S.getBody());
00499   }
00500 
00501   BreakContinueStack.pop_back();
00502 
00503   // Immediately force cleanup.
00504   ConditionScope.ForceCleanup();
00505 
00506   // Branch to the loop header again.
00507   EmitBranch(LoopHeader.getBlock());
00508 
00509   // Emit the exit block.
00510   EmitBlock(LoopExit.getBlock(), true);
00511 
00512   // The LoopHeader typically is just a branch if we skipped emitting
00513   // a branch, try to erase it.
00514   if (!EmitBoolCondBranch)
00515     SimplifyForwardingBlocks(LoopHeader.getBlock());
00516 }
00517 
00518 void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
00519   JumpDest LoopExit = getJumpDestInCurrentScope("do.end");
00520   JumpDest LoopCond = getJumpDestInCurrentScope("do.cond");
00521 
00522   // Store the blocks to use for break and continue.
00523   BreakContinueStack.push_back(BreakContinue(LoopExit, LoopCond));
00524 
00525   // Emit the body of the loop.
00526   llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
00527   EmitBlock(LoopBody);
00528   {
00529     RunCleanupsScope BodyScope(*this);
00530     EmitStmt(S.getBody());
00531   }
00532 
00533   BreakContinueStack.pop_back();
00534 
00535   EmitBlock(LoopCond.getBlock());
00536 
00537   // C99 6.8.5.2: "The evaluation of the controlling expression takes place
00538   // after each execution of the loop body."
00539 
00540   // Evaluate the conditional in the while header.
00541   // C99 6.8.5p2/p4: The first substatement is executed if the expression
00542   // compares unequal to 0.  The condition must be a scalar type.
00543   llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
00544 
00545   // "do {} while (0)" is common in macros, avoid extra blocks.  Be sure
00546   // to correctly handle break/continue though.
00547   bool EmitBoolCondBranch = true;
00548   if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
00549     if (C->isZero())
00550       EmitBoolCondBranch = false;
00551 
00552   // As long as the condition is true, iterate the loop.
00553   if (EmitBoolCondBranch)
00554     Builder.CreateCondBr(BoolCondVal, LoopBody, LoopExit.getBlock());
00555 
00556   // Emit the exit block.
00557   EmitBlock(LoopExit.getBlock());
00558 
00559   // The DoCond block typically is just a branch if we skipped
00560   // emitting a branch, try to erase it.
00561   if (!EmitBoolCondBranch)
00562     SimplifyForwardingBlocks(LoopCond.getBlock());
00563 }
00564 
00565 void CodeGenFunction::EmitForStmt(const ForStmt &S) {
00566   JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
00567 
00568   RunCleanupsScope ForScope(*this);
00569 
00570   CGDebugInfo *DI = getDebugInfo();
00571   if (DI)
00572     DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
00573 
00574   // Evaluate the first part before the loop.
00575   if (S.getInit())
00576     EmitStmt(S.getInit());
00577 
00578   // Start the loop with a block that tests the condition.
00579   // If there's an increment, the continue scope will be overwritten
00580   // later.
00581   JumpDest Continue = getJumpDestInCurrentScope("for.cond");
00582   llvm::BasicBlock *CondBlock = Continue.getBlock();
00583   EmitBlock(CondBlock);
00584 
00585   // Create a cleanup scope for the condition variable cleanups.
00586   RunCleanupsScope ConditionScope(*this);
00587   
00588   llvm::Value *BoolCondVal = 0;
00589   if (S.getCond()) {
00590     // If the for statement has a condition scope, emit the local variable
00591     // declaration.
00592     llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
00593     if (S.getConditionVariable()) {
00594       EmitAutoVarDecl(*S.getConditionVariable());
00595     }
00596 
00597     // If there are any cleanups between here and the loop-exit scope,
00598     // create a block to stage a loop exit along.
00599     if (ForScope.requiresCleanups())
00600       ExitBlock = createBasicBlock("for.cond.cleanup");
00601     
00602     // As long as the condition is true, iterate the loop.
00603     llvm::BasicBlock *ForBody = createBasicBlock("for.body");
00604 
00605     // C99 6.8.5p2/p4: The first substatement is executed if the expression
00606     // compares unequal to 0.  The condition must be a scalar type.
00607     BoolCondVal = EvaluateExprAsBool(S.getCond());
00608     Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock);
00609 
00610     if (ExitBlock != LoopExit.getBlock()) {
00611       EmitBlock(ExitBlock);
00612       EmitBranchThroughCleanup(LoopExit);
00613     }
00614 
00615     EmitBlock(ForBody);
00616   } else {
00617     // Treat it as a non-zero constant.  Don't even create a new block for the
00618     // body, just fall into it.
00619   }
00620 
00621   // If the for loop doesn't have an increment we can just use the
00622   // condition as the continue block.  Otherwise we'll need to create
00623   // a block for it (in the current scope, i.e. in the scope of the
00624   // condition), and that we will become our continue block.
00625   if (S.getInc())
00626     Continue = getJumpDestInCurrentScope("for.inc");
00627 
00628   // Store the blocks to use for break and continue.
00629   BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
00630 
00631   {
00632     // Create a separate cleanup scope for the body, in case it is not
00633     // a compound statement.
00634     RunCleanupsScope BodyScope(*this);
00635     EmitStmt(S.getBody());
00636   }
00637 
00638   // If there is an increment, emit it next.
00639   if (S.getInc()) {
00640     EmitBlock(Continue.getBlock());
00641     EmitStmt(S.getInc());
00642   }
00643 
00644   BreakContinueStack.pop_back();
00645 
00646   ConditionScope.ForceCleanup();
00647   EmitBranch(CondBlock);
00648 
00649   ForScope.ForceCleanup();
00650 
00651   if (DI)
00652     DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
00653 
00654   // Emit the fall-through block.
00655   EmitBlock(LoopExit.getBlock(), true);
00656 }
00657 
00658 void CodeGenFunction::EmitCXXForRangeStmt(const CXXForRangeStmt &S) {
00659   JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
00660 
00661   RunCleanupsScope ForScope(*this);
00662 
00663   CGDebugInfo *DI = getDebugInfo();
00664   if (DI)
00665     DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
00666 
00667   // Evaluate the first pieces before the loop.
00668   EmitStmt(S.getRangeStmt());
00669   EmitStmt(S.getBeginEndStmt());
00670 
00671   // Start the loop with a block that tests the condition.
00672   // If there's an increment, the continue scope will be overwritten
00673   // later.
00674   llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
00675   EmitBlock(CondBlock);
00676 
00677   // If there are any cleanups between here and the loop-exit scope,
00678   // create a block to stage a loop exit along.
00679   llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
00680   if (ForScope.requiresCleanups())
00681     ExitBlock = createBasicBlock("for.cond.cleanup");
00682   
00683   // The loop body, consisting of the specified body and the loop variable.
00684   llvm::BasicBlock *ForBody = createBasicBlock("for.body");
00685 
00686   // The body is executed if the expression, contextually converted
00687   // to bool, is true.
00688   llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
00689   Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock);
00690 
00691   if (ExitBlock != LoopExit.getBlock()) {
00692     EmitBlock(ExitBlock);
00693     EmitBranchThroughCleanup(LoopExit);
00694   }
00695 
00696   EmitBlock(ForBody);
00697 
00698   // Create a block for the increment. In case of a 'continue', we jump there.
00699   JumpDest Continue = getJumpDestInCurrentScope("for.inc");
00700 
00701   // Store the blocks to use for break and continue.
00702   BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
00703 
00704   {
00705     // Create a separate cleanup scope for the loop variable and body.
00706     RunCleanupsScope BodyScope(*this);
00707     EmitStmt(S.getLoopVarStmt());
00708     EmitStmt(S.getBody());
00709   }
00710 
00711   // If there is an increment, emit it next.
00712   EmitBlock(Continue.getBlock());
00713   EmitStmt(S.getInc());
00714 
00715   BreakContinueStack.pop_back();
00716 
00717   EmitBranch(CondBlock);
00718 
00719   ForScope.ForceCleanup();
00720 
00721   if (DI)
00722     DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
00723 
00724   // Emit the fall-through block.
00725   EmitBlock(LoopExit.getBlock(), true);
00726 }
00727 
00728 void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
00729   if (RV.isScalar()) {
00730     Builder.CreateStore(RV.getScalarVal(), ReturnValue);
00731   } else if (RV.isAggregate()) {
00732     EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
00733   } else {
00734     StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
00735   }
00736   EmitBranchThroughCleanup(ReturnBlock);
00737 }
00738 
00739 /// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
00740 /// if the function returns void, or may be missing one if the function returns
00741 /// non-void.  Fun stuff :).
00742 void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
00743   // Emit the result value, even if unused, to evalute the side effects.
00744   const Expr *RV = S.getRetValue();
00745 
00746   // FIXME: Clean this up by using an LValue for ReturnTemp,
00747   // EmitStoreThroughLValue, and EmitAnyExpr.
00748   if (S.getNRVOCandidate() && S.getNRVOCandidate()->isNRVOVariable() &&
00749       !Target.useGlobalsForAutomaticVariables()) {
00750     // Apply the named return value optimization for this return statement,
00751     // which means doing nothing: the appropriate result has already been
00752     // constructed into the NRVO variable.
00753     
00754     // If there is an NRVO flag for this variable, set it to 1 into indicate
00755     // that the cleanup code should not destroy the variable.
00756     if (llvm::Value *NRVOFlag = NRVOFlags[S.getNRVOCandidate()])
00757       Builder.CreateStore(Builder.getTrue(), NRVOFlag);
00758   } else if (!ReturnValue) {
00759     // Make sure not to return anything, but evaluate the expression
00760     // for side effects.
00761     if (RV)
00762       EmitAnyExpr(RV);
00763   } else if (RV == 0) {
00764     // Do nothing (return value is left uninitialized)
00765   } else if (FnRetTy->isReferenceType()) {
00766     // If this function returns a reference, take the address of the expression
00767     // rather than the value.
00768     RValue Result = EmitReferenceBindingToExpr(RV, /*InitializedDecl=*/0);
00769     Builder.CreateStore(Result.getScalarVal(), ReturnValue);
00770   } else if (!hasAggregateLLVMType(RV->getType())) {
00771     Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
00772   } else if (RV->getType()->isAnyComplexType()) {
00773     EmitComplexExprIntoAddr(RV, ReturnValue, false);
00774   } else {
00775     CharUnits Alignment = getContext().getTypeAlignInChars(RV->getType());
00776     EmitAggExpr(RV, AggValueSlot::forAddr(ReturnValue, Alignment, Qualifiers(),
00777                                           AggValueSlot::IsDestructed,
00778                                           AggValueSlot::DoesNotNeedGCBarriers,
00779                                           AggValueSlot::IsNotAliased));
00780   }
00781 
00782   EmitBranchThroughCleanup(ReturnBlock);
00783 }
00784 
00785 void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
00786   // As long as debug info is modeled with instructions, we have to ensure we
00787   // have a place to insert here and write the stop point here.
00788   if (HaveInsertPoint())
00789     EmitStopPoint(&S);
00790 
00791   for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
00792        I != E; ++I)
00793     EmitDecl(**I);
00794 }
00795 
00796 void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
00797   assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
00798 
00799   // If this code is reachable then emit a stop point (if generating
00800   // debug info). We have to do this ourselves because we are on the
00801   // "simple" statement path.
00802   if (HaveInsertPoint())
00803     EmitStopPoint(&S);
00804 
00805   JumpDest Block = BreakContinueStack.back().BreakBlock;
00806   EmitBranchThroughCleanup(Block);
00807 }
00808 
00809 void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
00810   assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
00811 
00812   // If this code is reachable then emit a stop point (if generating
00813   // debug info). We have to do this ourselves because we are on the
00814   // "simple" statement path.
00815   if (HaveInsertPoint())
00816     EmitStopPoint(&S);
00817 
00818   JumpDest Block = BreakContinueStack.back().ContinueBlock;
00819   EmitBranchThroughCleanup(Block);
00820 }
00821 
00822 /// EmitCaseStmtRange - If case statement range is not too big then
00823 /// add multiple cases to switch instruction, one for each value within
00824 /// the range. If range is too big then emit "if" condition check.
00825 void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
00826   assert(S.getRHS() && "Expected RHS value in CaseStmt");
00827 
00828   llvm::APSInt LHS = S.getLHS()->EvaluateKnownConstInt(getContext());
00829   llvm::APSInt RHS = S.getRHS()->EvaluateKnownConstInt(getContext());
00830 
00831   // Emit the code for this case. We do this first to make sure it is
00832   // properly chained from our predecessor before generating the
00833   // switch machinery to enter this block.
00834   EmitBlock(createBasicBlock("sw.bb"));
00835   llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
00836   EmitStmt(S.getSubStmt());
00837 
00838   // If range is empty, do nothing.
00839   if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
00840     return;
00841 
00842   llvm::APInt Range = RHS - LHS;
00843   // FIXME: parameters such as this should not be hardcoded.
00844   if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
00845     // Range is small enough to add multiple switch instruction cases.
00846     for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
00847       SwitchInsn->addCase(Builder.getInt(LHS), CaseDest);
00848       LHS++;
00849     }
00850     return;
00851   }
00852 
00853   // The range is too big. Emit "if" condition into a new block,
00854   // making sure to save and restore the current insertion point.
00855   llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
00856 
00857   // Push this test onto the chain of range checks (which terminates
00858   // in the default basic block). The switch's default will be changed
00859   // to the top of this chain after switch emission is complete.
00860   llvm::BasicBlock *FalseDest = CaseRangeBlock;
00861   CaseRangeBlock = createBasicBlock("sw.caserange");
00862 
00863   CurFn->getBasicBlockList().push_back(CaseRangeBlock);
00864   Builder.SetInsertPoint(CaseRangeBlock);
00865 
00866   // Emit range check.
00867   llvm::Value *Diff =
00868     Builder.CreateSub(SwitchInsn->getCondition(), Builder.getInt(LHS));
00869   llvm::Value *Cond =
00870     Builder.CreateICmpULE(Diff, Builder.getInt(Range), "inbounds");
00871   Builder.CreateCondBr(Cond, CaseDest, FalseDest);
00872 
00873   // Restore the appropriate insertion point.
00874   if (RestoreBB)
00875     Builder.SetInsertPoint(RestoreBB);
00876   else
00877     Builder.ClearInsertionPoint();
00878 }
00879 
00880 void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
00881   // If there is no enclosing switch instance that we're aware of, then this
00882   // case statement and its block can be elided.  This situation only happens
00883   // when we've constant-folded the switch, are emitting the constant case,
00884   // and part of the constant case includes another case statement.  For 
00885   // instance: switch (4) { case 4: do { case 5: } while (1); }
00886   if (!SwitchInsn) {
00887     EmitStmt(S.getSubStmt());
00888     return;
00889   }
00890 
00891   // Handle case ranges.
00892   if (S.getRHS()) {
00893     EmitCaseStmtRange(S);
00894     return;
00895   }
00896 
00897   llvm::ConstantInt *CaseVal =
00898     Builder.getInt(S.getLHS()->EvaluateKnownConstInt(getContext()));
00899 
00900   // If the body of the case is just a 'break', and if there was no fallthrough,
00901   // try to not emit an empty block.
00902   if ((CGM.getCodeGenOpts().OptimizationLevel > 0) && isa<BreakStmt>(S.getSubStmt())) {
00903     JumpDest Block = BreakContinueStack.back().BreakBlock;
00904     
00905     // Only do this optimization if there are no cleanups that need emitting.
00906     if (isObviouslyBranchWithoutCleanups(Block)) {
00907       SwitchInsn->addCase(CaseVal, Block.getBlock());
00908 
00909       // If there was a fallthrough into this case, make sure to redirect it to
00910       // the end of the switch as well.
00911       if (Builder.GetInsertBlock()) {
00912         Builder.CreateBr(Block.getBlock());
00913         Builder.ClearInsertionPoint();
00914       }
00915       return;
00916     }
00917   }
00918   
00919   EmitBlock(createBasicBlock("sw.bb"));
00920   llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
00921   SwitchInsn->addCase(CaseVal, CaseDest);
00922 
00923   // Recursively emitting the statement is acceptable, but is not wonderful for
00924   // code where we have many case statements nested together, i.e.:
00925   //  case 1:
00926   //    case 2:
00927   //      case 3: etc.
00928   // Handling this recursively will create a new block for each case statement
00929   // that falls through to the next case which is IR intensive.  It also causes
00930   // deep recursion which can run into stack depth limitations.  Handle
00931   // sequential non-range case statements specially.
00932   const CaseStmt *CurCase = &S;
00933   const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
00934 
00935   // Otherwise, iteratively add consecutive cases to this switch stmt.
00936   while (NextCase && NextCase->getRHS() == 0) {
00937     CurCase = NextCase;
00938     llvm::ConstantInt *CaseVal = 
00939       Builder.getInt(CurCase->getLHS()->EvaluateKnownConstInt(getContext()));
00940     SwitchInsn->addCase(CaseVal, CaseDest);
00941     NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt());
00942   }
00943 
00944   // Normal default recursion for non-cases.
00945   EmitStmt(CurCase->getSubStmt());
00946 }
00947 
00948 void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
00949   llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
00950   assert(DefaultBlock->empty() &&
00951          "EmitDefaultStmt: Default block already defined?");
00952   EmitBlock(DefaultBlock);
00953   EmitStmt(S.getSubStmt());
00954 }
00955 
00956 /// CollectStatementsForCase - Given the body of a 'switch' statement and a
00957 /// constant value that is being switched on, see if we can dead code eliminate
00958 /// the body of the switch to a simple series of statements to emit.  Basically,
00959 /// on a switch (5) we want to find these statements:
00960 ///    case 5:
00961 ///      printf(...);    <--
00962 ///      ++i;            <--
00963 ///      break;
00964 ///
00965 /// and add them to the ResultStmts vector.  If it is unsafe to do this
00966 /// transformation (for example, one of the elided statements contains a label
00967 /// that might be jumped to), return CSFC_Failure.  If we handled it and 'S'
00968 /// should include statements after it (e.g. the printf() line is a substmt of
00969 /// the case) then return CSFC_FallThrough.  If we handled it and found a break
00970 /// statement, then return CSFC_Success.
00971 ///
00972 /// If Case is non-null, then we are looking for the specified case, checking
00973 /// that nothing we jump over contains labels.  If Case is null, then we found
00974 /// the case and are looking for the break.
00975 ///
00976 /// If the recursive walk actually finds our Case, then we set FoundCase to
00977 /// true.
00978 ///
00979 enum CSFC_Result { CSFC_Failure, CSFC_FallThrough, CSFC_Success };
00980 static CSFC_Result CollectStatementsForCase(const Stmt *S,
00981                                             const SwitchCase *Case,
00982                                             bool &FoundCase,
00983                               SmallVectorImpl<const Stmt*> &ResultStmts) {
00984   // If this is a null statement, just succeed.
00985   if (S == 0)
00986     return Case ? CSFC_Success : CSFC_FallThrough;
00987     
00988   // If this is the switchcase (case 4: or default) that we're looking for, then
00989   // we're in business.  Just add the substatement.
00990   if (const SwitchCase *SC = dyn_cast<SwitchCase>(S)) {
00991     if (S == Case) {
00992       FoundCase = true;
00993       return CollectStatementsForCase(SC->getSubStmt(), 0, FoundCase,
00994                                       ResultStmts);
00995     }
00996     
00997     // Otherwise, this is some other case or default statement, just ignore it.
00998     return CollectStatementsForCase(SC->getSubStmt(), Case, FoundCase,
00999                                     ResultStmts);
01000   }
01001 
01002   // If we are in the live part of the code and we found our break statement,
01003   // return a success!
01004   if (Case == 0 && isa<BreakStmt>(S))
01005     return CSFC_Success;
01006   
01007   // If this is a switch statement, then it might contain the SwitchCase, the
01008   // break, or neither.
01009   if (const CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
01010     // Handle this as two cases: we might be looking for the SwitchCase (if so
01011     // the skipped statements must be skippable) or we might already have it.
01012     CompoundStmt::const_body_iterator I = CS->body_begin(), E = CS->body_end();
01013     if (Case) {
01014       // Keep track of whether we see a skipped declaration.  The code could be
01015       // using the declaration even if it is skipped, so we can't optimize out
01016       // the decl if the kept statements might refer to it.
01017       bool HadSkippedDecl = false;
01018       
01019       // If we're looking for the case, just see if we can skip each of the
01020       // substatements.
01021       for (; Case && I != E; ++I) {
01022         HadSkippedDecl |= isa<DeclStmt>(*I);
01023         
01024         switch (CollectStatementsForCase(*I, Case, FoundCase, ResultStmts)) {
01025         case CSFC_Failure: return CSFC_Failure;
01026         case CSFC_Success:
01027           // A successful result means that either 1) that the statement doesn't
01028           // have the case and is skippable, or 2) does contain the case value
01029           // and also contains the break to exit the switch.  In the later case,
01030           // we just verify the rest of the statements are elidable.
01031           if (FoundCase) {
01032             // If we found the case and skipped declarations, we can't do the
01033             // optimization.
01034             if (HadSkippedDecl)
01035               return CSFC_Failure;
01036             
01037             for (++I; I != E; ++I)
01038               if (CodeGenFunction::ContainsLabel(*I, true))
01039                 return CSFC_Failure;
01040             return CSFC_Success;
01041           }
01042           break;
01043         case CSFC_FallThrough:
01044           // If we have a fallthrough condition, then we must have found the
01045           // case started to include statements.  Consider the rest of the
01046           // statements in the compound statement as candidates for inclusion.
01047           assert(FoundCase && "Didn't find case but returned fallthrough?");
01048           // We recursively found Case, so we're not looking for it anymore.
01049           Case = 0;
01050             
01051           // If we found the case and skipped declarations, we can't do the
01052           // optimization.
01053           if (HadSkippedDecl)
01054             return CSFC_Failure;
01055           break;
01056         }
01057       }
01058     }
01059 
01060     // If we have statements in our range, then we know that the statements are
01061     // live and need to be added to the set of statements we're tracking.
01062     for (; I != E; ++I) {
01063       switch (CollectStatementsForCase(*I, 0, FoundCase, ResultStmts)) {
01064       case CSFC_Failure: return CSFC_Failure;
01065       case CSFC_FallThrough:
01066         // A fallthrough result means that the statement was simple and just
01067         // included in ResultStmt, keep adding them afterwards.
01068         break;
01069       case CSFC_Success:
01070         // A successful result means that we found the break statement and
01071         // stopped statement inclusion.  We just ensure that any leftover stmts
01072         // are skippable and return success ourselves.
01073         for (++I; I != E; ++I)
01074           if (CodeGenFunction::ContainsLabel(*I, true))
01075             return CSFC_Failure;
01076         return CSFC_Success;
01077       }      
01078     }
01079     
01080     return Case ? CSFC_Success : CSFC_FallThrough;
01081   }
01082 
01083   // Okay, this is some other statement that we don't handle explicitly, like a
01084   // for statement or increment etc.  If we are skipping over this statement,
01085   // just verify it doesn't have labels, which would make it invalid to elide.
01086   if (Case) {
01087     if (CodeGenFunction::ContainsLabel(S, true))
01088       return CSFC_Failure;
01089     return CSFC_Success;
01090   }
01091   
01092   // Otherwise, we want to include this statement.  Everything is cool with that
01093   // so long as it doesn't contain a break out of the switch we're in.
01094   if (CodeGenFunction::containsBreak(S)) return CSFC_Failure;
01095   
01096   // Otherwise, everything is great.  Include the statement and tell the caller
01097   // that we fall through and include the next statement as well.
01098   ResultStmts.push_back(S);
01099   return CSFC_FallThrough;
01100 }
01101 
01102 /// FindCaseStatementsForValue - Find the case statement being jumped to and
01103 /// then invoke CollectStatementsForCase to find the list of statements to emit
01104 /// for a switch on constant.  See the comment above CollectStatementsForCase
01105 /// for more details.
01106 static bool FindCaseStatementsForValue(const SwitchStmt &S,
01107                                        const llvm::APInt &ConstantCondValue,
01108                                 SmallVectorImpl<const Stmt*> &ResultStmts,
01109                                        ASTContext &C) {
01110   // First step, find the switch case that is being branched to.  We can do this
01111   // efficiently by scanning the SwitchCase list.
01112   const SwitchCase *Case = S.getSwitchCaseList();
01113   const DefaultStmt *DefaultCase = 0;
01114   
01115   for (; Case; Case = Case->getNextSwitchCase()) {
01116     // It's either a default or case.  Just remember the default statement in
01117     // case we're not jumping to any numbered cases.
01118     if (const DefaultStmt *DS = dyn_cast<DefaultStmt>(Case)) {
01119       DefaultCase = DS;
01120       continue;
01121     }
01122     
01123     // Check to see if this case is the one we're looking for.
01124     const CaseStmt *CS = cast<CaseStmt>(Case);
01125     // Don't handle case ranges yet.
01126     if (CS->getRHS()) return false;
01127     
01128     // If we found our case, remember it as 'case'.
01129     if (CS->getLHS()->EvaluateKnownConstInt(C) == ConstantCondValue)
01130       break;
01131   }
01132   
01133   // If we didn't find a matching case, we use a default if it exists, or we
01134   // elide the whole switch body!
01135   if (Case == 0) {
01136     // It is safe to elide the body of the switch if it doesn't contain labels
01137     // etc.  If it is safe, return successfully with an empty ResultStmts list.
01138     if (DefaultCase == 0)
01139       return !CodeGenFunction::ContainsLabel(&S);
01140     Case = DefaultCase;
01141   }
01142 
01143   // Ok, we know which case is being jumped to, try to collect all the
01144   // statements that follow it.  This can fail for a variety of reasons.  Also,
01145   // check to see that the recursive walk actually found our case statement.
01146   // Insane cases like this can fail to find it in the recursive walk since we
01147   // don't handle every stmt kind:
01148   // switch (4) {
01149   //   while (1) {
01150   //     case 4: ...
01151   bool FoundCase = false;
01152   return CollectStatementsForCase(S.getBody(), Case, FoundCase,
01153                                   ResultStmts) != CSFC_Failure &&
01154          FoundCase;
01155 }
01156 
01157 void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
01158   JumpDest SwitchExit = getJumpDestInCurrentScope("sw.epilog");
01159 
01160   RunCleanupsScope ConditionScope(*this);
01161 
01162   if (S.getConditionVariable())
01163     EmitAutoVarDecl(*S.getConditionVariable());
01164 
01165   // Handle nested switch statements.
01166   llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
01167   llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
01168 
01169   // See if we can constant fold the condition of the switch and therefore only
01170   // emit the live case statement (if any) of the switch.
01171   llvm::APInt ConstantCondValue;
01172   if (ConstantFoldsToSimpleInteger(S.getCond(), ConstantCondValue)) {
01173     SmallVector<const Stmt*, 4> CaseStmts;
01174     if (FindCaseStatementsForValue(S, ConstantCondValue, CaseStmts,
01175                                    getContext())) {
01176       RunCleanupsScope ExecutedScope(*this);
01177 
01178       // At this point, we are no longer "within" a switch instance, so
01179       // we can temporarily enforce this to ensure that any embedded case
01180       // statements are not emitted.
01181       SwitchInsn = 0;
01182 
01183       // Okay, we can dead code eliminate everything except this case.  Emit the
01184       // specified series of statements and we're good.
01185       for (unsigned i = 0, e = CaseStmts.size(); i != e; ++i)
01186         EmitStmt(CaseStmts[i]);
01187 
01188       // Now we want to restore the saved switch instance so that nested
01189       // switches continue to function properly
01190       SwitchInsn = SavedSwitchInsn;
01191 
01192       return;
01193     }
01194   }
01195     
01196   llvm::Value *CondV = EmitScalarExpr(S.getCond());
01197 
01198   // Create basic block to hold stuff that comes after switch
01199   // statement. We also need to create a default block now so that
01200   // explicit case ranges tests can have a place to jump to on
01201   // failure.
01202   llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
01203   SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
01204   CaseRangeBlock = DefaultBlock;
01205 
01206   // Clear the insertion point to indicate we are in unreachable code.
01207   Builder.ClearInsertionPoint();
01208 
01209   // All break statements jump to NextBlock. If BreakContinueStack is non empty
01210   // then reuse last ContinueBlock.
01211   JumpDest OuterContinue;
01212   if (!BreakContinueStack.empty())
01213     OuterContinue = BreakContinueStack.back().ContinueBlock;
01214 
01215   BreakContinueStack.push_back(BreakContinue(SwitchExit, OuterContinue));
01216 
01217   // Emit switch body.
01218   EmitStmt(S.getBody());
01219 
01220   BreakContinueStack.pop_back();
01221 
01222   // Update the default block in case explicit case range tests have
01223   // been chained on top.
01224   SwitchInsn->setDefaultDest(CaseRangeBlock);
01225 
01226   // If a default was never emitted:
01227   if (!DefaultBlock->getParent()) {
01228     // If we have cleanups, emit the default block so that there's a
01229     // place to jump through the cleanups from.
01230     if (ConditionScope.requiresCleanups()) {
01231       EmitBlock(DefaultBlock);
01232 
01233     // Otherwise, just forward the default block to the switch end.
01234     } else {
01235       DefaultBlock->replaceAllUsesWith(SwitchExit.getBlock());
01236       delete DefaultBlock;
01237     }
01238   }
01239 
01240   ConditionScope.ForceCleanup();
01241 
01242   // Emit continuation.
01243   EmitBlock(SwitchExit.getBlock(), true);
01244 
01245   SwitchInsn = SavedSwitchInsn;
01246   CaseRangeBlock = SavedCRBlock;
01247 }
01248 
01249 static std::string
01250 SimplifyConstraint(const char *Constraint, const TargetInfo &Target,
01251                  SmallVectorImpl<TargetInfo::ConstraintInfo> *OutCons=0) {
01252   std::string Result;
01253 
01254   while (*Constraint) {
01255     switch (*Constraint) {
01256     default:
01257       Result += Target.convertConstraint(Constraint);
01258       break;
01259     // Ignore these
01260     case '*':
01261     case '?':
01262     case '!':
01263     case '=': // Will see this and the following in mult-alt constraints.
01264     case '+':
01265       break;
01266     case ',':
01267       Result += "|";
01268       break;
01269     case 'g':
01270       Result += "imr";
01271       break;
01272     case '[': {
01273       assert(OutCons &&
01274              "Must pass output names to constraints with a symbolic name");
01275       unsigned Index;
01276       bool result = Target.resolveSymbolicName(Constraint,
01277                                                &(*OutCons)[0],
01278                                                OutCons->size(), Index);
01279       assert(result && "Could not resolve symbolic name"); (void)result;
01280       Result += llvm::utostr(Index);
01281       break;
01282     }
01283     }
01284 
01285     Constraint++;
01286   }
01287 
01288   return Result;
01289 }
01290 
01291 /// AddVariableConstraints - Look at AsmExpr and if it is a variable declared
01292 /// as using a particular register add that as a constraint that will be used
01293 /// in this asm stmt.
01294 static std::string
01295 AddVariableConstraints(const std::string &Constraint, const Expr &AsmExpr,
01296                        const TargetInfo &Target, CodeGenModule &CGM,
01297                        const AsmStmt &Stmt) {
01298   const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(&AsmExpr);
01299   if (!AsmDeclRef)
01300     return Constraint;
01301   const ValueDecl &Value = *AsmDeclRef->getDecl();
01302   const VarDecl *Variable = dyn_cast<VarDecl>(&Value);
01303   if (!Variable)
01304     return Constraint;
01305   if (Variable->getStorageClass() != SC_Register)
01306     return Constraint;
01307   AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>();
01308   if (!Attr)
01309     return Constraint;
01310   StringRef Register = Attr->getLabel();
01311   assert(Target.isValidGCCRegisterName(Register));
01312   // We're using validateOutputConstraint here because we only care if
01313   // this is a register constraint.
01314   TargetInfo::ConstraintInfo Info(Constraint, "");
01315   if (Target.validateOutputConstraint(Info) &&
01316       !Info.allowsRegister()) {
01317     CGM.ErrorUnsupported(&Stmt, "__asm__");
01318     return Constraint;
01319   }
01320   // Canonicalize the register here before returning it.
01321   Register = Target.getNormalizedGCCRegisterName(Register);
01322   return "{" + Register.str() + "}";
01323 }
01324 
01325 llvm::Value*
01326 CodeGenFunction::EmitAsmInputLValue(const AsmStmt &S,
01327                                     const TargetInfo::ConstraintInfo &Info,
01328                                     LValue InputValue, QualType InputType,
01329                                     std::string &ConstraintStr) {
01330   llvm::Value *Arg;
01331   if (Info.allowsRegister() || !Info.allowsMemory()) {
01332     if (!CodeGenFunction::hasAggregateLLVMType(InputType)) {
01333       Arg = EmitLoadOfLValue(InputValue).getScalarVal();
01334     } else {
01335       llvm::Type *Ty = ConvertType(InputType);
01336       uint64_t Size = CGM.getTargetData().getTypeSizeInBits(Ty);
01337       if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
01338         Ty = llvm::IntegerType::get(getLLVMContext(), Size);
01339         Ty = llvm::PointerType::getUnqual(Ty);
01340 
01341         Arg = Builder.CreateLoad(Builder.CreateBitCast(InputValue.getAddress(),
01342                                                        Ty));
01343       } else {
01344         Arg = InputValue.getAddress();
01345         ConstraintStr += '*';
01346       }
01347     }
01348   } else {
01349     Arg = InputValue.getAddress();
01350     ConstraintStr += '*';
01351   }
01352 
01353   return Arg;
01354 }
01355 
01356 llvm::Value* CodeGenFunction::EmitAsmInput(const AsmStmt &S,
01357                                          const TargetInfo::ConstraintInfo &Info,
01358                                            const Expr *InputExpr,
01359                                            std::string &ConstraintStr) {
01360   if (Info.allowsRegister() || !Info.allowsMemory())
01361     if (!CodeGenFunction::hasAggregateLLVMType(InputExpr->getType()))
01362       return EmitScalarExpr(InputExpr);
01363 
01364   InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
01365   LValue Dest = EmitLValue(InputExpr);
01366   return EmitAsmInputLValue(S, Info, Dest, InputExpr->getType(), ConstraintStr);
01367 }
01368 
01369 /// getAsmSrcLocInfo - Return the !srcloc metadata node to attach to an inline
01370 /// asm call instruction.  The !srcloc MDNode contains a list of constant
01371 /// integers which are the source locations of the start of each line in the
01372 /// asm.
01373 static llvm::MDNode *getAsmSrcLocInfo(const StringLiteral *Str,
01374                                       CodeGenFunction &CGF) {
01375   SmallVector<llvm::Value *, 8> Locs;
01376   // Add the location of the first line to the MDNode.
01377   Locs.push_back(llvm::ConstantInt::get(CGF.Int32Ty,
01378                                         Str->getLocStart().getRawEncoding()));
01379   StringRef StrVal = Str->getString();
01380   if (!StrVal.empty()) {
01381     const SourceManager &SM = CGF.CGM.getContext().getSourceManager();
01382     const LangOptions &LangOpts = CGF.CGM.getLangOpts();
01383     
01384     // Add the location of the start of each subsequent line of the asm to the
01385     // MDNode.
01386     for (unsigned i = 0, e = StrVal.size()-1; i != e; ++i) {
01387       if (StrVal[i] != '\n') continue;
01388       SourceLocation LineLoc = Str->getLocationOfByte(i+1, SM, LangOpts,
01389                                                       CGF.Target);
01390       Locs.push_back(llvm::ConstantInt::get(CGF.Int32Ty,
01391                                             LineLoc.getRawEncoding()));
01392     }
01393   }    
01394   
01395   return llvm::MDNode::get(CGF.getLLVMContext(), Locs);
01396 }
01397 
01398 void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
01399   // Analyze the asm string to decompose it into its pieces.  We know that Sema
01400   // has already done this, so it is guaranteed to be successful.
01401   SmallVector<AsmStmt::AsmStringPiece, 4> Pieces;
01402   unsigned DiagOffs;
01403   S.AnalyzeAsmString(Pieces, getContext(), DiagOffs);
01404 
01405   // Assemble the pieces into the final asm string.
01406   std::string AsmString;
01407   for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
01408     if (Pieces[i].isString())
01409       AsmString += Pieces[i].getString();
01410     else if (Pieces[i].getModifier() == '\0')
01411       AsmString += '$' + llvm::utostr(Pieces[i].getOperandNo());
01412     else
01413       AsmString += "${" + llvm::utostr(Pieces[i].getOperandNo()) + ':' +
01414                    Pieces[i].getModifier() + '}';
01415   }
01416 
01417   // Get all the output and input constraints together.
01418   SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
01419   SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
01420 
01421   for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
01422     TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i),
01423                                     S.getOutputName(i));
01424     bool IsValid = Target.validateOutputConstraint(Info); (void)IsValid;
01425     assert(IsValid && "Failed to parse output constraint"); 
01426     OutputConstraintInfos.push_back(Info);
01427   }
01428 
01429   for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
01430     TargetInfo::ConstraintInfo Info(S.getInputConstraint(i),
01431                                     S.getInputName(i));
01432     bool IsValid = Target.validateInputConstraint(OutputConstraintInfos.data(),
01433                                                   S.getNumOutputs(), Info);
01434     assert(IsValid && "Failed to parse input constraint"); (void)IsValid;
01435     InputConstraintInfos.push_back(Info);
01436   }
01437 
01438   std::string Constraints;
01439 
01440   std::vector<LValue> ResultRegDests;
01441   std::vector<QualType> ResultRegQualTys;
01442   std::vector<llvm::Type *> ResultRegTypes;
01443   std::vector<llvm::Type *> ResultTruncRegTypes;
01444   std::vector<llvm::Type *> ArgTypes;
01445   std::vector<llvm::Value*> Args;
01446 
01447   // Keep track of inout constraints.
01448   std::string InOutConstraints;
01449   std::vector<llvm::Value*> InOutArgs;
01450   std::vector<llvm::Type*> InOutArgTypes;
01451 
01452   for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
01453     TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
01454 
01455     // Simplify the output constraint.
01456     std::string OutputConstraint(S.getOutputConstraint(i));
01457     OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
01458 
01459     const Expr *OutExpr = S.getOutputExpr(i);
01460     OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
01461 
01462     OutputConstraint = AddVariableConstraints(OutputConstraint, *OutExpr,
01463                                               Target, CGM, S);
01464 
01465     LValue Dest = EmitLValue(OutExpr);
01466     if (!Constraints.empty())
01467       Constraints += ',';
01468 
01469     // If this is a register output, then make the inline asm return it
01470     // by-value.  If this is a memory result, return the value by-reference.
01471     if (!Info.allowsMemory() && !hasAggregateLLVMType(OutExpr->getType())) {
01472       Constraints += "=" + OutputConstraint;
01473       ResultRegQualTys.push_back(OutExpr->getType());
01474       ResultRegDests.push_back(Dest);
01475       ResultRegTypes.push_back(ConvertTypeForMem(OutExpr->getType()));
01476       ResultTruncRegTypes.push_back(ResultRegTypes.back());
01477 
01478       // If this output is tied to an input, and if the input is larger, then
01479       // we need to set the actual result type of the inline asm node to be the
01480       // same as the input type.
01481       if (Info.hasMatchingInput()) {
01482         unsigned InputNo;
01483         for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) {
01484           TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo];
01485           if (Input.hasTiedOperand() && Input.getTiedOperand() == i)
01486             break;
01487         }
01488         assert(InputNo != S.getNumInputs() && "Didn't find matching input!");
01489 
01490         QualType InputTy = S.getInputExpr(InputNo)->getType();
01491         QualType OutputType = OutExpr->getType();
01492 
01493         uint64_t InputSize = getContext().getTypeSize(InputTy);
01494         if (getContext().getTypeSize(OutputType) < InputSize) {
01495           // Form the asm to return the value as a larger integer or fp type.
01496           ResultRegTypes.back() = ConvertType(InputTy);
01497         }
01498       }
01499       if (llvm::Type* AdjTy = 
01500             getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
01501                                                  ResultRegTypes.back()))
01502         ResultRegTypes.back() = AdjTy;
01503     } else {
01504       ArgTypes.push_back(Dest.getAddress()->getType());
01505       Args.push_back(Dest.getAddress());
01506       Constraints += "=*";
01507       Constraints += OutputConstraint;
01508     }
01509 
01510     if (Info.isReadWrite()) {
01511       InOutConstraints += ',';
01512 
01513       const Expr *InputExpr = S.getOutputExpr(i);
01514       llvm::Value *Arg = EmitAsmInputLValue(S, Info, Dest, InputExpr->getType(),
01515                                             InOutConstraints);
01516 
01517       if (llvm::Type* AdjTy =
01518             getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
01519                                                  Arg->getType()))
01520         Arg = Builder.CreateBitCast(Arg, AdjTy);
01521 
01522       if (Info.allowsRegister())
01523         InOutConstraints += llvm::utostr(i);
01524       else
01525         InOutConstraints += OutputConstraint;
01526 
01527       InOutArgTypes.push_back(Arg->getType());
01528       InOutArgs.push_back(Arg);
01529     }
01530   }
01531 
01532   unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
01533 
01534   for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
01535     const Expr *InputExpr = S.getInputExpr(i);
01536 
01537     TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
01538 
01539     if (!Constraints.empty())
01540       Constraints += ',';
01541 
01542     // Simplify the input constraint.
01543     std::string InputConstraint(S.getInputConstraint(i));
01544     InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target,
01545                                          &OutputConstraintInfos);
01546 
01547     InputConstraint =
01548       AddVariableConstraints(InputConstraint,
01549                             *InputExpr->IgnoreParenNoopCasts(getContext()),
01550                             Target, CGM, S);
01551 
01552     llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, Constraints);
01553 
01554     // If this input argument is tied to a larger output result, extend the
01555     // input to be the same size as the output.  The LLVM backend wants to see
01556     // the input and output of a matching constraint be the same size.  Note
01557     // that GCC does not define what the top bits are here.  We use zext because
01558     // that is usually cheaper, but LLVM IR should really get an anyext someday.
01559     if (Info.hasTiedOperand()) {
01560       unsigned Output = Info.getTiedOperand();
01561       QualType OutputType = S.getOutputExpr(Output)->getType();
01562       QualType InputTy = InputExpr->getType();
01563 
01564       if (getContext().getTypeSize(OutputType) >
01565           getContext().getTypeSize(InputTy)) {
01566         // Use ptrtoint as appropriate so that we can do our extension.
01567         if (isa<llvm::PointerType>(Arg->getType()))
01568           Arg = Builder.CreatePtrToInt(Arg, IntPtrTy);
01569         llvm::Type *OutputTy = ConvertType(OutputType);
01570         if (isa<llvm::IntegerType>(OutputTy))
01571           Arg = Builder.CreateZExt(Arg, OutputTy);
01572         else if (isa<llvm::PointerType>(OutputTy))
01573           Arg = Builder.CreateZExt(Arg, IntPtrTy);
01574         else {
01575           assert(OutputTy->isFloatingPointTy() && "Unexpected output type");
01576           Arg = Builder.CreateFPExt(Arg, OutputTy);
01577         }
01578       }
01579     }
01580     if (llvm::Type* AdjTy =
01581               getTargetHooks().adjustInlineAsmType(*this, InputConstraint,
01582                                                    Arg->getType()))
01583       Arg = Builder.CreateBitCast(Arg, AdjTy);
01584 
01585     ArgTypes.push_back(Arg->getType());
01586     Args.push_back(Arg);
01587     Constraints += InputConstraint;
01588   }
01589 
01590   // Append the "input" part of inout constraints last.
01591   for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
01592     ArgTypes.push_back(InOutArgTypes[i]);
01593     Args.push_back(InOutArgs[i]);
01594   }
01595   Constraints += InOutConstraints;
01596 
01597   // Clobbers
01598   for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
01599     StringRef Clobber = S.getClobber(i)->getString();
01600 
01601     if (Clobber != "memory" && Clobber != "cc")
01602     Clobber = Target.getNormalizedGCCRegisterName(Clobber);
01603 
01604     if (i != 0 || NumConstraints != 0)
01605       Constraints += ',';
01606 
01607     Constraints += "~{";
01608     Constraints += Clobber;
01609     Constraints += '}';
01610   }
01611 
01612   // Add machine specific clobbers
01613   std::string MachineClobbers = Target.getClobbers();
01614   if (!MachineClobbers.empty()) {
01615     if (!Constraints.empty())
01616       Constraints += ',';
01617     Constraints += MachineClobbers;
01618   }
01619 
01620   llvm::Type *ResultType;
01621   if (ResultRegTypes.empty())
01622     ResultType = VoidTy;
01623   else if (ResultRegTypes.size() == 1)
01624     ResultType = ResultRegTypes[0];
01625   else
01626     ResultType = llvm::StructType::get(getLLVMContext(), ResultRegTypes);
01627 
01628   llvm::FunctionType *FTy =
01629     llvm::FunctionType::get(ResultType, ArgTypes, false);
01630 
01631   llvm::InlineAsm *IA =
01632     llvm::InlineAsm::get(FTy, AsmString, Constraints,
01633                          S.isVolatile() || S.getNumOutputs() == 0);
01634   llvm::CallInst *Result = Builder.CreateCall(IA, Args);
01635   Result->addAttribute(~0, llvm::Attribute::NoUnwind);
01636 
01637   // Slap the source location of the inline asm into a !srcloc metadata on the
01638   // call.
01639   Result->setMetadata("srcloc", getAsmSrcLocInfo(S.getAsmString(), *this));
01640 
01641   // Extract all of the register value results from the asm.
01642   std::vector<llvm::Value*> RegResults;
01643   if (ResultRegTypes.size() == 1) {
01644     RegResults.push_back(Result);
01645   } else {
01646     for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) {
01647       llvm::Value *Tmp = Builder.CreateExtractValue(Result, i, "asmresult");
01648       RegResults.push_back(Tmp);
01649     }
01650   }
01651 
01652   for (unsigned i = 0, e = RegResults.size(); i != e; ++i) {
01653     llvm::Value *Tmp = RegResults[i];
01654 
01655     // If the result type of the LLVM IR asm doesn't match the result type of
01656     // the expression, do the conversion.
01657     if (ResultRegTypes[i] != ResultTruncRegTypes[i]) {
01658       llvm::Type *TruncTy = ResultTruncRegTypes[i];
01659       
01660       // Truncate the integer result to the right size, note that TruncTy can be
01661       // a pointer.
01662       if (TruncTy->isFloatingPointTy())
01663         Tmp = Builder.CreateFPTrunc(Tmp, TruncTy);
01664       else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) {
01665         uint64_t ResSize = CGM.getTargetData().getTypeSizeInBits(TruncTy);
01666         Tmp = Builder.CreateTrunc(Tmp,
01667                    llvm::IntegerType::get(getLLVMContext(), (unsigned)ResSize));
01668         Tmp = Builder.CreateIntToPtr(Tmp, TruncTy);
01669       } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) {
01670         uint64_t TmpSize =CGM.getTargetData().getTypeSizeInBits(Tmp->getType());
01671         Tmp = Builder.CreatePtrToInt(Tmp,
01672                    llvm::IntegerType::get(getLLVMContext(), (unsigned)TmpSize));
01673         Tmp = Builder.CreateTrunc(Tmp, TruncTy);
01674       } else if (TruncTy->isIntegerTy()) {
01675         Tmp = Builder.CreateTrunc(Tmp, TruncTy);
01676       } else if (TruncTy->isVectorTy()) {
01677         Tmp = Builder.CreateBitCast(Tmp, TruncTy);
01678       }
01679     }
01680 
01681     EmitStoreThroughLValue(RValue::get(Tmp), ResultRegDests[i]);
01682   }
01683 }