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