1 //===--- CGStmt.cpp - Emit LLVM Code from Statements ----------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This contains code to emit Stmt nodes as LLVM code. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "CGDebugInfo.h" 14 #include "CGOpenMPRuntime.h" 15 #include "CodeGenFunction.h" 16 #include "CodeGenModule.h" 17 #include "TargetInfo.h" 18 #include "clang/AST/Attr.h" 19 #include "clang/AST/StmtVisitor.h" 20 #include "clang/Basic/Builtins.h" 21 #include "clang/Basic/DiagnosticSema.h" 22 #include "clang/Basic/PrettyStackTrace.h" 23 #include "clang/Basic/SourceManager.h" 24 #include "clang/Basic/TargetInfo.h" 25 #include "llvm/ADT/SmallSet.h" 26 #include "llvm/ADT/StringExtras.h" 27 #include "llvm/IR/DataLayout.h" 28 #include "llvm/IR/InlineAsm.h" 29 #include "llvm/IR/Intrinsics.h" 30 #include "llvm/IR/MDBuilder.h" 31 #include "llvm/Support/SaveAndRestore.h" 32 33 using namespace clang; 34 using namespace CodeGen; 35 36 //===----------------------------------------------------------------------===// 37 // Statement Emission 38 //===----------------------------------------------------------------------===// 39 40 void CodeGenFunction::EmitStopPoint(const Stmt *S) { 41 if (CGDebugInfo *DI = getDebugInfo()) { 42 SourceLocation Loc; 43 Loc = S->getBeginLoc(); 44 DI->EmitLocation(Builder, Loc); 45 46 LastStopPoint = Loc; 47 } 48 } 49 50 void CodeGenFunction::EmitStmt(const Stmt *S, ArrayRef<const Attr *> Attrs) { 51 assert(S && "Null statement?"); 52 PGO.setCurrentStmt(S); 53 54 // These statements have their own debug info handling. 55 if (EmitSimpleStmt(S, Attrs)) 56 return; 57 58 // Check if we are generating unreachable code. 59 if (!HaveInsertPoint()) { 60 // If so, and the statement doesn't contain a label, then we do not need to 61 // generate actual code. This is safe because (1) the current point is 62 // unreachable, so we don't need to execute the code, and (2) we've already 63 // handled the statements which update internal data structures (like the 64 // local variable map) which could be used by subsequent statements. 65 if (!ContainsLabel(S)) { 66 // Verify that any decl statements were handled as simple, they may be in 67 // scope of subsequent reachable statements. 68 assert(!isa<DeclStmt>(*S) && "Unexpected DeclStmt!"); 69 return; 70 } 71 72 // Otherwise, make a new block to hold the code. 73 EnsureInsertPoint(); 74 } 75 76 // Generate a stoppoint if we are emitting debug info. 77 EmitStopPoint(S); 78 79 // Ignore all OpenMP directives except for simd if OpenMP with Simd is 80 // enabled. 81 if (getLangOpts().OpenMP && getLangOpts().OpenMPSimd) { 82 if (const auto *D = dyn_cast<OMPExecutableDirective>(S)) { 83 EmitSimpleOMPExecutableDirective(*D); 84 return; 85 } 86 } 87 88 switch (S->getStmtClass()) { 89 case Stmt::NoStmtClass: 90 case Stmt::CXXCatchStmtClass: 91 case Stmt::SEHExceptStmtClass: 92 case Stmt::SEHFinallyStmtClass: 93 case Stmt::MSDependentExistsStmtClass: 94 llvm_unreachable("invalid statement class to emit generically"); 95 case Stmt::NullStmtClass: 96 case Stmt::CompoundStmtClass: 97 case Stmt::DeclStmtClass: 98 case Stmt::LabelStmtClass: 99 case Stmt::AttributedStmtClass: 100 case Stmt::GotoStmtClass: 101 case Stmt::BreakStmtClass: 102 case Stmt::ContinueStmtClass: 103 case Stmt::DefaultStmtClass: 104 case Stmt::CaseStmtClass: 105 case Stmt::SEHLeaveStmtClass: 106 llvm_unreachable("should have emitted these statements as simple"); 107 108 #define STMT(Type, Base) 109 #define ABSTRACT_STMT(Op) 110 #define EXPR(Type, Base) \ 111 case Stmt::Type##Class: 112 #include "clang/AST/StmtNodes.inc" 113 { 114 // Remember the block we came in on. 115 llvm::BasicBlock *incoming = Builder.GetInsertBlock(); 116 assert(incoming && "expression emission must have an insertion point"); 117 118 EmitIgnoredExpr(cast<Expr>(S)); 119 120 llvm::BasicBlock *outgoing = Builder.GetInsertBlock(); 121 assert(outgoing && "expression emission cleared block!"); 122 123 // The expression emitters assume (reasonably!) that the insertion 124 // point is always set. To maintain that, the call-emission code 125 // for noreturn functions has to enter a new block with no 126 // predecessors. We want to kill that block and mark the current 127 // insertion point unreachable in the common case of a call like 128 // "exit();". Since expression emission doesn't otherwise create 129 // blocks with no predecessors, we can just test for that. 130 // However, we must be careful not to do this to our incoming 131 // block, because *statement* emission does sometimes create 132 // reachable blocks which will have no predecessors until later in 133 // the function. This occurs with, e.g., labels that are not 134 // reachable by fallthrough. 135 if (incoming != outgoing && outgoing->use_empty()) { 136 outgoing->eraseFromParent(); 137 Builder.ClearInsertionPoint(); 138 } 139 break; 140 } 141 142 case Stmt::IndirectGotoStmtClass: 143 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break; 144 145 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break; 146 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S), Attrs); break; 147 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S), Attrs); break; 148 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S), Attrs); break; 149 150 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break; 151 152 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break; 153 case Stmt::GCCAsmStmtClass: // Intentional fall-through. 154 case Stmt::MSAsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break; 155 case Stmt::CoroutineBodyStmtClass: 156 EmitCoroutineBody(cast<CoroutineBodyStmt>(*S)); 157 break; 158 case Stmt::CoreturnStmtClass: 159 EmitCoreturnStmt(cast<CoreturnStmt>(*S)); 160 break; 161 case Stmt::CapturedStmtClass: { 162 const CapturedStmt *CS = cast<CapturedStmt>(S); 163 EmitCapturedStmt(*CS, CS->getCapturedRegionKind()); 164 } 165 break; 166 case Stmt::ObjCAtTryStmtClass: 167 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S)); 168 break; 169 case Stmt::ObjCAtCatchStmtClass: 170 llvm_unreachable( 171 "@catch statements should be handled by EmitObjCAtTryStmt"); 172 case Stmt::ObjCAtFinallyStmtClass: 173 llvm_unreachable( 174 "@finally statements should be handled by EmitObjCAtTryStmt"); 175 case Stmt::ObjCAtThrowStmtClass: 176 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S)); 177 break; 178 case Stmt::ObjCAtSynchronizedStmtClass: 179 EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S)); 180 break; 181 case Stmt::ObjCForCollectionStmtClass: 182 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S)); 183 break; 184 case Stmt::ObjCAutoreleasePoolStmtClass: 185 EmitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(*S)); 186 break; 187 188 case Stmt::CXXTryStmtClass: 189 EmitCXXTryStmt(cast<CXXTryStmt>(*S)); 190 break; 191 case Stmt::CXXForRangeStmtClass: 192 EmitCXXForRangeStmt(cast<CXXForRangeStmt>(*S), Attrs); 193 break; 194 case Stmt::SEHTryStmtClass: 195 EmitSEHTryStmt(cast<SEHTryStmt>(*S)); 196 break; 197 case Stmt::OMPCanonicalLoopClass: 198 EmitOMPCanonicalLoop(cast<OMPCanonicalLoop>(S)); 199 break; 200 case Stmt::OMPParallelDirectiveClass: 201 EmitOMPParallelDirective(cast<OMPParallelDirective>(*S)); 202 break; 203 case Stmt::OMPSimdDirectiveClass: 204 EmitOMPSimdDirective(cast<OMPSimdDirective>(*S)); 205 break; 206 case Stmt::OMPTileDirectiveClass: 207 EmitOMPTileDirective(cast<OMPTileDirective>(*S)); 208 break; 209 case Stmt::OMPForDirectiveClass: 210 EmitOMPForDirective(cast<OMPForDirective>(*S)); 211 break; 212 case Stmt::OMPForSimdDirectiveClass: 213 EmitOMPForSimdDirective(cast<OMPForSimdDirective>(*S)); 214 break; 215 case Stmt::OMPSectionsDirectiveClass: 216 EmitOMPSectionsDirective(cast<OMPSectionsDirective>(*S)); 217 break; 218 case Stmt::OMPSectionDirectiveClass: 219 EmitOMPSectionDirective(cast<OMPSectionDirective>(*S)); 220 break; 221 case Stmt::OMPSingleDirectiveClass: 222 EmitOMPSingleDirective(cast<OMPSingleDirective>(*S)); 223 break; 224 case Stmt::OMPMasterDirectiveClass: 225 EmitOMPMasterDirective(cast<OMPMasterDirective>(*S)); 226 break; 227 case Stmt::OMPCriticalDirectiveClass: 228 EmitOMPCriticalDirective(cast<OMPCriticalDirective>(*S)); 229 break; 230 case Stmt::OMPParallelForDirectiveClass: 231 EmitOMPParallelForDirective(cast<OMPParallelForDirective>(*S)); 232 break; 233 case Stmt::OMPParallelForSimdDirectiveClass: 234 EmitOMPParallelForSimdDirective(cast<OMPParallelForSimdDirective>(*S)); 235 break; 236 case Stmt::OMPParallelMasterDirectiveClass: 237 EmitOMPParallelMasterDirective(cast<OMPParallelMasterDirective>(*S)); 238 break; 239 case Stmt::OMPParallelSectionsDirectiveClass: 240 EmitOMPParallelSectionsDirective(cast<OMPParallelSectionsDirective>(*S)); 241 break; 242 case Stmt::OMPTaskDirectiveClass: 243 EmitOMPTaskDirective(cast<OMPTaskDirective>(*S)); 244 break; 245 case Stmt::OMPTaskyieldDirectiveClass: 246 EmitOMPTaskyieldDirective(cast<OMPTaskyieldDirective>(*S)); 247 break; 248 case Stmt::OMPBarrierDirectiveClass: 249 EmitOMPBarrierDirective(cast<OMPBarrierDirective>(*S)); 250 break; 251 case Stmt::OMPTaskwaitDirectiveClass: 252 EmitOMPTaskwaitDirective(cast<OMPTaskwaitDirective>(*S)); 253 break; 254 case Stmt::OMPTaskgroupDirectiveClass: 255 EmitOMPTaskgroupDirective(cast<OMPTaskgroupDirective>(*S)); 256 break; 257 case Stmt::OMPFlushDirectiveClass: 258 EmitOMPFlushDirective(cast<OMPFlushDirective>(*S)); 259 break; 260 case Stmt::OMPDepobjDirectiveClass: 261 EmitOMPDepobjDirective(cast<OMPDepobjDirective>(*S)); 262 break; 263 case Stmt::OMPScanDirectiveClass: 264 EmitOMPScanDirective(cast<OMPScanDirective>(*S)); 265 break; 266 case Stmt::OMPOrderedDirectiveClass: 267 EmitOMPOrderedDirective(cast<OMPOrderedDirective>(*S)); 268 break; 269 case Stmt::OMPAtomicDirectiveClass: 270 EmitOMPAtomicDirective(cast<OMPAtomicDirective>(*S)); 271 break; 272 case Stmt::OMPTargetDirectiveClass: 273 EmitOMPTargetDirective(cast<OMPTargetDirective>(*S)); 274 break; 275 case Stmt::OMPTeamsDirectiveClass: 276 EmitOMPTeamsDirective(cast<OMPTeamsDirective>(*S)); 277 break; 278 case Stmt::OMPCancellationPointDirectiveClass: 279 EmitOMPCancellationPointDirective(cast<OMPCancellationPointDirective>(*S)); 280 break; 281 case Stmt::OMPCancelDirectiveClass: 282 EmitOMPCancelDirective(cast<OMPCancelDirective>(*S)); 283 break; 284 case Stmt::OMPTargetDataDirectiveClass: 285 EmitOMPTargetDataDirective(cast<OMPTargetDataDirective>(*S)); 286 break; 287 case Stmt::OMPTargetEnterDataDirectiveClass: 288 EmitOMPTargetEnterDataDirective(cast<OMPTargetEnterDataDirective>(*S)); 289 break; 290 case Stmt::OMPTargetExitDataDirectiveClass: 291 EmitOMPTargetExitDataDirective(cast<OMPTargetExitDataDirective>(*S)); 292 break; 293 case Stmt::OMPTargetParallelDirectiveClass: 294 EmitOMPTargetParallelDirective(cast<OMPTargetParallelDirective>(*S)); 295 break; 296 case Stmt::OMPTargetParallelForDirectiveClass: 297 EmitOMPTargetParallelForDirective(cast<OMPTargetParallelForDirective>(*S)); 298 break; 299 case Stmt::OMPTaskLoopDirectiveClass: 300 EmitOMPTaskLoopDirective(cast<OMPTaskLoopDirective>(*S)); 301 break; 302 case Stmt::OMPTaskLoopSimdDirectiveClass: 303 EmitOMPTaskLoopSimdDirective(cast<OMPTaskLoopSimdDirective>(*S)); 304 break; 305 case Stmt::OMPMasterTaskLoopDirectiveClass: 306 EmitOMPMasterTaskLoopDirective(cast<OMPMasterTaskLoopDirective>(*S)); 307 break; 308 case Stmt::OMPMasterTaskLoopSimdDirectiveClass: 309 EmitOMPMasterTaskLoopSimdDirective( 310 cast<OMPMasterTaskLoopSimdDirective>(*S)); 311 break; 312 case Stmt::OMPParallelMasterTaskLoopDirectiveClass: 313 EmitOMPParallelMasterTaskLoopDirective( 314 cast<OMPParallelMasterTaskLoopDirective>(*S)); 315 break; 316 case Stmt::OMPParallelMasterTaskLoopSimdDirectiveClass: 317 EmitOMPParallelMasterTaskLoopSimdDirective( 318 cast<OMPParallelMasterTaskLoopSimdDirective>(*S)); 319 break; 320 case Stmt::OMPDistributeDirectiveClass: 321 EmitOMPDistributeDirective(cast<OMPDistributeDirective>(*S)); 322 break; 323 case Stmt::OMPTargetUpdateDirectiveClass: 324 EmitOMPTargetUpdateDirective(cast<OMPTargetUpdateDirective>(*S)); 325 break; 326 case Stmt::OMPDistributeParallelForDirectiveClass: 327 EmitOMPDistributeParallelForDirective( 328 cast<OMPDistributeParallelForDirective>(*S)); 329 break; 330 case Stmt::OMPDistributeParallelForSimdDirectiveClass: 331 EmitOMPDistributeParallelForSimdDirective( 332 cast<OMPDistributeParallelForSimdDirective>(*S)); 333 break; 334 case Stmt::OMPDistributeSimdDirectiveClass: 335 EmitOMPDistributeSimdDirective(cast<OMPDistributeSimdDirective>(*S)); 336 break; 337 case Stmt::OMPTargetParallelForSimdDirectiveClass: 338 EmitOMPTargetParallelForSimdDirective( 339 cast<OMPTargetParallelForSimdDirective>(*S)); 340 break; 341 case Stmt::OMPTargetSimdDirectiveClass: 342 EmitOMPTargetSimdDirective(cast<OMPTargetSimdDirective>(*S)); 343 break; 344 case Stmt::OMPTeamsDistributeDirectiveClass: 345 EmitOMPTeamsDistributeDirective(cast<OMPTeamsDistributeDirective>(*S)); 346 break; 347 case Stmt::OMPTeamsDistributeSimdDirectiveClass: 348 EmitOMPTeamsDistributeSimdDirective( 349 cast<OMPTeamsDistributeSimdDirective>(*S)); 350 break; 351 case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass: 352 EmitOMPTeamsDistributeParallelForSimdDirective( 353 cast<OMPTeamsDistributeParallelForSimdDirective>(*S)); 354 break; 355 case Stmt::OMPTeamsDistributeParallelForDirectiveClass: 356 EmitOMPTeamsDistributeParallelForDirective( 357 cast<OMPTeamsDistributeParallelForDirective>(*S)); 358 break; 359 case Stmt::OMPTargetTeamsDirectiveClass: 360 EmitOMPTargetTeamsDirective(cast<OMPTargetTeamsDirective>(*S)); 361 break; 362 case Stmt::OMPTargetTeamsDistributeDirectiveClass: 363 EmitOMPTargetTeamsDistributeDirective( 364 cast<OMPTargetTeamsDistributeDirective>(*S)); 365 break; 366 case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass: 367 EmitOMPTargetTeamsDistributeParallelForDirective( 368 cast<OMPTargetTeamsDistributeParallelForDirective>(*S)); 369 break; 370 case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass: 371 EmitOMPTargetTeamsDistributeParallelForSimdDirective( 372 cast<OMPTargetTeamsDistributeParallelForSimdDirective>(*S)); 373 break; 374 case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass: 375 EmitOMPTargetTeamsDistributeSimdDirective( 376 cast<OMPTargetTeamsDistributeSimdDirective>(*S)); 377 break; 378 case Stmt::OMPInteropDirectiveClass: 379 llvm_unreachable("Interop directive not supported yet."); 380 break; 381 } 382 } 383 384 bool CodeGenFunction::EmitSimpleStmt(const Stmt *S, 385 ArrayRef<const Attr *> Attrs) { 386 switch (S->getStmtClass()) { 387 default: 388 return false; 389 case Stmt::NullStmtClass: 390 break; 391 case Stmt::CompoundStmtClass: 392 EmitCompoundStmt(cast<CompoundStmt>(*S)); 393 break; 394 case Stmt::DeclStmtClass: 395 EmitDeclStmt(cast<DeclStmt>(*S)); 396 break; 397 case Stmt::LabelStmtClass: 398 EmitLabelStmt(cast<LabelStmt>(*S)); 399 break; 400 case Stmt::AttributedStmtClass: 401 EmitAttributedStmt(cast<AttributedStmt>(*S)); 402 break; 403 case Stmt::GotoStmtClass: 404 EmitGotoStmt(cast<GotoStmt>(*S)); 405 break; 406 case Stmt::BreakStmtClass: 407 EmitBreakStmt(cast<BreakStmt>(*S)); 408 break; 409 case Stmt::ContinueStmtClass: 410 EmitContinueStmt(cast<ContinueStmt>(*S)); 411 break; 412 case Stmt::DefaultStmtClass: 413 EmitDefaultStmt(cast<DefaultStmt>(*S), Attrs); 414 break; 415 case Stmt::CaseStmtClass: 416 EmitCaseStmt(cast<CaseStmt>(*S), Attrs); 417 break; 418 case Stmt::SEHLeaveStmtClass: 419 EmitSEHLeaveStmt(cast<SEHLeaveStmt>(*S)); 420 break; 421 } 422 return true; 423 } 424 425 /// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true, 426 /// this captures the expression result of the last sub-statement and returns it 427 /// (for use by the statement expression extension). 428 Address CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast, 429 AggValueSlot AggSlot) { 430 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(), 431 "LLVM IR generation of compound statement ('{}')"); 432 433 // Keep track of the current cleanup stack depth, including debug scopes. 434 LexicalScope Scope(*this, S.getSourceRange()); 435 436 return EmitCompoundStmtWithoutScope(S, GetLast, AggSlot); 437 } 438 439 Address 440 CodeGenFunction::EmitCompoundStmtWithoutScope(const CompoundStmt &S, 441 bool GetLast, 442 AggValueSlot AggSlot) { 443 444 const Stmt *ExprResult = S.getStmtExprResult(); 445 assert((!GetLast || (GetLast && ExprResult)) && 446 "If GetLast is true then the CompoundStmt must have a StmtExprResult"); 447 448 Address RetAlloca = Address::invalid(); 449 450 for (auto *CurStmt : S.body()) { 451 if (GetLast && ExprResult == CurStmt) { 452 // We have to special case labels here. They are statements, but when put 453 // at the end of a statement expression, they yield the value of their 454 // subexpression. Handle this by walking through all labels we encounter, 455 // emitting them before we evaluate the subexpr. 456 // Similar issues arise for attributed statements. 457 while (!isa<Expr>(ExprResult)) { 458 if (const auto *LS = dyn_cast<LabelStmt>(ExprResult)) { 459 EmitLabel(LS->getDecl()); 460 ExprResult = LS->getSubStmt(); 461 } else if (const auto *AS = dyn_cast<AttributedStmt>(ExprResult)) { 462 // FIXME: Update this if we ever have attributes that affect the 463 // semantics of an expression. 464 ExprResult = AS->getSubStmt(); 465 } else { 466 llvm_unreachable("unknown value statement"); 467 } 468 } 469 470 EnsureInsertPoint(); 471 472 const Expr *E = cast<Expr>(ExprResult); 473 QualType ExprTy = E->getType(); 474 if (hasAggregateEvaluationKind(ExprTy)) { 475 EmitAggExpr(E, AggSlot); 476 } else { 477 // We can't return an RValue here because there might be cleanups at 478 // the end of the StmtExpr. Because of that, we have to emit the result 479 // here into a temporary alloca. 480 RetAlloca = CreateMemTemp(ExprTy); 481 EmitAnyExprToMem(E, RetAlloca, Qualifiers(), 482 /*IsInit*/ false); 483 } 484 } else { 485 EmitStmt(CurStmt); 486 } 487 } 488 489 return RetAlloca; 490 } 491 492 void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) { 493 llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(BB->getTerminator()); 494 495 // If there is a cleanup stack, then we it isn't worth trying to 496 // simplify this block (we would need to remove it from the scope map 497 // and cleanup entry). 498 if (!EHStack.empty()) 499 return; 500 501 // Can only simplify direct branches. 502 if (!BI || !BI->isUnconditional()) 503 return; 504 505 // Can only simplify empty blocks. 506 if (BI->getIterator() != BB->begin()) 507 return; 508 509 BB->replaceAllUsesWith(BI->getSuccessor(0)); 510 BI->eraseFromParent(); 511 BB->eraseFromParent(); 512 } 513 514 void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) { 515 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 516 517 // Fall out of the current block (if necessary). 518 EmitBranch(BB); 519 520 if (IsFinished && BB->use_empty()) { 521 delete BB; 522 return; 523 } 524 525 // Place the block after the current block, if possible, or else at 526 // the end of the function. 527 if (CurBB && CurBB->getParent()) 528 CurFn->getBasicBlockList().insertAfter(CurBB->getIterator(), BB); 529 else 530 CurFn->getBasicBlockList().push_back(BB); 531 Builder.SetInsertPoint(BB); 532 } 533 534 void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) { 535 // Emit a branch from the current block to the target one if this 536 // was a real block. If this was just a fall-through block after a 537 // terminator, don't emit it. 538 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 539 540 if (!CurBB || CurBB->getTerminator()) { 541 // If there is no insert point or the previous block is already 542 // terminated, don't touch it. 543 } else { 544 // Otherwise, create a fall-through branch. 545 Builder.CreateBr(Target); 546 } 547 548 Builder.ClearInsertionPoint(); 549 } 550 551 void CodeGenFunction::EmitBlockAfterUses(llvm::BasicBlock *block) { 552 bool inserted = false; 553 for (llvm::User *u : block->users()) { 554 if (llvm::Instruction *insn = dyn_cast<llvm::Instruction>(u)) { 555 CurFn->getBasicBlockList().insertAfter(insn->getParent()->getIterator(), 556 block); 557 inserted = true; 558 break; 559 } 560 } 561 562 if (!inserted) 563 CurFn->getBasicBlockList().push_back(block); 564 565 Builder.SetInsertPoint(block); 566 } 567 568 CodeGenFunction::JumpDest 569 CodeGenFunction::getJumpDestForLabel(const LabelDecl *D) { 570 JumpDest &Dest = LabelMap[D]; 571 if (Dest.isValid()) return Dest; 572 573 // Create, but don't insert, the new block. 574 Dest = JumpDest(createBasicBlock(D->getName()), 575 EHScopeStack::stable_iterator::invalid(), 576 NextCleanupDestIndex++); 577 return Dest; 578 } 579 580 void CodeGenFunction::EmitLabel(const LabelDecl *D) { 581 // Add this label to the current lexical scope if we're within any 582 // normal cleanups. Jumps "in" to this label --- when permitted by 583 // the language --- may need to be routed around such cleanups. 584 if (EHStack.hasNormalCleanups() && CurLexicalScope) 585 CurLexicalScope->addLabel(D); 586 587 JumpDest &Dest = LabelMap[D]; 588 589 // If we didn't need a forward reference to this label, just go 590 // ahead and create a destination at the current scope. 591 if (!Dest.isValid()) { 592 Dest = getJumpDestInCurrentScope(D->getName()); 593 594 // Otherwise, we need to give this label a target depth and remove 595 // it from the branch-fixups list. 596 } else { 597 assert(!Dest.getScopeDepth().isValid() && "already emitted label!"); 598 Dest.setScopeDepth(EHStack.stable_begin()); 599 ResolveBranchFixups(Dest.getBlock()); 600 } 601 602 EmitBlock(Dest.getBlock()); 603 604 // Emit debug info for labels. 605 if (CGDebugInfo *DI = getDebugInfo()) { 606 if (CGM.getCodeGenOpts().hasReducedDebugInfo()) { 607 DI->setLocation(D->getLocation()); 608 DI->EmitLabel(D, Builder); 609 } 610 } 611 612 incrementProfileCounter(D->getStmt()); 613 } 614 615 /// Change the cleanup scope of the labels in this lexical scope to 616 /// match the scope of the enclosing context. 617 void CodeGenFunction::LexicalScope::rescopeLabels() { 618 assert(!Labels.empty()); 619 EHScopeStack::stable_iterator innermostScope 620 = CGF.EHStack.getInnermostNormalCleanup(); 621 622 // Change the scope depth of all the labels. 623 for (SmallVectorImpl<const LabelDecl*>::const_iterator 624 i = Labels.begin(), e = Labels.end(); i != e; ++i) { 625 assert(CGF.LabelMap.count(*i)); 626 JumpDest &dest = CGF.LabelMap.find(*i)->second; 627 assert(dest.getScopeDepth().isValid()); 628 assert(innermostScope.encloses(dest.getScopeDepth())); 629 dest.setScopeDepth(innermostScope); 630 } 631 632 // Reparent the labels if the new scope also has cleanups. 633 if (innermostScope != EHScopeStack::stable_end() && ParentScope) { 634 ParentScope->Labels.append(Labels.begin(), Labels.end()); 635 } 636 } 637 638 639 void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) { 640 EmitLabel(S.getDecl()); 641 EmitStmt(S.getSubStmt()); 642 } 643 644 void CodeGenFunction::EmitAttributedStmt(const AttributedStmt &S) { 645 bool nomerge = false; 646 for (const auto *A : S.getAttrs()) 647 if (A->getKind() == attr::NoMerge) { 648 nomerge = true; 649 break; 650 } 651 SaveAndRestore<bool> save_nomerge(InNoMergeAttributedStmt, nomerge); 652 EmitStmt(S.getSubStmt(), S.getAttrs()); 653 } 654 655 void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) { 656 // If this code is reachable then emit a stop point (if generating 657 // debug info). We have to do this ourselves because we are on the 658 // "simple" statement path. 659 if (HaveInsertPoint()) 660 EmitStopPoint(&S); 661 662 EmitBranchThroughCleanup(getJumpDestForLabel(S.getLabel())); 663 } 664 665 666 void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) { 667 if (const LabelDecl *Target = S.getConstantTarget()) { 668 EmitBranchThroughCleanup(getJumpDestForLabel(Target)); 669 return; 670 } 671 672 // Ensure that we have an i8* for our PHI node. 673 llvm::Value *V = Builder.CreateBitCast(EmitScalarExpr(S.getTarget()), 674 Int8PtrTy, "addr"); 675 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 676 677 // Get the basic block for the indirect goto. 678 llvm::BasicBlock *IndGotoBB = GetIndirectGotoBlock(); 679 680 // The first instruction in the block has to be the PHI for the switch dest, 681 // add an entry for this branch. 682 cast<llvm::PHINode>(IndGotoBB->begin())->addIncoming(V, CurBB); 683 684 EmitBranch(IndGotoBB); 685 } 686 687 void CodeGenFunction::EmitIfStmt(const IfStmt &S) { 688 // C99 6.8.4.1: The first substatement is executed if the expression compares 689 // unequal to 0. The condition must be a scalar type. 690 LexicalScope ConditionScope(*this, S.getCond()->getSourceRange()); 691 692 if (S.getInit()) 693 EmitStmt(S.getInit()); 694 695 if (S.getConditionVariable()) 696 EmitDecl(*S.getConditionVariable()); 697 698 // If the condition constant folds and can be elided, try to avoid emitting 699 // the condition and the dead arm of the if/else. 700 bool CondConstant; 701 if (ConstantFoldsToSimpleInteger(S.getCond(), CondConstant, 702 S.isConstexpr())) { 703 // Figure out which block (then or else) is executed. 704 const Stmt *Executed = S.getThen(); 705 const Stmt *Skipped = S.getElse(); 706 if (!CondConstant) // Condition false? 707 std::swap(Executed, Skipped); 708 709 // If the skipped block has no labels in it, just emit the executed block. 710 // This avoids emitting dead code and simplifies the CFG substantially. 711 if (S.isConstexpr() || !ContainsLabel(Skipped)) { 712 if (CondConstant) 713 incrementProfileCounter(&S); 714 if (Executed) { 715 RunCleanupsScope ExecutedScope(*this); 716 EmitStmt(Executed); 717 } 718 return; 719 } 720 } 721 722 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit 723 // the conditional branch. 724 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then"); 725 llvm::BasicBlock *ContBlock = createBasicBlock("if.end"); 726 llvm::BasicBlock *ElseBlock = ContBlock; 727 if (S.getElse()) 728 ElseBlock = createBasicBlock("if.else"); 729 730 // Prefer the PGO based weights over the likelihood attribute. 731 // When the build isn't optimized the metadata isn't used, so don't generate 732 // it. 733 Stmt::Likelihood LH = Stmt::LH_None; 734 uint64_t Count = getProfileCount(S.getThen()); 735 if (!Count && CGM.getCodeGenOpts().OptimizationLevel) 736 LH = Stmt::getLikelihood(S.getThen(), S.getElse()); 737 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock, Count, LH); 738 739 // Emit the 'then' code. 740 EmitBlock(ThenBlock); 741 incrementProfileCounter(&S); 742 { 743 RunCleanupsScope ThenScope(*this); 744 EmitStmt(S.getThen()); 745 } 746 EmitBranch(ContBlock); 747 748 // Emit the 'else' code if present. 749 if (const Stmt *Else = S.getElse()) { 750 { 751 // There is no need to emit line number for an unconditional branch. 752 auto NL = ApplyDebugLocation::CreateEmpty(*this); 753 EmitBlock(ElseBlock); 754 } 755 { 756 RunCleanupsScope ElseScope(*this); 757 EmitStmt(Else); 758 } 759 { 760 // There is no need to emit line number for an unconditional branch. 761 auto NL = ApplyDebugLocation::CreateEmpty(*this); 762 EmitBranch(ContBlock); 763 } 764 } 765 766 // Emit the continuation block for code after the if. 767 EmitBlock(ContBlock, true); 768 } 769 770 void CodeGenFunction::EmitWhileStmt(const WhileStmt &S, 771 ArrayRef<const Attr *> WhileAttrs) { 772 // Emit the header for the loop, which will also become 773 // the continue target. 774 JumpDest LoopHeader = getJumpDestInCurrentScope("while.cond"); 775 EmitBlock(LoopHeader.getBlock()); 776 777 // Create an exit block for when the condition fails, which will 778 // also become the break target. 779 JumpDest LoopExit = getJumpDestInCurrentScope("while.end"); 780 781 // Store the blocks to use for break and continue. 782 BreakContinueStack.push_back(BreakContinue(LoopExit, LoopHeader)); 783 784 // C++ [stmt.while]p2: 785 // When the condition of a while statement is a declaration, the 786 // scope of the variable that is declared extends from its point 787 // of declaration (3.3.2) to the end of the while statement. 788 // [...] 789 // The object created in a condition is destroyed and created 790 // with each iteration of the loop. 791 RunCleanupsScope ConditionScope(*this); 792 793 if (S.getConditionVariable()) 794 EmitDecl(*S.getConditionVariable()); 795 796 // Evaluate the conditional in the while header. C99 6.8.5.1: The 797 // evaluation of the controlling expression takes place before each 798 // execution of the loop body. 799 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond()); 800 801 // while(1) is common, avoid extra exit blocks. Be sure 802 // to correctly handle break/continue though. 803 bool EmitBoolCondBranch = true; 804 bool LoopMustProgress = false; 805 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal)) { 806 if (C->isOne()) { 807 EmitBoolCondBranch = false; 808 FnIsMustProgress = false; 809 } 810 } else if (LanguageRequiresProgress()) 811 LoopMustProgress = true; 812 813 const SourceRange &R = S.getSourceRange(); 814 LoopStack.push(LoopHeader.getBlock(), CGM.getContext(), CGM.getCodeGenOpts(), 815 WhileAttrs, SourceLocToDebugLoc(R.getBegin()), 816 SourceLocToDebugLoc(R.getEnd()), LoopMustProgress); 817 818 // As long as the condition is true, go to the loop body. 819 llvm::BasicBlock *LoopBody = createBasicBlock("while.body"); 820 if (EmitBoolCondBranch) { 821 llvm::BasicBlock *ExitBlock = LoopExit.getBlock(); 822 if (ConditionScope.requiresCleanups()) 823 ExitBlock = createBasicBlock("while.exit"); 824 llvm::MDNode *Weights = createProfileOrBranchWeightsForLoop( 825 S.getCond(), getProfileCount(S.getBody()), S.getBody()); 826 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock, Weights); 827 828 if (ExitBlock != LoopExit.getBlock()) { 829 EmitBlock(ExitBlock); 830 EmitBranchThroughCleanup(LoopExit); 831 } 832 } else if (const Attr *A = Stmt::getLikelihoodAttr(S.getBody())) { 833 CGM.getDiags().Report(A->getLocation(), 834 diag::warn_attribute_has_no_effect_on_infinite_loop) 835 << A << A->getRange(); 836 CGM.getDiags().Report( 837 S.getWhileLoc(), 838 diag::note_attribute_has_no_effect_on_infinite_loop_here) 839 << SourceRange(S.getWhileLoc(), S.getRParenLoc()); 840 } 841 842 // Emit the loop body. We have to emit this in a cleanup scope 843 // because it might be a singleton DeclStmt. 844 { 845 RunCleanupsScope BodyScope(*this); 846 EmitBlock(LoopBody); 847 incrementProfileCounter(&S); 848 EmitStmt(S.getBody()); 849 } 850 851 BreakContinueStack.pop_back(); 852 853 // Immediately force cleanup. 854 ConditionScope.ForceCleanup(); 855 856 EmitStopPoint(&S); 857 // Branch to the loop header again. 858 EmitBranch(LoopHeader.getBlock()); 859 860 LoopStack.pop(); 861 862 // Emit the exit block. 863 EmitBlock(LoopExit.getBlock(), true); 864 865 // The LoopHeader typically is just a branch if we skipped emitting 866 // a branch, try to erase it. 867 if (!EmitBoolCondBranch) 868 SimplifyForwardingBlocks(LoopHeader.getBlock()); 869 } 870 871 void CodeGenFunction::EmitDoStmt(const DoStmt &S, 872 ArrayRef<const Attr *> DoAttrs) { 873 JumpDest LoopExit = getJumpDestInCurrentScope("do.end"); 874 JumpDest LoopCond = getJumpDestInCurrentScope("do.cond"); 875 876 uint64_t ParentCount = getCurrentProfileCount(); 877 878 // Store the blocks to use for break and continue. 879 BreakContinueStack.push_back(BreakContinue(LoopExit, LoopCond)); 880 881 // Emit the body of the loop. 882 llvm::BasicBlock *LoopBody = createBasicBlock("do.body"); 883 884 EmitBlockWithFallThrough(LoopBody, &S); 885 { 886 RunCleanupsScope BodyScope(*this); 887 EmitStmt(S.getBody()); 888 } 889 890 EmitBlock(LoopCond.getBlock()); 891 892 // C99 6.8.5.2: "The evaluation of the controlling expression takes place 893 // after each execution of the loop body." 894 895 // Evaluate the conditional in the while header. 896 // C99 6.8.5p2/p4: The first substatement is executed if the expression 897 // compares unequal to 0. The condition must be a scalar type. 898 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond()); 899 900 BreakContinueStack.pop_back(); 901 902 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure 903 // to correctly handle break/continue though. 904 bool EmitBoolCondBranch = true; 905 bool LoopMustProgress = false; 906 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal)) { 907 if (C->isZero()) 908 EmitBoolCondBranch = false; 909 else if (C->isOne()) 910 FnIsMustProgress = false; 911 } else if (LanguageRequiresProgress()) 912 LoopMustProgress = true; 913 914 const SourceRange &R = S.getSourceRange(); 915 LoopStack.push(LoopBody, CGM.getContext(), CGM.getCodeGenOpts(), DoAttrs, 916 SourceLocToDebugLoc(R.getBegin()), 917 SourceLocToDebugLoc(R.getEnd()), LoopMustProgress); 918 919 // As long as the condition is true, iterate the loop. 920 if (EmitBoolCondBranch) { 921 uint64_t BackedgeCount = getProfileCount(S.getBody()) - ParentCount; 922 Builder.CreateCondBr( 923 BoolCondVal, LoopBody, LoopExit.getBlock(), 924 createProfileWeightsForLoop(S.getCond(), BackedgeCount)); 925 } 926 927 LoopStack.pop(); 928 929 // Emit the exit block. 930 EmitBlock(LoopExit.getBlock()); 931 932 // The DoCond block typically is just a branch if we skipped 933 // emitting a branch, try to erase it. 934 if (!EmitBoolCondBranch) 935 SimplifyForwardingBlocks(LoopCond.getBlock()); 936 } 937 938 void CodeGenFunction::EmitForStmt(const ForStmt &S, 939 ArrayRef<const Attr *> ForAttrs) { 940 JumpDest LoopExit = getJumpDestInCurrentScope("for.end"); 941 942 LexicalScope ForScope(*this, S.getSourceRange()); 943 944 // Evaluate the first part before the loop. 945 if (S.getInit()) 946 EmitStmt(S.getInit()); 947 948 // Start the loop with a block that tests the condition. 949 // If there's an increment, the continue scope will be overwritten 950 // later. 951 JumpDest CondDest = getJumpDestInCurrentScope("for.cond"); 952 llvm::BasicBlock *CondBlock = CondDest.getBlock(); 953 EmitBlock(CondBlock); 954 955 bool LoopMustProgress = false; 956 Expr::EvalResult Result; 957 if (LanguageRequiresProgress()) { 958 if (!S.getCond()) { 959 FnIsMustProgress = false; 960 } else if (!S.getCond()->EvaluateAsInt(Result, getContext())) { 961 LoopMustProgress = true; 962 } 963 } 964 965 const SourceRange &R = S.getSourceRange(); 966 LoopStack.push(CondBlock, CGM.getContext(), CGM.getCodeGenOpts(), ForAttrs, 967 SourceLocToDebugLoc(R.getBegin()), 968 SourceLocToDebugLoc(R.getEnd()), LoopMustProgress); 969 970 // Create a cleanup scope for the condition variable cleanups. 971 LexicalScope ConditionScope(*this, S.getSourceRange()); 972 973 // If the for loop doesn't have an increment we can just use the condition as 974 // the continue block. Otherwise, if there is no condition variable, we can 975 // form the continue block now. If there is a condition variable, we can't 976 // form the continue block until after we've emitted the condition, because 977 // the condition is in scope in the increment, but Sema's jump diagnostics 978 // ensure that there are no continues from the condition variable that jump 979 // to the loop increment. 980 JumpDest Continue; 981 if (!S.getInc()) 982 Continue = CondDest; 983 else if (!S.getConditionVariable()) 984 Continue = getJumpDestInCurrentScope("for.inc"); 985 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue)); 986 987 if (S.getCond()) { 988 // If the for statement has a condition scope, emit the local variable 989 // declaration. 990 if (S.getConditionVariable()) { 991 EmitDecl(*S.getConditionVariable()); 992 993 // We have entered the condition variable's scope, so we're now able to 994 // jump to the continue block. 995 Continue = getJumpDestInCurrentScope("for.inc"); 996 BreakContinueStack.back().ContinueBlock = Continue; 997 } 998 999 llvm::BasicBlock *ExitBlock = LoopExit.getBlock(); 1000 // If there are any cleanups between here and the loop-exit scope, 1001 // create a block to stage a loop exit along. 1002 if (ForScope.requiresCleanups()) 1003 ExitBlock = createBasicBlock("for.cond.cleanup"); 1004 1005 // As long as the condition is true, iterate the loop. 1006 llvm::BasicBlock *ForBody = createBasicBlock("for.body"); 1007 1008 // C99 6.8.5p2/p4: The first substatement is executed if the expression 1009 // compares unequal to 0. The condition must be a scalar type. 1010 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond()); 1011 llvm::MDNode *Weights = createProfileOrBranchWeightsForLoop( 1012 S.getCond(), getProfileCount(S.getBody()), S.getBody()); 1013 1014 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal)) 1015 if (C->isOne()) 1016 FnIsMustProgress = false; 1017 1018 Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock, Weights); 1019 1020 if (ExitBlock != LoopExit.getBlock()) { 1021 EmitBlock(ExitBlock); 1022 EmitBranchThroughCleanup(LoopExit); 1023 } 1024 1025 EmitBlock(ForBody); 1026 } else { 1027 // Treat it as a non-zero constant. Don't even create a new block for the 1028 // body, just fall into it. 1029 } 1030 incrementProfileCounter(&S); 1031 1032 { 1033 // Create a separate cleanup scope for the body, in case it is not 1034 // a compound statement. 1035 RunCleanupsScope BodyScope(*this); 1036 EmitStmt(S.getBody()); 1037 } 1038 1039 // If there is an increment, emit it next. 1040 if (S.getInc()) { 1041 EmitBlock(Continue.getBlock()); 1042 EmitStmt(S.getInc()); 1043 } 1044 1045 BreakContinueStack.pop_back(); 1046 1047 ConditionScope.ForceCleanup(); 1048 1049 EmitStopPoint(&S); 1050 EmitBranch(CondBlock); 1051 1052 ForScope.ForceCleanup(); 1053 1054 LoopStack.pop(); 1055 1056 // Emit the fall-through block. 1057 EmitBlock(LoopExit.getBlock(), true); 1058 } 1059 1060 void 1061 CodeGenFunction::EmitCXXForRangeStmt(const CXXForRangeStmt &S, 1062 ArrayRef<const Attr *> ForAttrs) { 1063 JumpDest LoopExit = getJumpDestInCurrentScope("for.end"); 1064 1065 LexicalScope ForScope(*this, S.getSourceRange()); 1066 1067 // Evaluate the first pieces before the loop. 1068 if (S.getInit()) 1069 EmitStmt(S.getInit()); 1070 EmitStmt(S.getRangeStmt()); 1071 EmitStmt(S.getBeginStmt()); 1072 EmitStmt(S.getEndStmt()); 1073 1074 // Start the loop with a block that tests the condition. 1075 // If there's an increment, the continue scope will be overwritten 1076 // later. 1077 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond"); 1078 EmitBlock(CondBlock); 1079 1080 const SourceRange &R = S.getSourceRange(); 1081 LoopStack.push(CondBlock, CGM.getContext(), CGM.getCodeGenOpts(), ForAttrs, 1082 SourceLocToDebugLoc(R.getBegin()), 1083 SourceLocToDebugLoc(R.getEnd())); 1084 1085 // If there are any cleanups between here and the loop-exit scope, 1086 // create a block to stage a loop exit along. 1087 llvm::BasicBlock *ExitBlock = LoopExit.getBlock(); 1088 if (ForScope.requiresCleanups()) 1089 ExitBlock = createBasicBlock("for.cond.cleanup"); 1090 1091 // The loop body, consisting of the specified body and the loop variable. 1092 llvm::BasicBlock *ForBody = createBasicBlock("for.body"); 1093 1094 // The body is executed if the expression, contextually converted 1095 // to bool, is true. 1096 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond()); 1097 llvm::MDNode *Weights = createProfileOrBranchWeightsForLoop( 1098 S.getCond(), getProfileCount(S.getBody()), S.getBody()); 1099 Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock, Weights); 1100 1101 if (ExitBlock != LoopExit.getBlock()) { 1102 EmitBlock(ExitBlock); 1103 EmitBranchThroughCleanup(LoopExit); 1104 } 1105 1106 EmitBlock(ForBody); 1107 incrementProfileCounter(&S); 1108 1109 // Create a block for the increment. In case of a 'continue', we jump there. 1110 JumpDest Continue = getJumpDestInCurrentScope("for.inc"); 1111 1112 // Store the blocks to use for break and continue. 1113 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue)); 1114 1115 { 1116 // Create a separate cleanup scope for the loop variable and body. 1117 LexicalScope BodyScope(*this, S.getSourceRange()); 1118 EmitStmt(S.getLoopVarStmt()); 1119 EmitStmt(S.getBody()); 1120 } 1121 1122 EmitStopPoint(&S); 1123 // If there is an increment, emit it next. 1124 EmitBlock(Continue.getBlock()); 1125 EmitStmt(S.getInc()); 1126 1127 BreakContinueStack.pop_back(); 1128 1129 EmitBranch(CondBlock); 1130 1131 ForScope.ForceCleanup(); 1132 1133 LoopStack.pop(); 1134 1135 // Emit the fall-through block. 1136 EmitBlock(LoopExit.getBlock(), true); 1137 } 1138 1139 void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) { 1140 if (RV.isScalar()) { 1141 Builder.CreateStore(RV.getScalarVal(), ReturnValue); 1142 } else if (RV.isAggregate()) { 1143 LValue Dest = MakeAddrLValue(ReturnValue, Ty); 1144 LValue Src = MakeAddrLValue(RV.getAggregateAddress(), Ty); 1145 EmitAggregateCopy(Dest, Src, Ty, getOverlapForReturnValue()); 1146 } else { 1147 EmitStoreOfComplex(RV.getComplexVal(), MakeAddrLValue(ReturnValue, Ty), 1148 /*init*/ true); 1149 } 1150 EmitBranchThroughCleanup(ReturnBlock); 1151 } 1152 1153 namespace { 1154 // RAII struct used to save and restore a return statment's result expression. 1155 struct SaveRetExprRAII { 1156 SaveRetExprRAII(const Expr *RetExpr, CodeGenFunction &CGF) 1157 : OldRetExpr(CGF.RetExpr), CGF(CGF) { 1158 CGF.RetExpr = RetExpr; 1159 } 1160 ~SaveRetExprRAII() { CGF.RetExpr = OldRetExpr; } 1161 const Expr *OldRetExpr; 1162 CodeGenFunction &CGF; 1163 }; 1164 } // namespace 1165 1166 /// EmitReturnStmt - Note that due to GCC extensions, this can have an operand 1167 /// if the function returns void, or may be missing one if the function returns 1168 /// non-void. Fun stuff :). 1169 void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) { 1170 if (requiresReturnValueCheck()) { 1171 llvm::Constant *SLoc = EmitCheckSourceLocation(S.getBeginLoc()); 1172 auto *SLocPtr = 1173 new llvm::GlobalVariable(CGM.getModule(), SLoc->getType(), false, 1174 llvm::GlobalVariable::PrivateLinkage, SLoc); 1175 SLocPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1176 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(SLocPtr); 1177 assert(ReturnLocation.isValid() && "No valid return location"); 1178 Builder.CreateStore(Builder.CreateBitCast(SLocPtr, Int8PtrTy), 1179 ReturnLocation); 1180 } 1181 1182 // Returning from an outlined SEH helper is UB, and we already warn on it. 1183 if (IsOutlinedSEHHelper) { 1184 Builder.CreateUnreachable(); 1185 Builder.ClearInsertionPoint(); 1186 } 1187 1188 // Emit the result value, even if unused, to evaluate the side effects. 1189 const Expr *RV = S.getRetValue(); 1190 1191 // Record the result expression of the return statement. The recorded 1192 // expression is used to determine whether a block capture's lifetime should 1193 // end at the end of the full expression as opposed to the end of the scope 1194 // enclosing the block expression. 1195 // 1196 // This permits a small, easily-implemented exception to our over-conservative 1197 // rules about not jumping to statements following block literals with 1198 // non-trivial cleanups. 1199 SaveRetExprRAII SaveRetExpr(RV, *this); 1200 1201 RunCleanupsScope cleanupScope(*this); 1202 if (const auto *EWC = dyn_cast_or_null<ExprWithCleanups>(RV)) 1203 RV = EWC->getSubExpr(); 1204 // FIXME: Clean this up by using an LValue for ReturnTemp, 1205 // EmitStoreThroughLValue, and EmitAnyExpr. 1206 // Check if the NRVO candidate was not globalized in OpenMP mode. 1207 if (getLangOpts().ElideConstructors && S.getNRVOCandidate() && 1208 S.getNRVOCandidate()->isNRVOVariable() && 1209 (!getLangOpts().OpenMP || 1210 !CGM.getOpenMPRuntime() 1211 .getAddressOfLocalVariable(*this, S.getNRVOCandidate()) 1212 .isValid())) { 1213 // Apply the named return value optimization for this return statement, 1214 // which means doing nothing: the appropriate result has already been 1215 // constructed into the NRVO variable. 1216 1217 // If there is an NRVO flag for this variable, set it to 1 into indicate 1218 // that the cleanup code should not destroy the variable. 1219 if (llvm::Value *NRVOFlag = NRVOFlags[S.getNRVOCandidate()]) 1220 Builder.CreateFlagStore(Builder.getTrue(), NRVOFlag); 1221 } else if (!ReturnValue.isValid() || (RV && RV->getType()->isVoidType())) { 1222 // Make sure not to return anything, but evaluate the expression 1223 // for side effects. 1224 if (RV) 1225 EmitAnyExpr(RV); 1226 } else if (!RV) { 1227 // Do nothing (return value is left uninitialized) 1228 } else if (FnRetTy->isReferenceType()) { 1229 // If this function returns a reference, take the address of the expression 1230 // rather than the value. 1231 RValue Result = EmitReferenceBindingToExpr(RV); 1232 Builder.CreateStore(Result.getScalarVal(), ReturnValue); 1233 } else { 1234 switch (getEvaluationKind(RV->getType())) { 1235 case TEK_Scalar: 1236 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue); 1237 break; 1238 case TEK_Complex: 1239 EmitComplexExprIntoLValue(RV, MakeAddrLValue(ReturnValue, RV->getType()), 1240 /*isInit*/ true); 1241 break; 1242 case TEK_Aggregate: 1243 EmitAggExpr(RV, AggValueSlot::forAddr( 1244 ReturnValue, Qualifiers(), 1245 AggValueSlot::IsDestructed, 1246 AggValueSlot::DoesNotNeedGCBarriers, 1247 AggValueSlot::IsNotAliased, 1248 getOverlapForReturnValue())); 1249 break; 1250 } 1251 } 1252 1253 ++NumReturnExprs; 1254 if (!RV || RV->isEvaluatable(getContext())) 1255 ++NumSimpleReturnExprs; 1256 1257 cleanupScope.ForceCleanup(); 1258 EmitBranchThroughCleanup(ReturnBlock); 1259 } 1260 1261 void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) { 1262 // As long as debug info is modeled with instructions, we have to ensure we 1263 // have a place to insert here and write the stop point here. 1264 if (HaveInsertPoint()) 1265 EmitStopPoint(&S); 1266 1267 for (const auto *I : S.decls()) 1268 EmitDecl(*I); 1269 } 1270 1271 void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) { 1272 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!"); 1273 1274 // If this code is reachable then emit a stop point (if generating 1275 // debug info). We have to do this ourselves because we are on the 1276 // "simple" statement path. 1277 if (HaveInsertPoint()) 1278 EmitStopPoint(&S); 1279 1280 EmitBranchThroughCleanup(BreakContinueStack.back().BreakBlock); 1281 } 1282 1283 void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) { 1284 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!"); 1285 1286 // If this code is reachable then emit a stop point (if generating 1287 // debug info). We have to do this ourselves because we are on the 1288 // "simple" statement path. 1289 if (HaveInsertPoint()) 1290 EmitStopPoint(&S); 1291 1292 EmitBranchThroughCleanup(BreakContinueStack.back().ContinueBlock); 1293 } 1294 1295 /// EmitCaseStmtRange - If case statement range is not too big then 1296 /// add multiple cases to switch instruction, one for each value within 1297 /// the range. If range is too big then emit "if" condition check. 1298 void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S, 1299 ArrayRef<const Attr *> Attrs) { 1300 assert(S.getRHS() && "Expected RHS value in CaseStmt"); 1301 1302 llvm::APSInt LHS = S.getLHS()->EvaluateKnownConstInt(getContext()); 1303 llvm::APSInt RHS = S.getRHS()->EvaluateKnownConstInt(getContext()); 1304 1305 // Emit the code for this case. We do this first to make sure it is 1306 // properly chained from our predecessor before generating the 1307 // switch machinery to enter this block. 1308 llvm::BasicBlock *CaseDest = createBasicBlock("sw.bb"); 1309 EmitBlockWithFallThrough(CaseDest, &S); 1310 EmitStmt(S.getSubStmt()); 1311 1312 // If range is empty, do nothing. 1313 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS)) 1314 return; 1315 1316 Stmt::Likelihood LH = Stmt::getLikelihood(Attrs); 1317 llvm::APInt Range = RHS - LHS; 1318 // FIXME: parameters such as this should not be hardcoded. 1319 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) { 1320 // Range is small enough to add multiple switch instruction cases. 1321 uint64_t Total = getProfileCount(&S); 1322 unsigned NCases = Range.getZExtValue() + 1; 1323 // We only have one region counter for the entire set of cases here, so we 1324 // need to divide the weights evenly between the generated cases, ensuring 1325 // that the total weight is preserved. E.g., a weight of 5 over three cases 1326 // will be distributed as weights of 2, 2, and 1. 1327 uint64_t Weight = Total / NCases, Rem = Total % NCases; 1328 for (unsigned I = 0; I != NCases; ++I) { 1329 if (SwitchWeights) 1330 SwitchWeights->push_back(Weight + (Rem ? 1 : 0)); 1331 else if (SwitchLikelihood) 1332 SwitchLikelihood->push_back(LH); 1333 1334 if (Rem) 1335 Rem--; 1336 SwitchInsn->addCase(Builder.getInt(LHS), CaseDest); 1337 ++LHS; 1338 } 1339 return; 1340 } 1341 1342 // The range is too big. Emit "if" condition into a new block, 1343 // making sure to save and restore the current insertion point. 1344 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock(); 1345 1346 // Push this test onto the chain of range checks (which terminates 1347 // in the default basic block). The switch's default will be changed 1348 // to the top of this chain after switch emission is complete. 1349 llvm::BasicBlock *FalseDest = CaseRangeBlock; 1350 CaseRangeBlock = createBasicBlock("sw.caserange"); 1351 1352 CurFn->getBasicBlockList().push_back(CaseRangeBlock); 1353 Builder.SetInsertPoint(CaseRangeBlock); 1354 1355 // Emit range check. 1356 llvm::Value *Diff = 1357 Builder.CreateSub(SwitchInsn->getCondition(), Builder.getInt(LHS)); 1358 llvm::Value *Cond = 1359 Builder.CreateICmpULE(Diff, Builder.getInt(Range), "inbounds"); 1360 1361 llvm::MDNode *Weights = nullptr; 1362 if (SwitchWeights) { 1363 uint64_t ThisCount = getProfileCount(&S); 1364 uint64_t DefaultCount = (*SwitchWeights)[0]; 1365 Weights = createProfileWeights(ThisCount, DefaultCount); 1366 1367 // Since we're chaining the switch default through each large case range, we 1368 // need to update the weight for the default, ie, the first case, to include 1369 // this case. 1370 (*SwitchWeights)[0] += ThisCount; 1371 } else if (SwitchLikelihood) 1372 Weights = createBranchWeights(LH); 1373 1374 Builder.CreateCondBr(Cond, CaseDest, FalseDest, Weights); 1375 1376 // Restore the appropriate insertion point. 1377 if (RestoreBB) 1378 Builder.SetInsertPoint(RestoreBB); 1379 else 1380 Builder.ClearInsertionPoint(); 1381 } 1382 1383 void CodeGenFunction::EmitCaseStmt(const CaseStmt &S, 1384 ArrayRef<const Attr *> Attrs) { 1385 // If there is no enclosing switch instance that we're aware of, then this 1386 // case statement and its block can be elided. This situation only happens 1387 // when we've constant-folded the switch, are emitting the constant case, 1388 // and part of the constant case includes another case statement. For 1389 // instance: switch (4) { case 4: do { case 5: } while (1); } 1390 if (!SwitchInsn) { 1391 EmitStmt(S.getSubStmt()); 1392 return; 1393 } 1394 1395 // Handle case ranges. 1396 if (S.getRHS()) { 1397 EmitCaseStmtRange(S, Attrs); 1398 return; 1399 } 1400 1401 llvm::ConstantInt *CaseVal = 1402 Builder.getInt(S.getLHS()->EvaluateKnownConstInt(getContext())); 1403 if (SwitchLikelihood) 1404 SwitchLikelihood->push_back(Stmt::getLikelihood(Attrs)); 1405 1406 // If the body of the case is just a 'break', try to not emit an empty block. 1407 // If we're profiling or we're not optimizing, leave the block in for better 1408 // debug and coverage analysis. 1409 if (!CGM.getCodeGenOpts().hasProfileClangInstr() && 1410 CGM.getCodeGenOpts().OptimizationLevel > 0 && 1411 isa<BreakStmt>(S.getSubStmt())) { 1412 JumpDest Block = BreakContinueStack.back().BreakBlock; 1413 1414 // Only do this optimization if there are no cleanups that need emitting. 1415 if (isObviouslyBranchWithoutCleanups(Block)) { 1416 if (SwitchWeights) 1417 SwitchWeights->push_back(getProfileCount(&S)); 1418 SwitchInsn->addCase(CaseVal, Block.getBlock()); 1419 1420 // If there was a fallthrough into this case, make sure to redirect it to 1421 // the end of the switch as well. 1422 if (Builder.GetInsertBlock()) { 1423 Builder.CreateBr(Block.getBlock()); 1424 Builder.ClearInsertionPoint(); 1425 } 1426 return; 1427 } 1428 } 1429 1430 llvm::BasicBlock *CaseDest = createBasicBlock("sw.bb"); 1431 EmitBlockWithFallThrough(CaseDest, &S); 1432 if (SwitchWeights) 1433 SwitchWeights->push_back(getProfileCount(&S)); 1434 SwitchInsn->addCase(CaseVal, CaseDest); 1435 1436 // Recursively emitting the statement is acceptable, but is not wonderful for 1437 // code where we have many case statements nested together, i.e.: 1438 // case 1: 1439 // case 2: 1440 // case 3: etc. 1441 // Handling this recursively will create a new block for each case statement 1442 // that falls through to the next case which is IR intensive. It also causes 1443 // deep recursion which can run into stack depth limitations. Handle 1444 // sequential non-range case statements specially. 1445 // 1446 // TODO When the next case has a likelihood attribute the code returns to the 1447 // recursive algorithm. Maybe improve this case if it becomes common practice 1448 // to use a lot of attributes. 1449 const CaseStmt *CurCase = &S; 1450 const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt()); 1451 1452 // Otherwise, iteratively add consecutive cases to this switch stmt. 1453 while (NextCase && NextCase->getRHS() == nullptr) { 1454 CurCase = NextCase; 1455 llvm::ConstantInt *CaseVal = 1456 Builder.getInt(CurCase->getLHS()->EvaluateKnownConstInt(getContext())); 1457 1458 if (SwitchWeights) 1459 SwitchWeights->push_back(getProfileCount(NextCase)); 1460 if (CGM.getCodeGenOpts().hasProfileClangInstr()) { 1461 CaseDest = createBasicBlock("sw.bb"); 1462 EmitBlockWithFallThrough(CaseDest, CurCase); 1463 } 1464 // Since this loop is only executed when the CaseStmt has no attributes 1465 // use a hard-coded value. 1466 if (SwitchLikelihood) 1467 SwitchLikelihood->push_back(Stmt::LH_None); 1468 1469 SwitchInsn->addCase(CaseVal, CaseDest); 1470 NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt()); 1471 } 1472 1473 // Normal default recursion for non-cases. 1474 EmitStmt(CurCase->getSubStmt()); 1475 } 1476 1477 void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S, 1478 ArrayRef<const Attr *> Attrs) { 1479 // If there is no enclosing switch instance that we're aware of, then this 1480 // default statement can be elided. This situation only happens when we've 1481 // constant-folded the switch. 1482 if (!SwitchInsn) { 1483 EmitStmt(S.getSubStmt()); 1484 return; 1485 } 1486 1487 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest(); 1488 assert(DefaultBlock->empty() && 1489 "EmitDefaultStmt: Default block already defined?"); 1490 1491 if (SwitchLikelihood) 1492 SwitchLikelihood->front() = Stmt::getLikelihood(Attrs); 1493 1494 EmitBlockWithFallThrough(DefaultBlock, &S); 1495 1496 EmitStmt(S.getSubStmt()); 1497 } 1498 1499 /// CollectStatementsForCase - Given the body of a 'switch' statement and a 1500 /// constant value that is being switched on, see if we can dead code eliminate 1501 /// the body of the switch to a simple series of statements to emit. Basically, 1502 /// on a switch (5) we want to find these statements: 1503 /// case 5: 1504 /// printf(...); <-- 1505 /// ++i; <-- 1506 /// break; 1507 /// 1508 /// and add them to the ResultStmts vector. If it is unsafe to do this 1509 /// transformation (for example, one of the elided statements contains a label 1510 /// that might be jumped to), return CSFC_Failure. If we handled it and 'S' 1511 /// should include statements after it (e.g. the printf() line is a substmt of 1512 /// the case) then return CSFC_FallThrough. If we handled it and found a break 1513 /// statement, then return CSFC_Success. 1514 /// 1515 /// If Case is non-null, then we are looking for the specified case, checking 1516 /// that nothing we jump over contains labels. If Case is null, then we found 1517 /// the case and are looking for the break. 1518 /// 1519 /// If the recursive walk actually finds our Case, then we set FoundCase to 1520 /// true. 1521 /// 1522 enum CSFC_Result { CSFC_Failure, CSFC_FallThrough, CSFC_Success }; 1523 static CSFC_Result CollectStatementsForCase(const Stmt *S, 1524 const SwitchCase *Case, 1525 bool &FoundCase, 1526 SmallVectorImpl<const Stmt*> &ResultStmts) { 1527 // If this is a null statement, just succeed. 1528 if (!S) 1529 return Case ? CSFC_Success : CSFC_FallThrough; 1530 1531 // If this is the switchcase (case 4: or default) that we're looking for, then 1532 // we're in business. Just add the substatement. 1533 if (const SwitchCase *SC = dyn_cast<SwitchCase>(S)) { 1534 if (S == Case) { 1535 FoundCase = true; 1536 return CollectStatementsForCase(SC->getSubStmt(), nullptr, FoundCase, 1537 ResultStmts); 1538 } 1539 1540 // Otherwise, this is some other case or default statement, just ignore it. 1541 return CollectStatementsForCase(SC->getSubStmt(), Case, FoundCase, 1542 ResultStmts); 1543 } 1544 1545 // If we are in the live part of the code and we found our break statement, 1546 // return a success! 1547 if (!Case && isa<BreakStmt>(S)) 1548 return CSFC_Success; 1549 1550 // If this is a switch statement, then it might contain the SwitchCase, the 1551 // break, or neither. 1552 if (const CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) { 1553 // Handle this as two cases: we might be looking for the SwitchCase (if so 1554 // the skipped statements must be skippable) or we might already have it. 1555 CompoundStmt::const_body_iterator I = CS->body_begin(), E = CS->body_end(); 1556 bool StartedInLiveCode = FoundCase; 1557 unsigned StartSize = ResultStmts.size(); 1558 1559 // If we've not found the case yet, scan through looking for it. 1560 if (Case) { 1561 // Keep track of whether we see a skipped declaration. The code could be 1562 // using the declaration even if it is skipped, so we can't optimize out 1563 // the decl if the kept statements might refer to it. 1564 bool HadSkippedDecl = false; 1565 1566 // If we're looking for the case, just see if we can skip each of the 1567 // substatements. 1568 for (; Case && I != E; ++I) { 1569 HadSkippedDecl |= CodeGenFunction::mightAddDeclToScope(*I); 1570 1571 switch (CollectStatementsForCase(*I, Case, FoundCase, ResultStmts)) { 1572 case CSFC_Failure: return CSFC_Failure; 1573 case CSFC_Success: 1574 // A successful result means that either 1) that the statement doesn't 1575 // have the case and is skippable, or 2) does contain the case value 1576 // and also contains the break to exit the switch. In the later case, 1577 // we just verify the rest of the statements are elidable. 1578 if (FoundCase) { 1579 // If we found the case and skipped declarations, we can't do the 1580 // optimization. 1581 if (HadSkippedDecl) 1582 return CSFC_Failure; 1583 1584 for (++I; I != E; ++I) 1585 if (CodeGenFunction::ContainsLabel(*I, true)) 1586 return CSFC_Failure; 1587 return CSFC_Success; 1588 } 1589 break; 1590 case CSFC_FallThrough: 1591 // If we have a fallthrough condition, then we must have found the 1592 // case started to include statements. Consider the rest of the 1593 // statements in the compound statement as candidates for inclusion. 1594 assert(FoundCase && "Didn't find case but returned fallthrough?"); 1595 // We recursively found Case, so we're not looking for it anymore. 1596 Case = nullptr; 1597 1598 // If we found the case and skipped declarations, we can't do the 1599 // optimization. 1600 if (HadSkippedDecl) 1601 return CSFC_Failure; 1602 break; 1603 } 1604 } 1605 1606 if (!FoundCase) 1607 return CSFC_Success; 1608 1609 assert(!HadSkippedDecl && "fallthrough after skipping decl"); 1610 } 1611 1612 // If we have statements in our range, then we know that the statements are 1613 // live and need to be added to the set of statements we're tracking. 1614 bool AnyDecls = false; 1615 for (; I != E; ++I) { 1616 AnyDecls |= CodeGenFunction::mightAddDeclToScope(*I); 1617 1618 switch (CollectStatementsForCase(*I, nullptr, FoundCase, ResultStmts)) { 1619 case CSFC_Failure: return CSFC_Failure; 1620 case CSFC_FallThrough: 1621 // A fallthrough result means that the statement was simple and just 1622 // included in ResultStmt, keep adding them afterwards. 1623 break; 1624 case CSFC_Success: 1625 // A successful result means that we found the break statement and 1626 // stopped statement inclusion. We just ensure that any leftover stmts 1627 // are skippable and return success ourselves. 1628 for (++I; I != E; ++I) 1629 if (CodeGenFunction::ContainsLabel(*I, true)) 1630 return CSFC_Failure; 1631 return CSFC_Success; 1632 } 1633 } 1634 1635 // If we're about to fall out of a scope without hitting a 'break;', we 1636 // can't perform the optimization if there were any decls in that scope 1637 // (we'd lose their end-of-lifetime). 1638 if (AnyDecls) { 1639 // If the entire compound statement was live, there's one more thing we 1640 // can try before giving up: emit the whole thing as a single statement. 1641 // We can do that unless the statement contains a 'break;'. 1642 // FIXME: Such a break must be at the end of a construct within this one. 1643 // We could emit this by just ignoring the BreakStmts entirely. 1644 if (StartedInLiveCode && !CodeGenFunction::containsBreak(S)) { 1645 ResultStmts.resize(StartSize); 1646 ResultStmts.push_back(S); 1647 } else { 1648 return CSFC_Failure; 1649 } 1650 } 1651 1652 return CSFC_FallThrough; 1653 } 1654 1655 // Okay, this is some other statement that we don't handle explicitly, like a 1656 // for statement or increment etc. If we are skipping over this statement, 1657 // just verify it doesn't have labels, which would make it invalid to elide. 1658 if (Case) { 1659 if (CodeGenFunction::ContainsLabel(S, true)) 1660 return CSFC_Failure; 1661 return CSFC_Success; 1662 } 1663 1664 // Otherwise, we want to include this statement. Everything is cool with that 1665 // so long as it doesn't contain a break out of the switch we're in. 1666 if (CodeGenFunction::containsBreak(S)) return CSFC_Failure; 1667 1668 // Otherwise, everything is great. Include the statement and tell the caller 1669 // that we fall through and include the next statement as well. 1670 ResultStmts.push_back(S); 1671 return CSFC_FallThrough; 1672 } 1673 1674 /// FindCaseStatementsForValue - Find the case statement being jumped to and 1675 /// then invoke CollectStatementsForCase to find the list of statements to emit 1676 /// for a switch on constant. See the comment above CollectStatementsForCase 1677 /// for more details. 1678 static bool FindCaseStatementsForValue(const SwitchStmt &S, 1679 const llvm::APSInt &ConstantCondValue, 1680 SmallVectorImpl<const Stmt*> &ResultStmts, 1681 ASTContext &C, 1682 const SwitchCase *&ResultCase) { 1683 // First step, find the switch case that is being branched to. We can do this 1684 // efficiently by scanning the SwitchCase list. 1685 const SwitchCase *Case = S.getSwitchCaseList(); 1686 const DefaultStmt *DefaultCase = nullptr; 1687 1688 for (; Case; Case = Case->getNextSwitchCase()) { 1689 // It's either a default or case. Just remember the default statement in 1690 // case we're not jumping to any numbered cases. 1691 if (const DefaultStmt *DS = dyn_cast<DefaultStmt>(Case)) { 1692 DefaultCase = DS; 1693 continue; 1694 } 1695 1696 // Check to see if this case is the one we're looking for. 1697 const CaseStmt *CS = cast<CaseStmt>(Case); 1698 // Don't handle case ranges yet. 1699 if (CS->getRHS()) return false; 1700 1701 // If we found our case, remember it as 'case'. 1702 if (CS->getLHS()->EvaluateKnownConstInt(C) == ConstantCondValue) 1703 break; 1704 } 1705 1706 // If we didn't find a matching case, we use a default if it exists, or we 1707 // elide the whole switch body! 1708 if (!Case) { 1709 // It is safe to elide the body of the switch if it doesn't contain labels 1710 // etc. If it is safe, return successfully with an empty ResultStmts list. 1711 if (!DefaultCase) 1712 return !CodeGenFunction::ContainsLabel(&S); 1713 Case = DefaultCase; 1714 } 1715 1716 // Ok, we know which case is being jumped to, try to collect all the 1717 // statements that follow it. This can fail for a variety of reasons. Also, 1718 // check to see that the recursive walk actually found our case statement. 1719 // Insane cases like this can fail to find it in the recursive walk since we 1720 // don't handle every stmt kind: 1721 // switch (4) { 1722 // while (1) { 1723 // case 4: ... 1724 bool FoundCase = false; 1725 ResultCase = Case; 1726 return CollectStatementsForCase(S.getBody(), Case, FoundCase, 1727 ResultStmts) != CSFC_Failure && 1728 FoundCase; 1729 } 1730 1731 static Optional<SmallVector<uint64_t, 16>> 1732 getLikelihoodWeights(ArrayRef<Stmt::Likelihood> Likelihoods) { 1733 // Are there enough branches to weight them? 1734 if (Likelihoods.size() <= 1) 1735 return None; 1736 1737 uint64_t NumUnlikely = 0; 1738 uint64_t NumNone = 0; 1739 uint64_t NumLikely = 0; 1740 for (const auto LH : Likelihoods) { 1741 switch (LH) { 1742 case Stmt::LH_Unlikely: 1743 ++NumUnlikely; 1744 break; 1745 case Stmt::LH_None: 1746 ++NumNone; 1747 break; 1748 case Stmt::LH_Likely: 1749 ++NumLikely; 1750 break; 1751 } 1752 } 1753 1754 // Is there a likelihood attribute used? 1755 if (NumUnlikely == 0 && NumLikely == 0) 1756 return None; 1757 1758 // When multiple cases share the same code they can be combined during 1759 // optimization. In that case the weights of the branch will be the sum of 1760 // the individual weights. Make sure the combined sum of all neutral cases 1761 // doesn't exceed the value of a single likely attribute. 1762 // The additions both avoid divisions by 0 and make sure the weights of None 1763 // don't exceed the weight of Likely. 1764 const uint64_t Likely = INT32_MAX / (NumLikely + 2); 1765 const uint64_t None = Likely / (NumNone + 1); 1766 const uint64_t Unlikely = 0; 1767 1768 SmallVector<uint64_t, 16> Result; 1769 Result.reserve(Likelihoods.size()); 1770 for (const auto LH : Likelihoods) { 1771 switch (LH) { 1772 case Stmt::LH_Unlikely: 1773 Result.push_back(Unlikely); 1774 break; 1775 case Stmt::LH_None: 1776 Result.push_back(None); 1777 break; 1778 case Stmt::LH_Likely: 1779 Result.push_back(Likely); 1780 break; 1781 } 1782 } 1783 1784 return Result; 1785 } 1786 1787 void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) { 1788 // Handle nested switch statements. 1789 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn; 1790 SmallVector<uint64_t, 16> *SavedSwitchWeights = SwitchWeights; 1791 SmallVector<Stmt::Likelihood, 16> *SavedSwitchLikelihood = SwitchLikelihood; 1792 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock; 1793 1794 // See if we can constant fold the condition of the switch and therefore only 1795 // emit the live case statement (if any) of the switch. 1796 llvm::APSInt ConstantCondValue; 1797 if (ConstantFoldsToSimpleInteger(S.getCond(), ConstantCondValue)) { 1798 SmallVector<const Stmt*, 4> CaseStmts; 1799 const SwitchCase *Case = nullptr; 1800 if (FindCaseStatementsForValue(S, ConstantCondValue, CaseStmts, 1801 getContext(), Case)) { 1802 if (Case) 1803 incrementProfileCounter(Case); 1804 RunCleanupsScope ExecutedScope(*this); 1805 1806 if (S.getInit()) 1807 EmitStmt(S.getInit()); 1808 1809 // Emit the condition variable if needed inside the entire cleanup scope 1810 // used by this special case for constant folded switches. 1811 if (S.getConditionVariable()) 1812 EmitDecl(*S.getConditionVariable()); 1813 1814 // At this point, we are no longer "within" a switch instance, so 1815 // we can temporarily enforce this to ensure that any embedded case 1816 // statements are not emitted. 1817 SwitchInsn = nullptr; 1818 1819 // Okay, we can dead code eliminate everything except this case. Emit the 1820 // specified series of statements and we're good. 1821 for (unsigned i = 0, e = CaseStmts.size(); i != e; ++i) 1822 EmitStmt(CaseStmts[i]); 1823 incrementProfileCounter(&S); 1824 1825 // Now we want to restore the saved switch instance so that nested 1826 // switches continue to function properly 1827 SwitchInsn = SavedSwitchInsn; 1828 1829 return; 1830 } 1831 } 1832 1833 JumpDest SwitchExit = getJumpDestInCurrentScope("sw.epilog"); 1834 1835 RunCleanupsScope ConditionScope(*this); 1836 1837 if (S.getInit()) 1838 EmitStmt(S.getInit()); 1839 1840 if (S.getConditionVariable()) 1841 EmitDecl(*S.getConditionVariable()); 1842 llvm::Value *CondV = EmitScalarExpr(S.getCond()); 1843 1844 // Create basic block to hold stuff that comes after switch 1845 // statement. We also need to create a default block now so that 1846 // explicit case ranges tests can have a place to jump to on 1847 // failure. 1848 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default"); 1849 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock); 1850 if (PGO.haveRegionCounts()) { 1851 // Walk the SwitchCase list to find how many there are. 1852 uint64_t DefaultCount = 0; 1853 unsigned NumCases = 0; 1854 for (const SwitchCase *Case = S.getSwitchCaseList(); 1855 Case; 1856 Case = Case->getNextSwitchCase()) { 1857 if (isa<DefaultStmt>(Case)) 1858 DefaultCount = getProfileCount(Case); 1859 NumCases += 1; 1860 } 1861 SwitchWeights = new SmallVector<uint64_t, 16>(); 1862 SwitchWeights->reserve(NumCases); 1863 // The default needs to be first. We store the edge count, so we already 1864 // know the right weight. 1865 SwitchWeights->push_back(DefaultCount); 1866 } else if (CGM.getCodeGenOpts().OptimizationLevel) { 1867 SwitchLikelihood = new SmallVector<Stmt::Likelihood, 16>(); 1868 // Initialize the default case. 1869 SwitchLikelihood->push_back(Stmt::LH_None); 1870 } 1871 1872 CaseRangeBlock = DefaultBlock; 1873 1874 // Clear the insertion point to indicate we are in unreachable code. 1875 Builder.ClearInsertionPoint(); 1876 1877 // All break statements jump to NextBlock. If BreakContinueStack is non-empty 1878 // then reuse last ContinueBlock. 1879 JumpDest OuterContinue; 1880 if (!BreakContinueStack.empty()) 1881 OuterContinue = BreakContinueStack.back().ContinueBlock; 1882 1883 BreakContinueStack.push_back(BreakContinue(SwitchExit, OuterContinue)); 1884 1885 // Emit switch body. 1886 EmitStmt(S.getBody()); 1887 1888 BreakContinueStack.pop_back(); 1889 1890 // Update the default block in case explicit case range tests have 1891 // been chained on top. 1892 SwitchInsn->setDefaultDest(CaseRangeBlock); 1893 1894 // If a default was never emitted: 1895 if (!DefaultBlock->getParent()) { 1896 // If we have cleanups, emit the default block so that there's a 1897 // place to jump through the cleanups from. 1898 if (ConditionScope.requiresCleanups()) { 1899 EmitBlock(DefaultBlock); 1900 1901 // Otherwise, just forward the default block to the switch end. 1902 } else { 1903 DefaultBlock->replaceAllUsesWith(SwitchExit.getBlock()); 1904 delete DefaultBlock; 1905 } 1906 } 1907 1908 ConditionScope.ForceCleanup(); 1909 1910 // Emit continuation. 1911 EmitBlock(SwitchExit.getBlock(), true); 1912 incrementProfileCounter(&S); 1913 1914 // If the switch has a condition wrapped by __builtin_unpredictable, 1915 // create metadata that specifies that the switch is unpredictable. 1916 // Don't bother if not optimizing because that metadata would not be used. 1917 auto *Call = dyn_cast<CallExpr>(S.getCond()); 1918 if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) { 1919 auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl()); 1920 if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) { 1921 llvm::MDBuilder MDHelper(getLLVMContext()); 1922 SwitchInsn->setMetadata(llvm::LLVMContext::MD_unpredictable, 1923 MDHelper.createUnpredictable()); 1924 } 1925 } 1926 1927 if (SwitchWeights) { 1928 assert(SwitchWeights->size() == 1 + SwitchInsn->getNumCases() && 1929 "switch weights do not match switch cases"); 1930 // If there's only one jump destination there's no sense weighting it. 1931 if (SwitchWeights->size() > 1) 1932 SwitchInsn->setMetadata(llvm::LLVMContext::MD_prof, 1933 createProfileWeights(*SwitchWeights)); 1934 delete SwitchWeights; 1935 } else if (SwitchLikelihood) { 1936 assert(SwitchLikelihood->size() == 1 + SwitchInsn->getNumCases() && 1937 "switch likelihoods do not match switch cases"); 1938 Optional<SmallVector<uint64_t, 16>> LHW = 1939 getLikelihoodWeights(*SwitchLikelihood); 1940 if (LHW) { 1941 llvm::MDBuilder MDHelper(CGM.getLLVMContext()); 1942 SwitchInsn->setMetadata(llvm::LLVMContext::MD_prof, 1943 createProfileWeights(*LHW)); 1944 } 1945 delete SwitchLikelihood; 1946 } 1947 SwitchInsn = SavedSwitchInsn; 1948 SwitchWeights = SavedSwitchWeights; 1949 SwitchLikelihood = SavedSwitchLikelihood; 1950 CaseRangeBlock = SavedCRBlock; 1951 } 1952 1953 static std::string 1954 SimplifyConstraint(const char *Constraint, const TargetInfo &Target, 1955 SmallVectorImpl<TargetInfo::ConstraintInfo> *OutCons=nullptr) { 1956 std::string Result; 1957 1958 while (*Constraint) { 1959 switch (*Constraint) { 1960 default: 1961 Result += Target.convertConstraint(Constraint); 1962 break; 1963 // Ignore these 1964 case '*': 1965 case '?': 1966 case '!': 1967 case '=': // Will see this and the following in mult-alt constraints. 1968 case '+': 1969 break; 1970 case '#': // Ignore the rest of the constraint alternative. 1971 while (Constraint[1] && Constraint[1] != ',') 1972 Constraint++; 1973 break; 1974 case '&': 1975 case '%': 1976 Result += *Constraint; 1977 while (Constraint[1] && Constraint[1] == *Constraint) 1978 Constraint++; 1979 break; 1980 case ',': 1981 Result += "|"; 1982 break; 1983 case 'g': 1984 Result += "imr"; 1985 break; 1986 case '[': { 1987 assert(OutCons && 1988 "Must pass output names to constraints with a symbolic name"); 1989 unsigned Index; 1990 bool result = Target.resolveSymbolicName(Constraint, *OutCons, Index); 1991 assert(result && "Could not resolve symbolic name"); (void)result; 1992 Result += llvm::utostr(Index); 1993 break; 1994 } 1995 } 1996 1997 Constraint++; 1998 } 1999 2000 return Result; 2001 } 2002 2003 /// AddVariableConstraints - Look at AsmExpr and if it is a variable declared 2004 /// as using a particular register add that as a constraint that will be used 2005 /// in this asm stmt. 2006 static std::string 2007 AddVariableConstraints(const std::string &Constraint, const Expr &AsmExpr, 2008 const TargetInfo &Target, CodeGenModule &CGM, 2009 const AsmStmt &Stmt, const bool EarlyClobber, 2010 std::string *GCCReg = nullptr) { 2011 const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(&AsmExpr); 2012 if (!AsmDeclRef) 2013 return Constraint; 2014 const ValueDecl &Value = *AsmDeclRef->getDecl(); 2015 const VarDecl *Variable = dyn_cast<VarDecl>(&Value); 2016 if (!Variable) 2017 return Constraint; 2018 if (Variable->getStorageClass() != SC_Register) 2019 return Constraint; 2020 AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>(); 2021 if (!Attr) 2022 return Constraint; 2023 StringRef Register = Attr->getLabel(); 2024 assert(Target.isValidGCCRegisterName(Register)); 2025 // We're using validateOutputConstraint here because we only care if 2026 // this is a register constraint. 2027 TargetInfo::ConstraintInfo Info(Constraint, ""); 2028 if (Target.validateOutputConstraint(Info) && 2029 !Info.allowsRegister()) { 2030 CGM.ErrorUnsupported(&Stmt, "__asm__"); 2031 return Constraint; 2032 } 2033 // Canonicalize the register here before returning it. 2034 Register = Target.getNormalizedGCCRegisterName(Register); 2035 if (GCCReg != nullptr) 2036 *GCCReg = Register.str(); 2037 return (EarlyClobber ? "&{" : "{") + Register.str() + "}"; 2038 } 2039 2040 llvm::Value* 2041 CodeGenFunction::EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info, 2042 LValue InputValue, QualType InputType, 2043 std::string &ConstraintStr, 2044 SourceLocation Loc) { 2045 llvm::Value *Arg; 2046 if (Info.allowsRegister() || !Info.allowsMemory()) { 2047 if (CodeGenFunction::hasScalarEvaluationKind(InputType)) { 2048 Arg = EmitLoadOfLValue(InputValue, Loc).getScalarVal(); 2049 } else { 2050 llvm::Type *Ty = ConvertType(InputType); 2051 uint64_t Size = CGM.getDataLayout().getTypeSizeInBits(Ty); 2052 if (Size <= 64 && llvm::isPowerOf2_64(Size)) { 2053 Ty = llvm::IntegerType::get(getLLVMContext(), Size); 2054 Ty = llvm::PointerType::getUnqual(Ty); 2055 2056 Arg = Builder.CreateLoad( 2057 Builder.CreateBitCast(InputValue.getAddress(*this), Ty)); 2058 } else { 2059 Arg = InputValue.getPointer(*this); 2060 ConstraintStr += '*'; 2061 } 2062 } 2063 } else { 2064 Arg = InputValue.getPointer(*this); 2065 ConstraintStr += '*'; 2066 } 2067 2068 return Arg; 2069 } 2070 2071 llvm::Value* CodeGenFunction::EmitAsmInput( 2072 const TargetInfo::ConstraintInfo &Info, 2073 const Expr *InputExpr, 2074 std::string &ConstraintStr) { 2075 // If this can't be a register or memory, i.e., has to be a constant 2076 // (immediate or symbolic), try to emit it as such. 2077 if (!Info.allowsRegister() && !Info.allowsMemory()) { 2078 if (Info.requiresImmediateConstant()) { 2079 Expr::EvalResult EVResult; 2080 InputExpr->EvaluateAsRValue(EVResult, getContext(), true); 2081 2082 llvm::APSInt IntResult; 2083 if (EVResult.Val.toIntegralConstant(IntResult, InputExpr->getType(), 2084 getContext())) 2085 return llvm::ConstantInt::get(getLLVMContext(), IntResult); 2086 } 2087 2088 Expr::EvalResult Result; 2089 if (InputExpr->EvaluateAsInt(Result, getContext())) 2090 return llvm::ConstantInt::get(getLLVMContext(), Result.Val.getInt()); 2091 } 2092 2093 if (Info.allowsRegister() || !Info.allowsMemory()) 2094 if (CodeGenFunction::hasScalarEvaluationKind(InputExpr->getType())) 2095 return EmitScalarExpr(InputExpr); 2096 if (InputExpr->getStmtClass() == Expr::CXXThisExprClass) 2097 return EmitScalarExpr(InputExpr); 2098 InputExpr = InputExpr->IgnoreParenNoopCasts(getContext()); 2099 LValue Dest = EmitLValue(InputExpr); 2100 return EmitAsmInputLValue(Info, Dest, InputExpr->getType(), ConstraintStr, 2101 InputExpr->getExprLoc()); 2102 } 2103 2104 /// getAsmSrcLocInfo - Return the !srcloc metadata node to attach to an inline 2105 /// asm call instruction. The !srcloc MDNode contains a list of constant 2106 /// integers which are the source locations of the start of each line in the 2107 /// asm. 2108 static llvm::MDNode *getAsmSrcLocInfo(const StringLiteral *Str, 2109 CodeGenFunction &CGF) { 2110 SmallVector<llvm::Metadata *, 8> Locs; 2111 // Add the location of the first line to the MDNode. 2112 Locs.push_back(llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 2113 CGF.Int32Ty, Str->getBeginLoc().getRawEncoding()))); 2114 StringRef StrVal = Str->getString(); 2115 if (!StrVal.empty()) { 2116 const SourceManager &SM = CGF.CGM.getContext().getSourceManager(); 2117 const LangOptions &LangOpts = CGF.CGM.getLangOpts(); 2118 unsigned StartToken = 0; 2119 unsigned ByteOffset = 0; 2120 2121 // Add the location of the start of each subsequent line of the asm to the 2122 // MDNode. 2123 for (unsigned i = 0, e = StrVal.size() - 1; i != e; ++i) { 2124 if (StrVal[i] != '\n') continue; 2125 SourceLocation LineLoc = Str->getLocationOfByte( 2126 i + 1, SM, LangOpts, CGF.getTarget(), &StartToken, &ByteOffset); 2127 Locs.push_back(llvm::ConstantAsMetadata::get( 2128 llvm::ConstantInt::get(CGF.Int32Ty, LineLoc.getRawEncoding()))); 2129 } 2130 } 2131 2132 return llvm::MDNode::get(CGF.getLLVMContext(), Locs); 2133 } 2134 2135 static void UpdateAsmCallInst(llvm::CallBase &Result, bool HasSideEffect, 2136 bool ReadOnly, bool ReadNone, bool NoMerge, 2137 const AsmStmt &S, 2138 const std::vector<llvm::Type *> &ResultRegTypes, 2139 CodeGenFunction &CGF, 2140 std::vector<llvm::Value *> &RegResults) { 2141 Result.addAttribute(llvm::AttributeList::FunctionIndex, 2142 llvm::Attribute::NoUnwind); 2143 if (NoMerge) 2144 Result.addAttribute(llvm::AttributeList::FunctionIndex, 2145 llvm::Attribute::NoMerge); 2146 // Attach readnone and readonly attributes. 2147 if (!HasSideEffect) { 2148 if (ReadNone) 2149 Result.addAttribute(llvm::AttributeList::FunctionIndex, 2150 llvm::Attribute::ReadNone); 2151 else if (ReadOnly) 2152 Result.addAttribute(llvm::AttributeList::FunctionIndex, 2153 llvm::Attribute::ReadOnly); 2154 } 2155 2156 // Slap the source location of the inline asm into a !srcloc metadata on the 2157 // call. 2158 if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(&S)) 2159 Result.setMetadata("srcloc", 2160 getAsmSrcLocInfo(gccAsmStmt->getAsmString(), CGF)); 2161 else { 2162 // At least put the line number on MS inline asm blobs. 2163 llvm::Constant *Loc = llvm::ConstantInt::get(CGF.Int32Ty, 2164 S.getAsmLoc().getRawEncoding()); 2165 Result.setMetadata("srcloc", 2166 llvm::MDNode::get(CGF.getLLVMContext(), 2167 llvm::ConstantAsMetadata::get(Loc))); 2168 } 2169 2170 if (CGF.getLangOpts().assumeFunctionsAreConvergent()) 2171 // Conservatively, mark all inline asm blocks in CUDA or OpenCL as 2172 // convergent (meaning, they may call an intrinsically convergent op, such 2173 // as bar.sync, and so can't have certain optimizations applied around 2174 // them). 2175 Result.addAttribute(llvm::AttributeList::FunctionIndex, 2176 llvm::Attribute::Convergent); 2177 // Extract all of the register value results from the asm. 2178 if (ResultRegTypes.size() == 1) { 2179 RegResults.push_back(&Result); 2180 } else { 2181 for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) { 2182 llvm::Value *Tmp = CGF.Builder.CreateExtractValue(&Result, i, "asmresult"); 2183 RegResults.push_back(Tmp); 2184 } 2185 } 2186 } 2187 2188 void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) { 2189 // Assemble the final asm string. 2190 std::string AsmString = S.generateAsmString(getContext()); 2191 2192 // Get all the output and input constraints together. 2193 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos; 2194 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos; 2195 2196 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) { 2197 StringRef Name; 2198 if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S)) 2199 Name = GAS->getOutputName(i); 2200 TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i), Name); 2201 bool IsValid = getTarget().validateOutputConstraint(Info); (void)IsValid; 2202 assert(IsValid && "Failed to parse output constraint"); 2203 OutputConstraintInfos.push_back(Info); 2204 } 2205 2206 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) { 2207 StringRef Name; 2208 if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S)) 2209 Name = GAS->getInputName(i); 2210 TargetInfo::ConstraintInfo Info(S.getInputConstraint(i), Name); 2211 bool IsValid = 2212 getTarget().validateInputConstraint(OutputConstraintInfos, Info); 2213 assert(IsValid && "Failed to parse input constraint"); (void)IsValid; 2214 InputConstraintInfos.push_back(Info); 2215 } 2216 2217 std::string Constraints; 2218 2219 std::vector<LValue> ResultRegDests; 2220 std::vector<QualType> ResultRegQualTys; 2221 std::vector<llvm::Type *> ResultRegTypes; 2222 std::vector<llvm::Type *> ResultTruncRegTypes; 2223 std::vector<llvm::Type *> ArgTypes; 2224 std::vector<llvm::Value*> Args; 2225 llvm::BitVector ResultTypeRequiresCast; 2226 2227 // Keep track of inout constraints. 2228 std::string InOutConstraints; 2229 std::vector<llvm::Value*> InOutArgs; 2230 std::vector<llvm::Type*> InOutArgTypes; 2231 2232 // Keep track of out constraints for tied input operand. 2233 std::vector<std::string> OutputConstraints; 2234 2235 // Keep track of defined physregs. 2236 llvm::SmallSet<std::string, 8> PhysRegOutputs; 2237 2238 // An inline asm can be marked readonly if it meets the following conditions: 2239 // - it doesn't have any sideeffects 2240 // - it doesn't clobber memory 2241 // - it doesn't return a value by-reference 2242 // It can be marked readnone if it doesn't have any input memory constraints 2243 // in addition to meeting the conditions listed above. 2244 bool ReadOnly = true, ReadNone = true; 2245 2246 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) { 2247 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i]; 2248 2249 // Simplify the output constraint. 2250 std::string OutputConstraint(S.getOutputConstraint(i)); 2251 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, 2252 getTarget(), &OutputConstraintInfos); 2253 2254 const Expr *OutExpr = S.getOutputExpr(i); 2255 OutExpr = OutExpr->IgnoreParenNoopCasts(getContext()); 2256 2257 std::string GCCReg; 2258 OutputConstraint = AddVariableConstraints(OutputConstraint, *OutExpr, 2259 getTarget(), CGM, S, 2260 Info.earlyClobber(), 2261 &GCCReg); 2262 // Give an error on multiple outputs to same physreg. 2263 if (!GCCReg.empty() && !PhysRegOutputs.insert(GCCReg).second) 2264 CGM.Error(S.getAsmLoc(), "multiple outputs to hard register: " + GCCReg); 2265 2266 OutputConstraints.push_back(OutputConstraint); 2267 LValue Dest = EmitLValue(OutExpr); 2268 if (!Constraints.empty()) 2269 Constraints += ','; 2270 2271 // If this is a register output, then make the inline asm return it 2272 // by-value. If this is a memory result, return the value by-reference. 2273 bool isScalarizableAggregate = 2274 hasAggregateEvaluationKind(OutExpr->getType()); 2275 if (!Info.allowsMemory() && (hasScalarEvaluationKind(OutExpr->getType()) || 2276 isScalarizableAggregate)) { 2277 Constraints += "=" + OutputConstraint; 2278 ResultRegQualTys.push_back(OutExpr->getType()); 2279 ResultRegDests.push_back(Dest); 2280 ResultTruncRegTypes.push_back(ConvertTypeForMem(OutExpr->getType())); 2281 if (Info.allowsRegister() && isScalarizableAggregate) { 2282 ResultTypeRequiresCast.push_back(true); 2283 unsigned Size = getContext().getTypeSize(OutExpr->getType()); 2284 llvm::Type *ConvTy = llvm::IntegerType::get(getLLVMContext(), Size); 2285 ResultRegTypes.push_back(ConvTy); 2286 } else { 2287 ResultTypeRequiresCast.push_back(false); 2288 ResultRegTypes.push_back(ResultTruncRegTypes.back()); 2289 } 2290 // If this output is tied to an input, and if the input is larger, then 2291 // we need to set the actual result type of the inline asm node to be the 2292 // same as the input type. 2293 if (Info.hasMatchingInput()) { 2294 unsigned InputNo; 2295 for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) { 2296 TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo]; 2297 if (Input.hasTiedOperand() && Input.getTiedOperand() == i) 2298 break; 2299 } 2300 assert(InputNo != S.getNumInputs() && "Didn't find matching input!"); 2301 2302 QualType InputTy = S.getInputExpr(InputNo)->getType(); 2303 QualType OutputType = OutExpr->getType(); 2304 2305 uint64_t InputSize = getContext().getTypeSize(InputTy); 2306 if (getContext().getTypeSize(OutputType) < InputSize) { 2307 // Form the asm to return the value as a larger integer or fp type. 2308 ResultRegTypes.back() = ConvertType(InputTy); 2309 } 2310 } 2311 if (llvm::Type* AdjTy = 2312 getTargetHooks().adjustInlineAsmType(*this, OutputConstraint, 2313 ResultRegTypes.back())) 2314 ResultRegTypes.back() = AdjTy; 2315 else { 2316 CGM.getDiags().Report(S.getAsmLoc(), 2317 diag::err_asm_invalid_type_in_input) 2318 << OutExpr->getType() << OutputConstraint; 2319 } 2320 2321 // Update largest vector width for any vector types. 2322 if (auto *VT = dyn_cast<llvm::VectorType>(ResultRegTypes.back())) 2323 LargestVectorWidth = 2324 std::max((uint64_t)LargestVectorWidth, 2325 VT->getPrimitiveSizeInBits().getKnownMinSize()); 2326 } else { 2327 llvm::Type *DestAddrTy = Dest.getAddress(*this).getType(); 2328 llvm::Value *DestPtr = Dest.getPointer(*this); 2329 // Matrix types in memory are represented by arrays, but accessed through 2330 // vector pointers, with the alignment specified on the access operation. 2331 // For inline assembly, update pointer arguments to use vector pointers. 2332 // Otherwise there will be a mis-match if the matrix is also an 2333 // input-argument which is represented as vector. 2334 if (isa<MatrixType>(OutExpr->getType().getCanonicalType())) { 2335 DestAddrTy = llvm::PointerType::get( 2336 ConvertType(OutExpr->getType()), 2337 cast<llvm::PointerType>(DestAddrTy)->getAddressSpace()); 2338 DestPtr = Builder.CreateBitCast(DestPtr, DestAddrTy); 2339 } 2340 ArgTypes.push_back(DestAddrTy); 2341 Args.push_back(DestPtr); 2342 Constraints += "=*"; 2343 Constraints += OutputConstraint; 2344 ReadOnly = ReadNone = false; 2345 } 2346 2347 if (Info.isReadWrite()) { 2348 InOutConstraints += ','; 2349 2350 const Expr *InputExpr = S.getOutputExpr(i); 2351 llvm::Value *Arg = EmitAsmInputLValue(Info, Dest, InputExpr->getType(), 2352 InOutConstraints, 2353 InputExpr->getExprLoc()); 2354 2355 if (llvm::Type* AdjTy = 2356 getTargetHooks().adjustInlineAsmType(*this, OutputConstraint, 2357 Arg->getType())) 2358 Arg = Builder.CreateBitCast(Arg, AdjTy); 2359 2360 // Update largest vector width for any vector types. 2361 if (auto *VT = dyn_cast<llvm::VectorType>(Arg->getType())) 2362 LargestVectorWidth = 2363 std::max((uint64_t)LargestVectorWidth, 2364 VT->getPrimitiveSizeInBits().getKnownMinSize()); 2365 // Only tie earlyclobber physregs. 2366 if (Info.allowsRegister() && (GCCReg.empty() || Info.earlyClobber())) 2367 InOutConstraints += llvm::utostr(i); 2368 else 2369 InOutConstraints += OutputConstraint; 2370 2371 InOutArgTypes.push_back(Arg->getType()); 2372 InOutArgs.push_back(Arg); 2373 } 2374 } 2375 2376 // If this is a Microsoft-style asm blob, store the return registers (EAX:EDX) 2377 // to the return value slot. Only do this when returning in registers. 2378 if (isa<MSAsmStmt>(&S)) { 2379 const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo(); 2380 if (RetAI.isDirect() || RetAI.isExtend()) { 2381 // Make a fake lvalue for the return value slot. 2382 LValue ReturnSlot = MakeAddrLValue(ReturnValue, FnRetTy); 2383 CGM.getTargetCodeGenInfo().addReturnRegisterOutputs( 2384 *this, ReturnSlot, Constraints, ResultRegTypes, ResultTruncRegTypes, 2385 ResultRegDests, AsmString, S.getNumOutputs()); 2386 SawAsmBlock = true; 2387 } 2388 } 2389 2390 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) { 2391 const Expr *InputExpr = S.getInputExpr(i); 2392 2393 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i]; 2394 2395 if (Info.allowsMemory()) 2396 ReadNone = false; 2397 2398 if (!Constraints.empty()) 2399 Constraints += ','; 2400 2401 // Simplify the input constraint. 2402 std::string InputConstraint(S.getInputConstraint(i)); 2403 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), getTarget(), 2404 &OutputConstraintInfos); 2405 2406 InputConstraint = AddVariableConstraints( 2407 InputConstraint, *InputExpr->IgnoreParenNoopCasts(getContext()), 2408 getTarget(), CGM, S, false /* No EarlyClobber */); 2409 2410 std::string ReplaceConstraint (InputConstraint); 2411 llvm::Value *Arg = EmitAsmInput(Info, InputExpr, Constraints); 2412 2413 // If this input argument is tied to a larger output result, extend the 2414 // input to be the same size as the output. The LLVM backend wants to see 2415 // the input and output of a matching constraint be the same size. Note 2416 // that GCC does not define what the top bits are here. We use zext because 2417 // that is usually cheaper, but LLVM IR should really get an anyext someday. 2418 if (Info.hasTiedOperand()) { 2419 unsigned Output = Info.getTiedOperand(); 2420 QualType OutputType = S.getOutputExpr(Output)->getType(); 2421 QualType InputTy = InputExpr->getType(); 2422 2423 if (getContext().getTypeSize(OutputType) > 2424 getContext().getTypeSize(InputTy)) { 2425 // Use ptrtoint as appropriate so that we can do our extension. 2426 if (isa<llvm::PointerType>(Arg->getType())) 2427 Arg = Builder.CreatePtrToInt(Arg, IntPtrTy); 2428 llvm::Type *OutputTy = ConvertType(OutputType); 2429 if (isa<llvm::IntegerType>(OutputTy)) 2430 Arg = Builder.CreateZExt(Arg, OutputTy); 2431 else if (isa<llvm::PointerType>(OutputTy)) 2432 Arg = Builder.CreateZExt(Arg, IntPtrTy); 2433 else { 2434 assert(OutputTy->isFloatingPointTy() && "Unexpected output type"); 2435 Arg = Builder.CreateFPExt(Arg, OutputTy); 2436 } 2437 } 2438 // Deal with the tied operands' constraint code in adjustInlineAsmType. 2439 ReplaceConstraint = OutputConstraints[Output]; 2440 } 2441 if (llvm::Type* AdjTy = 2442 getTargetHooks().adjustInlineAsmType(*this, ReplaceConstraint, 2443 Arg->getType())) 2444 Arg = Builder.CreateBitCast(Arg, AdjTy); 2445 else 2446 CGM.getDiags().Report(S.getAsmLoc(), diag::err_asm_invalid_type_in_input) 2447 << InputExpr->getType() << InputConstraint; 2448 2449 // Update largest vector width for any vector types. 2450 if (auto *VT = dyn_cast<llvm::VectorType>(Arg->getType())) 2451 LargestVectorWidth = 2452 std::max((uint64_t)LargestVectorWidth, 2453 VT->getPrimitiveSizeInBits().getKnownMinSize()); 2454 2455 ArgTypes.push_back(Arg->getType()); 2456 Args.push_back(Arg); 2457 Constraints += InputConstraint; 2458 } 2459 2460 // Labels 2461 SmallVector<llvm::BasicBlock *, 16> Transfer; 2462 llvm::BasicBlock *Fallthrough = nullptr; 2463 bool IsGCCAsmGoto = false; 2464 if (const auto *GS = dyn_cast<GCCAsmStmt>(&S)) { 2465 IsGCCAsmGoto = GS->isAsmGoto(); 2466 if (IsGCCAsmGoto) { 2467 for (const auto *E : GS->labels()) { 2468 JumpDest Dest = getJumpDestForLabel(E->getLabel()); 2469 Transfer.push_back(Dest.getBlock()); 2470 llvm::BlockAddress *BA = 2471 llvm::BlockAddress::get(CurFn, Dest.getBlock()); 2472 Args.push_back(BA); 2473 ArgTypes.push_back(BA->getType()); 2474 if (!Constraints.empty()) 2475 Constraints += ','; 2476 Constraints += 'X'; 2477 } 2478 Fallthrough = createBasicBlock("asm.fallthrough"); 2479 } 2480 } 2481 2482 // Append the "input" part of inout constraints last. 2483 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) { 2484 ArgTypes.push_back(InOutArgTypes[i]); 2485 Args.push_back(InOutArgs[i]); 2486 } 2487 Constraints += InOutConstraints; 2488 2489 // Clobbers 2490 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) { 2491 StringRef Clobber = S.getClobber(i); 2492 2493 if (Clobber == "memory") 2494 ReadOnly = ReadNone = false; 2495 else if (Clobber != "cc") { 2496 Clobber = getTarget().getNormalizedGCCRegisterName(Clobber); 2497 if (CGM.getCodeGenOpts().StackClashProtector && 2498 getTarget().isSPRegName(Clobber)) { 2499 CGM.getDiags().Report(S.getAsmLoc(), 2500 diag::warn_stack_clash_protection_inline_asm); 2501 } 2502 } 2503 2504 if (isa<MSAsmStmt>(&S)) { 2505 if (Clobber == "eax" || Clobber == "edx") { 2506 if (Constraints.find("=&A") != std::string::npos) 2507 continue; 2508 std::string::size_type position1 = 2509 Constraints.find("={" + Clobber.str() + "}"); 2510 if (position1 != std::string::npos) { 2511 Constraints.insert(position1 + 1, "&"); 2512 continue; 2513 } 2514 std::string::size_type position2 = Constraints.find("=A"); 2515 if (position2 != std::string::npos) { 2516 Constraints.insert(position2 + 1, "&"); 2517 continue; 2518 } 2519 } 2520 } 2521 if (!Constraints.empty()) 2522 Constraints += ','; 2523 2524 Constraints += "~{"; 2525 Constraints += Clobber; 2526 Constraints += '}'; 2527 } 2528 2529 // Add machine specific clobbers 2530 std::string MachineClobbers = getTarget().getClobbers(); 2531 if (!MachineClobbers.empty()) { 2532 if (!Constraints.empty()) 2533 Constraints += ','; 2534 Constraints += MachineClobbers; 2535 } 2536 2537 llvm::Type *ResultType; 2538 if (ResultRegTypes.empty()) 2539 ResultType = VoidTy; 2540 else if (ResultRegTypes.size() == 1) 2541 ResultType = ResultRegTypes[0]; 2542 else 2543 ResultType = llvm::StructType::get(getLLVMContext(), ResultRegTypes); 2544 2545 llvm::FunctionType *FTy = 2546 llvm::FunctionType::get(ResultType, ArgTypes, false); 2547 2548 bool HasSideEffect = S.isVolatile() || S.getNumOutputs() == 0; 2549 llvm::InlineAsm::AsmDialect AsmDialect = isa<MSAsmStmt>(&S) ? 2550 llvm::InlineAsm::AD_Intel : llvm::InlineAsm::AD_ATT; 2551 llvm::InlineAsm *IA = 2552 llvm::InlineAsm::get(FTy, AsmString, Constraints, HasSideEffect, 2553 /* IsAlignStack */ false, AsmDialect); 2554 std::vector<llvm::Value*> RegResults; 2555 if (IsGCCAsmGoto) { 2556 llvm::CallBrInst *Result = 2557 Builder.CreateCallBr(IA, Fallthrough, Transfer, Args); 2558 EmitBlock(Fallthrough); 2559 UpdateAsmCallInst(cast<llvm::CallBase>(*Result), HasSideEffect, ReadOnly, 2560 ReadNone, InNoMergeAttributedStmt, S, ResultRegTypes, 2561 *this, RegResults); 2562 } else { 2563 llvm::CallInst *Result = 2564 Builder.CreateCall(IA, Args, getBundlesForFunclet(IA)); 2565 UpdateAsmCallInst(cast<llvm::CallBase>(*Result), HasSideEffect, ReadOnly, 2566 ReadNone, InNoMergeAttributedStmt, S, ResultRegTypes, 2567 *this, RegResults); 2568 } 2569 2570 assert(RegResults.size() == ResultRegTypes.size()); 2571 assert(RegResults.size() == ResultTruncRegTypes.size()); 2572 assert(RegResults.size() == ResultRegDests.size()); 2573 // ResultRegDests can be also populated by addReturnRegisterOutputs() above, 2574 // in which case its size may grow. 2575 assert(ResultTypeRequiresCast.size() <= ResultRegDests.size()); 2576 for (unsigned i = 0, e = RegResults.size(); i != e; ++i) { 2577 llvm::Value *Tmp = RegResults[i]; 2578 2579 // If the result type of the LLVM IR asm doesn't match the result type of 2580 // the expression, do the conversion. 2581 if (ResultRegTypes[i] != ResultTruncRegTypes[i]) { 2582 llvm::Type *TruncTy = ResultTruncRegTypes[i]; 2583 2584 // Truncate the integer result to the right size, note that TruncTy can be 2585 // a pointer. 2586 if (TruncTy->isFloatingPointTy()) 2587 Tmp = Builder.CreateFPTrunc(Tmp, TruncTy); 2588 else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) { 2589 uint64_t ResSize = CGM.getDataLayout().getTypeSizeInBits(TruncTy); 2590 Tmp = Builder.CreateTrunc(Tmp, 2591 llvm::IntegerType::get(getLLVMContext(), (unsigned)ResSize)); 2592 Tmp = Builder.CreateIntToPtr(Tmp, TruncTy); 2593 } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) { 2594 uint64_t TmpSize =CGM.getDataLayout().getTypeSizeInBits(Tmp->getType()); 2595 Tmp = Builder.CreatePtrToInt(Tmp, 2596 llvm::IntegerType::get(getLLVMContext(), (unsigned)TmpSize)); 2597 Tmp = Builder.CreateTrunc(Tmp, TruncTy); 2598 } else if (TruncTy->isIntegerTy()) { 2599 Tmp = Builder.CreateZExtOrTrunc(Tmp, TruncTy); 2600 } else if (TruncTy->isVectorTy()) { 2601 Tmp = Builder.CreateBitCast(Tmp, TruncTy); 2602 } 2603 } 2604 2605 LValue Dest = ResultRegDests[i]; 2606 // ResultTypeRequiresCast elements correspond to the first 2607 // ResultTypeRequiresCast.size() elements of RegResults. 2608 if ((i < ResultTypeRequiresCast.size()) && ResultTypeRequiresCast[i]) { 2609 unsigned Size = getContext().getTypeSize(ResultRegQualTys[i]); 2610 Address A = Builder.CreateBitCast(Dest.getAddress(*this), 2611 ResultRegTypes[i]->getPointerTo()); 2612 QualType Ty = getContext().getIntTypeForBitwidth(Size, /*Signed*/ false); 2613 if (Ty.isNull()) { 2614 const Expr *OutExpr = S.getOutputExpr(i); 2615 CGM.Error( 2616 OutExpr->getExprLoc(), 2617 "impossible constraint in asm: can't store value into a register"); 2618 return; 2619 } 2620 Dest = MakeAddrLValue(A, Ty); 2621 } 2622 EmitStoreThroughLValue(RValue::get(Tmp), Dest); 2623 } 2624 } 2625 2626 LValue CodeGenFunction::InitCapturedStruct(const CapturedStmt &S) { 2627 const RecordDecl *RD = S.getCapturedRecordDecl(); 2628 QualType RecordTy = getContext().getRecordType(RD); 2629 2630 // Initialize the captured struct. 2631 LValue SlotLV = 2632 MakeAddrLValue(CreateMemTemp(RecordTy, "agg.captured"), RecordTy); 2633 2634 RecordDecl::field_iterator CurField = RD->field_begin(); 2635 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(), 2636 E = S.capture_init_end(); 2637 I != E; ++I, ++CurField) { 2638 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField); 2639 if (CurField->hasCapturedVLAType()) { 2640 EmitLambdaVLACapture(CurField->getCapturedVLAType(), LV); 2641 } else { 2642 EmitInitializerForField(*CurField, LV, *I); 2643 } 2644 } 2645 2646 return SlotLV; 2647 } 2648 2649 /// Generate an outlined function for the body of a CapturedStmt, store any 2650 /// captured variables into the captured struct, and call the outlined function. 2651 llvm::Function * 2652 CodeGenFunction::EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K) { 2653 LValue CapStruct = InitCapturedStruct(S); 2654 2655 // Emit the CapturedDecl 2656 CodeGenFunction CGF(CGM, true); 2657 CGCapturedStmtRAII CapInfoRAII(CGF, new CGCapturedStmtInfo(S, K)); 2658 llvm::Function *F = CGF.GenerateCapturedStmtFunction(S); 2659 delete CGF.CapturedStmtInfo; 2660 2661 // Emit call to the helper function. 2662 EmitCallOrInvoke(F, CapStruct.getPointer(*this)); 2663 2664 return F; 2665 } 2666 2667 Address CodeGenFunction::GenerateCapturedStmtArgument(const CapturedStmt &S) { 2668 LValue CapStruct = InitCapturedStruct(S); 2669 return CapStruct.getAddress(*this); 2670 } 2671 2672 /// Creates the outlined function for a CapturedStmt. 2673 llvm::Function * 2674 CodeGenFunction::GenerateCapturedStmtFunction(const CapturedStmt &S) { 2675 assert(CapturedStmtInfo && 2676 "CapturedStmtInfo should be set when generating the captured function"); 2677 const CapturedDecl *CD = S.getCapturedDecl(); 2678 const RecordDecl *RD = S.getCapturedRecordDecl(); 2679 SourceLocation Loc = S.getBeginLoc(); 2680 assert(CD->hasBody() && "missing CapturedDecl body"); 2681 2682 // Build the argument list. 2683 ASTContext &Ctx = CGM.getContext(); 2684 FunctionArgList Args; 2685 Args.append(CD->param_begin(), CD->param_end()); 2686 2687 // Create the function declaration. 2688 const CGFunctionInfo &FuncInfo = 2689 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Args); 2690 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo); 2691 2692 llvm::Function *F = 2693 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage, 2694 CapturedStmtInfo->getHelperName(), &CGM.getModule()); 2695 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo); 2696 if (CD->isNothrow()) 2697 F->addFnAttr(llvm::Attribute::NoUnwind); 2698 2699 // Generate the function. 2700 StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args, CD->getLocation(), 2701 CD->getBody()->getBeginLoc()); 2702 // Set the context parameter in CapturedStmtInfo. 2703 Address DeclPtr = GetAddrOfLocalVar(CD->getContextParam()); 2704 CapturedStmtInfo->setContextValue(Builder.CreateLoad(DeclPtr)); 2705 2706 // Initialize variable-length arrays. 2707 LValue Base = MakeNaturalAlignAddrLValue(CapturedStmtInfo->getContextValue(), 2708 Ctx.getTagDeclType(RD)); 2709 for (auto *FD : RD->fields()) { 2710 if (FD->hasCapturedVLAType()) { 2711 auto *ExprArg = 2712 EmitLoadOfLValue(EmitLValueForField(Base, FD), S.getBeginLoc()) 2713 .getScalarVal(); 2714 auto VAT = FD->getCapturedVLAType(); 2715 VLASizeMap[VAT->getSizeExpr()] = ExprArg; 2716 } 2717 } 2718 2719 // If 'this' is captured, load it into CXXThisValue. 2720 if (CapturedStmtInfo->isCXXThisExprCaptured()) { 2721 FieldDecl *FD = CapturedStmtInfo->getThisFieldDecl(); 2722 LValue ThisLValue = EmitLValueForField(Base, FD); 2723 CXXThisValue = EmitLoadOfLValue(ThisLValue, Loc).getScalarVal(); 2724 } 2725 2726 PGO.assignRegionCounters(GlobalDecl(CD), F); 2727 CapturedStmtInfo->EmitBody(*this, CD->getBody()); 2728 FinishFunction(CD->getBodyRBrace()); 2729 2730 return F; 2731 } 2732