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