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