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