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