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