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