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