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