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