1 //===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This coordinates the per-function state used while generating code. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "CodeGenFunction.h" 14 #include "CGBlocks.h" 15 #include "CGCUDARuntime.h" 16 #include "CGCXXABI.h" 17 #include "CGCleanup.h" 18 #include "CGDebugInfo.h" 19 #include "CGOpenMPRuntime.h" 20 #include "CodeGenModule.h" 21 #include "CodeGenPGO.h" 22 #include "TargetInfo.h" 23 #include "clang/AST/ASTContext.h" 24 #include "clang/AST/ASTLambda.h" 25 #include "clang/AST/Attr.h" 26 #include "clang/AST/Decl.h" 27 #include "clang/AST/DeclCXX.h" 28 #include "clang/AST/StmtCXX.h" 29 #include "clang/AST/StmtObjC.h" 30 #include "clang/Basic/Builtins.h" 31 #include "clang/Basic/CodeGenOptions.h" 32 #include "clang/Basic/TargetInfo.h" 33 #include "clang/CodeGen/CGFunctionInfo.h" 34 #include "clang/Frontend/FrontendDiagnostic.h" 35 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h" 36 #include "llvm/IR/DataLayout.h" 37 #include "llvm/IR/Dominators.h" 38 #include "llvm/IR/FPEnv.h" 39 #include "llvm/IR/IntrinsicInst.h" 40 #include "llvm/IR/Intrinsics.h" 41 #include "llvm/IR/MDBuilder.h" 42 #include "llvm/IR/Operator.h" 43 #include "llvm/Transforms/Utils/PromoteMemToReg.h" 44 using namespace clang; 45 using namespace CodeGen; 46 47 /// shouldEmitLifetimeMarkers - Decide whether we need emit the life-time 48 /// markers. 49 static bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts, 50 const LangOptions &LangOpts) { 51 if (CGOpts.DisableLifetimeMarkers) 52 return false; 53 54 // Sanitizers may use markers. 55 if (CGOpts.SanitizeAddressUseAfterScope || 56 LangOpts.Sanitize.has(SanitizerKind::HWAddress) || 57 LangOpts.Sanitize.has(SanitizerKind::Memory)) 58 return true; 59 60 // For now, only in optimized builds. 61 return CGOpts.OptimizationLevel != 0; 62 } 63 64 CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext) 65 : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()), 66 Builder(cgm, cgm.getModule().getContext(), llvm::ConstantFolder(), 67 CGBuilderInserterTy(this)), 68 SanOpts(CGM.getLangOpts().Sanitize), DebugInfo(CGM.getModuleDebugInfo()), 69 PGO(cgm), ShouldEmitLifetimeMarkers(shouldEmitLifetimeMarkers( 70 CGM.getCodeGenOpts(), CGM.getLangOpts())) { 71 if (!suppressNewContext) 72 CGM.getCXXABI().getMangleContext().startNewFunction(); 73 74 llvm::FastMathFlags FMF; 75 if (CGM.getLangOpts().FastMath) 76 FMF.setFast(); 77 if (CGM.getLangOpts().FiniteMathOnly) { 78 FMF.setNoNaNs(); 79 FMF.setNoInfs(); 80 } 81 if (CGM.getCodeGenOpts().NoNaNsFPMath) { 82 FMF.setNoNaNs(); 83 } 84 if (CGM.getCodeGenOpts().NoSignedZeros) { 85 FMF.setNoSignedZeros(); 86 } 87 if (CGM.getCodeGenOpts().ReciprocalMath) { 88 FMF.setAllowReciprocal(); 89 } 90 if (CGM.getCodeGenOpts().Reassociate) { 91 FMF.setAllowReassoc(); 92 } 93 Builder.setFastMathFlags(FMF); 94 SetFPModel(); 95 } 96 97 CodeGenFunction::~CodeGenFunction() { 98 assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup"); 99 100 // If there are any unclaimed block infos, go ahead and destroy them 101 // now. This can happen if IR-gen gets clever and skips evaluating 102 // something. 103 if (FirstBlockInfo) 104 destroyBlockInfos(FirstBlockInfo); 105 106 if (getLangOpts().OpenMP && CurFn) 107 CGM.getOpenMPRuntime().functionFinished(*this); 108 109 // If we have an OpenMPIRBuilder we want to finalize functions (incl. 110 // outlining etc) at some point. Doing it once the function codegen is done 111 // seems to be a reasonable spot. We do it here, as opposed to the deletion 112 // time of the CodeGenModule, because we have to ensure the IR has not yet 113 // been "emitted" to the outside, thus, modifications are still sensible. 114 if (llvm::OpenMPIRBuilder *OMPBuilder = CGM.getOpenMPIRBuilder()) 115 OMPBuilder->finalize(); 116 } 117 118 // Map the LangOption for exception behavior into 119 // the corresponding enum in the IR. 120 llvm::fp::ExceptionBehavior 121 clang::ToConstrainedExceptMD(LangOptions::FPExceptionModeKind Kind) { 122 123 switch (Kind) { 124 case LangOptions::FPE_Ignore: return llvm::fp::ebIgnore; 125 case LangOptions::FPE_MayTrap: return llvm::fp::ebMayTrap; 126 case LangOptions::FPE_Strict: return llvm::fp::ebStrict; 127 } 128 llvm_unreachable("Unsupported FP Exception Behavior"); 129 } 130 131 void CodeGenFunction::SetFPModel() { 132 llvm::RoundingMode RM = getLangOpts().getFPRoundingMode(); 133 auto fpExceptionBehavior = ToConstrainedExceptMD( 134 getLangOpts().getFPExceptionMode()); 135 136 Builder.setDefaultConstrainedRounding(RM); 137 Builder.setDefaultConstrainedExcept(fpExceptionBehavior); 138 Builder.setIsFPConstrained(fpExceptionBehavior != llvm::fp::ebIgnore || 139 RM != llvm::RoundingMode::NearestTiesToEven); 140 } 141 142 CharUnits CodeGenFunction::getNaturalPointeeTypeAlignment(QualType T, 143 LValueBaseInfo *BaseInfo, 144 TBAAAccessInfo *TBAAInfo) { 145 return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo, 146 /* forPointeeType= */ true); 147 } 148 149 CharUnits CodeGenFunction::getNaturalTypeAlignment(QualType T, 150 LValueBaseInfo *BaseInfo, 151 TBAAAccessInfo *TBAAInfo, 152 bool forPointeeType) { 153 if (TBAAInfo) 154 *TBAAInfo = CGM.getTBAAAccessInfo(T); 155 156 // Honor alignment typedef attributes even on incomplete types. 157 // We also honor them straight for C++ class types, even as pointees; 158 // there's an expressivity gap here. 159 if (auto TT = T->getAs<TypedefType>()) { 160 if (auto Align = TT->getDecl()->getMaxAlignment()) { 161 if (BaseInfo) 162 *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType); 163 return getContext().toCharUnitsFromBits(Align); 164 } 165 } 166 167 if (BaseInfo) 168 *BaseInfo = LValueBaseInfo(AlignmentSource::Type); 169 170 CharUnits Alignment; 171 if (T->isIncompleteType()) { 172 Alignment = CharUnits::One(); // Shouldn't be used, but pessimistic is best. 173 } else { 174 // For C++ class pointees, we don't know whether we're pointing at a 175 // base or a complete object, so we generally need to use the 176 // non-virtual alignment. 177 const CXXRecordDecl *RD; 178 if (forPointeeType && (RD = T->getAsCXXRecordDecl())) { 179 Alignment = CGM.getClassPointerAlignment(RD); 180 } else { 181 Alignment = getContext().getTypeAlignInChars(T); 182 if (T.getQualifiers().hasUnaligned()) 183 Alignment = CharUnits::One(); 184 } 185 186 // Cap to the global maximum type alignment unless the alignment 187 // was somehow explicit on the type. 188 if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) { 189 if (Alignment.getQuantity() > MaxAlign && 190 !getContext().isAlignmentRequired(T)) 191 Alignment = CharUnits::fromQuantity(MaxAlign); 192 } 193 } 194 return Alignment; 195 } 196 197 LValue CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) { 198 LValueBaseInfo BaseInfo; 199 TBAAAccessInfo TBAAInfo; 200 CharUnits Alignment = getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo); 201 return LValue::MakeAddr(Address(V, Alignment), T, getContext(), BaseInfo, 202 TBAAInfo); 203 } 204 205 /// Given a value of type T* that may not be to a complete object, 206 /// construct an l-value with the natural pointee alignment of T. 207 LValue 208 CodeGenFunction::MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T) { 209 LValueBaseInfo BaseInfo; 210 TBAAAccessInfo TBAAInfo; 211 CharUnits Align = getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo, 212 /* forPointeeType= */ true); 213 return MakeAddrLValue(Address(V, Align), T, BaseInfo, TBAAInfo); 214 } 215 216 217 llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) { 218 return CGM.getTypes().ConvertTypeForMem(T); 219 } 220 221 llvm::Type *CodeGenFunction::ConvertType(QualType T) { 222 return CGM.getTypes().ConvertType(T); 223 } 224 225 TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) { 226 type = type.getCanonicalType(); 227 while (true) { 228 switch (type->getTypeClass()) { 229 #define TYPE(name, parent) 230 #define ABSTRACT_TYPE(name, parent) 231 #define NON_CANONICAL_TYPE(name, parent) case Type::name: 232 #define DEPENDENT_TYPE(name, parent) case Type::name: 233 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name: 234 #include "clang/AST/TypeNodes.inc" 235 llvm_unreachable("non-canonical or dependent type in IR-generation"); 236 237 case Type::Auto: 238 case Type::DeducedTemplateSpecialization: 239 llvm_unreachable("undeduced type in IR-generation"); 240 241 // Various scalar types. 242 case Type::Builtin: 243 case Type::Pointer: 244 case Type::BlockPointer: 245 case Type::LValueReference: 246 case Type::RValueReference: 247 case Type::MemberPointer: 248 case Type::Vector: 249 case Type::ExtVector: 250 case Type::ConstantMatrix: 251 case Type::FunctionProto: 252 case Type::FunctionNoProto: 253 case Type::Enum: 254 case Type::ObjCObjectPointer: 255 case Type::Pipe: 256 case Type::ExtInt: 257 return TEK_Scalar; 258 259 // Complexes. 260 case Type::Complex: 261 return TEK_Complex; 262 263 // Arrays, records, and Objective-C objects. 264 case Type::ConstantArray: 265 case Type::IncompleteArray: 266 case Type::VariableArray: 267 case Type::Record: 268 case Type::ObjCObject: 269 case Type::ObjCInterface: 270 return TEK_Aggregate; 271 272 // We operate on atomic values according to their underlying type. 273 case Type::Atomic: 274 type = cast<AtomicType>(type)->getValueType(); 275 continue; 276 } 277 llvm_unreachable("unknown type kind!"); 278 } 279 } 280 281 llvm::DebugLoc CodeGenFunction::EmitReturnBlock() { 282 // For cleanliness, we try to avoid emitting the return block for 283 // simple cases. 284 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 285 286 if (CurBB) { 287 assert(!CurBB->getTerminator() && "Unexpected terminated block."); 288 289 // We have a valid insert point, reuse it if it is empty or there are no 290 // explicit jumps to the return block. 291 if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) { 292 ReturnBlock.getBlock()->replaceAllUsesWith(CurBB); 293 delete ReturnBlock.getBlock(); 294 ReturnBlock = JumpDest(); 295 } else 296 EmitBlock(ReturnBlock.getBlock()); 297 return llvm::DebugLoc(); 298 } 299 300 // Otherwise, if the return block is the target of a single direct 301 // branch then we can just put the code in that block instead. This 302 // cleans up functions which started with a unified return block. 303 if (ReturnBlock.getBlock()->hasOneUse()) { 304 llvm::BranchInst *BI = 305 dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin()); 306 if (BI && BI->isUnconditional() && 307 BI->getSuccessor(0) == ReturnBlock.getBlock()) { 308 // Record/return the DebugLoc of the simple 'return' expression to be used 309 // later by the actual 'ret' instruction. 310 llvm::DebugLoc Loc = BI->getDebugLoc(); 311 Builder.SetInsertPoint(BI->getParent()); 312 BI->eraseFromParent(); 313 delete ReturnBlock.getBlock(); 314 ReturnBlock = JumpDest(); 315 return Loc; 316 } 317 } 318 319 // FIXME: We are at an unreachable point, there is no reason to emit the block 320 // unless it has uses. However, we still need a place to put the debug 321 // region.end for now. 322 323 EmitBlock(ReturnBlock.getBlock()); 324 return llvm::DebugLoc(); 325 } 326 327 static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) { 328 if (!BB) return; 329 if (!BB->use_empty()) 330 return CGF.CurFn->getBasicBlockList().push_back(BB); 331 delete BB; 332 } 333 334 void CodeGenFunction::FinishFunction(SourceLocation EndLoc) { 335 assert(BreakContinueStack.empty() && 336 "mismatched push/pop in break/continue stack!"); 337 338 bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0 339 && NumSimpleReturnExprs == NumReturnExprs 340 && ReturnBlock.getBlock()->use_empty(); 341 // Usually the return expression is evaluated before the cleanup 342 // code. If the function contains only a simple return statement, 343 // such as a constant, the location before the cleanup code becomes 344 // the last useful breakpoint in the function, because the simple 345 // return expression will be evaluated after the cleanup code. To be 346 // safe, set the debug location for cleanup code to the location of 347 // the return statement. Otherwise the cleanup code should be at the 348 // end of the function's lexical scope. 349 // 350 // If there are multiple branches to the return block, the branch 351 // instructions will get the location of the return statements and 352 // all will be fine. 353 if (CGDebugInfo *DI = getDebugInfo()) { 354 if (OnlySimpleReturnStmts) 355 DI->EmitLocation(Builder, LastStopPoint); 356 else 357 DI->EmitLocation(Builder, EndLoc); 358 } 359 360 // Pop any cleanups that might have been associated with the 361 // parameters. Do this in whatever block we're currently in; it's 362 // important to do this before we enter the return block or return 363 // edges will be *really* confused. 364 bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth; 365 bool HasOnlyLifetimeMarkers = 366 HasCleanups && EHStack.containsOnlyLifetimeMarkers(PrologueCleanupDepth); 367 bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers; 368 if (HasCleanups) { 369 // Make sure the line table doesn't jump back into the body for 370 // the ret after it's been at EndLoc. 371 Optional<ApplyDebugLocation> AL; 372 if (CGDebugInfo *DI = getDebugInfo()) { 373 if (OnlySimpleReturnStmts) 374 DI->EmitLocation(Builder, EndLoc); 375 else 376 // We may not have a valid end location. Try to apply it anyway, and 377 // fall back to an artificial location if needed. 378 AL = ApplyDebugLocation::CreateDefaultArtificial(*this, EndLoc); 379 } 380 381 PopCleanupBlocks(PrologueCleanupDepth); 382 } 383 384 // Emit function epilog (to return). 385 llvm::DebugLoc Loc = EmitReturnBlock(); 386 387 if (ShouldInstrumentFunction()) { 388 if (CGM.getCodeGenOpts().InstrumentFunctions) 389 CurFn->addFnAttr("instrument-function-exit", "__cyg_profile_func_exit"); 390 if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining) 391 CurFn->addFnAttr("instrument-function-exit-inlined", 392 "__cyg_profile_func_exit"); 393 } 394 395 // Emit debug descriptor for function end. 396 if (CGDebugInfo *DI = getDebugInfo()) 397 DI->EmitFunctionEnd(Builder, CurFn); 398 399 // Reset the debug location to that of the simple 'return' expression, if any 400 // rather than that of the end of the function's scope '}'. 401 ApplyDebugLocation AL(*this, Loc); 402 EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc); 403 EmitEndEHSpec(CurCodeDecl); 404 405 assert(EHStack.empty() && 406 "did not remove all scopes from cleanup stack!"); 407 408 // If someone did an indirect goto, emit the indirect goto block at the end of 409 // the function. 410 if (IndirectBranch) { 411 EmitBlock(IndirectBranch->getParent()); 412 Builder.ClearInsertionPoint(); 413 } 414 415 // If some of our locals escaped, insert a call to llvm.localescape in the 416 // entry block. 417 if (!EscapedLocals.empty()) { 418 // Invert the map from local to index into a simple vector. There should be 419 // no holes. 420 SmallVector<llvm::Value *, 4> EscapeArgs; 421 EscapeArgs.resize(EscapedLocals.size()); 422 for (auto &Pair : EscapedLocals) 423 EscapeArgs[Pair.second] = Pair.first; 424 llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration( 425 &CGM.getModule(), llvm::Intrinsic::localescape); 426 CGBuilderTy(*this, AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs); 427 } 428 429 // Remove the AllocaInsertPt instruction, which is just a convenience for us. 430 llvm::Instruction *Ptr = AllocaInsertPt; 431 AllocaInsertPt = nullptr; 432 Ptr->eraseFromParent(); 433 434 // If someone took the address of a label but never did an indirect goto, we 435 // made a zero entry PHI node, which is illegal, zap it now. 436 if (IndirectBranch) { 437 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress()); 438 if (PN->getNumIncomingValues() == 0) { 439 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType())); 440 PN->eraseFromParent(); 441 } 442 } 443 444 EmitIfUsed(*this, EHResumeBlock); 445 EmitIfUsed(*this, TerminateLandingPad); 446 EmitIfUsed(*this, TerminateHandler); 447 EmitIfUsed(*this, UnreachableBlock); 448 449 for (const auto &FuncletAndParent : TerminateFunclets) 450 EmitIfUsed(*this, FuncletAndParent.second); 451 452 if (CGM.getCodeGenOpts().EmitDeclMetadata) 453 EmitDeclMetadata(); 454 455 for (SmallVectorImpl<std::pair<llvm::Instruction *, llvm::Value *> >::iterator 456 I = DeferredReplacements.begin(), 457 E = DeferredReplacements.end(); 458 I != E; ++I) { 459 I->first->replaceAllUsesWith(I->second); 460 I->first->eraseFromParent(); 461 } 462 463 // Eliminate CleanupDestSlot alloca by replacing it with SSA values and 464 // PHIs if the current function is a coroutine. We don't do it for all 465 // functions as it may result in slight increase in numbers of instructions 466 // if compiled with no optimizations. We do it for coroutine as the lifetime 467 // of CleanupDestSlot alloca make correct coroutine frame building very 468 // difficult. 469 if (NormalCleanupDest.isValid() && isCoroutine()) { 470 llvm::DominatorTree DT(*CurFn); 471 llvm::PromoteMemToReg( 472 cast<llvm::AllocaInst>(NormalCleanupDest.getPointer()), DT); 473 NormalCleanupDest = Address::invalid(); 474 } 475 476 // Scan function arguments for vector width. 477 for (llvm::Argument &A : CurFn->args()) 478 if (auto *VT = dyn_cast<llvm::VectorType>(A.getType())) 479 LargestVectorWidth = 480 std::max((uint64_t)LargestVectorWidth, 481 VT->getPrimitiveSizeInBits().getKnownMinSize()); 482 483 // Update vector width based on return type. 484 if (auto *VT = dyn_cast<llvm::VectorType>(CurFn->getReturnType())) 485 LargestVectorWidth = 486 std::max((uint64_t)LargestVectorWidth, 487 VT->getPrimitiveSizeInBits().getKnownMinSize()); 488 489 // Add the required-vector-width attribute. This contains the max width from: 490 // 1. min-vector-width attribute used in the source program. 491 // 2. Any builtins used that have a vector width specified. 492 // 3. Values passed in and out of inline assembly. 493 // 4. Width of vector arguments and return types for this function. 494 // 5. Width of vector aguments and return types for functions called by this 495 // function. 496 CurFn->addFnAttr("min-legal-vector-width", llvm::utostr(LargestVectorWidth)); 497 498 // If we generated an unreachable return block, delete it now. 499 if (ReturnBlock.isValid() && ReturnBlock.getBlock()->use_empty()) { 500 Builder.ClearInsertionPoint(); 501 ReturnBlock.getBlock()->eraseFromParent(); 502 } 503 if (ReturnValue.isValid()) { 504 auto *RetAlloca = dyn_cast<llvm::AllocaInst>(ReturnValue.getPointer()); 505 if (RetAlloca && RetAlloca->use_empty()) { 506 RetAlloca->eraseFromParent(); 507 ReturnValue = Address::invalid(); 508 } 509 } 510 } 511 512 /// ShouldInstrumentFunction - Return true if the current function should be 513 /// instrumented with __cyg_profile_func_* calls 514 bool CodeGenFunction::ShouldInstrumentFunction() { 515 if (!CGM.getCodeGenOpts().InstrumentFunctions && 516 !CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining && 517 !CGM.getCodeGenOpts().InstrumentFunctionEntryBare) 518 return false; 519 if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) 520 return false; 521 return true; 522 } 523 524 /// ShouldXRayInstrument - Return true if the current function should be 525 /// instrumented with XRay nop sleds. 526 bool CodeGenFunction::ShouldXRayInstrumentFunction() const { 527 return CGM.getCodeGenOpts().XRayInstrumentFunctions; 528 } 529 530 /// AlwaysEmitXRayCustomEvents - Return true if we should emit IR for calls to 531 /// the __xray_customevent(...) builtin calls, when doing XRay instrumentation. 532 bool CodeGenFunction::AlwaysEmitXRayCustomEvents() const { 533 return CGM.getCodeGenOpts().XRayInstrumentFunctions && 534 (CGM.getCodeGenOpts().XRayAlwaysEmitCustomEvents || 535 CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask == 536 XRayInstrKind::Custom); 537 } 538 539 bool CodeGenFunction::AlwaysEmitXRayTypedEvents() const { 540 return CGM.getCodeGenOpts().XRayInstrumentFunctions && 541 (CGM.getCodeGenOpts().XRayAlwaysEmitTypedEvents || 542 CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask == 543 XRayInstrKind::Typed); 544 } 545 546 llvm::Constant * 547 CodeGenFunction::EncodeAddrForUseInPrologue(llvm::Function *F, 548 llvm::Constant *Addr) { 549 // Addresses stored in prologue data can't require run-time fixups and must 550 // be PC-relative. Run-time fixups are undesirable because they necessitate 551 // writable text segments, which are unsafe. And absolute addresses are 552 // undesirable because they break PIE mode. 553 554 // Add a layer of indirection through a private global. Taking its address 555 // won't result in a run-time fixup, even if Addr has linkonce_odr linkage. 556 auto *GV = new llvm::GlobalVariable(CGM.getModule(), Addr->getType(), 557 /*isConstant=*/true, 558 llvm::GlobalValue::PrivateLinkage, Addr); 559 560 // Create a PC-relative address. 561 auto *GOTAsInt = llvm::ConstantExpr::getPtrToInt(GV, IntPtrTy); 562 auto *FuncAsInt = llvm::ConstantExpr::getPtrToInt(F, IntPtrTy); 563 auto *PCRelAsInt = llvm::ConstantExpr::getSub(GOTAsInt, FuncAsInt); 564 return (IntPtrTy == Int32Ty) 565 ? PCRelAsInt 566 : llvm::ConstantExpr::getTrunc(PCRelAsInt, Int32Ty); 567 } 568 569 llvm::Value * 570 CodeGenFunction::DecodeAddrUsedInPrologue(llvm::Value *F, 571 llvm::Value *EncodedAddr) { 572 // Reconstruct the address of the global. 573 auto *PCRelAsInt = Builder.CreateSExt(EncodedAddr, IntPtrTy); 574 auto *FuncAsInt = Builder.CreatePtrToInt(F, IntPtrTy, "func_addr.int"); 575 auto *GOTAsInt = Builder.CreateAdd(PCRelAsInt, FuncAsInt, "global_addr.int"); 576 auto *GOTAddr = Builder.CreateIntToPtr(GOTAsInt, Int8PtrPtrTy, "global_addr"); 577 578 // Load the original pointer through the global. 579 return Builder.CreateLoad(Address(GOTAddr, getPointerAlign()), 580 "decoded_addr"); 581 } 582 583 void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD, 584 llvm::Function *Fn) 585 { 586 if (!FD->hasAttr<OpenCLKernelAttr>()) 587 return; 588 589 llvm::LLVMContext &Context = getLLVMContext(); 590 591 CGM.GenOpenCLArgMetadata(Fn, FD, this); 592 593 if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) { 594 QualType HintQTy = A->getTypeHint(); 595 const ExtVectorType *HintEltQTy = HintQTy->getAs<ExtVectorType>(); 596 bool IsSignedInteger = 597 HintQTy->isSignedIntegerType() || 598 (HintEltQTy && HintEltQTy->getElementType()->isSignedIntegerType()); 599 llvm::Metadata *AttrMDArgs[] = { 600 llvm::ConstantAsMetadata::get(llvm::UndefValue::get( 601 CGM.getTypes().ConvertType(A->getTypeHint()))), 602 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 603 llvm::IntegerType::get(Context, 32), 604 llvm::APInt(32, (uint64_t)(IsSignedInteger ? 1 : 0))))}; 605 Fn->setMetadata("vec_type_hint", llvm::MDNode::get(Context, AttrMDArgs)); 606 } 607 608 if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) { 609 llvm::Metadata *AttrMDArgs[] = { 610 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())), 611 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())), 612 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))}; 613 Fn->setMetadata("work_group_size_hint", llvm::MDNode::get(Context, AttrMDArgs)); 614 } 615 616 if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) { 617 llvm::Metadata *AttrMDArgs[] = { 618 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())), 619 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())), 620 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))}; 621 Fn->setMetadata("reqd_work_group_size", llvm::MDNode::get(Context, AttrMDArgs)); 622 } 623 624 if (const OpenCLIntelReqdSubGroupSizeAttr *A = 625 FD->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) { 626 llvm::Metadata *AttrMDArgs[] = { 627 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getSubGroupSize()))}; 628 Fn->setMetadata("intel_reqd_sub_group_size", 629 llvm::MDNode::get(Context, AttrMDArgs)); 630 } 631 } 632 633 /// Determine whether the function F ends with a return stmt. 634 static bool endsWithReturn(const Decl* F) { 635 const Stmt *Body = nullptr; 636 if (auto *FD = dyn_cast_or_null<FunctionDecl>(F)) 637 Body = FD->getBody(); 638 else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F)) 639 Body = OMD->getBody(); 640 641 if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) { 642 auto LastStmt = CS->body_rbegin(); 643 if (LastStmt != CS->body_rend()) 644 return isa<ReturnStmt>(*LastStmt); 645 } 646 return false; 647 } 648 649 void CodeGenFunction::markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn) { 650 if (SanOpts.has(SanitizerKind::Thread)) { 651 Fn->addFnAttr("sanitize_thread_no_checking_at_run_time"); 652 Fn->removeFnAttr(llvm::Attribute::SanitizeThread); 653 } 654 } 655 656 /// Check if the return value of this function requires sanitization. 657 bool CodeGenFunction::requiresReturnValueCheck() const { 658 return requiresReturnValueNullabilityCheck() || 659 (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) && CurCodeDecl && 660 CurCodeDecl->getAttr<ReturnsNonNullAttr>()); 661 } 662 663 static bool matchesStlAllocatorFn(const Decl *D, const ASTContext &Ctx) { 664 auto *MD = dyn_cast_or_null<CXXMethodDecl>(D); 665 if (!MD || !MD->getDeclName().getAsIdentifierInfo() || 666 !MD->getDeclName().getAsIdentifierInfo()->isStr("allocate") || 667 (MD->getNumParams() != 1 && MD->getNumParams() != 2)) 668 return false; 669 670 if (MD->parameters()[0]->getType().getCanonicalType() != Ctx.getSizeType()) 671 return false; 672 673 if (MD->getNumParams() == 2) { 674 auto *PT = MD->parameters()[1]->getType()->getAs<PointerType>(); 675 if (!PT || !PT->isVoidPointerType() || 676 !PT->getPointeeType().isConstQualified()) 677 return false; 678 } 679 680 return true; 681 } 682 683 /// Return the UBSan prologue signature for \p FD if one is available. 684 static llvm::Constant *getPrologueSignature(CodeGenModule &CGM, 685 const FunctionDecl *FD) { 686 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 687 if (!MD->isStatic()) 688 return nullptr; 689 return CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM); 690 } 691 692 void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy, 693 llvm::Function *Fn, 694 const CGFunctionInfo &FnInfo, 695 const FunctionArgList &Args, 696 SourceLocation Loc, 697 SourceLocation StartLoc) { 698 assert(!CurFn && 699 "Do not use a CodeGenFunction object for more than one function"); 700 701 const Decl *D = GD.getDecl(); 702 703 DidCallStackSave = false; 704 CurCodeDecl = D; 705 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) 706 if (FD->usesSEHTry()) 707 CurSEHParent = FD; 708 CurFuncDecl = (D ? D->getNonClosureContext() : nullptr); 709 FnRetTy = RetTy; 710 CurFn = Fn; 711 CurFnInfo = &FnInfo; 712 assert(CurFn->isDeclaration() && "Function already has body?"); 713 714 // If this function has been blacklisted for any of the enabled sanitizers, 715 // disable the sanitizer for the function. 716 do { 717 #define SANITIZER(NAME, ID) \ 718 if (SanOpts.empty()) \ 719 break; \ 720 if (SanOpts.has(SanitizerKind::ID)) \ 721 if (CGM.isInSanitizerBlacklist(SanitizerKind::ID, Fn, Loc)) \ 722 SanOpts.set(SanitizerKind::ID, false); 723 724 #include "clang/Basic/Sanitizers.def" 725 #undef SANITIZER 726 } while (0); 727 728 if (D) { 729 // Apply the no_sanitize* attributes to SanOpts. 730 for (auto Attr : D->specific_attrs<NoSanitizeAttr>()) { 731 SanitizerMask mask = Attr->getMask(); 732 SanOpts.Mask &= ~mask; 733 if (mask & SanitizerKind::Address) 734 SanOpts.set(SanitizerKind::KernelAddress, false); 735 if (mask & SanitizerKind::KernelAddress) 736 SanOpts.set(SanitizerKind::Address, false); 737 if (mask & SanitizerKind::HWAddress) 738 SanOpts.set(SanitizerKind::KernelHWAddress, false); 739 if (mask & SanitizerKind::KernelHWAddress) 740 SanOpts.set(SanitizerKind::HWAddress, false); 741 } 742 } 743 744 // Apply sanitizer attributes to the function. 745 if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress)) 746 Fn->addFnAttr(llvm::Attribute::SanitizeAddress); 747 if (SanOpts.hasOneOf(SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress)) 748 Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress); 749 if (SanOpts.has(SanitizerKind::MemTag)) 750 Fn->addFnAttr(llvm::Attribute::SanitizeMemTag); 751 if (SanOpts.has(SanitizerKind::Thread)) 752 Fn->addFnAttr(llvm::Attribute::SanitizeThread); 753 if (SanOpts.hasOneOf(SanitizerKind::Memory | SanitizerKind::KernelMemory)) 754 Fn->addFnAttr(llvm::Attribute::SanitizeMemory); 755 if (SanOpts.has(SanitizerKind::SafeStack)) 756 Fn->addFnAttr(llvm::Attribute::SafeStack); 757 if (SanOpts.has(SanitizerKind::ShadowCallStack)) 758 Fn->addFnAttr(llvm::Attribute::ShadowCallStack); 759 760 // Apply fuzzing attribute to the function. 761 if (SanOpts.hasOneOf(SanitizerKind::Fuzzer | SanitizerKind::FuzzerNoLink)) 762 Fn->addFnAttr(llvm::Attribute::OptForFuzzing); 763 764 // Ignore TSan memory acesses from within ObjC/ObjC++ dealloc, initialize, 765 // .cxx_destruct, __destroy_helper_block_ and all of their calees at run time. 766 if (SanOpts.has(SanitizerKind::Thread)) { 767 if (const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) { 768 IdentifierInfo *II = OMD->getSelector().getIdentifierInfoForSlot(0); 769 if (OMD->getMethodFamily() == OMF_dealloc || 770 OMD->getMethodFamily() == OMF_initialize || 771 (OMD->getSelector().isUnarySelector() && II->isStr(".cxx_destruct"))) { 772 markAsIgnoreThreadCheckingAtRuntime(Fn); 773 } 774 } 775 } 776 777 // Ignore unrelated casts in STL allocate() since the allocator must cast 778 // from void* to T* before object initialization completes. Don't match on the 779 // namespace because not all allocators are in std:: 780 if (D && SanOpts.has(SanitizerKind::CFIUnrelatedCast)) { 781 if (matchesStlAllocatorFn(D, getContext())) 782 SanOpts.Mask &= ~SanitizerKind::CFIUnrelatedCast; 783 } 784 785 // Ignore null checks in coroutine functions since the coroutines passes 786 // are not aware of how to move the extra UBSan instructions across the split 787 // coroutine boundaries. 788 if (D && SanOpts.has(SanitizerKind::Null)) 789 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 790 if (FD->getBody() && 791 FD->getBody()->getStmtClass() == Stmt::CoroutineBodyStmtClass) 792 SanOpts.Mask &= ~SanitizerKind::Null; 793 794 // Apply xray attributes to the function (as a string, for now) 795 if (const auto *XRayAttr = D ? D->getAttr<XRayInstrumentAttr>() : nullptr) { 796 if (CGM.getCodeGenOpts().XRayInstrumentationBundle.has( 797 XRayInstrKind::FunctionEntry) || 798 CGM.getCodeGenOpts().XRayInstrumentationBundle.has( 799 XRayInstrKind::FunctionExit)) { 800 if (XRayAttr->alwaysXRayInstrument() && ShouldXRayInstrumentFunction()) 801 Fn->addFnAttr("function-instrument", "xray-always"); 802 if (XRayAttr->neverXRayInstrument()) 803 Fn->addFnAttr("function-instrument", "xray-never"); 804 if (const auto *LogArgs = D->getAttr<XRayLogArgsAttr>()) 805 if (ShouldXRayInstrumentFunction()) 806 Fn->addFnAttr("xray-log-args", 807 llvm::utostr(LogArgs->getArgumentCount())); 808 } 809 } else { 810 if (ShouldXRayInstrumentFunction() && !CGM.imbueXRayAttrs(Fn, Loc)) 811 Fn->addFnAttr( 812 "xray-instruction-threshold", 813 llvm::itostr(CGM.getCodeGenOpts().XRayInstructionThreshold)); 814 } 815 816 if (ShouldXRayInstrumentFunction()) { 817 if (CGM.getCodeGenOpts().XRayIgnoreLoops) 818 Fn->addFnAttr("xray-ignore-loops"); 819 820 if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has( 821 XRayInstrKind::FunctionExit)) 822 Fn->addFnAttr("xray-skip-exit"); 823 824 if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has( 825 XRayInstrKind::FunctionEntry)) 826 Fn->addFnAttr("xray-skip-entry"); 827 } 828 829 unsigned Count, Offset; 830 if (const auto *Attr = 831 D ? D->getAttr<PatchableFunctionEntryAttr>() : nullptr) { 832 Count = Attr->getCount(); 833 Offset = Attr->getOffset(); 834 } else { 835 Count = CGM.getCodeGenOpts().PatchableFunctionEntryCount; 836 Offset = CGM.getCodeGenOpts().PatchableFunctionEntryOffset; 837 } 838 if (Count && Offset <= Count) { 839 Fn->addFnAttr("patchable-function-entry", std::to_string(Count - Offset)); 840 if (Offset) 841 Fn->addFnAttr("patchable-function-prefix", std::to_string(Offset)); 842 } 843 844 // Add no-jump-tables value. 845 Fn->addFnAttr("no-jump-tables", 846 llvm::toStringRef(CGM.getCodeGenOpts().NoUseJumpTables)); 847 848 // Add no-inline-line-tables value. 849 if (CGM.getCodeGenOpts().NoInlineLineTables) 850 Fn->addFnAttr("no-inline-line-tables"); 851 852 // Add profile-sample-accurate value. 853 if (CGM.getCodeGenOpts().ProfileSampleAccurate) 854 Fn->addFnAttr("profile-sample-accurate"); 855 856 if (D && D->hasAttr<CFICanonicalJumpTableAttr>()) 857 Fn->addFnAttr("cfi-canonical-jump-table"); 858 859 if (getLangOpts().OpenCL) { 860 // Add metadata for a kernel function. 861 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) 862 EmitOpenCLKernelMetadata(FD, Fn); 863 } 864 865 // If we are checking function types, emit a function type signature as 866 // prologue data. 867 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function)) { 868 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 869 if (llvm::Constant *PrologueSig = getPrologueSignature(CGM, FD)) { 870 // Remove any (C++17) exception specifications, to allow calling e.g. a 871 // noexcept function through a non-noexcept pointer. 872 auto ProtoTy = 873 getContext().getFunctionTypeWithExceptionSpec(FD->getType(), 874 EST_None); 875 llvm::Constant *FTRTTIConst = 876 CGM.GetAddrOfRTTIDescriptor(ProtoTy, /*ForEH=*/true); 877 llvm::Constant *FTRTTIConstEncoded = 878 EncodeAddrForUseInPrologue(Fn, FTRTTIConst); 879 llvm::Constant *PrologueStructElems[] = {PrologueSig, 880 FTRTTIConstEncoded}; 881 llvm::Constant *PrologueStructConst = 882 llvm::ConstantStruct::getAnon(PrologueStructElems, /*Packed=*/true); 883 Fn->setPrologueData(PrologueStructConst); 884 } 885 } 886 } 887 888 // If we're checking nullability, we need to know whether we can check the 889 // return value. Initialize the flag to 'true' and refine it in EmitParmDecl. 890 if (SanOpts.has(SanitizerKind::NullabilityReturn)) { 891 auto Nullability = FnRetTy->getNullability(getContext()); 892 if (Nullability && *Nullability == NullabilityKind::NonNull) { 893 if (!(SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) && 894 CurCodeDecl && CurCodeDecl->getAttr<ReturnsNonNullAttr>())) 895 RetValNullabilityPrecondition = 896 llvm::ConstantInt::getTrue(getLLVMContext()); 897 } 898 } 899 900 // If we're in C++ mode and the function name is "main", it is guaranteed 901 // to be norecurse by the standard (3.6.1.3 "The function main shall not be 902 // used within a program"). 903 // 904 // OpenCL C 2.0 v2.2-11 s6.9.i: 905 // Recursion is not supported. 906 // 907 // SYCL v1.2.1 s3.10: 908 // kernels cannot include RTTI information, exception classes, 909 // recursive code, virtual functions or make use of C++ libraries that 910 // are not compiled for the device. 911 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 912 if ((getLangOpts().CPlusPlus && FD->isMain()) || getLangOpts().OpenCL || 913 getLangOpts().SYCLIsDevice || 914 (getLangOpts().CUDA && FD->hasAttr<CUDAGlobalAttr>())) 915 Fn->addFnAttr(llvm::Attribute::NoRecurse); 916 } 917 918 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 919 Builder.setIsFPConstrained(FD->usesFPIntrin()); 920 if (FD->usesFPIntrin()) 921 Fn->addFnAttr(llvm::Attribute::StrictFP); 922 } 923 924 // If a custom alignment is used, force realigning to this alignment on 925 // any main function which certainly will need it. 926 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) 927 if ((FD->isMain() || FD->isMSVCRTEntryPoint()) && 928 CGM.getCodeGenOpts().StackAlignment) 929 Fn->addFnAttr("stackrealign"); 930 931 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn); 932 933 // Create a marker to make it easy to insert allocas into the entryblock 934 // later. Don't create this with the builder, because we don't want it 935 // folded. 936 llvm::Value *Undef = llvm::UndefValue::get(Int32Ty); 937 AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "allocapt", EntryBB); 938 939 ReturnBlock = getJumpDestInCurrentScope("return"); 940 941 Builder.SetInsertPoint(EntryBB); 942 943 // If we're checking the return value, allocate space for a pointer to a 944 // precise source location of the checked return statement. 945 if (requiresReturnValueCheck()) { 946 ReturnLocation = CreateDefaultAlignTempAlloca(Int8PtrTy, "return.sloc.ptr"); 947 InitTempAlloca(ReturnLocation, llvm::ConstantPointerNull::get(Int8PtrTy)); 948 } 949 950 // Emit subprogram debug descriptor. 951 if (CGDebugInfo *DI = getDebugInfo()) { 952 // Reconstruct the type from the argument list so that implicit parameters, 953 // such as 'this' and 'vtt', show up in the debug info. Preserve the calling 954 // convention. 955 CallingConv CC = CallingConv::CC_C; 956 if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) 957 if (const auto *SrcFnTy = FD->getType()->getAs<FunctionType>()) 958 CC = SrcFnTy->getCallConv(); 959 SmallVector<QualType, 16> ArgTypes; 960 for (const VarDecl *VD : Args) 961 ArgTypes.push_back(VD->getType()); 962 QualType FnType = getContext().getFunctionType( 963 RetTy, ArgTypes, FunctionProtoType::ExtProtoInfo(CC)); 964 DI->EmitFunctionStart(GD, Loc, StartLoc, FnType, CurFn, CurFuncIsThunk, 965 Builder); 966 } 967 968 if (ShouldInstrumentFunction()) { 969 if (CGM.getCodeGenOpts().InstrumentFunctions) 970 CurFn->addFnAttr("instrument-function-entry", "__cyg_profile_func_enter"); 971 if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining) 972 CurFn->addFnAttr("instrument-function-entry-inlined", 973 "__cyg_profile_func_enter"); 974 if (CGM.getCodeGenOpts().InstrumentFunctionEntryBare) 975 CurFn->addFnAttr("instrument-function-entry-inlined", 976 "__cyg_profile_func_enter_bare"); 977 } 978 979 // Since emitting the mcount call here impacts optimizations such as function 980 // inlining, we just add an attribute to insert a mcount call in backend. 981 // The attribute "counting-function" is set to mcount function name which is 982 // architecture dependent. 983 if (CGM.getCodeGenOpts().InstrumentForProfiling) { 984 // Calls to fentry/mcount should not be generated if function has 985 // the no_instrument_function attribute. 986 if (!CurFuncDecl || !CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) { 987 if (CGM.getCodeGenOpts().CallFEntry) 988 Fn->addFnAttr("fentry-call", "true"); 989 else { 990 Fn->addFnAttr("instrument-function-entry-inlined", 991 getTarget().getMCountName()); 992 } 993 if (CGM.getCodeGenOpts().MNopMCount) { 994 if (!CGM.getCodeGenOpts().CallFEntry) 995 CGM.getDiags().Report(diag::err_opt_not_valid_without_opt) 996 << "-mnop-mcount" << "-mfentry"; 997 Fn->addFnAttr("mnop-mcount"); 998 } 999 1000 if (CGM.getCodeGenOpts().RecordMCount) { 1001 if (!CGM.getCodeGenOpts().CallFEntry) 1002 CGM.getDiags().Report(diag::err_opt_not_valid_without_opt) 1003 << "-mrecord-mcount" << "-mfentry"; 1004 Fn->addFnAttr("mrecord-mcount"); 1005 } 1006 } 1007 } 1008 1009 if (CGM.getCodeGenOpts().PackedStack) { 1010 if (getContext().getTargetInfo().getTriple().getArch() != 1011 llvm::Triple::systemz) 1012 CGM.getDiags().Report(diag::err_opt_not_valid_on_target) 1013 << "-mpacked-stack"; 1014 Fn->addFnAttr("packed-stack"); 1015 } 1016 1017 if (RetTy->isVoidType()) { 1018 // Void type; nothing to return. 1019 ReturnValue = Address::invalid(); 1020 1021 // Count the implicit return. 1022 if (!endsWithReturn(D)) 1023 ++NumReturnExprs; 1024 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect) { 1025 // Indirect return; emit returned value directly into sret slot. 1026 // This reduces code size, and affects correctness in C++. 1027 auto AI = CurFn->arg_begin(); 1028 if (CurFnInfo->getReturnInfo().isSRetAfterThis()) 1029 ++AI; 1030 ReturnValue = Address(&*AI, CurFnInfo->getReturnInfo().getIndirectAlign()); 1031 if (!CurFnInfo->getReturnInfo().getIndirectByVal()) { 1032 ReturnValuePointer = 1033 CreateDefaultAlignTempAlloca(Int8PtrTy, "result.ptr"); 1034 Builder.CreateStore(Builder.CreatePointerBitCastOrAddrSpaceCast( 1035 ReturnValue.getPointer(), Int8PtrTy), 1036 ReturnValuePointer); 1037 } 1038 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca && 1039 !hasScalarEvaluationKind(CurFnInfo->getReturnType())) { 1040 // Load the sret pointer from the argument struct and return into that. 1041 unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex(); 1042 llvm::Function::arg_iterator EI = CurFn->arg_end(); 1043 --EI; 1044 llvm::Value *Addr = Builder.CreateStructGEP(nullptr, &*EI, Idx); 1045 ReturnValuePointer = Address(Addr, getPointerAlign()); 1046 Addr = Builder.CreateAlignedLoad(Addr, getPointerAlign(), "agg.result"); 1047 ReturnValue = Address(Addr, getNaturalTypeAlignment(RetTy)); 1048 } else { 1049 ReturnValue = CreateIRTemp(RetTy, "retval"); 1050 1051 // Tell the epilog emitter to autorelease the result. We do this 1052 // now so that various specialized functions can suppress it 1053 // during their IR-generation. 1054 if (getLangOpts().ObjCAutoRefCount && 1055 !CurFnInfo->isReturnsRetained() && 1056 RetTy->isObjCRetainableType()) 1057 AutoreleaseResult = true; 1058 } 1059 1060 EmitStartEHSpec(CurCodeDecl); 1061 1062 PrologueCleanupDepth = EHStack.stable_begin(); 1063 1064 // Emit OpenMP specific initialization of the device functions. 1065 if (getLangOpts().OpenMP && CurCodeDecl) 1066 CGM.getOpenMPRuntime().emitFunctionProlog(*this, CurCodeDecl); 1067 1068 EmitFunctionProlog(*CurFnInfo, CurFn, Args); 1069 1070 if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) { 1071 CGM.getCXXABI().EmitInstanceFunctionProlog(*this); 1072 const CXXMethodDecl *MD = cast<CXXMethodDecl>(D); 1073 if (MD->getParent()->isLambda() && 1074 MD->getOverloadedOperator() == OO_Call) { 1075 // We're in a lambda; figure out the captures. 1076 MD->getParent()->getCaptureFields(LambdaCaptureFields, 1077 LambdaThisCaptureField); 1078 if (LambdaThisCaptureField) { 1079 // If the lambda captures the object referred to by '*this' - either by 1080 // value or by reference, make sure CXXThisValue points to the correct 1081 // object. 1082 1083 // Get the lvalue for the field (which is a copy of the enclosing object 1084 // or contains the address of the enclosing object). 1085 LValue ThisFieldLValue = EmitLValueForLambdaField(LambdaThisCaptureField); 1086 if (!LambdaThisCaptureField->getType()->isPointerType()) { 1087 // If the enclosing object was captured by value, just use its address. 1088 CXXThisValue = ThisFieldLValue.getAddress(*this).getPointer(); 1089 } else { 1090 // Load the lvalue pointed to by the field, since '*this' was captured 1091 // by reference. 1092 CXXThisValue = 1093 EmitLoadOfLValue(ThisFieldLValue, SourceLocation()).getScalarVal(); 1094 } 1095 } 1096 for (auto *FD : MD->getParent()->fields()) { 1097 if (FD->hasCapturedVLAType()) { 1098 auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD), 1099 SourceLocation()).getScalarVal(); 1100 auto VAT = FD->getCapturedVLAType(); 1101 VLASizeMap[VAT->getSizeExpr()] = ExprArg; 1102 } 1103 } 1104 } else { 1105 // Not in a lambda; just use 'this' from the method. 1106 // FIXME: Should we generate a new load for each use of 'this'? The 1107 // fast register allocator would be happier... 1108 CXXThisValue = CXXABIThisValue; 1109 } 1110 1111 // Check the 'this' pointer once per function, if it's available. 1112 if (CXXABIThisValue) { 1113 SanitizerSet SkippedChecks; 1114 SkippedChecks.set(SanitizerKind::ObjectSize, true); 1115 QualType ThisTy = MD->getThisType(); 1116 1117 // If this is the call operator of a lambda with no capture-default, it 1118 // may have a static invoker function, which may call this operator with 1119 // a null 'this' pointer. 1120 if (isLambdaCallOperator(MD) && 1121 MD->getParent()->getLambdaCaptureDefault() == LCD_None) 1122 SkippedChecks.set(SanitizerKind::Null, true); 1123 1124 EmitTypeCheck(isa<CXXConstructorDecl>(MD) ? TCK_ConstructorCall 1125 : TCK_MemberCall, 1126 Loc, CXXABIThisValue, ThisTy, 1127 getContext().getTypeAlignInChars(ThisTy->getPointeeType()), 1128 SkippedChecks); 1129 } 1130 } 1131 1132 // If any of the arguments have a variably modified type, make sure to 1133 // emit the type size. 1134 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end(); 1135 i != e; ++i) { 1136 const VarDecl *VD = *i; 1137 1138 // Dig out the type as written from ParmVarDecls; it's unclear whether 1139 // the standard (C99 6.9.1p10) requires this, but we're following the 1140 // precedent set by gcc. 1141 QualType Ty; 1142 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) 1143 Ty = PVD->getOriginalType(); 1144 else 1145 Ty = VD->getType(); 1146 1147 if (Ty->isVariablyModifiedType()) 1148 EmitVariablyModifiedType(Ty); 1149 } 1150 // Emit a location at the end of the prologue. 1151 if (CGDebugInfo *DI = getDebugInfo()) 1152 DI->EmitLocation(Builder, StartLoc); 1153 1154 // TODO: Do we need to handle this in two places like we do with 1155 // target-features/target-cpu? 1156 if (CurFuncDecl) 1157 if (const auto *VecWidth = CurFuncDecl->getAttr<MinVectorWidthAttr>()) 1158 LargestVectorWidth = VecWidth->getVectorWidth(); 1159 } 1160 1161 void CodeGenFunction::EmitFunctionBody(const Stmt *Body) { 1162 incrementProfileCounter(Body); 1163 if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body)) 1164 EmitCompoundStmtWithoutScope(*S); 1165 else 1166 EmitStmt(Body); 1167 } 1168 1169 /// When instrumenting to collect profile data, the counts for some blocks 1170 /// such as switch cases need to not include the fall-through counts, so 1171 /// emit a branch around the instrumentation code. When not instrumenting, 1172 /// this just calls EmitBlock(). 1173 void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB, 1174 const Stmt *S) { 1175 llvm::BasicBlock *SkipCountBB = nullptr; 1176 if (HaveInsertPoint() && CGM.getCodeGenOpts().hasProfileClangInstr()) { 1177 // When instrumenting for profiling, the fallthrough to certain 1178 // statements needs to skip over the instrumentation code so that we 1179 // get an accurate count. 1180 SkipCountBB = createBasicBlock("skipcount"); 1181 EmitBranch(SkipCountBB); 1182 } 1183 EmitBlock(BB); 1184 uint64_t CurrentCount = getCurrentProfileCount(); 1185 incrementProfileCounter(S); 1186 setCurrentProfileCount(getCurrentProfileCount() + CurrentCount); 1187 if (SkipCountBB) 1188 EmitBlock(SkipCountBB); 1189 } 1190 1191 /// Tries to mark the given function nounwind based on the 1192 /// non-existence of any throwing calls within it. We believe this is 1193 /// lightweight enough to do at -O0. 1194 static void TryMarkNoThrow(llvm::Function *F) { 1195 // LLVM treats 'nounwind' on a function as part of the type, so we 1196 // can't do this on functions that can be overwritten. 1197 if (F->isInterposable()) return; 1198 1199 for (llvm::BasicBlock &BB : *F) 1200 for (llvm::Instruction &I : BB) 1201 if (I.mayThrow()) 1202 return; 1203 1204 F->setDoesNotThrow(); 1205 } 1206 1207 QualType CodeGenFunction::BuildFunctionArgList(GlobalDecl GD, 1208 FunctionArgList &Args) { 1209 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 1210 QualType ResTy = FD->getReturnType(); 1211 1212 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 1213 if (MD && MD->isInstance()) { 1214 if (CGM.getCXXABI().HasThisReturn(GD)) 1215 ResTy = MD->getThisType(); 1216 else if (CGM.getCXXABI().hasMostDerivedReturn(GD)) 1217 ResTy = CGM.getContext().VoidPtrTy; 1218 CGM.getCXXABI().buildThisParam(*this, Args); 1219 } 1220 1221 // The base version of an inheriting constructor whose constructed base is a 1222 // virtual base is not passed any arguments (because it doesn't actually call 1223 // the inherited constructor). 1224 bool PassedParams = true; 1225 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 1226 if (auto Inherited = CD->getInheritedConstructor()) 1227 PassedParams = 1228 getTypes().inheritingCtorHasParams(Inherited, GD.getCtorType()); 1229 1230 if (PassedParams) { 1231 for (auto *Param : FD->parameters()) { 1232 Args.push_back(Param); 1233 if (!Param->hasAttr<PassObjectSizeAttr>()) 1234 continue; 1235 1236 auto *Implicit = ImplicitParamDecl::Create( 1237 getContext(), Param->getDeclContext(), Param->getLocation(), 1238 /*Id=*/nullptr, getContext().getSizeType(), ImplicitParamDecl::Other); 1239 SizeArguments[Param] = Implicit; 1240 Args.push_back(Implicit); 1241 } 1242 } 1243 1244 if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD))) 1245 CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args); 1246 1247 return ResTy; 1248 } 1249 1250 static bool 1251 shouldUseUndefinedBehaviorReturnOptimization(const FunctionDecl *FD, 1252 const ASTContext &Context) { 1253 QualType T = FD->getReturnType(); 1254 // Avoid the optimization for functions that return a record type with a 1255 // trivial destructor or another trivially copyable type. 1256 if (const RecordType *RT = T.getCanonicalType()->getAs<RecordType>()) { 1257 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) 1258 return !ClassDecl->hasTrivialDestructor(); 1259 } 1260 return !T.isTriviallyCopyableType(Context); 1261 } 1262 1263 void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn, 1264 const CGFunctionInfo &FnInfo) { 1265 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 1266 CurGD = GD; 1267 1268 FunctionArgList Args; 1269 QualType ResTy = BuildFunctionArgList(GD, Args); 1270 1271 // Check if we should generate debug info for this function. 1272 if (FD->hasAttr<NoDebugAttr>()) 1273 DebugInfo = nullptr; // disable debug info indefinitely for this function 1274 1275 // The function might not have a body if we're generating thunks for a 1276 // function declaration. 1277 SourceRange BodyRange; 1278 if (Stmt *Body = FD->getBody()) 1279 BodyRange = Body->getSourceRange(); 1280 else 1281 BodyRange = FD->getLocation(); 1282 CurEHLocation = BodyRange.getEnd(); 1283 1284 // Use the location of the start of the function to determine where 1285 // the function definition is located. By default use the location 1286 // of the declaration as the location for the subprogram. A function 1287 // may lack a declaration in the source code if it is created by code 1288 // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk). 1289 SourceLocation Loc = FD->getLocation(); 1290 1291 // If this is a function specialization then use the pattern body 1292 // as the location for the function. 1293 if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern()) 1294 if (SpecDecl->hasBody(SpecDecl)) 1295 Loc = SpecDecl->getLocation(); 1296 1297 Stmt *Body = FD->getBody(); 1298 1299 // Initialize helper which will detect jumps which can cause invalid lifetime 1300 // markers. 1301 if (Body && ShouldEmitLifetimeMarkers) 1302 Bypasses.Init(Body); 1303 1304 // Emit the standard function prologue. 1305 StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin()); 1306 1307 // Generate the body of the function. 1308 PGO.assignRegionCounters(GD, CurFn); 1309 if (isa<CXXDestructorDecl>(FD)) 1310 EmitDestructorBody(Args); 1311 else if (isa<CXXConstructorDecl>(FD)) 1312 EmitConstructorBody(Args); 1313 else if (getLangOpts().CUDA && 1314 !getLangOpts().CUDAIsDevice && 1315 FD->hasAttr<CUDAGlobalAttr>()) 1316 CGM.getCUDARuntime().emitDeviceStub(*this, Args); 1317 else if (isa<CXXMethodDecl>(FD) && 1318 cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) { 1319 // The lambda static invoker function is special, because it forwards or 1320 // clones the body of the function call operator (but is actually static). 1321 EmitLambdaStaticInvokeBody(cast<CXXMethodDecl>(FD)); 1322 } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) && 1323 (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() || 1324 cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) { 1325 // Implicit copy-assignment gets the same special treatment as implicit 1326 // copy-constructors. 1327 emitImplicitAssignmentOperatorBody(Args); 1328 } else if (Body) { 1329 EmitFunctionBody(Body); 1330 } else 1331 llvm_unreachable("no definition for emitted function"); 1332 1333 // C++11 [stmt.return]p2: 1334 // Flowing off the end of a function [...] results in undefined behavior in 1335 // a value-returning function. 1336 // C11 6.9.1p12: 1337 // If the '}' that terminates a function is reached, and the value of the 1338 // function call is used by the caller, the behavior is undefined. 1339 if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock && 1340 !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) { 1341 bool ShouldEmitUnreachable = 1342 CGM.getCodeGenOpts().StrictReturn || 1343 shouldUseUndefinedBehaviorReturnOptimization(FD, getContext()); 1344 if (SanOpts.has(SanitizerKind::Return)) { 1345 SanitizerScope SanScope(this); 1346 llvm::Value *IsFalse = Builder.getFalse(); 1347 EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return), 1348 SanitizerHandler::MissingReturn, 1349 EmitCheckSourceLocation(FD->getLocation()), None); 1350 } else if (ShouldEmitUnreachable) { 1351 if (CGM.getCodeGenOpts().OptimizationLevel == 0) 1352 EmitTrapCall(llvm::Intrinsic::trap); 1353 } 1354 if (SanOpts.has(SanitizerKind::Return) || ShouldEmitUnreachable) { 1355 Builder.CreateUnreachable(); 1356 Builder.ClearInsertionPoint(); 1357 } 1358 } 1359 1360 // Emit the standard function epilogue. 1361 FinishFunction(BodyRange.getEnd()); 1362 1363 // If we haven't marked the function nothrow through other means, do 1364 // a quick pass now to see if we can. 1365 if (!CurFn->doesNotThrow()) 1366 TryMarkNoThrow(CurFn); 1367 } 1368 1369 /// ContainsLabel - Return true if the statement contains a label in it. If 1370 /// this statement is not executed normally, it not containing a label means 1371 /// that we can just remove the code. 1372 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) { 1373 // Null statement, not a label! 1374 if (!S) return false; 1375 1376 // If this is a label, we have to emit the code, consider something like: 1377 // if (0) { ... foo: bar(); } goto foo; 1378 // 1379 // TODO: If anyone cared, we could track __label__'s, since we know that you 1380 // can't jump to one from outside their declared region. 1381 if (isa<LabelStmt>(S)) 1382 return true; 1383 1384 // If this is a case/default statement, and we haven't seen a switch, we have 1385 // to emit the code. 1386 if (isa<SwitchCase>(S) && !IgnoreCaseStmts) 1387 return true; 1388 1389 // If this is a switch statement, we want to ignore cases below it. 1390 if (isa<SwitchStmt>(S)) 1391 IgnoreCaseStmts = true; 1392 1393 // Scan subexpressions for verboten labels. 1394 for (const Stmt *SubStmt : S->children()) 1395 if (ContainsLabel(SubStmt, IgnoreCaseStmts)) 1396 return true; 1397 1398 return false; 1399 } 1400 1401 /// containsBreak - Return true if the statement contains a break out of it. 1402 /// If the statement (recursively) contains a switch or loop with a break 1403 /// inside of it, this is fine. 1404 bool CodeGenFunction::containsBreak(const Stmt *S) { 1405 // Null statement, not a label! 1406 if (!S) return false; 1407 1408 // If this is a switch or loop that defines its own break scope, then we can 1409 // include it and anything inside of it. 1410 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) || 1411 isa<ForStmt>(S)) 1412 return false; 1413 1414 if (isa<BreakStmt>(S)) 1415 return true; 1416 1417 // Scan subexpressions for verboten breaks. 1418 for (const Stmt *SubStmt : S->children()) 1419 if (containsBreak(SubStmt)) 1420 return true; 1421 1422 return false; 1423 } 1424 1425 bool CodeGenFunction::mightAddDeclToScope(const Stmt *S) { 1426 if (!S) return false; 1427 1428 // Some statement kinds add a scope and thus never add a decl to the current 1429 // scope. Note, this list is longer than the list of statements that might 1430 // have an unscoped decl nested within them, but this way is conservatively 1431 // correct even if more statement kinds are added. 1432 if (isa<IfStmt>(S) || isa<SwitchStmt>(S) || isa<WhileStmt>(S) || 1433 isa<DoStmt>(S) || isa<ForStmt>(S) || isa<CompoundStmt>(S) || 1434 isa<CXXForRangeStmt>(S) || isa<CXXTryStmt>(S) || 1435 isa<ObjCForCollectionStmt>(S) || isa<ObjCAtTryStmt>(S)) 1436 return false; 1437 1438 if (isa<DeclStmt>(S)) 1439 return true; 1440 1441 for (const Stmt *SubStmt : S->children()) 1442 if (mightAddDeclToScope(SubStmt)) 1443 return true; 1444 1445 return false; 1446 } 1447 1448 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 1449 /// to a constant, or if it does but contains a label, return false. If it 1450 /// constant folds return true and set the boolean result in Result. 1451 bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond, 1452 bool &ResultBool, 1453 bool AllowLabels) { 1454 llvm::APSInt ResultInt; 1455 if (!ConstantFoldsToSimpleInteger(Cond, ResultInt, AllowLabels)) 1456 return false; 1457 1458 ResultBool = ResultInt.getBoolValue(); 1459 return true; 1460 } 1461 1462 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 1463 /// to a constant, or if it does but contains a label, return false. If it 1464 /// constant folds return true and set the folded value. 1465 bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond, 1466 llvm::APSInt &ResultInt, 1467 bool AllowLabels) { 1468 // FIXME: Rename and handle conversion of other evaluatable things 1469 // to bool. 1470 Expr::EvalResult Result; 1471 if (!Cond->EvaluateAsInt(Result, getContext())) 1472 return false; // Not foldable, not integer or not fully evaluatable. 1473 1474 llvm::APSInt Int = Result.Val.getInt(); 1475 if (!AllowLabels && CodeGenFunction::ContainsLabel(Cond)) 1476 return false; // Contains a label. 1477 1478 ResultInt = Int; 1479 return true; 1480 } 1481 1482 1483 1484 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if 1485 /// statement) to the specified blocks. Based on the condition, this might try 1486 /// to simplify the codegen of the conditional based on the branch. 1487 /// 1488 void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond, 1489 llvm::BasicBlock *TrueBlock, 1490 llvm::BasicBlock *FalseBlock, 1491 uint64_t TrueCount) { 1492 Cond = Cond->IgnoreParens(); 1493 1494 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) { 1495 1496 // Handle X && Y in a condition. 1497 if (CondBOp->getOpcode() == BO_LAnd) { 1498 // If we have "1 && X", simplify the code. "0 && X" would have constant 1499 // folded if the case was simple enough. 1500 bool ConstantBool = false; 1501 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) && 1502 ConstantBool) { 1503 // br(1 && X) -> br(X). 1504 incrementProfileCounter(CondBOp); 1505 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, 1506 TrueCount); 1507 } 1508 1509 // If we have "X && 1", simplify the code to use an uncond branch. 1510 // "X && 0" would have been constant folded to 0. 1511 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) && 1512 ConstantBool) { 1513 // br(X && 1) -> br(X). 1514 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock, 1515 TrueCount); 1516 } 1517 1518 // Emit the LHS as a conditional. If the LHS conditional is false, we 1519 // want to jump to the FalseBlock. 1520 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true"); 1521 // The counter tells us how often we evaluate RHS, and all of TrueCount 1522 // can be propagated to that branch. 1523 uint64_t RHSCount = getProfileCount(CondBOp->getRHS()); 1524 1525 ConditionalEvaluation eval(*this); 1526 { 1527 ApplyDebugLocation DL(*this, Cond); 1528 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount); 1529 EmitBlock(LHSTrue); 1530 } 1531 1532 incrementProfileCounter(CondBOp); 1533 setCurrentProfileCount(getProfileCount(CondBOp->getRHS())); 1534 1535 // Any temporaries created here are conditional. 1536 eval.begin(*this); 1537 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, TrueCount); 1538 eval.end(*this); 1539 1540 return; 1541 } 1542 1543 if (CondBOp->getOpcode() == BO_LOr) { 1544 // If we have "0 || X", simplify the code. "1 || X" would have constant 1545 // folded if the case was simple enough. 1546 bool ConstantBool = false; 1547 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) && 1548 !ConstantBool) { 1549 // br(0 || X) -> br(X). 1550 incrementProfileCounter(CondBOp); 1551 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, 1552 TrueCount); 1553 } 1554 1555 // If we have "X || 0", simplify the code to use an uncond branch. 1556 // "X || 1" would have been constant folded to 1. 1557 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) && 1558 !ConstantBool) { 1559 // br(X || 0) -> br(X). 1560 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock, 1561 TrueCount); 1562 } 1563 1564 // Emit the LHS as a conditional. If the LHS conditional is true, we 1565 // want to jump to the TrueBlock. 1566 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false"); 1567 // We have the count for entry to the RHS and for the whole expression 1568 // being true, so we can divy up True count between the short circuit and 1569 // the RHS. 1570 uint64_t LHSCount = 1571 getCurrentProfileCount() - getProfileCount(CondBOp->getRHS()); 1572 uint64_t RHSCount = TrueCount - LHSCount; 1573 1574 ConditionalEvaluation eval(*this); 1575 { 1576 ApplyDebugLocation DL(*this, Cond); 1577 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount); 1578 EmitBlock(LHSFalse); 1579 } 1580 1581 incrementProfileCounter(CondBOp); 1582 setCurrentProfileCount(getProfileCount(CondBOp->getRHS())); 1583 1584 // Any temporaries created here are conditional. 1585 eval.begin(*this); 1586 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, RHSCount); 1587 1588 eval.end(*this); 1589 1590 return; 1591 } 1592 } 1593 1594 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) { 1595 // br(!x, t, f) -> br(x, f, t) 1596 if (CondUOp->getOpcode() == UO_LNot) { 1597 // Negate the count. 1598 uint64_t FalseCount = getCurrentProfileCount() - TrueCount; 1599 // Negate the condition and swap the destination blocks. 1600 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock, 1601 FalseCount); 1602 } 1603 } 1604 1605 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) { 1606 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f)) 1607 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true"); 1608 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false"); 1609 1610 ConditionalEvaluation cond(*this); 1611 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock, 1612 getProfileCount(CondOp)); 1613 1614 // When computing PGO branch weights, we only know the overall count for 1615 // the true block. This code is essentially doing tail duplication of the 1616 // naive code-gen, introducing new edges for which counts are not 1617 // available. Divide the counts proportionally between the LHS and RHS of 1618 // the conditional operator. 1619 uint64_t LHSScaledTrueCount = 0; 1620 if (TrueCount) { 1621 double LHSRatio = 1622 getProfileCount(CondOp) / (double)getCurrentProfileCount(); 1623 LHSScaledTrueCount = TrueCount * LHSRatio; 1624 } 1625 1626 cond.begin(*this); 1627 EmitBlock(LHSBlock); 1628 incrementProfileCounter(CondOp); 1629 { 1630 ApplyDebugLocation DL(*this, Cond); 1631 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock, 1632 LHSScaledTrueCount); 1633 } 1634 cond.end(*this); 1635 1636 cond.begin(*this); 1637 EmitBlock(RHSBlock); 1638 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock, 1639 TrueCount - LHSScaledTrueCount); 1640 cond.end(*this); 1641 1642 return; 1643 } 1644 1645 if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) { 1646 // Conditional operator handling can give us a throw expression as a 1647 // condition for a case like: 1648 // br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f) 1649 // Fold this to: 1650 // br(c, throw x, br(y, t, f)) 1651 EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false); 1652 return; 1653 } 1654 1655 // If the branch has a condition wrapped by __builtin_unpredictable, 1656 // create metadata that specifies that the branch is unpredictable. 1657 // Don't bother if not optimizing because that metadata would not be used. 1658 llvm::MDNode *Unpredictable = nullptr; 1659 auto *Call = dyn_cast<CallExpr>(Cond->IgnoreImpCasts()); 1660 if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) { 1661 auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl()); 1662 if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) { 1663 llvm::MDBuilder MDHelper(getLLVMContext()); 1664 Unpredictable = MDHelper.createUnpredictable(); 1665 } 1666 } 1667 1668 // Create branch weights based on the number of times we get here and the 1669 // number of times the condition should be true. 1670 uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount); 1671 llvm::MDNode *Weights = 1672 createProfileWeights(TrueCount, CurrentCount - TrueCount); 1673 1674 // Emit the code with the fully general case. 1675 llvm::Value *CondV; 1676 { 1677 ApplyDebugLocation DL(*this, Cond); 1678 CondV = EvaluateExprAsBool(Cond); 1679 } 1680 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable); 1681 } 1682 1683 /// ErrorUnsupported - Print out an error that codegen doesn't support the 1684 /// specified stmt yet. 1685 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) { 1686 CGM.ErrorUnsupported(S, Type); 1687 } 1688 1689 /// emitNonZeroVLAInit - Emit the "zero" initialization of a 1690 /// variable-length array whose elements have a non-zero bit-pattern. 1691 /// 1692 /// \param baseType the inner-most element type of the array 1693 /// \param src - a char* pointing to the bit-pattern for a single 1694 /// base element of the array 1695 /// \param sizeInChars - the total size of the VLA, in chars 1696 static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType, 1697 Address dest, Address src, 1698 llvm::Value *sizeInChars) { 1699 CGBuilderTy &Builder = CGF.Builder; 1700 1701 CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType); 1702 llvm::Value *baseSizeInChars 1703 = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity()); 1704 1705 Address begin = 1706 Builder.CreateElementBitCast(dest, CGF.Int8Ty, "vla.begin"); 1707 llvm::Value *end = 1708 Builder.CreateInBoundsGEP(begin.getPointer(), sizeInChars, "vla.end"); 1709 1710 llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock(); 1711 llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop"); 1712 llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont"); 1713 1714 // Make a loop over the VLA. C99 guarantees that the VLA element 1715 // count must be nonzero. 1716 CGF.EmitBlock(loopBB); 1717 1718 llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur"); 1719 cur->addIncoming(begin.getPointer(), originBB); 1720 1721 CharUnits curAlign = 1722 dest.getAlignment().alignmentOfArrayElement(baseSize); 1723 1724 // memcpy the individual element bit-pattern. 1725 Builder.CreateMemCpy(Address(cur, curAlign), src, baseSizeInChars, 1726 /*volatile*/ false); 1727 1728 // Go to the next element. 1729 llvm::Value *next = 1730 Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next"); 1731 1732 // Leave if that's the end of the VLA. 1733 llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone"); 1734 Builder.CreateCondBr(done, contBB, loopBB); 1735 cur->addIncoming(next, loopBB); 1736 1737 CGF.EmitBlock(contBB); 1738 } 1739 1740 void 1741 CodeGenFunction::EmitNullInitialization(Address DestPtr, QualType Ty) { 1742 // Ignore empty classes in C++. 1743 if (getLangOpts().CPlusPlus) { 1744 if (const RecordType *RT = Ty->getAs<RecordType>()) { 1745 if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty()) 1746 return; 1747 } 1748 } 1749 1750 // Cast the dest ptr to the appropriate i8 pointer type. 1751 if (DestPtr.getElementType() != Int8Ty) 1752 DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty); 1753 1754 // Get size and alignment info for this aggregate. 1755 CharUnits size = getContext().getTypeSizeInChars(Ty); 1756 1757 llvm::Value *SizeVal; 1758 const VariableArrayType *vla; 1759 1760 // Don't bother emitting a zero-byte memset. 1761 if (size.isZero()) { 1762 // But note that getTypeInfo returns 0 for a VLA. 1763 if (const VariableArrayType *vlaType = 1764 dyn_cast_or_null<VariableArrayType>( 1765 getContext().getAsArrayType(Ty))) { 1766 auto VlaSize = getVLASize(vlaType); 1767 SizeVal = VlaSize.NumElts; 1768 CharUnits eltSize = getContext().getTypeSizeInChars(VlaSize.Type); 1769 if (!eltSize.isOne()) 1770 SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize)); 1771 vla = vlaType; 1772 } else { 1773 return; 1774 } 1775 } else { 1776 SizeVal = CGM.getSize(size); 1777 vla = nullptr; 1778 } 1779 1780 // If the type contains a pointer to data member we can't memset it to zero. 1781 // Instead, create a null constant and copy it to the destination. 1782 // TODO: there are other patterns besides zero that we can usefully memset, 1783 // like -1, which happens to be the pattern used by member-pointers. 1784 if (!CGM.getTypes().isZeroInitializable(Ty)) { 1785 // For a VLA, emit a single element, then splat that over the VLA. 1786 if (vla) Ty = getContext().getBaseElementType(vla); 1787 1788 llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty); 1789 1790 llvm::GlobalVariable *NullVariable = 1791 new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(), 1792 /*isConstant=*/true, 1793 llvm::GlobalVariable::PrivateLinkage, 1794 NullConstant, Twine()); 1795 CharUnits NullAlign = DestPtr.getAlignment(); 1796 NullVariable->setAlignment(NullAlign.getAsAlign()); 1797 Address SrcPtr(Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy()), 1798 NullAlign); 1799 1800 if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal); 1801 1802 // Get and call the appropriate llvm.memcpy overload. 1803 Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false); 1804 return; 1805 } 1806 1807 // Otherwise, just memset the whole thing to zero. This is legal 1808 // because in LLVM, all default initializers (other than the ones we just 1809 // handled above) are guaranteed to have a bit pattern of all zeros. 1810 Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false); 1811 } 1812 1813 llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) { 1814 // Make sure that there is a block for the indirect goto. 1815 if (!IndirectBranch) 1816 GetIndirectGotoBlock(); 1817 1818 llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock(); 1819 1820 // Make sure the indirect branch includes all of the address-taken blocks. 1821 IndirectBranch->addDestination(BB); 1822 return llvm::BlockAddress::get(CurFn, BB); 1823 } 1824 1825 llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() { 1826 // If we already made the indirect branch for indirect goto, return its block. 1827 if (IndirectBranch) return IndirectBranch->getParent(); 1828 1829 CGBuilderTy TmpBuilder(*this, createBasicBlock("indirectgoto")); 1830 1831 // Create the PHI node that indirect gotos will add entries to. 1832 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0, 1833 "indirect.goto.dest"); 1834 1835 // Create the indirect branch instruction. 1836 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal); 1837 return IndirectBranch->getParent(); 1838 } 1839 1840 /// Computes the length of an array in elements, as well as the base 1841 /// element type and a properly-typed first element pointer. 1842 llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType, 1843 QualType &baseType, 1844 Address &addr) { 1845 const ArrayType *arrayType = origArrayType; 1846 1847 // If it's a VLA, we have to load the stored size. Note that 1848 // this is the size of the VLA in bytes, not its size in elements. 1849 llvm::Value *numVLAElements = nullptr; 1850 if (isa<VariableArrayType>(arrayType)) { 1851 numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).NumElts; 1852 1853 // Walk into all VLAs. This doesn't require changes to addr, 1854 // which has type T* where T is the first non-VLA element type. 1855 do { 1856 QualType elementType = arrayType->getElementType(); 1857 arrayType = getContext().getAsArrayType(elementType); 1858 1859 // If we only have VLA components, 'addr' requires no adjustment. 1860 if (!arrayType) { 1861 baseType = elementType; 1862 return numVLAElements; 1863 } 1864 } while (isa<VariableArrayType>(arrayType)); 1865 1866 // We get out here only if we find a constant array type 1867 // inside the VLA. 1868 } 1869 1870 // We have some number of constant-length arrays, so addr should 1871 // have LLVM type [M x [N x [...]]]*. Build a GEP that walks 1872 // down to the first element of addr. 1873 SmallVector<llvm::Value*, 8> gepIndices; 1874 1875 // GEP down to the array type. 1876 llvm::ConstantInt *zero = Builder.getInt32(0); 1877 gepIndices.push_back(zero); 1878 1879 uint64_t countFromCLAs = 1; 1880 QualType eltType; 1881 1882 llvm::ArrayType *llvmArrayType = 1883 dyn_cast<llvm::ArrayType>(addr.getElementType()); 1884 while (llvmArrayType) { 1885 assert(isa<ConstantArrayType>(arrayType)); 1886 assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue() 1887 == llvmArrayType->getNumElements()); 1888 1889 gepIndices.push_back(zero); 1890 countFromCLAs *= llvmArrayType->getNumElements(); 1891 eltType = arrayType->getElementType(); 1892 1893 llvmArrayType = 1894 dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType()); 1895 arrayType = getContext().getAsArrayType(arrayType->getElementType()); 1896 assert((!llvmArrayType || arrayType) && 1897 "LLVM and Clang types are out-of-synch"); 1898 } 1899 1900 if (arrayType) { 1901 // From this point onwards, the Clang array type has been emitted 1902 // as some other type (probably a packed struct). Compute the array 1903 // size, and just emit the 'begin' expression as a bitcast. 1904 while (arrayType) { 1905 countFromCLAs *= 1906 cast<ConstantArrayType>(arrayType)->getSize().getZExtValue(); 1907 eltType = arrayType->getElementType(); 1908 arrayType = getContext().getAsArrayType(eltType); 1909 } 1910 1911 llvm::Type *baseType = ConvertType(eltType); 1912 addr = Builder.CreateElementBitCast(addr, baseType, "array.begin"); 1913 } else { 1914 // Create the actual GEP. 1915 addr = Address(Builder.CreateInBoundsGEP(addr.getPointer(), 1916 gepIndices, "array.begin"), 1917 addr.getAlignment()); 1918 } 1919 1920 baseType = eltType; 1921 1922 llvm::Value *numElements 1923 = llvm::ConstantInt::get(SizeTy, countFromCLAs); 1924 1925 // If we had any VLA dimensions, factor them in. 1926 if (numVLAElements) 1927 numElements = Builder.CreateNUWMul(numVLAElements, numElements); 1928 1929 return numElements; 1930 } 1931 1932 CodeGenFunction::VlaSizePair CodeGenFunction::getVLASize(QualType type) { 1933 const VariableArrayType *vla = getContext().getAsVariableArrayType(type); 1934 assert(vla && "type was not a variable array type!"); 1935 return getVLASize(vla); 1936 } 1937 1938 CodeGenFunction::VlaSizePair 1939 CodeGenFunction::getVLASize(const VariableArrayType *type) { 1940 // The number of elements so far; always size_t. 1941 llvm::Value *numElements = nullptr; 1942 1943 QualType elementType; 1944 do { 1945 elementType = type->getElementType(); 1946 llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()]; 1947 assert(vlaSize && "no size for VLA!"); 1948 assert(vlaSize->getType() == SizeTy); 1949 1950 if (!numElements) { 1951 numElements = vlaSize; 1952 } else { 1953 // It's undefined behavior if this wraps around, so mark it that way. 1954 // FIXME: Teach -fsanitize=undefined to trap this. 1955 numElements = Builder.CreateNUWMul(numElements, vlaSize); 1956 } 1957 } while ((type = getContext().getAsVariableArrayType(elementType))); 1958 1959 return { numElements, elementType }; 1960 } 1961 1962 CodeGenFunction::VlaSizePair 1963 CodeGenFunction::getVLAElements1D(QualType type) { 1964 const VariableArrayType *vla = getContext().getAsVariableArrayType(type); 1965 assert(vla && "type was not a variable array type!"); 1966 return getVLAElements1D(vla); 1967 } 1968 1969 CodeGenFunction::VlaSizePair 1970 CodeGenFunction::getVLAElements1D(const VariableArrayType *Vla) { 1971 llvm::Value *VlaSize = VLASizeMap[Vla->getSizeExpr()]; 1972 assert(VlaSize && "no size for VLA!"); 1973 assert(VlaSize->getType() == SizeTy); 1974 return { VlaSize, Vla->getElementType() }; 1975 } 1976 1977 void CodeGenFunction::EmitVariablyModifiedType(QualType type) { 1978 assert(type->isVariablyModifiedType() && 1979 "Must pass variably modified type to EmitVLASizes!"); 1980 1981 EnsureInsertPoint(); 1982 1983 // We're going to walk down into the type and look for VLA 1984 // expressions. 1985 do { 1986 assert(type->isVariablyModifiedType()); 1987 1988 const Type *ty = type.getTypePtr(); 1989 switch (ty->getTypeClass()) { 1990 1991 #define TYPE(Class, Base) 1992 #define ABSTRACT_TYPE(Class, Base) 1993 #define NON_CANONICAL_TYPE(Class, Base) 1994 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 1995 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 1996 #include "clang/AST/TypeNodes.inc" 1997 llvm_unreachable("unexpected dependent type!"); 1998 1999 // These types are never variably-modified. 2000 case Type::Builtin: 2001 case Type::Complex: 2002 case Type::Vector: 2003 case Type::ExtVector: 2004 case Type::ConstantMatrix: 2005 case Type::Record: 2006 case Type::Enum: 2007 case Type::Elaborated: 2008 case Type::TemplateSpecialization: 2009 case Type::ObjCTypeParam: 2010 case Type::ObjCObject: 2011 case Type::ObjCInterface: 2012 case Type::ObjCObjectPointer: 2013 case Type::ExtInt: 2014 llvm_unreachable("type class is never variably-modified!"); 2015 2016 case Type::Adjusted: 2017 type = cast<AdjustedType>(ty)->getAdjustedType(); 2018 break; 2019 2020 case Type::Decayed: 2021 type = cast<DecayedType>(ty)->getPointeeType(); 2022 break; 2023 2024 case Type::Pointer: 2025 type = cast<PointerType>(ty)->getPointeeType(); 2026 break; 2027 2028 case Type::BlockPointer: 2029 type = cast<BlockPointerType>(ty)->getPointeeType(); 2030 break; 2031 2032 case Type::LValueReference: 2033 case Type::RValueReference: 2034 type = cast<ReferenceType>(ty)->getPointeeType(); 2035 break; 2036 2037 case Type::MemberPointer: 2038 type = cast<MemberPointerType>(ty)->getPointeeType(); 2039 break; 2040 2041 case Type::ConstantArray: 2042 case Type::IncompleteArray: 2043 // Losing element qualification here is fine. 2044 type = cast<ArrayType>(ty)->getElementType(); 2045 break; 2046 2047 case Type::VariableArray: { 2048 // Losing element qualification here is fine. 2049 const VariableArrayType *vat = cast<VariableArrayType>(ty); 2050 2051 // Unknown size indication requires no size computation. 2052 // Otherwise, evaluate and record it. 2053 if (const Expr *size = vat->getSizeExpr()) { 2054 // It's possible that we might have emitted this already, 2055 // e.g. with a typedef and a pointer to it. 2056 llvm::Value *&entry = VLASizeMap[size]; 2057 if (!entry) { 2058 llvm::Value *Size = EmitScalarExpr(size); 2059 2060 // C11 6.7.6.2p5: 2061 // If the size is an expression that is not an integer constant 2062 // expression [...] each time it is evaluated it shall have a value 2063 // greater than zero. 2064 if (SanOpts.has(SanitizerKind::VLABound) && 2065 size->getType()->isSignedIntegerType()) { 2066 SanitizerScope SanScope(this); 2067 llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType()); 2068 llvm::Constant *StaticArgs[] = { 2069 EmitCheckSourceLocation(size->getBeginLoc()), 2070 EmitCheckTypeDescriptor(size->getType())}; 2071 EmitCheck(std::make_pair(Builder.CreateICmpSGT(Size, Zero), 2072 SanitizerKind::VLABound), 2073 SanitizerHandler::VLABoundNotPositive, StaticArgs, Size); 2074 } 2075 2076 // Always zexting here would be wrong if it weren't 2077 // undefined behavior to have a negative bound. 2078 entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false); 2079 } 2080 } 2081 type = vat->getElementType(); 2082 break; 2083 } 2084 2085 case Type::FunctionProto: 2086 case Type::FunctionNoProto: 2087 type = cast<FunctionType>(ty)->getReturnType(); 2088 break; 2089 2090 case Type::Paren: 2091 case Type::TypeOf: 2092 case Type::UnaryTransform: 2093 case Type::Attributed: 2094 case Type::SubstTemplateTypeParm: 2095 case Type::PackExpansion: 2096 case Type::MacroQualified: 2097 // Keep walking after single level desugaring. 2098 type = type.getSingleStepDesugaredType(getContext()); 2099 break; 2100 2101 case Type::Typedef: 2102 case Type::Decltype: 2103 case Type::Auto: 2104 case Type::DeducedTemplateSpecialization: 2105 // Stop walking: nothing to do. 2106 return; 2107 2108 case Type::TypeOfExpr: 2109 // Stop walking: emit typeof expression. 2110 EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr()); 2111 return; 2112 2113 case Type::Atomic: 2114 type = cast<AtomicType>(ty)->getValueType(); 2115 break; 2116 2117 case Type::Pipe: 2118 type = cast<PipeType>(ty)->getElementType(); 2119 break; 2120 } 2121 } while (type->isVariablyModifiedType()); 2122 } 2123 2124 Address CodeGenFunction::EmitVAListRef(const Expr* E) { 2125 if (getContext().getBuiltinVaListType()->isArrayType()) 2126 return EmitPointerWithAlignment(E); 2127 return EmitLValue(E).getAddress(*this); 2128 } 2129 2130 Address CodeGenFunction::EmitMSVAListRef(const Expr *E) { 2131 return EmitLValue(E).getAddress(*this); 2132 } 2133 2134 void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E, 2135 const APValue &Init) { 2136 assert(Init.hasValue() && "Invalid DeclRefExpr initializer!"); 2137 if (CGDebugInfo *Dbg = getDebugInfo()) 2138 if (CGM.getCodeGenOpts().hasReducedDebugInfo()) 2139 Dbg->EmitGlobalVariable(E->getDecl(), Init); 2140 } 2141 2142 CodeGenFunction::PeepholeProtection 2143 CodeGenFunction::protectFromPeepholes(RValue rvalue) { 2144 // At the moment, the only aggressive peephole we do in IR gen 2145 // is trunc(zext) folding, but if we add more, we can easily 2146 // extend this protection. 2147 2148 if (!rvalue.isScalar()) return PeepholeProtection(); 2149 llvm::Value *value = rvalue.getScalarVal(); 2150 if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection(); 2151 2152 // Just make an extra bitcast. 2153 assert(HaveInsertPoint()); 2154 llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "", 2155 Builder.GetInsertBlock()); 2156 2157 PeepholeProtection protection; 2158 protection.Inst = inst; 2159 return protection; 2160 } 2161 2162 void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) { 2163 if (!protection.Inst) return; 2164 2165 // In theory, we could try to duplicate the peepholes now, but whatever. 2166 protection.Inst->eraseFromParent(); 2167 } 2168 2169 void CodeGenFunction::emitAlignmentAssumption(llvm::Value *PtrValue, 2170 QualType Ty, SourceLocation Loc, 2171 SourceLocation AssumptionLoc, 2172 llvm::Value *Alignment, 2173 llvm::Value *OffsetValue) { 2174 llvm::Value *TheCheck; 2175 llvm::Instruction *Assumption = Builder.CreateAlignmentAssumption( 2176 CGM.getDataLayout(), PtrValue, Alignment, OffsetValue, &TheCheck); 2177 if (SanOpts.has(SanitizerKind::Alignment)) { 2178 emitAlignmentAssumptionCheck(PtrValue, Ty, Loc, AssumptionLoc, Alignment, 2179 OffsetValue, TheCheck, Assumption); 2180 } 2181 } 2182 2183 void CodeGenFunction::emitAlignmentAssumption(llvm::Value *PtrValue, 2184 const Expr *E, 2185 SourceLocation AssumptionLoc, 2186 llvm::Value *Alignment, 2187 llvm::Value *OffsetValue) { 2188 if (auto *CE = dyn_cast<CastExpr>(E)) 2189 E = CE->getSubExprAsWritten(); 2190 QualType Ty = E->getType(); 2191 SourceLocation Loc = E->getExprLoc(); 2192 2193 emitAlignmentAssumption(PtrValue, Ty, Loc, AssumptionLoc, Alignment, 2194 OffsetValue); 2195 } 2196 2197 llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Function *AnnotationFn, 2198 llvm::Value *AnnotatedVal, 2199 StringRef AnnotationStr, 2200 SourceLocation Location) { 2201 llvm::Value *Args[4] = { 2202 AnnotatedVal, 2203 Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy), 2204 Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy), 2205 CGM.EmitAnnotationLineNo(Location) 2206 }; 2207 return Builder.CreateCall(AnnotationFn, Args); 2208 } 2209 2210 void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) { 2211 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 2212 // FIXME We create a new bitcast for every annotation because that's what 2213 // llvm-gcc was doing. 2214 for (const auto *I : D->specific_attrs<AnnotateAttr>()) 2215 EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation), 2216 Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()), 2217 I->getAnnotation(), D->getLocation()); 2218 } 2219 2220 Address CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D, 2221 Address Addr) { 2222 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 2223 llvm::Value *V = Addr.getPointer(); 2224 llvm::Type *VTy = V->getType(); 2225 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation, 2226 CGM.Int8PtrTy); 2227 2228 for (const auto *I : D->specific_attrs<AnnotateAttr>()) { 2229 // FIXME Always emit the cast inst so we can differentiate between 2230 // annotation on the first field of a struct and annotation on the struct 2231 // itself. 2232 if (VTy != CGM.Int8PtrTy) 2233 V = Builder.CreateBitCast(V, CGM.Int8PtrTy); 2234 V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation()); 2235 V = Builder.CreateBitCast(V, VTy); 2236 } 2237 2238 return Address(V, Addr.getAlignment()); 2239 } 2240 2241 CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { } 2242 2243 CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF) 2244 : CGF(CGF) { 2245 assert(!CGF->IsSanitizerScope); 2246 CGF->IsSanitizerScope = true; 2247 } 2248 2249 CodeGenFunction::SanitizerScope::~SanitizerScope() { 2250 CGF->IsSanitizerScope = false; 2251 } 2252 2253 void CodeGenFunction::InsertHelper(llvm::Instruction *I, 2254 const llvm::Twine &Name, 2255 llvm::BasicBlock *BB, 2256 llvm::BasicBlock::iterator InsertPt) const { 2257 LoopStack.InsertHelper(I); 2258 if (IsSanitizerScope) 2259 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(I); 2260 } 2261 2262 void CGBuilderInserter::InsertHelper( 2263 llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB, 2264 llvm::BasicBlock::iterator InsertPt) const { 2265 llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt); 2266 if (CGF) 2267 CGF->InsertHelper(I, Name, BB, InsertPt); 2268 } 2269 2270 static bool hasRequiredFeatures(const SmallVectorImpl<StringRef> &ReqFeatures, 2271 CodeGenModule &CGM, const FunctionDecl *FD, 2272 std::string &FirstMissing) { 2273 // If there aren't any required features listed then go ahead and return. 2274 if (ReqFeatures.empty()) 2275 return false; 2276 2277 // Now build up the set of caller features and verify that all the required 2278 // features are there. 2279 llvm::StringMap<bool> CallerFeatureMap; 2280 CGM.getContext().getFunctionFeatureMap(CallerFeatureMap, FD); 2281 2282 // If we have at least one of the features in the feature list return 2283 // true, otherwise return false. 2284 return std::all_of( 2285 ReqFeatures.begin(), ReqFeatures.end(), [&](StringRef Feature) { 2286 SmallVector<StringRef, 1> OrFeatures; 2287 Feature.split(OrFeatures, '|'); 2288 return llvm::any_of(OrFeatures, [&](StringRef Feature) { 2289 if (!CallerFeatureMap.lookup(Feature)) { 2290 FirstMissing = Feature.str(); 2291 return false; 2292 } 2293 return true; 2294 }); 2295 }); 2296 } 2297 2298 // Emits an error if we don't have a valid set of target features for the 2299 // called function. 2300 void CodeGenFunction::checkTargetFeatures(const CallExpr *E, 2301 const FunctionDecl *TargetDecl) { 2302 return checkTargetFeatures(E->getBeginLoc(), TargetDecl); 2303 } 2304 2305 // Emits an error if we don't have a valid set of target features for the 2306 // called function. 2307 void CodeGenFunction::checkTargetFeatures(SourceLocation Loc, 2308 const FunctionDecl *TargetDecl) { 2309 // Early exit if this is an indirect call. 2310 if (!TargetDecl) 2311 return; 2312 2313 // Get the current enclosing function if it exists. If it doesn't 2314 // we can't check the target features anyhow. 2315 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl); 2316 if (!FD) 2317 return; 2318 2319 // Grab the required features for the call. For a builtin this is listed in 2320 // the td file with the default cpu, for an always_inline function this is any 2321 // listed cpu and any listed features. 2322 unsigned BuiltinID = TargetDecl->getBuiltinID(); 2323 std::string MissingFeature; 2324 if (BuiltinID) { 2325 SmallVector<StringRef, 1> ReqFeatures; 2326 const char *FeatureList = 2327 CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID); 2328 // Return if the builtin doesn't have any required features. 2329 if (!FeatureList || StringRef(FeatureList) == "") 2330 return; 2331 StringRef(FeatureList).split(ReqFeatures, ','); 2332 if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature)) 2333 CGM.getDiags().Report(Loc, diag::err_builtin_needs_feature) 2334 << TargetDecl->getDeclName() 2335 << CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID); 2336 2337 } else if (!TargetDecl->isMultiVersion() && 2338 TargetDecl->hasAttr<TargetAttr>()) { 2339 // Get the required features for the callee. 2340 2341 const TargetAttr *TD = TargetDecl->getAttr<TargetAttr>(); 2342 ParsedTargetAttr ParsedAttr = 2343 CGM.getContext().filterFunctionTargetAttrs(TD); 2344 2345 SmallVector<StringRef, 1> ReqFeatures; 2346 llvm::StringMap<bool> CalleeFeatureMap; 2347 CGM.getContext().getFunctionFeatureMap(CalleeFeatureMap, TargetDecl); 2348 2349 for (const auto &F : ParsedAttr.Features) { 2350 if (F[0] == '+' && CalleeFeatureMap.lookup(F.substr(1))) 2351 ReqFeatures.push_back(StringRef(F).substr(1)); 2352 } 2353 2354 for (const auto &F : CalleeFeatureMap) { 2355 // Only positive features are "required". 2356 if (F.getValue()) 2357 ReqFeatures.push_back(F.getKey()); 2358 } 2359 if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature)) 2360 CGM.getDiags().Report(Loc, diag::err_function_needs_feature) 2361 << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature; 2362 } 2363 } 2364 2365 void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) { 2366 if (!CGM.getCodeGenOpts().SanitizeStats) 2367 return; 2368 2369 llvm::IRBuilder<> IRB(Builder.GetInsertBlock(), Builder.GetInsertPoint()); 2370 IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation()); 2371 CGM.getSanStats().create(IRB, SSK); 2372 } 2373 2374 llvm::Value * 2375 CodeGenFunction::FormResolverCondition(const MultiVersionResolverOption &RO) { 2376 llvm::Value *Condition = nullptr; 2377 2378 if (!RO.Conditions.Architecture.empty()) 2379 Condition = EmitX86CpuIs(RO.Conditions.Architecture); 2380 2381 if (!RO.Conditions.Features.empty()) { 2382 llvm::Value *FeatureCond = EmitX86CpuSupports(RO.Conditions.Features); 2383 Condition = 2384 Condition ? Builder.CreateAnd(Condition, FeatureCond) : FeatureCond; 2385 } 2386 return Condition; 2387 } 2388 2389 static void CreateMultiVersionResolverReturn(CodeGenModule &CGM, 2390 llvm::Function *Resolver, 2391 CGBuilderTy &Builder, 2392 llvm::Function *FuncToReturn, 2393 bool SupportsIFunc) { 2394 if (SupportsIFunc) { 2395 Builder.CreateRet(FuncToReturn); 2396 return; 2397 } 2398 2399 llvm::SmallVector<llvm::Value *, 10> Args; 2400 llvm::for_each(Resolver->args(), 2401 [&](llvm::Argument &Arg) { Args.push_back(&Arg); }); 2402 2403 llvm::CallInst *Result = Builder.CreateCall(FuncToReturn, Args); 2404 Result->setTailCallKind(llvm::CallInst::TCK_MustTail); 2405 2406 if (Resolver->getReturnType()->isVoidTy()) 2407 Builder.CreateRetVoid(); 2408 else 2409 Builder.CreateRet(Result); 2410 } 2411 2412 void CodeGenFunction::EmitMultiVersionResolver( 2413 llvm::Function *Resolver, ArrayRef<MultiVersionResolverOption> Options) { 2414 assert(getContext().getTargetInfo().getTriple().isX86() && 2415 "Only implemented for x86 targets"); 2416 2417 bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc(); 2418 2419 // Main function's basic block. 2420 llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver); 2421 Builder.SetInsertPoint(CurBlock); 2422 EmitX86CpuInit(); 2423 2424 for (const MultiVersionResolverOption &RO : Options) { 2425 Builder.SetInsertPoint(CurBlock); 2426 llvm::Value *Condition = FormResolverCondition(RO); 2427 2428 // The 'default' or 'generic' case. 2429 if (!Condition) { 2430 assert(&RO == Options.end() - 1 && 2431 "Default or Generic case must be last"); 2432 CreateMultiVersionResolverReturn(CGM, Resolver, Builder, RO.Function, 2433 SupportsIFunc); 2434 return; 2435 } 2436 2437 llvm::BasicBlock *RetBlock = createBasicBlock("resolver_return", Resolver); 2438 CGBuilderTy RetBuilder(*this, RetBlock); 2439 CreateMultiVersionResolverReturn(CGM, Resolver, RetBuilder, RO.Function, 2440 SupportsIFunc); 2441 CurBlock = createBasicBlock("resolver_else", Resolver); 2442 Builder.CreateCondBr(Condition, RetBlock, CurBlock); 2443 } 2444 2445 // If no generic/default, emit an unreachable. 2446 Builder.SetInsertPoint(CurBlock); 2447 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap); 2448 TrapCall->setDoesNotReturn(); 2449 TrapCall->setDoesNotThrow(); 2450 Builder.CreateUnreachable(); 2451 Builder.ClearInsertionPoint(); 2452 } 2453 2454 // Loc - where the diagnostic will point, where in the source code this 2455 // alignment has failed. 2456 // SecondaryLoc - if present (will be present if sufficiently different from 2457 // Loc), the diagnostic will additionally point a "Note:" to this location. 2458 // It should be the location where the __attribute__((assume_aligned)) 2459 // was written e.g. 2460 void CodeGenFunction::emitAlignmentAssumptionCheck( 2461 llvm::Value *Ptr, QualType Ty, SourceLocation Loc, 2462 SourceLocation SecondaryLoc, llvm::Value *Alignment, 2463 llvm::Value *OffsetValue, llvm::Value *TheCheck, 2464 llvm::Instruction *Assumption) { 2465 assert(Assumption && isa<llvm::CallInst>(Assumption) && 2466 cast<llvm::CallInst>(Assumption)->getCalledOperand() == 2467 llvm::Intrinsic::getDeclaration( 2468 Builder.GetInsertBlock()->getParent()->getParent(), 2469 llvm::Intrinsic::assume) && 2470 "Assumption should be a call to llvm.assume()."); 2471 assert(&(Builder.GetInsertBlock()->back()) == Assumption && 2472 "Assumption should be the last instruction of the basic block, " 2473 "since the basic block is still being generated."); 2474 2475 if (!SanOpts.has(SanitizerKind::Alignment)) 2476 return; 2477 2478 // Don't check pointers to volatile data. The behavior here is implementation- 2479 // defined. 2480 if (Ty->getPointeeType().isVolatileQualified()) 2481 return; 2482 2483 // We need to temorairly remove the assumption so we can insert the 2484 // sanitizer check before it, else the check will be dropped by optimizations. 2485 Assumption->removeFromParent(); 2486 2487 { 2488 SanitizerScope SanScope(this); 2489 2490 if (!OffsetValue) 2491 OffsetValue = Builder.getInt1(0); // no offset. 2492 2493 llvm::Constant *StaticData[] = {EmitCheckSourceLocation(Loc), 2494 EmitCheckSourceLocation(SecondaryLoc), 2495 EmitCheckTypeDescriptor(Ty)}; 2496 llvm::Value *DynamicData[] = {EmitCheckValue(Ptr), 2497 EmitCheckValue(Alignment), 2498 EmitCheckValue(OffsetValue)}; 2499 EmitCheck({std::make_pair(TheCheck, SanitizerKind::Alignment)}, 2500 SanitizerHandler::AlignmentAssumption, StaticData, DynamicData); 2501 } 2502 2503 // We are now in the (new, empty) "cont" basic block. 2504 // Reintroduce the assumption. 2505 Builder.Insert(Assumption); 2506 // FIXME: Assumption still has it's original basic block as it's Parent. 2507 } 2508 2509 llvm::DebugLoc CodeGenFunction::SourceLocToDebugLoc(SourceLocation Location) { 2510 if (CGDebugInfo *DI = getDebugInfo()) 2511 return DI->SourceLocToDebugLoc(Location); 2512 2513 return llvm::DebugLoc(); 2514 } 2515