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