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/SourceManager.h" 22 #include "clang/Basic/TargetInfo.h" 23 #include "llvm/ADT/StringExtras.h" 24 #include "llvm/IR/DataLayout.h" 25 #include "llvm/IR/InlineAsm.h" 26 #include "llvm/IR/Intrinsics.h" 27 #include "llvm/IR/MDBuilder.h" 28 29 using namespace clang; 30 using namespace CodeGen; 31 32 //===----------------------------------------------------------------------===// 33 // Statement Emission 34 //===----------------------------------------------------------------------===// 35 36 void CodeGenFunction::EmitStopPoint(const Stmt *S) { 37 if (CGDebugInfo *DI = getDebugInfo()) { 38 SourceLocation Loc; 39 Loc = S->getBeginLoc(); 40 DI->EmitLocation(Builder, Loc); 41 42 LastStopPoint = Loc; 43 } 44 } 45 46 void CodeGenFunction::EmitStmt(const Stmt *S, ArrayRef<const Attr *> Attrs) { 47 assert(S && "Null statement?"); 48 PGO.setCurrentStmt(S); 49 50 // These statements have their own debug info handling. 51 if (EmitSimpleStmt(S)) 52 return; 53 54 // Check if we are generating unreachable code. 55 if (!HaveInsertPoint()) { 56 // If so, and the statement doesn't contain a label, then we do not need to 57 // generate actual code. This is safe because (1) the current point is 58 // unreachable, so we don't need to execute the code, and (2) we've already 59 // handled the statements which update internal data structures (like the 60 // local variable map) which could be used by subsequent statements. 61 if (!ContainsLabel(S)) { 62 // Verify that any decl statements were handled as simple, they may be in 63 // scope of subsequent reachable statements. 64 assert(!isa<DeclStmt>(*S) && "Unexpected DeclStmt!"); 65 return; 66 } 67 68 // Otherwise, make a new block to hold the code. 69 EnsureInsertPoint(); 70 } 71 72 // Generate a stoppoint if we are emitting debug info. 73 EmitStopPoint(S); 74 75 // Ignore all OpenMP directives except for simd if OpenMP with Simd is 76 // enabled. 77 if (getLangOpts().OpenMP && getLangOpts().OpenMPSimd) { 78 if (const auto *D = dyn_cast<OMPExecutableDirective>(S)) { 79 EmitSimpleOMPExecutableDirective(*D); 80 return; 81 } 82 } 83 84 switch (S->getStmtClass()) { 85 case Stmt::NoStmtClass: 86 case Stmt::CXXCatchStmtClass: 87 case Stmt::SEHExceptStmtClass: 88 case Stmt::SEHFinallyStmtClass: 89 case Stmt::MSDependentExistsStmtClass: 90 llvm_unreachable("invalid statement class to emit generically"); 91 case Stmt::NullStmtClass: 92 case Stmt::CompoundStmtClass: 93 case Stmt::DeclStmtClass: 94 case Stmt::LabelStmtClass: 95 case Stmt::AttributedStmtClass: 96 case Stmt::GotoStmtClass: 97 case Stmt::BreakStmtClass: 98 case Stmt::ContinueStmtClass: 99 case Stmt::DefaultStmtClass: 100 case Stmt::CaseStmtClass: 101 case Stmt::SEHLeaveStmtClass: 102 llvm_unreachable("should have emitted these statements as simple"); 103 104 #define STMT(Type, Base) 105 #define ABSTRACT_STMT(Op) 106 #define EXPR(Type, Base) \ 107 case Stmt::Type##Class: 108 #include "clang/AST/StmtNodes.inc" 109 { 110 // Remember the block we came in on. 111 llvm::BasicBlock *incoming = Builder.GetInsertBlock(); 112 assert(incoming && "expression emission must have an insertion point"); 113 114 EmitIgnoredExpr(cast<Expr>(S)); 115 116 llvm::BasicBlock *outgoing = Builder.GetInsertBlock(); 117 assert(outgoing && "expression emission cleared block!"); 118 119 // The expression emitters assume (reasonably!) that the insertion 120 // point is always set. To maintain that, the call-emission code 121 // for noreturn functions has to enter a new block with no 122 // predecessors. We want to kill that block and mark the current 123 // insertion point unreachable in the common case of a call like 124 // "exit();". Since expression emission doesn't otherwise create 125 // blocks with no predecessors, we can just test for that. 126 // However, we must be careful not to do this to our incoming 127 // block, because *statement* emission does sometimes create 128 // reachable blocks which will have no predecessors until later in 129 // the function. This occurs with, e.g., labels that are not 130 // reachable by fallthrough. 131 if (incoming != outgoing && outgoing->use_empty()) { 132 outgoing->eraseFromParent(); 133 Builder.ClearInsertionPoint(); 134 } 135 break; 136 } 137 138 case Stmt::IndirectGotoStmtClass: 139 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break; 140 141 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break; 142 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S), Attrs); break; 143 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S), Attrs); break; 144 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S), Attrs); break; 145 146 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break; 147 148 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break; 149 case Stmt::GCCAsmStmtClass: // Intentional fall-through. 150 case Stmt::MSAsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break; 151 case Stmt::CoroutineBodyStmtClass: 152 EmitCoroutineBody(cast<CoroutineBodyStmt>(*S)); 153 break; 154 case Stmt::CoreturnStmtClass: 155 EmitCoreturnStmt(cast<CoreturnStmt>(*S)); 156 break; 157 case Stmt::CapturedStmtClass: { 158 const CapturedStmt *CS = cast<CapturedStmt>(S); 159 EmitCapturedStmt(*CS, CS->getCapturedRegionKind()); 160 } 161 break; 162 case Stmt::ObjCAtTryStmtClass: 163 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S)); 164 break; 165 case Stmt::ObjCAtCatchStmtClass: 166 llvm_unreachable( 167 "@catch statements should be handled by EmitObjCAtTryStmt"); 168 case Stmt::ObjCAtFinallyStmtClass: 169 llvm_unreachable( 170 "@finally statements should be handled by EmitObjCAtTryStmt"); 171 case Stmt::ObjCAtThrowStmtClass: 172 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S)); 173 break; 174 case Stmt::ObjCAtSynchronizedStmtClass: 175 EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S)); 176 break; 177 case Stmt::ObjCForCollectionStmtClass: 178 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S)); 179 break; 180 case Stmt::ObjCAutoreleasePoolStmtClass: 181 EmitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(*S)); 182 break; 183 184 case Stmt::CXXTryStmtClass: 185 EmitCXXTryStmt(cast<CXXTryStmt>(*S)); 186 break; 187 case Stmt::CXXForRangeStmtClass: 188 EmitCXXForRangeStmt(cast<CXXForRangeStmt>(*S), Attrs); 189 break; 190 case Stmt::SEHTryStmtClass: 191 EmitSEHTryStmt(cast<SEHTryStmt>(*S)); 192 break; 193 case Stmt::OMPParallelDirectiveClass: 194 EmitOMPParallelDirective(cast<OMPParallelDirective>(*S)); 195 break; 196 case Stmt::OMPSimdDirectiveClass: 197 EmitOMPSimdDirective(cast<OMPSimdDirective>(*S)); 198 break; 199 case Stmt::OMPForDirectiveClass: 200 EmitOMPForDirective(cast<OMPForDirective>(*S)); 201 break; 202 case Stmt::OMPForSimdDirectiveClass: 203 EmitOMPForSimdDirective(cast<OMPForSimdDirective>(*S)); 204 break; 205 case Stmt::OMPSectionsDirectiveClass: 206 EmitOMPSectionsDirective(cast<OMPSectionsDirective>(*S)); 207 break; 208 case Stmt::OMPSectionDirectiveClass: 209 EmitOMPSectionDirective(cast<OMPSectionDirective>(*S)); 210 break; 211 case Stmt::OMPSingleDirectiveClass: 212 EmitOMPSingleDirective(cast<OMPSingleDirective>(*S)); 213 break; 214 case Stmt::OMPMasterDirectiveClass: 215 EmitOMPMasterDirective(cast<OMPMasterDirective>(*S)); 216 break; 217 case Stmt::OMPCriticalDirectiveClass: 218 EmitOMPCriticalDirective(cast<OMPCriticalDirective>(*S)); 219 break; 220 case Stmt::OMPParallelForDirectiveClass: 221 EmitOMPParallelForDirective(cast<OMPParallelForDirective>(*S)); 222 break; 223 case Stmt::OMPParallelForSimdDirectiveClass: 224 EmitOMPParallelForSimdDirective(cast<OMPParallelForSimdDirective>(*S)); 225 break; 226 case Stmt::OMPParallelMasterDirectiveClass: 227 EmitOMPParallelMasterDirective(cast<OMPParallelMasterDirective>(*S)); 228 break; 229 case Stmt::OMPParallelSectionsDirectiveClass: 230 EmitOMPParallelSectionsDirective(cast<OMPParallelSectionsDirective>(*S)); 231 break; 232 case Stmt::OMPTaskDirectiveClass: 233 EmitOMPTaskDirective(cast<OMPTaskDirective>(*S)); 234 break; 235 case Stmt::OMPTaskyieldDirectiveClass: 236 EmitOMPTaskyieldDirective(cast<OMPTaskyieldDirective>(*S)); 237 break; 238 case Stmt::OMPBarrierDirectiveClass: 239 EmitOMPBarrierDirective(cast<OMPBarrierDirective>(*S)); 240 break; 241 case Stmt::OMPTaskwaitDirectiveClass: 242 EmitOMPTaskwaitDirective(cast<OMPTaskwaitDirective>(*S)); 243 break; 244 case Stmt::OMPTaskgroupDirectiveClass: 245 EmitOMPTaskgroupDirective(cast<OMPTaskgroupDirective>(*S)); 246 break; 247 case Stmt::OMPFlushDirectiveClass: 248 EmitOMPFlushDirective(cast<OMPFlushDirective>(*S)); 249 break; 250 case Stmt::OMPOrderedDirectiveClass: 251 EmitOMPOrderedDirective(cast<OMPOrderedDirective>(*S)); 252 break; 253 case Stmt::OMPAtomicDirectiveClass: 254 EmitOMPAtomicDirective(cast<OMPAtomicDirective>(*S)); 255 break; 256 case Stmt::OMPTargetDirectiveClass: 257 EmitOMPTargetDirective(cast<OMPTargetDirective>(*S)); 258 break; 259 case Stmt::OMPTeamsDirectiveClass: 260 EmitOMPTeamsDirective(cast<OMPTeamsDirective>(*S)); 261 break; 262 case Stmt::OMPCancellationPointDirectiveClass: 263 EmitOMPCancellationPointDirective(cast<OMPCancellationPointDirective>(*S)); 264 break; 265 case Stmt::OMPCancelDirectiveClass: 266 EmitOMPCancelDirective(cast<OMPCancelDirective>(*S)); 267 break; 268 case Stmt::OMPTargetDataDirectiveClass: 269 EmitOMPTargetDataDirective(cast<OMPTargetDataDirective>(*S)); 270 break; 271 case Stmt::OMPTargetEnterDataDirectiveClass: 272 EmitOMPTargetEnterDataDirective(cast<OMPTargetEnterDataDirective>(*S)); 273 break; 274 case Stmt::OMPTargetExitDataDirectiveClass: 275 EmitOMPTargetExitDataDirective(cast<OMPTargetExitDataDirective>(*S)); 276 break; 277 case Stmt::OMPTargetParallelDirectiveClass: 278 EmitOMPTargetParallelDirective(cast<OMPTargetParallelDirective>(*S)); 279 break; 280 case Stmt::OMPTargetParallelForDirectiveClass: 281 EmitOMPTargetParallelForDirective(cast<OMPTargetParallelForDirective>(*S)); 282 break; 283 case Stmt::OMPTaskLoopDirectiveClass: 284 EmitOMPTaskLoopDirective(cast<OMPTaskLoopDirective>(*S)); 285 break; 286 case Stmt::OMPTaskLoopSimdDirectiveClass: 287 EmitOMPTaskLoopSimdDirective(cast<OMPTaskLoopSimdDirective>(*S)); 288 break; 289 case Stmt::OMPMasterTaskLoopDirectiveClass: 290 EmitOMPMasterTaskLoopDirective(cast<OMPMasterTaskLoopDirective>(*S)); 291 break; 292 case Stmt::OMPMasterTaskLoopSimdDirectiveClass: 293 EmitOMPMasterTaskLoopSimdDirective( 294 cast<OMPMasterTaskLoopSimdDirective>(*S)); 295 break; 296 case Stmt::OMPParallelMasterTaskLoopDirectiveClass: 297 EmitOMPParallelMasterTaskLoopDirective( 298 cast<OMPParallelMasterTaskLoopDirective>(*S)); 299 break; 300 case Stmt::OMPParallelMasterTaskLoopSimdDirectiveClass: 301 EmitOMPParallelMasterTaskLoopSimdDirective( 302 cast<OMPParallelMasterTaskLoopSimdDirective>(*S)); 303 break; 304 case Stmt::OMPDistributeDirectiveClass: 305 EmitOMPDistributeDirective(cast<OMPDistributeDirective>(*S)); 306 break; 307 case Stmt::OMPTargetUpdateDirectiveClass: 308 EmitOMPTargetUpdateDirective(cast<OMPTargetUpdateDirective>(*S)); 309 break; 310 case Stmt::OMPDistributeParallelForDirectiveClass: 311 EmitOMPDistributeParallelForDirective( 312 cast<OMPDistributeParallelForDirective>(*S)); 313 break; 314 case Stmt::OMPDistributeParallelForSimdDirectiveClass: 315 EmitOMPDistributeParallelForSimdDirective( 316 cast<OMPDistributeParallelForSimdDirective>(*S)); 317 break; 318 case Stmt::OMPDistributeSimdDirectiveClass: 319 EmitOMPDistributeSimdDirective(cast<OMPDistributeSimdDirective>(*S)); 320 break; 321 case Stmt::OMPTargetParallelForSimdDirectiveClass: 322 EmitOMPTargetParallelForSimdDirective( 323 cast<OMPTargetParallelForSimdDirective>(*S)); 324 break; 325 case Stmt::OMPTargetSimdDirectiveClass: 326 EmitOMPTargetSimdDirective(cast<OMPTargetSimdDirective>(*S)); 327 break; 328 case Stmt::OMPTeamsDistributeDirectiveClass: 329 EmitOMPTeamsDistributeDirective(cast<OMPTeamsDistributeDirective>(*S)); 330 break; 331 case Stmt::OMPTeamsDistributeSimdDirectiveClass: 332 EmitOMPTeamsDistributeSimdDirective( 333 cast<OMPTeamsDistributeSimdDirective>(*S)); 334 break; 335 case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass: 336 EmitOMPTeamsDistributeParallelForSimdDirective( 337 cast<OMPTeamsDistributeParallelForSimdDirective>(*S)); 338 break; 339 case Stmt::OMPTeamsDistributeParallelForDirectiveClass: 340 EmitOMPTeamsDistributeParallelForDirective( 341 cast<OMPTeamsDistributeParallelForDirective>(*S)); 342 break; 343 case Stmt::OMPTargetTeamsDirectiveClass: 344 EmitOMPTargetTeamsDirective(cast<OMPTargetTeamsDirective>(*S)); 345 break; 346 case Stmt::OMPTargetTeamsDistributeDirectiveClass: 347 EmitOMPTargetTeamsDistributeDirective( 348 cast<OMPTargetTeamsDistributeDirective>(*S)); 349 break; 350 case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass: 351 EmitOMPTargetTeamsDistributeParallelForDirective( 352 cast<OMPTargetTeamsDistributeParallelForDirective>(*S)); 353 break; 354 case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass: 355 EmitOMPTargetTeamsDistributeParallelForSimdDirective( 356 cast<OMPTargetTeamsDistributeParallelForSimdDirective>(*S)); 357 break; 358 case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass: 359 EmitOMPTargetTeamsDistributeSimdDirective( 360 cast<OMPTargetTeamsDistributeSimdDirective>(*S)); 361 break; 362 } 363 } 364 365 bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) { 366 switch (S->getStmtClass()) { 367 default: return false; 368 case Stmt::NullStmtClass: break; 369 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break; 370 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break; 371 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break; 372 case Stmt::AttributedStmtClass: 373 EmitAttributedStmt(cast<AttributedStmt>(*S)); break; 374 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break; 375 case Stmt::BreakStmtClass: EmitBreakStmt(cast<BreakStmt>(*S)); break; 376 case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break; 377 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break; 378 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break; 379 case Stmt::SEHLeaveStmtClass: EmitSEHLeaveStmt(cast<SEHLeaveStmt>(*S)); break; 380 } 381 382 return true; 383 } 384 385 /// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true, 386 /// this captures the expression result of the last sub-statement and returns it 387 /// (for use by the statement expression extension). 388 Address CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast, 389 AggValueSlot AggSlot) { 390 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(), 391 "LLVM IR generation of compound statement ('{}')"); 392 393 // Keep track of the current cleanup stack depth, including debug scopes. 394 LexicalScope Scope(*this, S.getSourceRange()); 395 396 return EmitCompoundStmtWithoutScope(S, GetLast, AggSlot); 397 } 398 399 Address 400 CodeGenFunction::EmitCompoundStmtWithoutScope(const CompoundStmt &S, 401 bool GetLast, 402 AggValueSlot AggSlot) { 403 404 const Stmt *ExprResult = S.getStmtExprResult(); 405 assert((!GetLast || (GetLast && ExprResult)) && 406 "If GetLast is true then the CompoundStmt must have a StmtExprResult"); 407 408 Address RetAlloca = Address::invalid(); 409 410 for (auto *CurStmt : S.body()) { 411 if (GetLast && ExprResult == CurStmt) { 412 // We have to special case labels here. They are statements, but when put 413 // at the end of a statement expression, they yield the value of their 414 // subexpression. Handle this by walking through all labels we encounter, 415 // emitting them before we evaluate the subexpr. 416 // Similar issues arise for attributed statements. 417 while (!isa<Expr>(ExprResult)) { 418 if (const auto *LS = dyn_cast<LabelStmt>(ExprResult)) { 419 EmitLabel(LS->getDecl()); 420 ExprResult = LS->getSubStmt(); 421 } else if (const auto *AS = dyn_cast<AttributedStmt>(ExprResult)) { 422 // FIXME: Update this if we ever have attributes that affect the 423 // semantics of an expression. 424 ExprResult = AS->getSubStmt(); 425 } else { 426 llvm_unreachable("unknown value statement"); 427 } 428 } 429 430 EnsureInsertPoint(); 431 432 const Expr *E = cast<Expr>(ExprResult); 433 QualType ExprTy = E->getType(); 434 if (hasAggregateEvaluationKind(ExprTy)) { 435 EmitAggExpr(E, AggSlot); 436 } else { 437 // We can't return an RValue here because there might be cleanups at 438 // the end of the StmtExpr. Because of that, we have to emit the result 439 // here into a temporary alloca. 440 RetAlloca = CreateMemTemp(ExprTy); 441 EmitAnyExprToMem(E, RetAlloca, Qualifiers(), 442 /*IsInit*/ false); 443 } 444 } else { 445 EmitStmt(CurStmt); 446 } 447 } 448 449 return RetAlloca; 450 } 451 452 void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) { 453 llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(BB->getTerminator()); 454 455 // If there is a cleanup stack, then we it isn't worth trying to 456 // simplify this block (we would need to remove it from the scope map 457 // and cleanup entry). 458 if (!EHStack.empty()) 459 return; 460 461 // Can only simplify direct branches. 462 if (!BI || !BI->isUnconditional()) 463 return; 464 465 // Can only simplify empty blocks. 466 if (BI->getIterator() != BB->begin()) 467 return; 468 469 BB->replaceAllUsesWith(BI->getSuccessor(0)); 470 BI->eraseFromParent(); 471 BB->eraseFromParent(); 472 } 473 474 void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) { 475 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 476 477 // Fall out of the current block (if necessary). 478 EmitBranch(BB); 479 480 if (IsFinished && BB->use_empty()) { 481 delete BB; 482 return; 483 } 484 485 // Place the block after the current block, if possible, or else at 486 // the end of the function. 487 if (CurBB && CurBB->getParent()) 488 CurFn->getBasicBlockList().insertAfter(CurBB->getIterator(), BB); 489 else 490 CurFn->getBasicBlockList().push_back(BB); 491 Builder.SetInsertPoint(BB); 492 } 493 494 void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) { 495 // Emit a branch from the current block to the target one if this 496 // was a real block. If this was just a fall-through block after a 497 // terminator, don't emit it. 498 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 499 500 if (!CurBB || CurBB->getTerminator()) { 501 // If there is no insert point or the previous block is already 502 // terminated, don't touch it. 503 } else { 504 // Otherwise, create a fall-through branch. 505 Builder.CreateBr(Target); 506 } 507 508 Builder.ClearInsertionPoint(); 509 } 510 511 void CodeGenFunction::EmitBlockAfterUses(llvm::BasicBlock *block) { 512 bool inserted = false; 513 for (llvm::User *u : block->users()) { 514 if (llvm::Instruction *insn = dyn_cast<llvm::Instruction>(u)) { 515 CurFn->getBasicBlockList().insertAfter(insn->getParent()->getIterator(), 516 block); 517 inserted = true; 518 break; 519 } 520 } 521 522 if (!inserted) 523 CurFn->getBasicBlockList().push_back(block); 524 525 Builder.SetInsertPoint(block); 526 } 527 528 CodeGenFunction::JumpDest 529 CodeGenFunction::getJumpDestForLabel(const LabelDecl *D) { 530 JumpDest &Dest = LabelMap[D]; 531 if (Dest.isValid()) return Dest; 532 533 // Create, but don't insert, the new block. 534 Dest = JumpDest(createBasicBlock(D->getName()), 535 EHScopeStack::stable_iterator::invalid(), 536 NextCleanupDestIndex++); 537 return Dest; 538 } 539 540 void CodeGenFunction::EmitLabel(const LabelDecl *D) { 541 // Add this label to the current lexical scope if we're within any 542 // normal cleanups. Jumps "in" to this label --- when permitted by 543 // the language --- may need to be routed around such cleanups. 544 if (EHStack.hasNormalCleanups() && CurLexicalScope) 545 CurLexicalScope->addLabel(D); 546 547 JumpDest &Dest = LabelMap[D]; 548 549 // If we didn't need a forward reference to this label, just go 550 // ahead and create a destination at the current scope. 551 if (!Dest.isValid()) { 552 Dest = getJumpDestInCurrentScope(D->getName()); 553 554 // Otherwise, we need to give this label a target depth and remove 555 // it from the branch-fixups list. 556 } else { 557 assert(!Dest.getScopeDepth().isValid() && "already emitted label!"); 558 Dest.setScopeDepth(EHStack.stable_begin()); 559 ResolveBranchFixups(Dest.getBlock()); 560 } 561 562 EmitBlock(Dest.getBlock()); 563 564 // Emit debug info for labels. 565 if (CGDebugInfo *DI = getDebugInfo()) { 566 if (CGM.getCodeGenOpts().hasReducedDebugInfo()) { 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 // Labels 2216 SmallVector<llvm::BasicBlock *, 16> Transfer; 2217 llvm::BasicBlock *Fallthrough = nullptr; 2218 bool IsGCCAsmGoto = false; 2219 if (const auto *GS = dyn_cast<GCCAsmStmt>(&S)) { 2220 IsGCCAsmGoto = GS->isAsmGoto(); 2221 if (IsGCCAsmGoto) { 2222 for (const auto *E : GS->labels()) { 2223 JumpDest Dest = getJumpDestForLabel(E->getLabel()); 2224 Transfer.push_back(Dest.getBlock()); 2225 llvm::BlockAddress *BA = 2226 llvm::BlockAddress::get(CurFn, Dest.getBlock()); 2227 Args.push_back(BA); 2228 ArgTypes.push_back(BA->getType()); 2229 if (!Constraints.empty()) 2230 Constraints += ','; 2231 Constraints += 'X'; 2232 } 2233 Fallthrough = createBasicBlock("asm.fallthrough"); 2234 } 2235 } 2236 2237 // Append the "input" part of inout constraints last. 2238 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) { 2239 ArgTypes.push_back(InOutArgTypes[i]); 2240 Args.push_back(InOutArgs[i]); 2241 } 2242 Constraints += InOutConstraints; 2243 2244 // Clobbers 2245 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) { 2246 StringRef Clobber = S.getClobber(i); 2247 2248 if (Clobber == "memory") 2249 ReadOnly = ReadNone = false; 2250 else if (Clobber != "cc") { 2251 Clobber = getTarget().getNormalizedGCCRegisterName(Clobber); 2252 if (CGM.getCodeGenOpts().StackClashProtector && 2253 getTarget().isSPRegName(Clobber)) { 2254 CGM.getDiags().Report(S.getAsmLoc(), 2255 diag::warn_stack_clash_protection_inline_asm); 2256 } 2257 } 2258 2259 if (!Constraints.empty()) 2260 Constraints += ','; 2261 2262 Constraints += "~{"; 2263 Constraints += Clobber; 2264 Constraints += '}'; 2265 } 2266 2267 // Add machine specific clobbers 2268 std::string MachineClobbers = getTarget().getClobbers(); 2269 if (!MachineClobbers.empty()) { 2270 if (!Constraints.empty()) 2271 Constraints += ','; 2272 Constraints += MachineClobbers; 2273 } 2274 2275 llvm::Type *ResultType; 2276 if (ResultRegTypes.empty()) 2277 ResultType = VoidTy; 2278 else if (ResultRegTypes.size() == 1) 2279 ResultType = ResultRegTypes[0]; 2280 else 2281 ResultType = llvm::StructType::get(getLLVMContext(), ResultRegTypes); 2282 2283 llvm::FunctionType *FTy = 2284 llvm::FunctionType::get(ResultType, ArgTypes, false); 2285 2286 bool HasSideEffect = S.isVolatile() || S.getNumOutputs() == 0; 2287 llvm::InlineAsm::AsmDialect AsmDialect = isa<MSAsmStmt>(&S) ? 2288 llvm::InlineAsm::AD_Intel : llvm::InlineAsm::AD_ATT; 2289 llvm::InlineAsm *IA = 2290 llvm::InlineAsm::get(FTy, AsmString, Constraints, HasSideEffect, 2291 /* IsAlignStack */ false, AsmDialect); 2292 std::vector<llvm::Value*> RegResults; 2293 if (IsGCCAsmGoto) { 2294 llvm::CallBrInst *Result = 2295 Builder.CreateCallBr(IA, Fallthrough, Transfer, Args); 2296 EmitBlock(Fallthrough); 2297 UpdateAsmCallInst(cast<llvm::CallBase>(*Result), HasSideEffect, ReadOnly, 2298 ReadNone, S, ResultRegTypes, *this, RegResults); 2299 } else { 2300 llvm::CallInst *Result = 2301 Builder.CreateCall(IA, Args, getBundlesForFunclet(IA)); 2302 UpdateAsmCallInst(cast<llvm::CallBase>(*Result), HasSideEffect, ReadOnly, 2303 ReadNone, S, ResultRegTypes, *this, RegResults); 2304 } 2305 2306 assert(RegResults.size() == ResultRegTypes.size()); 2307 assert(RegResults.size() == ResultTruncRegTypes.size()); 2308 assert(RegResults.size() == ResultRegDests.size()); 2309 // ResultRegDests can be also populated by addReturnRegisterOutputs() above, 2310 // in which case its size may grow. 2311 assert(ResultTypeRequiresCast.size() <= ResultRegDests.size()); 2312 for (unsigned i = 0, e = RegResults.size(); i != e; ++i) { 2313 llvm::Value *Tmp = RegResults[i]; 2314 2315 // If the result type of the LLVM IR asm doesn't match the result type of 2316 // the expression, do the conversion. 2317 if (ResultRegTypes[i] != ResultTruncRegTypes[i]) { 2318 llvm::Type *TruncTy = ResultTruncRegTypes[i]; 2319 2320 // Truncate the integer result to the right size, note that TruncTy can be 2321 // a pointer. 2322 if (TruncTy->isFloatingPointTy()) 2323 Tmp = Builder.CreateFPTrunc(Tmp, TruncTy); 2324 else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) { 2325 uint64_t ResSize = CGM.getDataLayout().getTypeSizeInBits(TruncTy); 2326 Tmp = Builder.CreateTrunc(Tmp, 2327 llvm::IntegerType::get(getLLVMContext(), (unsigned)ResSize)); 2328 Tmp = Builder.CreateIntToPtr(Tmp, TruncTy); 2329 } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) { 2330 uint64_t TmpSize =CGM.getDataLayout().getTypeSizeInBits(Tmp->getType()); 2331 Tmp = Builder.CreatePtrToInt(Tmp, 2332 llvm::IntegerType::get(getLLVMContext(), (unsigned)TmpSize)); 2333 Tmp = Builder.CreateTrunc(Tmp, TruncTy); 2334 } else if (TruncTy->isIntegerTy()) { 2335 Tmp = Builder.CreateZExtOrTrunc(Tmp, TruncTy); 2336 } else if (TruncTy->isVectorTy()) { 2337 Tmp = Builder.CreateBitCast(Tmp, TruncTy); 2338 } 2339 } 2340 2341 LValue Dest = ResultRegDests[i]; 2342 // ResultTypeRequiresCast elements correspond to the first 2343 // ResultTypeRequiresCast.size() elements of RegResults. 2344 if ((i < ResultTypeRequiresCast.size()) && ResultTypeRequiresCast[i]) { 2345 unsigned Size = getContext().getTypeSize(ResultRegQualTys[i]); 2346 Address A = Builder.CreateBitCast(Dest.getAddress(*this), 2347 ResultRegTypes[i]->getPointerTo()); 2348 QualType Ty = getContext().getIntTypeForBitwidth(Size, /*Signed*/ false); 2349 if (Ty.isNull()) { 2350 const Expr *OutExpr = S.getOutputExpr(i); 2351 CGM.Error( 2352 OutExpr->getExprLoc(), 2353 "impossible constraint in asm: can't store value into a register"); 2354 return; 2355 } 2356 Dest = MakeAddrLValue(A, Ty); 2357 } 2358 EmitStoreThroughLValue(RValue::get(Tmp), Dest); 2359 } 2360 } 2361 2362 LValue CodeGenFunction::InitCapturedStruct(const CapturedStmt &S) { 2363 const RecordDecl *RD = S.getCapturedRecordDecl(); 2364 QualType RecordTy = getContext().getRecordType(RD); 2365 2366 // Initialize the captured struct. 2367 LValue SlotLV = 2368 MakeAddrLValue(CreateMemTemp(RecordTy, "agg.captured"), RecordTy); 2369 2370 RecordDecl::field_iterator CurField = RD->field_begin(); 2371 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(), 2372 E = S.capture_init_end(); 2373 I != E; ++I, ++CurField) { 2374 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField); 2375 if (CurField->hasCapturedVLAType()) { 2376 auto VAT = CurField->getCapturedVLAType(); 2377 EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV); 2378 } else { 2379 EmitInitializerForField(*CurField, LV, *I); 2380 } 2381 } 2382 2383 return SlotLV; 2384 } 2385 2386 /// Generate an outlined function for the body of a CapturedStmt, store any 2387 /// captured variables into the captured struct, and call the outlined function. 2388 llvm::Function * 2389 CodeGenFunction::EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K) { 2390 LValue CapStruct = InitCapturedStruct(S); 2391 2392 // Emit the CapturedDecl 2393 CodeGenFunction CGF(CGM, true); 2394 CGCapturedStmtRAII CapInfoRAII(CGF, new CGCapturedStmtInfo(S, K)); 2395 llvm::Function *F = CGF.GenerateCapturedStmtFunction(S); 2396 delete CGF.CapturedStmtInfo; 2397 2398 // Emit call to the helper function. 2399 EmitCallOrInvoke(F, CapStruct.getPointer(*this)); 2400 2401 return F; 2402 } 2403 2404 Address CodeGenFunction::GenerateCapturedStmtArgument(const CapturedStmt &S) { 2405 LValue CapStruct = InitCapturedStruct(S); 2406 return CapStruct.getAddress(*this); 2407 } 2408 2409 /// Creates the outlined function for a CapturedStmt. 2410 llvm::Function * 2411 CodeGenFunction::GenerateCapturedStmtFunction(const CapturedStmt &S) { 2412 assert(CapturedStmtInfo && 2413 "CapturedStmtInfo should be set when generating the captured function"); 2414 const CapturedDecl *CD = S.getCapturedDecl(); 2415 const RecordDecl *RD = S.getCapturedRecordDecl(); 2416 SourceLocation Loc = S.getBeginLoc(); 2417 assert(CD->hasBody() && "missing CapturedDecl body"); 2418 2419 // Build the argument list. 2420 ASTContext &Ctx = CGM.getContext(); 2421 FunctionArgList Args; 2422 Args.append(CD->param_begin(), CD->param_end()); 2423 2424 // Create the function declaration. 2425 const CGFunctionInfo &FuncInfo = 2426 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Args); 2427 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo); 2428 2429 llvm::Function *F = 2430 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage, 2431 CapturedStmtInfo->getHelperName(), &CGM.getModule()); 2432 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo); 2433 if (CD->isNothrow()) 2434 F->addFnAttr(llvm::Attribute::NoUnwind); 2435 2436 // Generate the function. 2437 StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args, CD->getLocation(), 2438 CD->getBody()->getBeginLoc()); 2439 // Set the context parameter in CapturedStmtInfo. 2440 Address DeclPtr = GetAddrOfLocalVar(CD->getContextParam()); 2441 CapturedStmtInfo->setContextValue(Builder.CreateLoad(DeclPtr)); 2442 2443 // Initialize variable-length arrays. 2444 LValue Base = MakeNaturalAlignAddrLValue(CapturedStmtInfo->getContextValue(), 2445 Ctx.getTagDeclType(RD)); 2446 for (auto *FD : RD->fields()) { 2447 if (FD->hasCapturedVLAType()) { 2448 auto *ExprArg = 2449 EmitLoadOfLValue(EmitLValueForField(Base, FD), S.getBeginLoc()) 2450 .getScalarVal(); 2451 auto VAT = FD->getCapturedVLAType(); 2452 VLASizeMap[VAT->getSizeExpr()] = ExprArg; 2453 } 2454 } 2455 2456 // If 'this' is captured, load it into CXXThisValue. 2457 if (CapturedStmtInfo->isCXXThisExprCaptured()) { 2458 FieldDecl *FD = CapturedStmtInfo->getThisFieldDecl(); 2459 LValue ThisLValue = EmitLValueForField(Base, FD); 2460 CXXThisValue = EmitLoadOfLValue(ThisLValue, Loc).getScalarVal(); 2461 } 2462 2463 PGO.assignRegionCounters(GlobalDecl(CD), F); 2464 CapturedStmtInfo->EmitBody(*this, CD->getBody()); 2465 FinishFunction(CD->getBodyRBrace()); 2466 2467 return F; 2468 } 2469