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