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