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