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