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