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