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