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