1 //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===// 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-module state used while generating code. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CodeGenModule.h" 15 #include "CGBlocks.h" 16 #include "CGCUDARuntime.h" 17 #include "CGCXXABI.h" 18 #include "CGCall.h" 19 #include "CGDebugInfo.h" 20 #include "CGObjCRuntime.h" 21 #include "CGOpenCLRuntime.h" 22 #include "CGOpenMPRuntime.h" 23 #include "CGOpenMPRuntimeNVPTX.h" 24 #include "CodeGenFunction.h" 25 #include "CodeGenPGO.h" 26 #include "CodeGenTBAA.h" 27 #include "CoverageMappingGen.h" 28 #include "TargetInfo.h" 29 #include "clang/AST/ASTContext.h" 30 #include "clang/AST/CharUnits.h" 31 #include "clang/AST/DeclCXX.h" 32 #include "clang/AST/DeclObjC.h" 33 #include "clang/AST/DeclTemplate.h" 34 #include "clang/AST/Mangle.h" 35 #include "clang/AST/RecordLayout.h" 36 #include "clang/AST/RecursiveASTVisitor.h" 37 #include "clang/Basic/Builtins.h" 38 #include "clang/Basic/CharInfo.h" 39 #include "clang/Basic/Diagnostic.h" 40 #include "clang/Basic/Module.h" 41 #include "clang/Basic/SourceManager.h" 42 #include "clang/Basic/TargetInfo.h" 43 #include "clang/Basic/Version.h" 44 #include "clang/Frontend/CodeGenOptions.h" 45 #include "clang/Sema/SemaDiagnostic.h" 46 #include "llvm/ADT/APSInt.h" 47 #include "llvm/ADT/Triple.h" 48 #include "llvm/IR/CallSite.h" 49 #include "llvm/IR/CallingConv.h" 50 #include "llvm/IR/DataLayout.h" 51 #include "llvm/IR/Intrinsics.h" 52 #include "llvm/IR/LLVMContext.h" 53 #include "llvm/IR/Module.h" 54 #include "llvm/ProfileData/InstrProfReader.h" 55 #include "llvm/Support/ConvertUTF.h" 56 #include "llvm/Support/ErrorHandling.h" 57 #include "llvm/Support/MD5.h" 58 59 using namespace clang; 60 using namespace CodeGen; 61 62 static const char AnnotationSection[] = "llvm.metadata"; 63 64 static CGCXXABI *createCXXABI(CodeGenModule &CGM) { 65 switch (CGM.getTarget().getCXXABI().getKind()) { 66 case TargetCXXABI::GenericAArch64: 67 case TargetCXXABI::GenericARM: 68 case TargetCXXABI::iOS: 69 case TargetCXXABI::iOS64: 70 case TargetCXXABI::WatchOS: 71 case TargetCXXABI::GenericMIPS: 72 case TargetCXXABI::GenericItanium: 73 case TargetCXXABI::WebAssembly: 74 return CreateItaniumCXXABI(CGM); 75 case TargetCXXABI::Microsoft: 76 return CreateMicrosoftCXXABI(CGM); 77 } 78 79 llvm_unreachable("invalid C++ ABI kind"); 80 } 81 82 CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO, 83 const PreprocessorOptions &PPO, 84 const CodeGenOptions &CGO, llvm::Module &M, 85 DiagnosticsEngine &diags, 86 CoverageSourceInfo *CoverageInfo) 87 : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO), 88 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags), 89 Target(C.getTargetInfo()), ABI(createCXXABI(*this)), 90 VMContext(M.getContext()), Types(*this), VTables(*this), 91 SanitizerMD(new SanitizerMetadata(*this)) { 92 93 // Initialize the type cache. 94 llvm::LLVMContext &LLVMContext = M.getContext(); 95 VoidTy = llvm::Type::getVoidTy(LLVMContext); 96 Int8Ty = llvm::Type::getInt8Ty(LLVMContext); 97 Int16Ty = llvm::Type::getInt16Ty(LLVMContext); 98 Int32Ty = llvm::Type::getInt32Ty(LLVMContext); 99 Int64Ty = llvm::Type::getInt64Ty(LLVMContext); 100 FloatTy = llvm::Type::getFloatTy(LLVMContext); 101 DoubleTy = llvm::Type::getDoubleTy(LLVMContext); 102 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0); 103 PointerAlignInBytes = 104 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity(); 105 IntAlignInBytes = 106 C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity(); 107 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth()); 108 IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits); 109 Int8PtrTy = Int8Ty->getPointerTo(0); 110 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0); 111 112 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC(); 113 BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC(); 114 115 if (LangOpts.ObjC1) 116 createObjCRuntime(); 117 if (LangOpts.OpenCL) 118 createOpenCLRuntime(); 119 if (LangOpts.OpenMP) 120 createOpenMPRuntime(); 121 if (LangOpts.CUDA) 122 createCUDARuntime(); 123 124 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0. 125 if (LangOpts.Sanitize.has(SanitizerKind::Thread) || 126 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)) 127 TBAA.reset(new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(), 128 getCXXABI().getMangleContext())); 129 130 // If debug info or coverage generation is enabled, create the CGDebugInfo 131 // object. 132 if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo || 133 CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes) 134 DebugInfo.reset(new CGDebugInfo(*this)); 135 136 Block.GlobalUniqueCount = 0; 137 138 if (C.getLangOpts().ObjC1) 139 ObjCData.reset(new ObjCEntrypoints()); 140 141 if (CodeGenOpts.hasProfileClangUse()) { 142 auto ReaderOrErr = llvm::IndexedInstrProfReader::create( 143 CodeGenOpts.ProfileInstrumentUsePath); 144 if (auto E = ReaderOrErr.takeError()) { 145 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 146 "Could not read profile %0: %1"); 147 llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) { 148 getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath 149 << EI.message(); 150 }); 151 } else 152 PGOReader = std::move(ReaderOrErr.get()); 153 } 154 155 // If coverage mapping generation is enabled, create the 156 // CoverageMappingModuleGen object. 157 if (CodeGenOpts.CoverageMapping) 158 CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo)); 159 } 160 161 CodeGenModule::~CodeGenModule() {} 162 163 void CodeGenModule::createObjCRuntime() { 164 // This is just isGNUFamily(), but we want to force implementors of 165 // new ABIs to decide how best to do this. 166 switch (LangOpts.ObjCRuntime.getKind()) { 167 case ObjCRuntime::GNUstep: 168 case ObjCRuntime::GCC: 169 case ObjCRuntime::ObjFW: 170 ObjCRuntime.reset(CreateGNUObjCRuntime(*this)); 171 return; 172 173 case ObjCRuntime::FragileMacOSX: 174 case ObjCRuntime::MacOSX: 175 case ObjCRuntime::iOS: 176 case ObjCRuntime::WatchOS: 177 ObjCRuntime.reset(CreateMacObjCRuntime(*this)); 178 return; 179 } 180 llvm_unreachable("bad runtime kind"); 181 } 182 183 void CodeGenModule::createOpenCLRuntime() { 184 OpenCLRuntime.reset(new CGOpenCLRuntime(*this)); 185 } 186 187 void CodeGenModule::createOpenMPRuntime() { 188 // Select a specialized code generation class based on the target, if any. 189 // If it does not exist use the default implementation. 190 switch (getTarget().getTriple().getArch()) { 191 192 case llvm::Triple::nvptx: 193 case llvm::Triple::nvptx64: 194 assert(getLangOpts().OpenMPIsDevice && 195 "OpenMP NVPTX is only prepared to deal with device code."); 196 OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this)); 197 break; 198 default: 199 OpenMPRuntime.reset(new CGOpenMPRuntime(*this)); 200 break; 201 } 202 } 203 204 void CodeGenModule::createCUDARuntime() { 205 CUDARuntime.reset(CreateNVCUDARuntime(*this)); 206 } 207 208 void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) { 209 Replacements[Name] = C; 210 } 211 212 void CodeGenModule::applyReplacements() { 213 for (auto &I : Replacements) { 214 StringRef MangledName = I.first(); 215 llvm::Constant *Replacement = I.second; 216 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 217 if (!Entry) 218 continue; 219 auto *OldF = cast<llvm::Function>(Entry); 220 auto *NewF = dyn_cast<llvm::Function>(Replacement); 221 if (!NewF) { 222 if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) { 223 NewF = dyn_cast<llvm::Function>(Alias->getAliasee()); 224 } else { 225 auto *CE = cast<llvm::ConstantExpr>(Replacement); 226 assert(CE->getOpcode() == llvm::Instruction::BitCast || 227 CE->getOpcode() == llvm::Instruction::GetElementPtr); 228 NewF = dyn_cast<llvm::Function>(CE->getOperand(0)); 229 } 230 } 231 232 // Replace old with new, but keep the old order. 233 OldF->replaceAllUsesWith(Replacement); 234 if (NewF) { 235 NewF->removeFromParent(); 236 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(), 237 NewF); 238 } 239 OldF->eraseFromParent(); 240 } 241 } 242 243 void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) { 244 GlobalValReplacements.push_back(std::make_pair(GV, C)); 245 } 246 247 void CodeGenModule::applyGlobalValReplacements() { 248 for (auto &I : GlobalValReplacements) { 249 llvm::GlobalValue *GV = I.first; 250 llvm::Constant *C = I.second; 251 252 GV->replaceAllUsesWith(C); 253 GV->eraseFromParent(); 254 } 255 } 256 257 // This is only used in aliases that we created and we know they have a 258 // linear structure. 259 static const llvm::GlobalObject *getAliasedGlobal( 260 const llvm::GlobalIndirectSymbol &GIS) { 261 llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited; 262 const llvm::Constant *C = &GIS; 263 for (;;) { 264 C = C->stripPointerCasts(); 265 if (auto *GO = dyn_cast<llvm::GlobalObject>(C)) 266 return GO; 267 // stripPointerCasts will not walk over weak aliases. 268 auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C); 269 if (!GIS2) 270 return nullptr; 271 if (!Visited.insert(GIS2).second) 272 return nullptr; 273 C = GIS2->getIndirectSymbol(); 274 } 275 } 276 277 void CodeGenModule::checkAliases() { 278 // Check if the constructed aliases are well formed. It is really unfortunate 279 // that we have to do this in CodeGen, but we only construct mangled names 280 // and aliases during codegen. 281 bool Error = false; 282 DiagnosticsEngine &Diags = getDiags(); 283 for (const GlobalDecl &GD : Aliases) { 284 const auto *D = cast<ValueDecl>(GD.getDecl()); 285 SourceLocation Location; 286 bool IsIFunc = D->hasAttr<IFuncAttr>(); 287 if (const Attr *A = D->getDefiningAttr()) 288 Location = A->getLocation(); 289 else 290 llvm_unreachable("Not an alias or ifunc?"); 291 StringRef MangledName = getMangledName(GD); 292 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 293 auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry); 294 const llvm::GlobalValue *GV = getAliasedGlobal(*Alias); 295 if (!GV) { 296 Error = true; 297 Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc; 298 } else if (GV->isDeclaration()) { 299 Error = true; 300 Diags.Report(Location, diag::err_alias_to_undefined) 301 << IsIFunc << IsIFunc; 302 } else if (IsIFunc) { 303 // Check resolver function type. 304 llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>( 305 GV->getType()->getPointerElementType()); 306 assert(FTy); 307 if (!FTy->getReturnType()->isPointerTy()) 308 Diags.Report(Location, diag::err_ifunc_resolver_return); 309 if (FTy->getNumParams()) 310 Diags.Report(Location, diag::err_ifunc_resolver_params); 311 } 312 313 llvm::Constant *Aliasee = Alias->getIndirectSymbol(); 314 llvm::GlobalValue *AliaseeGV; 315 if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee)) 316 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0)); 317 else 318 AliaseeGV = cast<llvm::GlobalValue>(Aliasee); 319 320 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 321 StringRef AliasSection = SA->getName(); 322 if (AliasSection != AliaseeGV->getSection()) 323 Diags.Report(SA->getLocation(), diag::warn_alias_with_section) 324 << AliasSection << IsIFunc << IsIFunc; 325 } 326 327 // We have to handle alias to weak aliases in here. LLVM itself disallows 328 // this since the object semantics would not match the IL one. For 329 // compatibility with gcc we implement it by just pointing the alias 330 // to its aliasee's aliasee. We also warn, since the user is probably 331 // expecting the link to be weak. 332 if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) { 333 if (GA->isInterposable()) { 334 Diags.Report(Location, diag::warn_alias_to_weak_alias) 335 << GV->getName() << GA->getName() << IsIFunc; 336 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 337 GA->getIndirectSymbol(), Alias->getType()); 338 Alias->setIndirectSymbol(Aliasee); 339 } 340 } 341 } 342 if (!Error) 343 return; 344 345 for (const GlobalDecl &GD : Aliases) { 346 StringRef MangledName = getMangledName(GD); 347 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 348 auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry); 349 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType())); 350 Alias->eraseFromParent(); 351 } 352 } 353 354 void CodeGenModule::clear() { 355 DeferredDeclsToEmit.clear(); 356 if (OpenMPRuntime) 357 OpenMPRuntime->clear(); 358 } 359 360 void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags, 361 StringRef MainFile) { 362 if (!hasDiagnostics()) 363 return; 364 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) { 365 if (MainFile.empty()) 366 MainFile = "<stdin>"; 367 Diags.Report(diag::warn_profile_data_unprofiled) << MainFile; 368 } else 369 Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Missing 370 << Mismatched; 371 } 372 373 void CodeGenModule::Release() { 374 EmitDeferred(); 375 applyGlobalValReplacements(); 376 applyReplacements(); 377 checkAliases(); 378 EmitCXXGlobalInitFunc(); 379 EmitCXXGlobalDtorFunc(); 380 EmitCXXThreadLocalInitFunc(); 381 if (ObjCRuntime) 382 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction()) 383 AddGlobalCtor(ObjCInitFunction); 384 if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice && 385 CUDARuntime) { 386 if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction()) 387 AddGlobalCtor(CudaCtorFunction); 388 if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction()) 389 AddGlobalDtor(CudaDtorFunction); 390 } 391 if (OpenMPRuntime) 392 if (llvm::Function *OpenMPRegistrationFunction = 393 OpenMPRuntime->emitRegistrationFunction()) 394 AddGlobalCtor(OpenMPRegistrationFunction, 0); 395 if (PGOReader) { 396 getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext)); 397 if (PGOStats.hasDiagnostics()) 398 PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName); 399 } 400 EmitCtorList(GlobalCtors, "llvm.global_ctors"); 401 EmitCtorList(GlobalDtors, "llvm.global_dtors"); 402 EmitGlobalAnnotations(); 403 EmitStaticExternCAliases(); 404 EmitDeferredUnusedCoverageMappings(); 405 if (CoverageMapping) 406 CoverageMapping->emit(); 407 if (CodeGenOpts.SanitizeCfiCrossDso) 408 CodeGenFunction(*this).EmitCfiCheckFail(); 409 emitLLVMUsed(); 410 if (SanStats) 411 SanStats->finish(); 412 413 if (CodeGenOpts.Autolink && 414 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) { 415 EmitModuleLinkOptions(); 416 } 417 if (CodeGenOpts.DwarfVersion) { 418 // We actually want the latest version when there are conflicts. 419 // We can change from Warning to Latest if such mode is supported. 420 getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version", 421 CodeGenOpts.DwarfVersion); 422 } 423 if (CodeGenOpts.EmitCodeView) { 424 // Indicate that we want CodeView in the metadata. 425 getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1); 426 } 427 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) { 428 // We don't support LTO with 2 with different StrictVTablePointers 429 // FIXME: we could support it by stripping all the information introduced 430 // by StrictVTablePointers. 431 432 getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1); 433 434 llvm::Metadata *Ops[2] = { 435 llvm::MDString::get(VMContext, "StrictVTablePointers"), 436 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 437 llvm::Type::getInt32Ty(VMContext), 1))}; 438 439 getModule().addModuleFlag(llvm::Module::Require, 440 "StrictVTablePointersRequirement", 441 llvm::MDNode::get(VMContext, Ops)); 442 } 443 if (DebugInfo) 444 // We support a single version in the linked module. The LLVM 445 // parser will drop debug info with a different version number 446 // (and warn about it, too). 447 getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version", 448 llvm::DEBUG_METADATA_VERSION); 449 450 // We need to record the widths of enums and wchar_t, so that we can generate 451 // the correct build attributes in the ARM backend. 452 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 453 if ( Arch == llvm::Triple::arm 454 || Arch == llvm::Triple::armeb 455 || Arch == llvm::Triple::thumb 456 || Arch == llvm::Triple::thumbeb) { 457 // Width of wchar_t in bytes 458 uint64_t WCharWidth = 459 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity(); 460 getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth); 461 462 // The minimum width of an enum in bytes 463 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4; 464 getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth); 465 } 466 467 if (CodeGenOpts.SanitizeCfiCrossDso) { 468 // Indicate that we want cross-DSO control flow integrity checks. 469 getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1); 470 } 471 472 if (LangOpts.CUDAIsDevice && getTarget().getTriple().isNVPTX()) { 473 // Indicate whether __nvvm_reflect should be configured to flush denormal 474 // floating point values to 0. (This corresponds to its "__CUDA_FTZ" 475 // property.) 476 getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz", 477 LangOpts.CUDADeviceFlushDenormalsToZero ? 1 : 0); 478 } 479 480 if (uint32_t PLevel = Context.getLangOpts().PICLevel) { 481 assert(PLevel < 3 && "Invalid PIC Level"); 482 getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel)); 483 if (Context.getLangOpts().PIE) 484 getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel)); 485 } 486 487 SimplifyPersonality(); 488 489 if (getCodeGenOpts().EmitDeclMetadata) 490 EmitDeclMetadata(); 491 492 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes) 493 EmitCoverageFile(); 494 495 if (DebugInfo) 496 DebugInfo->finalize(); 497 498 EmitVersionIdentMetadata(); 499 500 EmitTargetMetadata(); 501 } 502 503 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 504 // Make sure that this type is translated. 505 Types.UpdateCompletedType(TD); 506 } 507 508 void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) { 509 // Make sure that this type is translated. 510 Types.RefreshTypeCacheForClass(RD); 511 } 512 513 llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) { 514 if (!TBAA) 515 return nullptr; 516 return TBAA->getTBAAInfo(QTy); 517 } 518 519 llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() { 520 if (!TBAA) 521 return nullptr; 522 return TBAA->getTBAAInfoForVTablePtr(); 523 } 524 525 llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) { 526 if (!TBAA) 527 return nullptr; 528 return TBAA->getTBAAStructInfo(QTy); 529 } 530 531 llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy, 532 llvm::MDNode *AccessN, 533 uint64_t O) { 534 if (!TBAA) 535 return nullptr; 536 return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O); 537 } 538 539 /// Decorate the instruction with a TBAA tag. For both scalar TBAA 540 /// and struct-path aware TBAA, the tag has the same format: 541 /// base type, access type and offset. 542 /// When ConvertTypeToTag is true, we create a tag based on the scalar type. 543 void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst, 544 llvm::MDNode *TBAAInfo, 545 bool ConvertTypeToTag) { 546 if (ConvertTypeToTag && TBAA) 547 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, 548 TBAA->getTBAAScalarTagInfo(TBAAInfo)); 549 else 550 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo); 551 } 552 553 void CodeGenModule::DecorateInstructionWithInvariantGroup( 554 llvm::Instruction *I, const CXXRecordDecl *RD) { 555 llvm::Metadata *MD = CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)); 556 auto *MetaDataNode = dyn_cast<llvm::MDNode>(MD); 557 // Check if we have to wrap MDString in MDNode. 558 if (!MetaDataNode) 559 MetaDataNode = llvm::MDNode::get(getLLVMContext(), MD); 560 I->setMetadata(llvm::LLVMContext::MD_invariant_group, MetaDataNode); 561 } 562 563 void CodeGenModule::Error(SourceLocation loc, StringRef message) { 564 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0"); 565 getDiags().Report(Context.getFullLoc(loc), diagID) << message; 566 } 567 568 /// ErrorUnsupported - Print out an error that codegen doesn't support the 569 /// specified stmt yet. 570 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) { 571 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 572 "cannot compile this %0 yet"); 573 std::string Msg = Type; 574 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID) 575 << Msg << S->getSourceRange(); 576 } 577 578 /// ErrorUnsupported - Print out an error that codegen doesn't support the 579 /// specified decl yet. 580 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) { 581 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 582 "cannot compile this %0 yet"); 583 std::string Msg = Type; 584 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 585 } 586 587 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) { 588 return llvm::ConstantInt::get(SizeTy, size.getQuantity()); 589 } 590 591 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 592 const NamedDecl *D) const { 593 // Internal definitions always have default visibility. 594 if (GV->hasLocalLinkage()) { 595 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 596 return; 597 } 598 599 // Set visibility for definitions. 600 LinkageInfo LV = D->getLinkageAndVisibility(); 601 if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage()) 602 GV->setVisibility(GetLLVMVisibility(LV.getVisibility())); 603 } 604 605 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) { 606 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S) 607 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel) 608 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel) 609 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel) 610 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel); 611 } 612 613 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel( 614 CodeGenOptions::TLSModel M) { 615 switch (M) { 616 case CodeGenOptions::GeneralDynamicTLSModel: 617 return llvm::GlobalVariable::GeneralDynamicTLSModel; 618 case CodeGenOptions::LocalDynamicTLSModel: 619 return llvm::GlobalVariable::LocalDynamicTLSModel; 620 case CodeGenOptions::InitialExecTLSModel: 621 return llvm::GlobalVariable::InitialExecTLSModel; 622 case CodeGenOptions::LocalExecTLSModel: 623 return llvm::GlobalVariable::LocalExecTLSModel; 624 } 625 llvm_unreachable("Invalid TLS model!"); 626 } 627 628 void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const { 629 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!"); 630 631 llvm::GlobalValue::ThreadLocalMode TLM; 632 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel()); 633 634 // Override the TLS model if it is explicitly specified. 635 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) { 636 TLM = GetLLVMTLSModel(Attr->getModel()); 637 } 638 639 GV->setThreadLocalMode(TLM); 640 } 641 642 StringRef CodeGenModule::getMangledName(GlobalDecl GD) { 643 GlobalDecl CanonicalGD = GD.getCanonicalDecl(); 644 645 // Some ABIs don't have constructor variants. Make sure that base and 646 // complete constructors get mangled the same. 647 if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) { 648 if (!getTarget().getCXXABI().hasConstructorVariants()) { 649 CXXCtorType OrigCtorType = GD.getCtorType(); 650 assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete); 651 if (OrigCtorType == Ctor_Base) 652 CanonicalGD = GlobalDecl(CD, Ctor_Complete); 653 } 654 } 655 656 StringRef &FoundStr = MangledDeclNames[CanonicalGD]; 657 if (!FoundStr.empty()) 658 return FoundStr; 659 660 const auto *ND = cast<NamedDecl>(GD.getDecl()); 661 SmallString<256> Buffer; 662 StringRef Str; 663 if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) { 664 llvm::raw_svector_ostream Out(Buffer); 665 if (const auto *D = dyn_cast<CXXConstructorDecl>(ND)) 666 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out); 667 else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND)) 668 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out); 669 else 670 getCXXABI().getMangleContext().mangleName(ND, Out); 671 Str = Out.str(); 672 } else { 673 IdentifierInfo *II = ND->getIdentifier(); 674 assert(II && "Attempt to mangle unnamed decl."); 675 Str = II->getName(); 676 } 677 678 // Keep the first result in the case of a mangling collision. 679 auto Result = Manglings.insert(std::make_pair(Str, GD)); 680 return FoundStr = Result.first->first(); 681 } 682 683 StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD, 684 const BlockDecl *BD) { 685 MangleContext &MangleCtx = getCXXABI().getMangleContext(); 686 const Decl *D = GD.getDecl(); 687 688 SmallString<256> Buffer; 689 llvm::raw_svector_ostream Out(Buffer); 690 if (!D) 691 MangleCtx.mangleGlobalBlock(BD, 692 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out); 693 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D)) 694 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out); 695 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D)) 696 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out); 697 else 698 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out); 699 700 auto Result = Manglings.insert(std::make_pair(Out.str(), BD)); 701 return Result.first->first(); 702 } 703 704 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) { 705 return getModule().getNamedValue(Name); 706 } 707 708 /// AddGlobalCtor - Add a function to the list that will be called before 709 /// main() runs. 710 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority, 711 llvm::Constant *AssociatedData) { 712 // FIXME: Type coercion of void()* types. 713 GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData)); 714 } 715 716 /// AddGlobalDtor - Add a function to the list that will be called 717 /// when the module is unloaded. 718 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) { 719 // FIXME: Type coercion of void()* types. 720 GlobalDtors.push_back(Structor(Priority, Dtor, nullptr)); 721 } 722 723 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) { 724 // Ctor function type is void()*. 725 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false); 726 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy); 727 728 // Get the type of a ctor entry, { i32, void ()*, i8* }. 729 llvm::StructType *CtorStructTy = llvm::StructType::get( 730 Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy, nullptr); 731 732 // Construct the constructor and destructor arrays. 733 SmallVector<llvm::Constant *, 8> Ctors; 734 for (const auto &I : Fns) { 735 llvm::Constant *S[] = { 736 llvm::ConstantInt::get(Int32Ty, I.Priority, false), 737 llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy), 738 (I.AssociatedData 739 ? llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy) 740 : llvm::Constant::getNullValue(VoidPtrTy))}; 741 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S)); 742 } 743 744 if (!Ctors.empty()) { 745 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size()); 746 new llvm::GlobalVariable(TheModule, AT, false, 747 llvm::GlobalValue::AppendingLinkage, 748 llvm::ConstantArray::get(AT, Ctors), 749 GlobalName); 750 } 751 } 752 753 llvm::GlobalValue::LinkageTypes 754 CodeGenModule::getFunctionLinkage(GlobalDecl GD) { 755 const auto *D = cast<FunctionDecl>(GD.getDecl()); 756 757 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D); 758 759 if (isa<CXXDestructorDecl>(D) && 760 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 761 GD.getDtorType())) { 762 // Destructor variants in the Microsoft C++ ABI are always internal or 763 // linkonce_odr thunks emitted on an as-needed basis. 764 return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage 765 : llvm::GlobalValue::LinkOnceODRLinkage; 766 } 767 768 return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false); 769 } 770 771 void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) { 772 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 773 774 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) { 775 if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) { 776 // Don't dllexport/import destructor thunks. 777 F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 778 return; 779 } 780 } 781 782 if (FD->hasAttr<DLLImportAttr>()) 783 F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 784 else if (FD->hasAttr<DLLExportAttr>()) 785 F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 786 else 787 F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 788 } 789 790 llvm::ConstantInt * 791 CodeGenModule::CreateCfiIdForTypeMetadata(llvm::Metadata *MD) { 792 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD); 793 if (!MDS) return nullptr; 794 795 llvm::MD5 md5; 796 llvm::MD5::MD5Result result; 797 md5.update(MDS->getString()); 798 md5.final(result); 799 uint64_t id = 0; 800 for (int i = 0; i < 8; ++i) 801 id |= static_cast<uint64_t>(result[i]) << (i * 8); 802 return llvm::ConstantInt::get(Int64Ty, id); 803 } 804 805 void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D, 806 llvm::Function *F) { 807 setNonAliasAttributes(D, F); 808 } 809 810 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D, 811 const CGFunctionInfo &Info, 812 llvm::Function *F) { 813 unsigned CallingConv; 814 AttributeListType AttributeList; 815 ConstructAttributeList(F->getName(), Info, D, AttributeList, CallingConv, 816 false); 817 F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList)); 818 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 819 } 820 821 /// Determines whether the language options require us to model 822 /// unwind exceptions. We treat -fexceptions as mandating this 823 /// except under the fragile ObjC ABI with only ObjC exceptions 824 /// enabled. This means, for example, that C with -fexceptions 825 /// enables this. 826 static bool hasUnwindExceptions(const LangOptions &LangOpts) { 827 // If exceptions are completely disabled, obviously this is false. 828 if (!LangOpts.Exceptions) return false; 829 830 // If C++ exceptions are enabled, this is true. 831 if (LangOpts.CXXExceptions) return true; 832 833 // If ObjC exceptions are enabled, this depends on the ABI. 834 if (LangOpts.ObjCExceptions) { 835 return LangOpts.ObjCRuntime.hasUnwindExceptions(); 836 } 837 838 return true; 839 } 840 841 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 842 llvm::Function *F) { 843 llvm::AttrBuilder B; 844 845 if (CodeGenOpts.UnwindTables) 846 B.addAttribute(llvm::Attribute::UWTable); 847 848 if (!hasUnwindExceptions(LangOpts)) 849 B.addAttribute(llvm::Attribute::NoUnwind); 850 851 if (LangOpts.getStackProtector() == LangOptions::SSPOn) 852 B.addAttribute(llvm::Attribute::StackProtect); 853 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong) 854 B.addAttribute(llvm::Attribute::StackProtectStrong); 855 else if (LangOpts.getStackProtector() == LangOptions::SSPReq) 856 B.addAttribute(llvm::Attribute::StackProtectReq); 857 858 if (!D) { 859 F->addAttributes(llvm::AttributeSet::FunctionIndex, 860 llvm::AttributeSet::get( 861 F->getContext(), 862 llvm::AttributeSet::FunctionIndex, B)); 863 return; 864 } 865 866 if (D->hasAttr<NakedAttr>()) { 867 // Naked implies noinline: we should not be inlining such functions. 868 B.addAttribute(llvm::Attribute::Naked); 869 B.addAttribute(llvm::Attribute::NoInline); 870 } else if (D->hasAttr<NoDuplicateAttr>()) { 871 B.addAttribute(llvm::Attribute::NoDuplicate); 872 } else if (D->hasAttr<NoInlineAttr>()) { 873 B.addAttribute(llvm::Attribute::NoInline); 874 } else if (D->hasAttr<AlwaysInlineAttr>() && 875 !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex, 876 llvm::Attribute::NoInline)) { 877 // (noinline wins over always_inline, and we can't specify both in IR) 878 B.addAttribute(llvm::Attribute::AlwaysInline); 879 } 880 881 if (D->hasAttr<ColdAttr>()) { 882 if (!D->hasAttr<OptimizeNoneAttr>()) 883 B.addAttribute(llvm::Attribute::OptimizeForSize); 884 B.addAttribute(llvm::Attribute::Cold); 885 } 886 887 if (D->hasAttr<MinSizeAttr>()) 888 B.addAttribute(llvm::Attribute::MinSize); 889 890 F->addAttributes(llvm::AttributeSet::FunctionIndex, 891 llvm::AttributeSet::get( 892 F->getContext(), llvm::AttributeSet::FunctionIndex, B)); 893 894 if (D->hasAttr<OptimizeNoneAttr>()) { 895 // OptimizeNone implies noinline; we should not be inlining such functions. 896 F->addFnAttr(llvm::Attribute::OptimizeNone); 897 F->addFnAttr(llvm::Attribute::NoInline); 898 899 // OptimizeNone wins over OptimizeForSize, MinSize, AlwaysInline. 900 F->removeFnAttr(llvm::Attribute::OptimizeForSize); 901 F->removeFnAttr(llvm::Attribute::MinSize); 902 assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) && 903 "OptimizeNone and AlwaysInline on same function!"); 904 905 // Attribute 'inlinehint' has no effect on 'optnone' functions. 906 // Explicitly remove it from the set of function attributes. 907 F->removeFnAttr(llvm::Attribute::InlineHint); 908 } 909 910 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth(); 911 if (alignment) 912 F->setAlignment(alignment); 913 914 // Some C++ ABIs require 2-byte alignment for member functions, in order to 915 // reserve a bit for differentiating between virtual and non-virtual member 916 // functions. If the current target's C++ ABI requires this and this is a 917 // member function, set its alignment accordingly. 918 if (getTarget().getCXXABI().areMemberFunctionsAligned()) { 919 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) 920 F->setAlignment(2); 921 } 922 } 923 924 void CodeGenModule::SetCommonAttributes(const Decl *D, 925 llvm::GlobalValue *GV) { 926 if (const auto *ND = dyn_cast_or_null<NamedDecl>(D)) 927 setGlobalVisibility(GV, ND); 928 else 929 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 930 931 if (D && D->hasAttr<UsedAttr>()) 932 addUsedGlobal(GV); 933 } 934 935 void CodeGenModule::setAliasAttributes(const Decl *D, 936 llvm::GlobalValue *GV) { 937 SetCommonAttributes(D, GV); 938 939 // Process the dllexport attribute based on whether the original definition 940 // (not necessarily the aliasee) was exported. 941 if (D->hasAttr<DLLExportAttr>()) 942 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 943 } 944 945 void CodeGenModule::setNonAliasAttributes(const Decl *D, 946 llvm::GlobalObject *GO) { 947 SetCommonAttributes(D, GO); 948 949 if (D) 950 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 951 GO->setSection(SA->getName()); 952 953 getTargetCodeGenInfo().setTargetAttributes(D, GO, *this); 954 } 955 956 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D, 957 llvm::Function *F, 958 const CGFunctionInfo &FI) { 959 SetLLVMFunctionAttributes(D, FI, F); 960 SetLLVMFunctionAttributesForDefinition(D, F); 961 962 F->setLinkage(llvm::Function::InternalLinkage); 963 964 setNonAliasAttributes(D, F); 965 } 966 967 static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV, 968 const NamedDecl *ND) { 969 // Set linkage and visibility in case we never see a definition. 970 LinkageInfo LV = ND->getLinkageAndVisibility(); 971 if (LV.getLinkage() != ExternalLinkage) { 972 // Don't set internal linkage on declarations. 973 } else { 974 if (ND->hasAttr<DLLImportAttr>()) { 975 GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 976 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 977 } else if (ND->hasAttr<DLLExportAttr>()) { 978 GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 979 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 980 } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) { 981 // "extern_weak" is overloaded in LLVM; we probably should have 982 // separate linkage types for this. 983 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 984 } 985 986 // Set visibility on a declaration only if it's explicit. 987 if (LV.isVisibilityExplicit()) 988 GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility())); 989 } 990 } 991 992 void CodeGenModule::CreateFunctionBitSetEntry(const FunctionDecl *FD, 993 llvm::Function *F) { 994 // Only if we are checking indirect calls. 995 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall)) 996 return; 997 998 // Non-static class methods are handled via vtable pointer checks elsewhere. 999 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 1000 return; 1001 1002 // Additionally, if building with cross-DSO support... 1003 if (CodeGenOpts.SanitizeCfiCrossDso) { 1004 // Don't emit entries for function declarations. In cross-DSO mode these are 1005 // handled with better precision at run time. 1006 if (!FD->hasBody()) 1007 return; 1008 // Skip available_externally functions. They won't be codegen'ed in the 1009 // current module anyway. 1010 if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally) 1011 return; 1012 } 1013 1014 llvm::NamedMDNode *BitsetsMD = 1015 getModule().getOrInsertNamedMetadata("llvm.bitsets"); 1016 1017 llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType()); 1018 llvm::Metadata *BitsetOps[] = { 1019 MD, llvm::ConstantAsMetadata::get(F), 1020 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int64Ty, 0))}; 1021 BitsetsMD->addOperand(llvm::MDTuple::get(getLLVMContext(), BitsetOps)); 1022 1023 // Emit a hash-based bit set entry for cross-DSO calls. 1024 if (CodeGenOpts.SanitizeCfiCrossDso) { 1025 if (auto TypeId = CreateCfiIdForTypeMetadata(MD)) { 1026 llvm::Metadata *BitsetOps2[] = { 1027 llvm::ConstantAsMetadata::get(TypeId), 1028 llvm::ConstantAsMetadata::get(F), 1029 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int64Ty, 0))}; 1030 BitsetsMD->addOperand(llvm::MDTuple::get(getLLVMContext(), BitsetOps2)); 1031 } 1032 } 1033 } 1034 1035 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F, 1036 bool IsIncompleteFunction, 1037 bool IsThunk) { 1038 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) { 1039 // If this is an intrinsic function, set the function's attributes 1040 // to the intrinsic's attributes. 1041 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID)); 1042 return; 1043 } 1044 1045 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 1046 1047 if (!IsIncompleteFunction) 1048 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F); 1049 1050 // Add the Returned attribute for "this", except for iOS 5 and earlier 1051 // where substantial code, including the libstdc++ dylib, was compiled with 1052 // GCC and does not actually return "this". 1053 if (!IsThunk && getCXXABI().HasThisReturn(GD) && 1054 !(getTarget().getTriple().isiOS() && 1055 getTarget().getTriple().isOSVersionLT(6))) { 1056 assert(!F->arg_empty() && 1057 F->arg_begin()->getType() 1058 ->canLosslesslyBitCastTo(F->getReturnType()) && 1059 "unexpected this return"); 1060 F->addAttribute(1, llvm::Attribute::Returned); 1061 } 1062 1063 // Only a few attributes are set on declarations; these may later be 1064 // overridden by a definition. 1065 1066 setLinkageAndVisibilityForGV(F, FD); 1067 1068 if (const SectionAttr *SA = FD->getAttr<SectionAttr>()) 1069 F->setSection(SA->getName()); 1070 1071 if (FD->isReplaceableGlobalAllocationFunction()) { 1072 // A replaceable global allocation function does not act like a builtin by 1073 // default, only if it is invoked by a new-expression or delete-expression. 1074 F->addAttribute(llvm::AttributeSet::FunctionIndex, 1075 llvm::Attribute::NoBuiltin); 1076 1077 // A sane operator new returns a non-aliasing pointer. 1078 // FIXME: Also add NonNull attribute to the return value 1079 // for the non-nothrow forms? 1080 auto Kind = FD->getDeclName().getCXXOverloadedOperator(); 1081 if (getCodeGenOpts().AssumeSaneOperatorNew && 1082 (Kind == OO_New || Kind == OO_Array_New)) 1083 F->addAttribute(llvm::AttributeSet::ReturnIndex, 1084 llvm::Attribute::NoAlias); 1085 } 1086 1087 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD)) 1088 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1089 else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 1090 if (MD->isVirtual()) 1091 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1092 1093 CreateFunctionBitSetEntry(FD, F); 1094 } 1095 1096 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) { 1097 assert(!GV->isDeclaration() && 1098 "Only globals with definition can force usage."); 1099 LLVMUsed.emplace_back(GV); 1100 } 1101 1102 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) { 1103 assert(!GV->isDeclaration() && 1104 "Only globals with definition can force usage."); 1105 LLVMCompilerUsed.emplace_back(GV); 1106 } 1107 1108 static void emitUsed(CodeGenModule &CGM, StringRef Name, 1109 std::vector<llvm::WeakVH> &List) { 1110 // Don't create llvm.used if there is no need. 1111 if (List.empty()) 1112 return; 1113 1114 // Convert List to what ConstantArray needs. 1115 SmallVector<llvm::Constant*, 8> UsedArray; 1116 UsedArray.resize(List.size()); 1117 for (unsigned i = 0, e = List.size(); i != e; ++i) { 1118 UsedArray[i] = 1119 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 1120 cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy); 1121 } 1122 1123 if (UsedArray.empty()) 1124 return; 1125 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size()); 1126 1127 auto *GV = new llvm::GlobalVariable( 1128 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage, 1129 llvm::ConstantArray::get(ATy, UsedArray), Name); 1130 1131 GV->setSection("llvm.metadata"); 1132 } 1133 1134 void CodeGenModule::emitLLVMUsed() { 1135 emitUsed(*this, "llvm.used", LLVMUsed); 1136 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed); 1137 } 1138 1139 void CodeGenModule::AppendLinkerOptions(StringRef Opts) { 1140 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts); 1141 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 1142 } 1143 1144 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) { 1145 llvm::SmallString<32> Opt; 1146 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt); 1147 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 1148 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 1149 } 1150 1151 void CodeGenModule::AddDependentLib(StringRef Lib) { 1152 llvm::SmallString<24> Opt; 1153 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt); 1154 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 1155 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 1156 } 1157 1158 /// \brief Add link options implied by the given module, including modules 1159 /// it depends on, using a postorder walk. 1160 static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod, 1161 SmallVectorImpl<llvm::Metadata *> &Metadata, 1162 llvm::SmallPtrSet<Module *, 16> &Visited) { 1163 // Import this module's parent. 1164 if (Mod->Parent && Visited.insert(Mod->Parent).second) { 1165 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited); 1166 } 1167 1168 // Import this module's dependencies. 1169 for (unsigned I = Mod->Imports.size(); I > 0; --I) { 1170 if (Visited.insert(Mod->Imports[I - 1]).second) 1171 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited); 1172 } 1173 1174 // Add linker options to link against the libraries/frameworks 1175 // described by this module. 1176 llvm::LLVMContext &Context = CGM.getLLVMContext(); 1177 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) { 1178 // Link against a framework. Frameworks are currently Darwin only, so we 1179 // don't to ask TargetCodeGenInfo for the spelling of the linker option. 1180 if (Mod->LinkLibraries[I-1].IsFramework) { 1181 llvm::Metadata *Args[2] = { 1182 llvm::MDString::get(Context, "-framework"), 1183 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)}; 1184 1185 Metadata.push_back(llvm::MDNode::get(Context, Args)); 1186 continue; 1187 } 1188 1189 // Link against a library. 1190 llvm::SmallString<24> Opt; 1191 CGM.getTargetCodeGenInfo().getDependentLibraryOption( 1192 Mod->LinkLibraries[I-1].Library, Opt); 1193 auto *OptString = llvm::MDString::get(Context, Opt); 1194 Metadata.push_back(llvm::MDNode::get(Context, OptString)); 1195 } 1196 } 1197 1198 void CodeGenModule::EmitModuleLinkOptions() { 1199 // Collect the set of all of the modules we want to visit to emit link 1200 // options, which is essentially the imported modules and all of their 1201 // non-explicit child modules. 1202 llvm::SetVector<clang::Module *> LinkModules; 1203 llvm::SmallPtrSet<clang::Module *, 16> Visited; 1204 SmallVector<clang::Module *, 16> Stack; 1205 1206 // Seed the stack with imported modules. 1207 for (Module *M : ImportedModules) 1208 if (Visited.insert(M).second) 1209 Stack.push_back(M); 1210 1211 // Find all of the modules to import, making a little effort to prune 1212 // non-leaf modules. 1213 while (!Stack.empty()) { 1214 clang::Module *Mod = Stack.pop_back_val(); 1215 1216 bool AnyChildren = false; 1217 1218 // Visit the submodules of this module. 1219 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(), 1220 SubEnd = Mod->submodule_end(); 1221 Sub != SubEnd; ++Sub) { 1222 // Skip explicit children; they need to be explicitly imported to be 1223 // linked against. 1224 if ((*Sub)->IsExplicit) 1225 continue; 1226 1227 if (Visited.insert(*Sub).second) { 1228 Stack.push_back(*Sub); 1229 AnyChildren = true; 1230 } 1231 } 1232 1233 // We didn't find any children, so add this module to the list of 1234 // modules to link against. 1235 if (!AnyChildren) { 1236 LinkModules.insert(Mod); 1237 } 1238 } 1239 1240 // Add link options for all of the imported modules in reverse topological 1241 // order. We don't do anything to try to order import link flags with respect 1242 // to linker options inserted by things like #pragma comment(). 1243 SmallVector<llvm::Metadata *, 16> MetadataArgs; 1244 Visited.clear(); 1245 for (Module *M : LinkModules) 1246 if (Visited.insert(M).second) 1247 addLinkOptionsPostorder(*this, M, MetadataArgs, Visited); 1248 std::reverse(MetadataArgs.begin(), MetadataArgs.end()); 1249 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end()); 1250 1251 // Add the linker options metadata flag. 1252 getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options", 1253 llvm::MDNode::get(getLLVMContext(), 1254 LinkerOptionsMetadata)); 1255 } 1256 1257 void CodeGenModule::EmitDeferred() { 1258 // Emit code for any potentially referenced deferred decls. Since a 1259 // previously unused static decl may become used during the generation of code 1260 // for a static function, iterate until no changes are made. 1261 1262 if (!DeferredVTables.empty()) { 1263 EmitDeferredVTables(); 1264 1265 // Emitting a vtable doesn't directly cause more vtables to 1266 // become deferred, although it can cause functions to be 1267 // emitted that then need those vtables. 1268 assert(DeferredVTables.empty()); 1269 } 1270 1271 // Stop if we're out of both deferred vtables and deferred declarations. 1272 if (DeferredDeclsToEmit.empty()) 1273 return; 1274 1275 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more 1276 // work, it will not interfere with this. 1277 std::vector<DeferredGlobal> CurDeclsToEmit; 1278 CurDeclsToEmit.swap(DeferredDeclsToEmit); 1279 1280 for (DeferredGlobal &G : CurDeclsToEmit) { 1281 GlobalDecl D = G.GD; 1282 G.GV = nullptr; 1283 1284 // We should call GetAddrOfGlobal with IsForDefinition set to true in order 1285 // to get GlobalValue with exactly the type we need, not something that 1286 // might had been created for another decl with the same mangled name but 1287 // different type. 1288 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>( 1289 GetAddrOfGlobal(D, /*IsForDefinition=*/true)); 1290 1291 // In case of different address spaces, we may still get a cast, even with 1292 // IsForDefinition equal to true. Query mangled names table to get 1293 // GlobalValue. 1294 if (!GV) 1295 GV = GetGlobalValue(getMangledName(D)); 1296 1297 // Make sure GetGlobalValue returned non-null. 1298 assert(GV); 1299 1300 // Check to see if we've already emitted this. This is necessary 1301 // for a couple of reasons: first, decls can end up in the 1302 // deferred-decls queue multiple times, and second, decls can end 1303 // up with definitions in unusual ways (e.g. by an extern inline 1304 // function acquiring a strong function redefinition). Just 1305 // ignore these cases. 1306 if (!GV->isDeclaration()) 1307 continue; 1308 1309 // Otherwise, emit the definition and move on to the next one. 1310 EmitGlobalDefinition(D, GV); 1311 1312 // If we found out that we need to emit more decls, do that recursively. 1313 // This has the advantage that the decls are emitted in a DFS and related 1314 // ones are close together, which is convenient for testing. 1315 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) { 1316 EmitDeferred(); 1317 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty()); 1318 } 1319 } 1320 } 1321 1322 void CodeGenModule::EmitGlobalAnnotations() { 1323 if (Annotations.empty()) 1324 return; 1325 1326 // Create a new global variable for the ConstantStruct in the Module. 1327 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( 1328 Annotations[0]->getType(), Annotations.size()), Annotations); 1329 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false, 1330 llvm::GlobalValue::AppendingLinkage, 1331 Array, "llvm.global.annotations"); 1332 gv->setSection(AnnotationSection); 1333 } 1334 1335 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) { 1336 llvm::Constant *&AStr = AnnotationStrings[Str]; 1337 if (AStr) 1338 return AStr; 1339 1340 // Not found yet, create a new global. 1341 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str); 1342 auto *gv = 1343 new llvm::GlobalVariable(getModule(), s->getType(), true, 1344 llvm::GlobalValue::PrivateLinkage, s, ".str"); 1345 gv->setSection(AnnotationSection); 1346 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1347 AStr = gv; 1348 return gv; 1349 } 1350 1351 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { 1352 SourceManager &SM = getContext().getSourceManager(); 1353 PresumedLoc PLoc = SM.getPresumedLoc(Loc); 1354 if (PLoc.isValid()) 1355 return EmitAnnotationString(PLoc.getFilename()); 1356 return EmitAnnotationString(SM.getBufferName(Loc)); 1357 } 1358 1359 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { 1360 SourceManager &SM = getContext().getSourceManager(); 1361 PresumedLoc PLoc = SM.getPresumedLoc(L); 1362 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : 1363 SM.getExpansionLineNumber(L); 1364 return llvm::ConstantInt::get(Int32Ty, LineNo); 1365 } 1366 1367 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 1368 const AnnotateAttr *AA, 1369 SourceLocation L) { 1370 // Get the globals for file name, annotation, and the line number. 1371 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), 1372 *UnitGV = EmitAnnotationUnit(L), 1373 *LineNoCst = EmitAnnotationLineNo(L); 1374 1375 // Create the ConstantStruct for the global annotation. 1376 llvm::Constant *Fields[4] = { 1377 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy), 1378 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy), 1379 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy), 1380 LineNoCst 1381 }; 1382 return llvm::ConstantStruct::getAnon(Fields); 1383 } 1384 1385 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, 1386 llvm::GlobalValue *GV) { 1387 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 1388 // Get the struct elements for these annotations. 1389 for (const auto *I : D->specific_attrs<AnnotateAttr>()) 1390 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation())); 1391 } 1392 1393 bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn, 1394 SourceLocation Loc) const { 1395 const auto &SanitizerBL = getContext().getSanitizerBlacklist(); 1396 // Blacklist by function name. 1397 if (SanitizerBL.isBlacklistedFunction(Fn->getName())) 1398 return true; 1399 // Blacklist by location. 1400 if (Loc.isValid()) 1401 return SanitizerBL.isBlacklistedLocation(Loc); 1402 // If location is unknown, this may be a compiler-generated function. Assume 1403 // it's located in the main file. 1404 auto &SM = Context.getSourceManager(); 1405 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 1406 return SanitizerBL.isBlacklistedFile(MainFile->getName()); 1407 } 1408 return false; 1409 } 1410 1411 bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV, 1412 SourceLocation Loc, QualType Ty, 1413 StringRef Category) const { 1414 // For now globals can be blacklisted only in ASan and KASan. 1415 if (!LangOpts.Sanitize.hasOneOf( 1416 SanitizerKind::Address | SanitizerKind::KernelAddress)) 1417 return false; 1418 const auto &SanitizerBL = getContext().getSanitizerBlacklist(); 1419 if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category)) 1420 return true; 1421 if (SanitizerBL.isBlacklistedLocation(Loc, Category)) 1422 return true; 1423 // Check global type. 1424 if (!Ty.isNull()) { 1425 // Drill down the array types: if global variable of a fixed type is 1426 // blacklisted, we also don't instrument arrays of them. 1427 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr())) 1428 Ty = AT->getElementType(); 1429 Ty = Ty.getCanonicalType().getUnqualifiedType(); 1430 // We allow to blacklist only record types (classes, structs etc.) 1431 if (Ty->isRecordType()) { 1432 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy()); 1433 if (SanitizerBL.isBlacklistedType(TypeStr, Category)) 1434 return true; 1435 } 1436 } 1437 return false; 1438 } 1439 1440 bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) { 1441 // Never defer when EmitAllDecls is specified. 1442 if (LangOpts.EmitAllDecls) 1443 return true; 1444 1445 return getContext().DeclMustBeEmitted(Global); 1446 } 1447 1448 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) { 1449 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) 1450 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1451 // Implicit template instantiations may change linkage if they are later 1452 // explicitly instantiated, so they should not be emitted eagerly. 1453 return false; 1454 // If OpenMP is enabled and threadprivates must be generated like TLS, delay 1455 // codegen for global variables, because they may be marked as threadprivate. 1456 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS && 1457 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global)) 1458 return false; 1459 1460 return true; 1461 } 1462 1463 ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor( 1464 const CXXUuidofExpr* E) { 1465 // Sema has verified that IIDSource has a __declspec(uuid()), and that its 1466 // well-formed. 1467 StringRef Uuid = E->getUuidStr(); 1468 std::string Name = "_GUID_" + Uuid.lower(); 1469 std::replace(Name.begin(), Name.end(), '-', '_'); 1470 1471 // The UUID descriptor should be pointer aligned. 1472 CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes); 1473 1474 // Look for an existing global. 1475 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 1476 return ConstantAddress(GV, Alignment); 1477 1478 llvm::Constant *Init = EmitUuidofInitializer(Uuid); 1479 assert(Init && "failed to initialize as constant"); 1480 1481 auto *GV = new llvm::GlobalVariable( 1482 getModule(), Init->getType(), 1483 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); 1484 if (supportsCOMDAT()) 1485 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 1486 return ConstantAddress(GV, Alignment); 1487 } 1488 1489 ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 1490 const AliasAttr *AA = VD->getAttr<AliasAttr>(); 1491 assert(AA && "No alias?"); 1492 1493 CharUnits Alignment = getContext().getDeclAlign(VD); 1494 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 1495 1496 // See if there is already something with the target's name in the module. 1497 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 1498 if (Entry) { 1499 unsigned AS = getContext().getTargetAddressSpace(VD->getType()); 1500 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS)); 1501 return ConstantAddress(Ptr, Alignment); 1502 } 1503 1504 llvm::Constant *Aliasee; 1505 if (isa<llvm::FunctionType>(DeclTy)) 1506 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, 1507 GlobalDecl(cast<FunctionDecl>(VD)), 1508 /*ForVTable=*/false); 1509 else 1510 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 1511 llvm::PointerType::getUnqual(DeclTy), 1512 nullptr); 1513 1514 auto *F = cast<llvm::GlobalValue>(Aliasee); 1515 F->setLinkage(llvm::Function::ExternalWeakLinkage); 1516 WeakRefReferences.insert(F); 1517 1518 return ConstantAddress(Aliasee, Alignment); 1519 } 1520 1521 void CodeGenModule::EmitGlobal(GlobalDecl GD) { 1522 const auto *Global = cast<ValueDecl>(GD.getDecl()); 1523 1524 // Weak references don't produce any output by themselves. 1525 if (Global->hasAttr<WeakRefAttr>()) 1526 return; 1527 1528 // If this is an alias definition (which otherwise looks like a declaration) 1529 // emit it now. 1530 if (Global->hasAttr<AliasAttr>()) 1531 return EmitAliasDefinition(GD); 1532 1533 // IFunc like an alias whose value is resolved at runtime by calling resolver. 1534 if (Global->hasAttr<IFuncAttr>()) 1535 return emitIFuncDefinition(GD); 1536 1537 // If this is CUDA, be selective about which declarations we emit. 1538 if (LangOpts.CUDA) { 1539 if (LangOpts.CUDAIsDevice) { 1540 if (!Global->hasAttr<CUDADeviceAttr>() && 1541 !Global->hasAttr<CUDAGlobalAttr>() && 1542 !Global->hasAttr<CUDAConstantAttr>() && 1543 !Global->hasAttr<CUDASharedAttr>()) 1544 return; 1545 } else { 1546 // We need to emit host-side 'shadows' for all global 1547 // device-side variables because the CUDA runtime needs their 1548 // size and host-side address in order to provide access to 1549 // their device-side incarnations. 1550 1551 // So device-only functions are the only things we skip. 1552 if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() && 1553 Global->hasAttr<CUDADeviceAttr>()) 1554 return; 1555 1556 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) && 1557 "Expected Variable or Function"); 1558 } 1559 } 1560 1561 if (LangOpts.OpenMP) { 1562 // If this is OpenMP device, check if it is legal to emit this global 1563 // normally. 1564 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD)) 1565 return; 1566 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) { 1567 if (MustBeEmitted(Global)) 1568 EmitOMPDeclareReduction(DRD); 1569 return; 1570 } 1571 } 1572 1573 // Ignore declarations, they will be emitted on their first use. 1574 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { 1575 // Forward declarations are emitted lazily on first use. 1576 if (!FD->doesThisDeclarationHaveABody()) { 1577 if (!FD->doesDeclarationForceExternallyVisibleDefinition()) 1578 return; 1579 1580 StringRef MangledName = getMangledName(GD); 1581 1582 // Compute the function info and LLVM type. 1583 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 1584 llvm::Type *Ty = getTypes().GetFunctionType(FI); 1585 1586 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false, 1587 /*DontDefer=*/false); 1588 return; 1589 } 1590 } else { 1591 const auto *VD = cast<VarDecl>(Global); 1592 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 1593 // We need to emit device-side global CUDA variables even if a 1594 // variable does not have a definition -- we still need to define 1595 // host-side shadow for it. 1596 bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice && 1597 !VD->hasDefinition() && 1598 (VD->hasAttr<CUDAConstantAttr>() || 1599 VD->hasAttr<CUDADeviceAttr>()); 1600 if (!MustEmitForCuda && 1601 VD->isThisDeclarationADefinition() != VarDecl::Definition && 1602 !Context.isMSStaticDataMemberInlineDefinition(VD)) 1603 return; 1604 } 1605 1606 // Defer code generation to first use when possible, e.g. if this is an inline 1607 // function. If the global must always be emitted, do it eagerly if possible 1608 // to benefit from cache locality. 1609 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) { 1610 // Emit the definition if it can't be deferred. 1611 EmitGlobalDefinition(GD); 1612 return; 1613 } 1614 1615 // If we're deferring emission of a C++ variable with an 1616 // initializer, remember the order in which it appeared in the file. 1617 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) && 1618 cast<VarDecl>(Global)->hasInit()) { 1619 DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 1620 CXXGlobalInits.push_back(nullptr); 1621 } 1622 1623 StringRef MangledName = getMangledName(GD); 1624 if (llvm::GlobalValue *GV = GetGlobalValue(MangledName)) { 1625 // The value has already been used and should therefore be emitted. 1626 addDeferredDeclToEmit(GV, GD); 1627 } else if (MustBeEmitted(Global)) { 1628 // The value must be emitted, but cannot be emitted eagerly. 1629 assert(!MayBeEmittedEagerly(Global)); 1630 addDeferredDeclToEmit(/*GV=*/nullptr, GD); 1631 } else { 1632 // Otherwise, remember that we saw a deferred decl with this name. The 1633 // first use of the mangled name will cause it to move into 1634 // DeferredDeclsToEmit. 1635 DeferredDecls[MangledName] = GD; 1636 } 1637 } 1638 1639 namespace { 1640 struct FunctionIsDirectlyRecursive : 1641 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> { 1642 const StringRef Name; 1643 const Builtin::Context &BI; 1644 bool Result; 1645 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) : 1646 Name(N), BI(C), Result(false) { 1647 } 1648 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base; 1649 1650 bool TraverseCallExpr(CallExpr *E) { 1651 const FunctionDecl *FD = E->getDirectCallee(); 1652 if (!FD) 1653 return true; 1654 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 1655 if (Attr && Name == Attr->getLabel()) { 1656 Result = true; 1657 return false; 1658 } 1659 unsigned BuiltinID = FD->getBuiltinID(); 1660 if (!BuiltinID || !BI.isLibFunction(BuiltinID)) 1661 return true; 1662 StringRef BuiltinName = BI.getName(BuiltinID); 1663 if (BuiltinName.startswith("__builtin_") && 1664 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) { 1665 Result = true; 1666 return false; 1667 } 1668 return true; 1669 } 1670 }; 1671 1672 struct DLLImportFunctionVisitor 1673 : public RecursiveASTVisitor<DLLImportFunctionVisitor> { 1674 bool SafeToInline = true; 1675 1676 bool VisitVarDecl(VarDecl *VD) { 1677 // A thread-local variable cannot be imported. 1678 SafeToInline = !VD->getTLSKind(); 1679 return SafeToInline; 1680 } 1681 1682 // Make sure we're not referencing non-imported vars or functions. 1683 bool VisitDeclRefExpr(DeclRefExpr *E) { 1684 ValueDecl *VD = E->getDecl(); 1685 if (isa<FunctionDecl>(VD)) 1686 SafeToInline = VD->hasAttr<DLLImportAttr>(); 1687 else if (VarDecl *V = dyn_cast<VarDecl>(VD)) 1688 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>(); 1689 return SafeToInline; 1690 } 1691 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) { 1692 SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>(); 1693 return SafeToInline; 1694 } 1695 bool VisitCXXNewExpr(CXXNewExpr *E) { 1696 SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>(); 1697 return SafeToInline; 1698 } 1699 }; 1700 } 1701 1702 // isTriviallyRecursive - Check if this function calls another 1703 // decl that, because of the asm attribute or the other decl being a builtin, 1704 // ends up pointing to itself. 1705 bool 1706 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) { 1707 StringRef Name; 1708 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) { 1709 // asm labels are a special kind of mangling we have to support. 1710 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 1711 if (!Attr) 1712 return false; 1713 Name = Attr->getLabel(); 1714 } else { 1715 Name = FD->getName(); 1716 } 1717 1718 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo); 1719 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD)); 1720 return Walker.Result; 1721 } 1722 1723 bool 1724 CodeGenModule::shouldEmitFunction(GlobalDecl GD) { 1725 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage) 1726 return true; 1727 const auto *F = cast<FunctionDecl>(GD.getDecl()); 1728 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>()) 1729 return false; 1730 1731 if (F->hasAttr<DLLImportAttr>()) { 1732 // Check whether it would be safe to inline this dllimport function. 1733 DLLImportFunctionVisitor Visitor; 1734 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F)); 1735 if (!Visitor.SafeToInline) 1736 return false; 1737 } 1738 1739 // PR9614. Avoid cases where the source code is lying to us. An available 1740 // externally function should have an equivalent function somewhere else, 1741 // but a function that calls itself is clearly not equivalent to the real 1742 // implementation. 1743 // This happens in glibc's btowc and in some configure checks. 1744 return !isTriviallyRecursive(F); 1745 } 1746 1747 /// If the type for the method's class was generated by 1748 /// CGDebugInfo::createContextChain(), the cache contains only a 1749 /// limited DIType without any declarations. Since EmitFunctionStart() 1750 /// needs to find the canonical declaration for each method, we need 1751 /// to construct the complete type prior to emitting the method. 1752 void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) { 1753 if (!D->isInstance()) 1754 return; 1755 1756 if (CGDebugInfo *DI = getModuleDebugInfo()) 1757 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) { 1758 const auto *ThisPtr = cast<PointerType>(D->getThisType(getContext())); 1759 DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation()); 1760 } 1761 } 1762 1763 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) { 1764 const auto *D = cast<ValueDecl>(GD.getDecl()); 1765 1766 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 1767 Context.getSourceManager(), 1768 "Generating code for declaration"); 1769 1770 if (isa<FunctionDecl>(D)) { 1771 // At -O0, don't generate IR for functions with available_externally 1772 // linkage. 1773 if (!shouldEmitFunction(GD)) 1774 return; 1775 1776 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) { 1777 CompleteDIClassType(Method); 1778 // Make sure to emit the definition(s) before we emit the thunks. 1779 // This is necessary for the generation of certain thunks. 1780 if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method)) 1781 ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType())); 1782 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method)) 1783 ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType())); 1784 else 1785 EmitGlobalFunctionDefinition(GD, GV); 1786 1787 if (Method->isVirtual()) 1788 getVTables().EmitThunks(GD); 1789 1790 return; 1791 } 1792 1793 return EmitGlobalFunctionDefinition(GD, GV); 1794 } 1795 1796 if (const auto *VD = dyn_cast<VarDecl>(D)) 1797 return EmitGlobalVarDefinition(VD, !VD->hasDefinition()); 1798 1799 llvm_unreachable("Invalid argument to EmitGlobalDefinition()"); 1800 } 1801 1802 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 1803 llvm::Function *NewFn); 1804 1805 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 1806 /// module, create and return an llvm Function with the specified type. If there 1807 /// is something in the module with the specified name, return it potentially 1808 /// bitcasted to the right type. 1809 /// 1810 /// If D is non-null, it specifies a decl that correspond to this. This is used 1811 /// to set the attributes on the function when it is first created. 1812 llvm::Constant * 1813 CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName, 1814 llvm::Type *Ty, 1815 GlobalDecl GD, bool ForVTable, 1816 bool DontDefer, bool IsThunk, 1817 llvm::AttributeSet ExtraAttrs, 1818 bool IsForDefinition) { 1819 const Decl *D = GD.getDecl(); 1820 1821 // Lookup the entry, lazily creating it if necessary. 1822 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1823 if (Entry) { 1824 if (WeakRefReferences.erase(Entry)) { 1825 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D); 1826 if (FD && !FD->hasAttr<WeakAttr>()) 1827 Entry->setLinkage(llvm::Function::ExternalLinkage); 1828 } 1829 1830 // Handle dropped DLL attributes. 1831 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) 1832 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 1833 1834 // If there are two attempts to define the same mangled name, issue an 1835 // error. 1836 if (IsForDefinition && !Entry->isDeclaration()) { 1837 GlobalDecl OtherGD; 1838 // Check that GD is not yet in DiagnosedConflictingDefinitions is required 1839 // to make sure that we issue an error only once. 1840 if (lookupRepresentativeDecl(MangledName, OtherGD) && 1841 (GD.getCanonicalDecl().getDecl() != 1842 OtherGD.getCanonicalDecl().getDecl()) && 1843 DiagnosedConflictingDefinitions.insert(GD).second) { 1844 getDiags().Report(D->getLocation(), 1845 diag::err_duplicate_mangled_name); 1846 getDiags().Report(OtherGD.getDecl()->getLocation(), 1847 diag::note_previous_definition); 1848 } 1849 } 1850 1851 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) && 1852 (Entry->getType()->getElementType() == Ty)) { 1853 return Entry; 1854 } 1855 1856 // Make sure the result is of the correct type. 1857 // (If function is requested for a definition, we always need to create a new 1858 // function, not just return a bitcast.) 1859 if (!IsForDefinition) 1860 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo()); 1861 } 1862 1863 // This function doesn't have a complete type (for example, the return 1864 // type is an incomplete struct). Use a fake type instead, and make 1865 // sure not to try to set attributes. 1866 bool IsIncompleteFunction = false; 1867 1868 llvm::FunctionType *FTy; 1869 if (isa<llvm::FunctionType>(Ty)) { 1870 FTy = cast<llvm::FunctionType>(Ty); 1871 } else { 1872 FTy = llvm::FunctionType::get(VoidTy, false); 1873 IsIncompleteFunction = true; 1874 } 1875 1876 llvm::Function *F = 1877 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage, 1878 Entry ? StringRef() : MangledName, &getModule()); 1879 1880 // If we already created a function with the same mangled name (but different 1881 // type) before, take its name and add it to the list of functions to be 1882 // replaced with F at the end of CodeGen. 1883 // 1884 // This happens if there is a prototype for a function (e.g. "int f()") and 1885 // then a definition of a different type (e.g. "int f(int x)"). 1886 if (Entry) { 1887 F->takeName(Entry); 1888 1889 // This might be an implementation of a function without a prototype, in 1890 // which case, try to do special replacement of calls which match the new 1891 // prototype. The really key thing here is that we also potentially drop 1892 // arguments from the call site so as to make a direct call, which makes the 1893 // inliner happier and suppresses a number of optimizer warnings (!) about 1894 // dropping arguments. 1895 if (!Entry->use_empty()) { 1896 ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F); 1897 Entry->removeDeadConstantUsers(); 1898 } 1899 1900 llvm::Constant *BC = llvm::ConstantExpr::getBitCast( 1901 F, Entry->getType()->getElementType()->getPointerTo()); 1902 addGlobalValReplacement(Entry, BC); 1903 } 1904 1905 assert(F->getName() == MangledName && "name was uniqued!"); 1906 if (D) 1907 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk); 1908 if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) { 1909 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex); 1910 F->addAttributes(llvm::AttributeSet::FunctionIndex, 1911 llvm::AttributeSet::get(VMContext, 1912 llvm::AttributeSet::FunctionIndex, 1913 B)); 1914 } 1915 1916 if (!DontDefer) { 1917 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to 1918 // each other bottoming out with the base dtor. Therefore we emit non-base 1919 // dtors on usage, even if there is no dtor definition in the TU. 1920 if (D && isa<CXXDestructorDecl>(D) && 1921 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 1922 GD.getDtorType())) 1923 addDeferredDeclToEmit(F, GD); 1924 1925 // This is the first use or definition of a mangled name. If there is a 1926 // deferred decl with this name, remember that we need to emit it at the end 1927 // of the file. 1928 auto DDI = DeferredDecls.find(MangledName); 1929 if (DDI != DeferredDecls.end()) { 1930 // Move the potentially referenced deferred decl to the 1931 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we 1932 // don't need it anymore). 1933 addDeferredDeclToEmit(F, DDI->second); 1934 DeferredDecls.erase(DDI); 1935 1936 // Otherwise, there are cases we have to worry about where we're 1937 // using a declaration for which we must emit a definition but where 1938 // we might not find a top-level definition: 1939 // - member functions defined inline in their classes 1940 // - friend functions defined inline in some class 1941 // - special member functions with implicit definitions 1942 // If we ever change our AST traversal to walk into class methods, 1943 // this will be unnecessary. 1944 // 1945 // We also don't emit a definition for a function if it's going to be an 1946 // entry in a vtable, unless it's already marked as used. 1947 } else if (getLangOpts().CPlusPlus && D) { 1948 // Look for a declaration that's lexically in a record. 1949 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD; 1950 FD = FD->getPreviousDecl()) { 1951 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 1952 if (FD->doesThisDeclarationHaveABody()) { 1953 addDeferredDeclToEmit(F, GD.getWithDecl(FD)); 1954 break; 1955 } 1956 } 1957 } 1958 } 1959 } 1960 1961 // Make sure the result is of the requested type. 1962 if (!IsIncompleteFunction) { 1963 assert(F->getType()->getElementType() == Ty); 1964 return F; 1965 } 1966 1967 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 1968 return llvm::ConstantExpr::getBitCast(F, PTy); 1969 } 1970 1971 /// GetAddrOfFunction - Return the address of the given function. If Ty is 1972 /// non-null, then this function will use the specified type if it has to 1973 /// create it (this occurs when we see a definition of the function). 1974 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 1975 llvm::Type *Ty, 1976 bool ForVTable, 1977 bool DontDefer, 1978 bool IsForDefinition) { 1979 // If there was no specific requested type, just convert it now. 1980 if (!Ty) { 1981 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 1982 auto CanonTy = Context.getCanonicalType(FD->getType()); 1983 Ty = getTypes().ConvertFunctionType(CanonTy, FD); 1984 } 1985 1986 StringRef MangledName = getMangledName(GD); 1987 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer, 1988 /*IsThunk=*/false, llvm::AttributeSet(), 1989 IsForDefinition); 1990 } 1991 1992 /// CreateRuntimeFunction - Create a new runtime function with the specified 1993 /// type and name. 1994 llvm::Constant * 1995 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, 1996 StringRef Name, 1997 llvm::AttributeSet ExtraAttrs) { 1998 llvm::Constant *C = 1999 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 2000 /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs); 2001 if (auto *F = dyn_cast<llvm::Function>(C)) 2002 if (F->empty()) 2003 F->setCallingConv(getRuntimeCC()); 2004 return C; 2005 } 2006 2007 /// CreateBuiltinFunction - Create a new builtin function with the specified 2008 /// type and name. 2009 llvm::Constant * 2010 CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, 2011 StringRef Name, 2012 llvm::AttributeSet ExtraAttrs) { 2013 llvm::Constant *C = 2014 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 2015 /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs); 2016 if (auto *F = dyn_cast<llvm::Function>(C)) 2017 if (F->empty()) 2018 F->setCallingConv(getBuiltinCC()); 2019 return C; 2020 } 2021 2022 /// isTypeConstant - Determine whether an object of this type can be emitted 2023 /// as a constant. 2024 /// 2025 /// If ExcludeCtor is true, the duration when the object's constructor runs 2026 /// will not be considered. The caller will need to verify that the object is 2027 /// not written to during its construction. 2028 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) { 2029 if (!Ty.isConstant(Context) && !Ty->isReferenceType()) 2030 return false; 2031 2032 if (Context.getLangOpts().CPlusPlus) { 2033 if (const CXXRecordDecl *Record 2034 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl()) 2035 return ExcludeCtor && !Record->hasMutableFields() && 2036 Record->hasTrivialDestructor(); 2037 } 2038 2039 return true; 2040 } 2041 2042 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 2043 /// create and return an llvm GlobalVariable with the specified type. If there 2044 /// is something in the module with the specified name, return it potentially 2045 /// bitcasted to the right type. 2046 /// 2047 /// If D is non-null, it specifies a decl that correspond to this. This is used 2048 /// to set the attributes on the global when it is first created. 2049 /// 2050 /// If IsForDefinition is true, it is guranteed that an actual global with 2051 /// type Ty will be returned, not conversion of a variable with the same 2052 /// mangled name but some other type. 2053 llvm::Constant * 2054 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, 2055 llvm::PointerType *Ty, 2056 const VarDecl *D, 2057 bool IsForDefinition) { 2058 // Lookup the entry, lazily creating it if necessary. 2059 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 2060 if (Entry) { 2061 if (WeakRefReferences.erase(Entry)) { 2062 if (D && !D->hasAttr<WeakAttr>()) 2063 Entry->setLinkage(llvm::Function::ExternalLinkage); 2064 } 2065 2066 // Handle dropped DLL attributes. 2067 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) 2068 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 2069 2070 if (Entry->getType() == Ty) 2071 return Entry; 2072 2073 // If there are two attempts to define the same mangled name, issue an 2074 // error. 2075 if (IsForDefinition && !Entry->isDeclaration()) { 2076 GlobalDecl OtherGD; 2077 const VarDecl *OtherD; 2078 2079 // Check that D is not yet in DiagnosedConflictingDefinitions is required 2080 // to make sure that we issue an error only once. 2081 if (D && lookupRepresentativeDecl(MangledName, OtherGD) && 2082 (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) && 2083 (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) && 2084 OtherD->hasInit() && 2085 DiagnosedConflictingDefinitions.insert(D).second) { 2086 getDiags().Report(D->getLocation(), 2087 diag::err_duplicate_mangled_name); 2088 getDiags().Report(OtherGD.getDecl()->getLocation(), 2089 diag::note_previous_definition); 2090 } 2091 } 2092 2093 // Make sure the result is of the correct type. 2094 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace()) 2095 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty); 2096 2097 // (If global is requested for a definition, we always need to create a new 2098 // global, not just return a bitcast.) 2099 if (!IsForDefinition) 2100 return llvm::ConstantExpr::getBitCast(Entry, Ty); 2101 } 2102 2103 unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace()); 2104 auto *GV = new llvm::GlobalVariable( 2105 getModule(), Ty->getElementType(), false, 2106 llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr, 2107 llvm::GlobalVariable::NotThreadLocal, AddrSpace); 2108 2109 // If we already created a global with the same mangled name (but different 2110 // type) before, take its name and remove it from its parent. 2111 if (Entry) { 2112 GV->takeName(Entry); 2113 2114 if (!Entry->use_empty()) { 2115 llvm::Constant *NewPtrForOldDecl = 2116 llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 2117 Entry->replaceAllUsesWith(NewPtrForOldDecl); 2118 } 2119 2120 Entry->eraseFromParent(); 2121 } 2122 2123 // This is the first use or definition of a mangled name. If there is a 2124 // deferred decl with this name, remember that we need to emit it at the end 2125 // of the file. 2126 auto DDI = DeferredDecls.find(MangledName); 2127 if (DDI != DeferredDecls.end()) { 2128 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 2129 // list, and remove it from DeferredDecls (since we don't need it anymore). 2130 addDeferredDeclToEmit(GV, DDI->second); 2131 DeferredDecls.erase(DDI); 2132 } 2133 2134 // Handle things which are present even on external declarations. 2135 if (D) { 2136 // FIXME: This code is overly simple and should be merged with other global 2137 // handling. 2138 GV->setConstant(isTypeConstant(D->getType(), false)); 2139 2140 GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 2141 2142 setLinkageAndVisibilityForGV(GV, D); 2143 2144 if (D->getTLSKind()) { 2145 if (D->getTLSKind() == VarDecl::TLS_Dynamic) 2146 CXXThreadLocals.push_back(D); 2147 setTLSMode(GV, *D); 2148 } 2149 2150 // If required by the ABI, treat declarations of static data members with 2151 // inline initializers as definitions. 2152 if (getContext().isMSStaticDataMemberInlineDefinition(D)) { 2153 EmitGlobalVarDefinition(D); 2154 } 2155 2156 // Handle XCore specific ABI requirements. 2157 if (getTarget().getTriple().getArch() == llvm::Triple::xcore && 2158 D->getLanguageLinkage() == CLanguageLinkage && 2159 D->getType().isConstant(Context) && 2160 isExternallyVisible(D->getLinkageAndVisibility().getLinkage())) 2161 GV->setSection(".cp.rodata"); 2162 } 2163 2164 if (AddrSpace != Ty->getAddressSpace()) 2165 return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty); 2166 2167 return GV; 2168 } 2169 2170 llvm::Constant * 2171 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, 2172 bool IsForDefinition) { 2173 if (isa<CXXConstructorDecl>(GD.getDecl())) 2174 return getAddrOfCXXStructor(cast<CXXConstructorDecl>(GD.getDecl()), 2175 getFromCtorType(GD.getCtorType()), 2176 /*FnInfo=*/nullptr, /*FnType=*/nullptr, 2177 /*DontDefer=*/false, IsForDefinition); 2178 else if (isa<CXXDestructorDecl>(GD.getDecl())) 2179 return getAddrOfCXXStructor(cast<CXXDestructorDecl>(GD.getDecl()), 2180 getFromDtorType(GD.getDtorType()), 2181 /*FnInfo=*/nullptr, /*FnType=*/nullptr, 2182 /*DontDefer=*/false, IsForDefinition); 2183 else if (isa<CXXMethodDecl>(GD.getDecl())) { 2184 auto FInfo = &getTypes().arrangeCXXMethodDeclaration( 2185 cast<CXXMethodDecl>(GD.getDecl())); 2186 auto Ty = getTypes().GetFunctionType(*FInfo); 2187 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 2188 IsForDefinition); 2189 } else if (isa<FunctionDecl>(GD.getDecl())) { 2190 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 2191 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 2192 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 2193 IsForDefinition); 2194 } else 2195 return GetAddrOfGlobalVar(cast<VarDecl>(GD.getDecl()), /*Ty=*/nullptr, 2196 IsForDefinition); 2197 } 2198 2199 llvm::GlobalVariable * 2200 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name, 2201 llvm::Type *Ty, 2202 llvm::GlobalValue::LinkageTypes Linkage) { 2203 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); 2204 llvm::GlobalVariable *OldGV = nullptr; 2205 2206 if (GV) { 2207 // Check if the variable has the right type. 2208 if (GV->getType()->getElementType() == Ty) 2209 return GV; 2210 2211 // Because C++ name mangling, the only way we can end up with an already 2212 // existing global with the same name is if it has been declared extern "C". 2213 assert(GV->isDeclaration() && "Declaration has wrong type!"); 2214 OldGV = GV; 2215 } 2216 2217 // Create a new variable. 2218 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, 2219 Linkage, nullptr, Name); 2220 2221 if (OldGV) { 2222 // Replace occurrences of the old variable if needed. 2223 GV->takeName(OldGV); 2224 2225 if (!OldGV->use_empty()) { 2226 llvm::Constant *NewPtrForOldDecl = 2227 llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 2228 OldGV->replaceAllUsesWith(NewPtrForOldDecl); 2229 } 2230 2231 OldGV->eraseFromParent(); 2232 } 2233 2234 if (supportsCOMDAT() && GV->isWeakForLinker() && 2235 !GV->hasAvailableExternallyLinkage()) 2236 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 2237 2238 return GV; 2239 } 2240 2241 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 2242 /// given global variable. If Ty is non-null and if the global doesn't exist, 2243 /// then it will be created with the specified type instead of whatever the 2244 /// normal requested type would be. If IsForDefinition is true, it is guranteed 2245 /// that an actual global with type Ty will be returned, not conversion of a 2246 /// variable with the same mangled name but some other type. 2247 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 2248 llvm::Type *Ty, 2249 bool IsForDefinition) { 2250 assert(D->hasGlobalStorage() && "Not a global variable"); 2251 QualType ASTTy = D->getType(); 2252 if (!Ty) 2253 Ty = getTypes().ConvertTypeForMem(ASTTy); 2254 2255 llvm::PointerType *PTy = 2256 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy)); 2257 2258 StringRef MangledName = getMangledName(D); 2259 return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition); 2260 } 2261 2262 /// CreateRuntimeVariable - Create a new runtime global variable with the 2263 /// specified type and name. 2264 llvm::Constant * 2265 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, 2266 StringRef Name) { 2267 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr); 2268 } 2269 2270 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 2271 assert(!D->getInit() && "Cannot emit definite definitions here!"); 2272 2273 StringRef MangledName = getMangledName(D); 2274 llvm::GlobalValue *GV = GetGlobalValue(MangledName); 2275 2276 // We already have a definition, not declaration, with the same mangled name. 2277 // Emitting of declaration is not required (and actually overwrites emitted 2278 // definition). 2279 if (GV && !GV->isDeclaration()) 2280 return; 2281 2282 // If we have not seen a reference to this variable yet, place it into the 2283 // deferred declarations table to be emitted if needed later. 2284 if (!MustBeEmitted(D) && !GV) { 2285 DeferredDecls[MangledName] = D; 2286 return; 2287 } 2288 2289 // The tentative definition is the only definition. 2290 EmitGlobalVarDefinition(D); 2291 } 2292 2293 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { 2294 return Context.toCharUnitsFromBits( 2295 getDataLayout().getTypeStoreSizeInBits(Ty)); 2296 } 2297 2298 unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D, 2299 unsigned AddrSpace) { 2300 if (D && LangOpts.CUDA && LangOpts.CUDAIsDevice) { 2301 if (D->hasAttr<CUDAConstantAttr>()) 2302 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant); 2303 else if (D->hasAttr<CUDASharedAttr>()) 2304 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared); 2305 else 2306 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device); 2307 } 2308 2309 return AddrSpace; 2310 } 2311 2312 template<typename SomeDecl> 2313 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D, 2314 llvm::GlobalValue *GV) { 2315 if (!getLangOpts().CPlusPlus) 2316 return; 2317 2318 // Must have 'used' attribute, or else inline assembly can't rely on 2319 // the name existing. 2320 if (!D->template hasAttr<UsedAttr>()) 2321 return; 2322 2323 // Must have internal linkage and an ordinary name. 2324 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage) 2325 return; 2326 2327 // Must be in an extern "C" context. Entities declared directly within 2328 // a record are not extern "C" even if the record is in such a context. 2329 const SomeDecl *First = D->getFirstDecl(); 2330 if (First->getDeclContext()->isRecord() || !First->isInExternCContext()) 2331 return; 2332 2333 // OK, this is an internal linkage entity inside an extern "C" linkage 2334 // specification. Make a note of that so we can give it the "expected" 2335 // mangled name if nothing else is using that name. 2336 std::pair<StaticExternCMap::iterator, bool> R = 2337 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV)); 2338 2339 // If we have multiple internal linkage entities with the same name 2340 // in extern "C" regions, none of them gets that name. 2341 if (!R.second) 2342 R.first->second = nullptr; 2343 } 2344 2345 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) { 2346 if (!CGM.supportsCOMDAT()) 2347 return false; 2348 2349 if (D.hasAttr<SelectAnyAttr>()) 2350 return true; 2351 2352 GVALinkage Linkage; 2353 if (auto *VD = dyn_cast<VarDecl>(&D)) 2354 Linkage = CGM.getContext().GetGVALinkageForVariable(VD); 2355 else 2356 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D)); 2357 2358 switch (Linkage) { 2359 case GVA_Internal: 2360 case GVA_AvailableExternally: 2361 case GVA_StrongExternal: 2362 return false; 2363 case GVA_DiscardableODR: 2364 case GVA_StrongODR: 2365 return true; 2366 } 2367 llvm_unreachable("No such linkage"); 2368 } 2369 2370 void CodeGenModule::maybeSetTrivialComdat(const Decl &D, 2371 llvm::GlobalObject &GO) { 2372 if (!shouldBeInCOMDAT(*this, D)) 2373 return; 2374 GO.setComdat(TheModule.getOrInsertComdat(GO.getName())); 2375 } 2376 2377 /// Pass IsTentative as true if you want to create a tentative definition. 2378 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D, 2379 bool IsTentative) { 2380 llvm::Constant *Init = nullptr; 2381 QualType ASTTy = D->getType(); 2382 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 2383 bool NeedsGlobalCtor = false; 2384 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor(); 2385 2386 const VarDecl *InitDecl; 2387 const Expr *InitExpr = D->getAnyInitializer(InitDecl); 2388 2389 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization 2390 // as part of their declaration." Sema has already checked for 2391 // error cases, so we just need to set Init to UndefValue. 2392 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice && 2393 D->hasAttr<CUDASharedAttr>()) 2394 Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy)); 2395 else if (!InitExpr) { 2396 // This is a tentative definition; tentative definitions are 2397 // implicitly initialized with { 0 }. 2398 // 2399 // Note that tentative definitions are only emitted at the end of 2400 // a translation unit, so they should never have incomplete 2401 // type. In addition, EmitTentativeDefinition makes sure that we 2402 // never attempt to emit a tentative definition if a real one 2403 // exists. A use may still exists, however, so we still may need 2404 // to do a RAUW. 2405 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 2406 Init = EmitNullConstant(D->getType()); 2407 } else { 2408 initializedGlobalDecl = GlobalDecl(D); 2409 Init = EmitConstantInit(*InitDecl); 2410 2411 if (!Init) { 2412 QualType T = InitExpr->getType(); 2413 if (D->getType()->isReferenceType()) 2414 T = D->getType(); 2415 2416 if (getLangOpts().CPlusPlus) { 2417 Init = EmitNullConstant(T); 2418 NeedsGlobalCtor = true; 2419 } else { 2420 ErrorUnsupported(D, "static initializer"); 2421 Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 2422 } 2423 } else { 2424 // We don't need an initializer, so remove the entry for the delayed 2425 // initializer position (just in case this entry was delayed) if we 2426 // also don't need to register a destructor. 2427 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor) 2428 DelayedCXXInitPosition.erase(D); 2429 } 2430 } 2431 2432 llvm::Type* InitType = Init->getType(); 2433 llvm::Constant *Entry = 2434 GetAddrOfGlobalVar(D, InitType, /*IsForDefinition=*/!IsTentative); 2435 2436 // Strip off a bitcast if we got one back. 2437 if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 2438 assert(CE->getOpcode() == llvm::Instruction::BitCast || 2439 CE->getOpcode() == llvm::Instruction::AddrSpaceCast || 2440 // All zero index gep. 2441 CE->getOpcode() == llvm::Instruction::GetElementPtr); 2442 Entry = CE->getOperand(0); 2443 } 2444 2445 // Entry is now either a Function or GlobalVariable. 2446 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry); 2447 2448 // We have a definition after a declaration with the wrong type. 2449 // We must make a new GlobalVariable* and update everything that used OldGV 2450 // (a declaration or tentative definition) with the new GlobalVariable* 2451 // (which will be a definition). 2452 // 2453 // This happens if there is a prototype for a global (e.g. 2454 // "extern int x[];") and then a definition of a different type (e.g. 2455 // "int x[10];"). This also happens when an initializer has a different type 2456 // from the type of the global (this happens with unions). 2457 if (!GV || 2458 GV->getType()->getElementType() != InitType || 2459 GV->getType()->getAddressSpace() != 2460 GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) { 2461 2462 // Move the old entry aside so that we'll create a new one. 2463 Entry->setName(StringRef()); 2464 2465 // Make a new global with the correct type, this is now guaranteed to work. 2466 GV = cast<llvm::GlobalVariable>( 2467 GetAddrOfGlobalVar(D, InitType, /*IsForDefinition=*/!IsTentative)); 2468 2469 // Replace all uses of the old global with the new global 2470 llvm::Constant *NewPtrForOldDecl = 2471 llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 2472 Entry->replaceAllUsesWith(NewPtrForOldDecl); 2473 2474 // Erase the old global, since it is no longer used. 2475 cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 2476 } 2477 2478 MaybeHandleStaticInExternC(D, GV); 2479 2480 if (D->hasAttr<AnnotateAttr>()) 2481 AddGlobalAnnotations(D, GV); 2482 2483 // Set the llvm linkage type as appropriate. 2484 llvm::GlobalValue::LinkageTypes Linkage = 2485 getLLVMLinkageVarDefinition(D, GV->isConstant()); 2486 2487 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on 2488 // the device. [...]" 2489 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with 2490 // __device__, declares a variable that: [...] 2491 // Is accessible from all the threads within the grid and from the host 2492 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize() 2493 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())." 2494 if (GV && LangOpts.CUDA) { 2495 if (LangOpts.CUDAIsDevice) { 2496 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) 2497 GV->setExternallyInitialized(true); 2498 } else { 2499 // Host-side shadows of external declarations of device-side 2500 // global variables become internal definitions. These have to 2501 // be internal in order to prevent name conflicts with global 2502 // host variables with the same name in a different TUs. 2503 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) { 2504 Linkage = llvm::GlobalValue::InternalLinkage; 2505 2506 // Shadow variables and their properties must be registered 2507 // with CUDA runtime. 2508 unsigned Flags = 0; 2509 if (!D->hasDefinition()) 2510 Flags |= CGCUDARuntime::ExternDeviceVar; 2511 if (D->hasAttr<CUDAConstantAttr>()) 2512 Flags |= CGCUDARuntime::ConstantDeviceVar; 2513 getCUDARuntime().registerDeviceVar(*GV, Flags); 2514 } else if (D->hasAttr<CUDASharedAttr>()) 2515 // __shared__ variables are odd. Shadows do get created, but 2516 // they are not registered with the CUDA runtime, so they 2517 // can't really be used to access their device-side 2518 // counterparts. It's not clear yet whether it's nvcc's bug or 2519 // a feature, but we've got to do the same for compatibility. 2520 Linkage = llvm::GlobalValue::InternalLinkage; 2521 } 2522 } 2523 GV->setInitializer(Init); 2524 2525 // If it is safe to mark the global 'constant', do so now. 2526 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor && 2527 isTypeConstant(D->getType(), true)); 2528 2529 // If it is in a read-only section, mark it 'constant'. 2530 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 2531 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()]; 2532 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0) 2533 GV->setConstant(true); 2534 } 2535 2536 GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 2537 2538 2539 // On Darwin, if the normal linkage of a C++ thread_local variable is 2540 // LinkOnce or Weak, we keep the normal linkage to prevent multiple 2541 // copies within a linkage unit; otherwise, the backing variable has 2542 // internal linkage and all accesses should just be calls to the 2543 // Itanium-specified entry point, which has the normal linkage of the 2544 // variable. This is to preserve the ability to change the implementation 2545 // behind the scenes. 2546 if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic && 2547 Context.getTargetInfo().getTriple().isOSDarwin() && 2548 !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) && 2549 !llvm::GlobalVariable::isWeakLinkage(Linkage)) 2550 Linkage = llvm::GlobalValue::InternalLinkage; 2551 2552 GV->setLinkage(Linkage); 2553 if (D->hasAttr<DLLImportAttr>()) 2554 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 2555 else if (D->hasAttr<DLLExportAttr>()) 2556 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 2557 else 2558 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 2559 2560 if (Linkage == llvm::GlobalVariable::CommonLinkage) 2561 // common vars aren't constant even if declared const. 2562 GV->setConstant(false); 2563 2564 setNonAliasAttributes(D, GV); 2565 2566 if (D->getTLSKind() && !GV->isThreadLocal()) { 2567 if (D->getTLSKind() == VarDecl::TLS_Dynamic) 2568 CXXThreadLocals.push_back(D); 2569 setTLSMode(GV, *D); 2570 } 2571 2572 maybeSetTrivialComdat(*D, *GV); 2573 2574 // Emit the initializer function if necessary. 2575 if (NeedsGlobalCtor || NeedsGlobalDtor) 2576 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor); 2577 2578 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor); 2579 2580 // Emit global variable debug information. 2581 if (CGDebugInfo *DI = getModuleDebugInfo()) 2582 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) 2583 DI->EmitGlobalVariable(GV, D); 2584 } 2585 2586 static bool isVarDeclStrongDefinition(const ASTContext &Context, 2587 CodeGenModule &CGM, const VarDecl *D, 2588 bool NoCommon) { 2589 // Don't give variables common linkage if -fno-common was specified unless it 2590 // was overridden by a NoCommon attribute. 2591 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>()) 2592 return true; 2593 2594 // C11 6.9.2/2: 2595 // A declaration of an identifier for an object that has file scope without 2596 // an initializer, and without a storage-class specifier or with the 2597 // storage-class specifier static, constitutes a tentative definition. 2598 if (D->getInit() || D->hasExternalStorage()) 2599 return true; 2600 2601 // A variable cannot be both common and exist in a section. 2602 if (D->hasAttr<SectionAttr>()) 2603 return true; 2604 2605 // Thread local vars aren't considered common linkage. 2606 if (D->getTLSKind()) 2607 return true; 2608 2609 // Tentative definitions marked with WeakImportAttr are true definitions. 2610 if (D->hasAttr<WeakImportAttr>()) 2611 return true; 2612 2613 // A variable cannot be both common and exist in a comdat. 2614 if (shouldBeInCOMDAT(CGM, *D)) 2615 return true; 2616 2617 // Declarations with a required alignment do not have common linakge in MSVC 2618 // mode. 2619 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2620 if (D->hasAttr<AlignedAttr>()) 2621 return true; 2622 QualType VarType = D->getType(); 2623 if (Context.isAlignmentRequired(VarType)) 2624 return true; 2625 2626 if (const auto *RT = VarType->getAs<RecordType>()) { 2627 const RecordDecl *RD = RT->getDecl(); 2628 for (const FieldDecl *FD : RD->fields()) { 2629 if (FD->isBitField()) 2630 continue; 2631 if (FD->hasAttr<AlignedAttr>()) 2632 return true; 2633 if (Context.isAlignmentRequired(FD->getType())) 2634 return true; 2635 } 2636 } 2637 } 2638 2639 return false; 2640 } 2641 2642 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator( 2643 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) { 2644 if (Linkage == GVA_Internal) 2645 return llvm::Function::InternalLinkage; 2646 2647 if (D->hasAttr<WeakAttr>()) { 2648 if (IsConstantVariable) 2649 return llvm::GlobalVariable::WeakODRLinkage; 2650 else 2651 return llvm::GlobalVariable::WeakAnyLinkage; 2652 } 2653 2654 // We are guaranteed to have a strong definition somewhere else, 2655 // so we can use available_externally linkage. 2656 if (Linkage == GVA_AvailableExternally) 2657 return llvm::Function::AvailableExternallyLinkage; 2658 2659 // Note that Apple's kernel linker doesn't support symbol 2660 // coalescing, so we need to avoid linkonce and weak linkages there. 2661 // Normally, this means we just map to internal, but for explicit 2662 // instantiations we'll map to external. 2663 2664 // In C++, the compiler has to emit a definition in every translation unit 2665 // that references the function. We should use linkonce_odr because 2666 // a) if all references in this translation unit are optimized away, we 2667 // don't need to codegen it. b) if the function persists, it needs to be 2668 // merged with other definitions. c) C++ has the ODR, so we know the 2669 // definition is dependable. 2670 if (Linkage == GVA_DiscardableODR) 2671 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage 2672 : llvm::Function::InternalLinkage; 2673 2674 // An explicit instantiation of a template has weak linkage, since 2675 // explicit instantiations can occur in multiple translation units 2676 // and must all be equivalent. However, we are not allowed to 2677 // throw away these explicit instantiations. 2678 if (Linkage == GVA_StrongODR) 2679 return !Context.getLangOpts().AppleKext ? llvm::Function::WeakODRLinkage 2680 : llvm::Function::ExternalLinkage; 2681 2682 // C++ doesn't have tentative definitions and thus cannot have common 2683 // linkage. 2684 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) && 2685 !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D), 2686 CodeGenOpts.NoCommon)) 2687 return llvm::GlobalVariable::CommonLinkage; 2688 2689 // selectany symbols are externally visible, so use weak instead of 2690 // linkonce. MSVC optimizes away references to const selectany globals, so 2691 // all definitions should be the same and ODR linkage should be used. 2692 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx 2693 if (D->hasAttr<SelectAnyAttr>()) 2694 return llvm::GlobalVariable::WeakODRLinkage; 2695 2696 // Otherwise, we have strong external linkage. 2697 assert(Linkage == GVA_StrongExternal); 2698 return llvm::GlobalVariable::ExternalLinkage; 2699 } 2700 2701 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition( 2702 const VarDecl *VD, bool IsConstant) { 2703 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD); 2704 return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant); 2705 } 2706 2707 /// Replace the uses of a function that was declared with a non-proto type. 2708 /// We want to silently drop extra arguments from call sites 2709 static void replaceUsesOfNonProtoConstant(llvm::Constant *old, 2710 llvm::Function *newFn) { 2711 // Fast path. 2712 if (old->use_empty()) return; 2713 2714 llvm::Type *newRetTy = newFn->getReturnType(); 2715 SmallVector<llvm::Value*, 4> newArgs; 2716 SmallVector<llvm::OperandBundleDef, 1> newBundles; 2717 2718 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end(); 2719 ui != ue; ) { 2720 llvm::Value::use_iterator use = ui++; // Increment before the use is erased. 2721 llvm::User *user = use->getUser(); 2722 2723 // Recognize and replace uses of bitcasts. Most calls to 2724 // unprototyped functions will use bitcasts. 2725 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) { 2726 if (bitcast->getOpcode() == llvm::Instruction::BitCast) 2727 replaceUsesOfNonProtoConstant(bitcast, newFn); 2728 continue; 2729 } 2730 2731 // Recognize calls to the function. 2732 llvm::CallSite callSite(user); 2733 if (!callSite) continue; 2734 if (!callSite.isCallee(&*use)) continue; 2735 2736 // If the return types don't match exactly, then we can't 2737 // transform this call unless it's dead. 2738 if (callSite->getType() != newRetTy && !callSite->use_empty()) 2739 continue; 2740 2741 // Get the call site's attribute list. 2742 SmallVector<llvm::AttributeSet, 8> newAttrs; 2743 llvm::AttributeSet oldAttrs = callSite.getAttributes(); 2744 2745 // Collect any return attributes from the call. 2746 if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex)) 2747 newAttrs.push_back( 2748 llvm::AttributeSet::get(newFn->getContext(), 2749 oldAttrs.getRetAttributes())); 2750 2751 // If the function was passed too few arguments, don't transform. 2752 unsigned newNumArgs = newFn->arg_size(); 2753 if (callSite.arg_size() < newNumArgs) continue; 2754 2755 // If extra arguments were passed, we silently drop them. 2756 // If any of the types mismatch, we don't transform. 2757 unsigned argNo = 0; 2758 bool dontTransform = false; 2759 for (llvm::Function::arg_iterator ai = newFn->arg_begin(), 2760 ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) { 2761 if (callSite.getArgument(argNo)->getType() != ai->getType()) { 2762 dontTransform = true; 2763 break; 2764 } 2765 2766 // Add any parameter attributes. 2767 if (oldAttrs.hasAttributes(argNo + 1)) 2768 newAttrs. 2769 push_back(llvm:: 2770 AttributeSet::get(newFn->getContext(), 2771 oldAttrs.getParamAttributes(argNo + 1))); 2772 } 2773 if (dontTransform) 2774 continue; 2775 2776 if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) 2777 newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(), 2778 oldAttrs.getFnAttributes())); 2779 2780 // Okay, we can transform this. Create the new call instruction and copy 2781 // over the required information. 2782 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo); 2783 2784 // Copy over any operand bundles. 2785 callSite.getOperandBundlesAsDefs(newBundles); 2786 2787 llvm::CallSite newCall; 2788 if (callSite.isCall()) { 2789 newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "", 2790 callSite.getInstruction()); 2791 } else { 2792 auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction()); 2793 newCall = llvm::InvokeInst::Create(newFn, 2794 oldInvoke->getNormalDest(), 2795 oldInvoke->getUnwindDest(), 2796 newArgs, newBundles, "", 2797 callSite.getInstruction()); 2798 } 2799 newArgs.clear(); // for the next iteration 2800 2801 if (!newCall->getType()->isVoidTy()) 2802 newCall->takeName(callSite.getInstruction()); 2803 newCall.setAttributes( 2804 llvm::AttributeSet::get(newFn->getContext(), newAttrs)); 2805 newCall.setCallingConv(callSite.getCallingConv()); 2806 2807 // Finally, remove the old call, replacing any uses with the new one. 2808 if (!callSite->use_empty()) 2809 callSite->replaceAllUsesWith(newCall.getInstruction()); 2810 2811 // Copy debug location attached to CI. 2812 if (callSite->getDebugLoc()) 2813 newCall->setDebugLoc(callSite->getDebugLoc()); 2814 2815 callSite->eraseFromParent(); 2816 } 2817 } 2818 2819 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 2820 /// implement a function with no prototype, e.g. "int foo() {}". If there are 2821 /// existing call uses of the old function in the module, this adjusts them to 2822 /// call the new function directly. 2823 /// 2824 /// This is not just a cleanup: the always_inline pass requires direct calls to 2825 /// functions to be able to inline them. If there is a bitcast in the way, it 2826 /// won't inline them. Instcombine normally deletes these calls, but it isn't 2827 /// run at -O0. 2828 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 2829 llvm::Function *NewFn) { 2830 // If we're redefining a global as a function, don't transform it. 2831 if (!isa<llvm::Function>(Old)) return; 2832 2833 replaceUsesOfNonProtoConstant(Old, NewFn); 2834 } 2835 2836 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) { 2837 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind(); 2838 // If we have a definition, this might be a deferred decl. If the 2839 // instantiation is explicit, make sure we emit it at the end. 2840 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition) 2841 GetAddrOfGlobalVar(VD); 2842 2843 EmitTopLevelDecl(VD); 2844 } 2845 2846 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD, 2847 llvm::GlobalValue *GV) { 2848 const auto *D = cast<FunctionDecl>(GD.getDecl()); 2849 2850 // Compute the function info and LLVM type. 2851 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 2852 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 2853 2854 // Get or create the prototype for the function. 2855 if (!GV || (GV->getType()->getElementType() != Ty)) 2856 GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, 2857 /*DontDefer=*/true, 2858 /*IsForDefinition=*/true)); 2859 2860 // Already emitted. 2861 if (!GV->isDeclaration()) 2862 return; 2863 2864 // We need to set linkage and visibility on the function before 2865 // generating code for it because various parts of IR generation 2866 // want to propagate this information down (e.g. to local static 2867 // declarations). 2868 auto *Fn = cast<llvm::Function>(GV); 2869 setFunctionLinkage(GD, Fn); 2870 setFunctionDLLStorageClass(GD, Fn); 2871 2872 // FIXME: this is redundant with part of setFunctionDefinitionAttributes 2873 setGlobalVisibility(Fn, D); 2874 2875 MaybeHandleStaticInExternC(D, Fn); 2876 2877 maybeSetTrivialComdat(*D, *Fn); 2878 2879 CodeGenFunction(*this).GenerateCode(D, Fn, FI); 2880 2881 setFunctionDefinitionAttributes(D, Fn); 2882 SetLLVMFunctionAttributesForDefinition(D, Fn); 2883 2884 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 2885 AddGlobalCtor(Fn, CA->getPriority()); 2886 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 2887 AddGlobalDtor(Fn, DA->getPriority()); 2888 if (D->hasAttr<AnnotateAttr>()) 2889 AddGlobalAnnotations(D, Fn); 2890 } 2891 2892 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 2893 const auto *D = cast<ValueDecl>(GD.getDecl()); 2894 const AliasAttr *AA = D->getAttr<AliasAttr>(); 2895 assert(AA && "Not an alias?"); 2896 2897 StringRef MangledName = getMangledName(GD); 2898 2899 if (AA->getAliasee() == MangledName) { 2900 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 2901 return; 2902 } 2903 2904 // If there is a definition in the module, then it wins over the alias. 2905 // This is dubious, but allow it to be safe. Just ignore the alias. 2906 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 2907 if (Entry && !Entry->isDeclaration()) 2908 return; 2909 2910 Aliases.push_back(GD); 2911 2912 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 2913 2914 // Create a reference to the named value. This ensures that it is emitted 2915 // if a deferred decl. 2916 llvm::Constant *Aliasee; 2917 if (isa<llvm::FunctionType>(DeclTy)) 2918 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD, 2919 /*ForVTable=*/false); 2920 else 2921 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 2922 llvm::PointerType::getUnqual(DeclTy), 2923 /*D=*/nullptr); 2924 2925 // Create the new alias itself, but don't set a name yet. 2926 auto *GA = llvm::GlobalAlias::create( 2927 DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule()); 2928 2929 if (Entry) { 2930 if (GA->getAliasee() == Entry) { 2931 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 2932 return; 2933 } 2934 2935 assert(Entry->isDeclaration()); 2936 2937 // If there is a declaration in the module, then we had an extern followed 2938 // by the alias, as in: 2939 // extern int test6(); 2940 // ... 2941 // int test6() __attribute__((alias("test7"))); 2942 // 2943 // Remove it and replace uses of it with the alias. 2944 GA->takeName(Entry); 2945 2946 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 2947 Entry->getType())); 2948 Entry->eraseFromParent(); 2949 } else { 2950 GA->setName(MangledName); 2951 } 2952 2953 // Set attributes which are particular to an alias; this is a 2954 // specialization of the attributes which may be set on a global 2955 // variable/function. 2956 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() || 2957 D->isWeakImported()) { 2958 GA->setLinkage(llvm::Function::WeakAnyLinkage); 2959 } 2960 2961 if (const auto *VD = dyn_cast<VarDecl>(D)) 2962 if (VD->getTLSKind()) 2963 setTLSMode(GA, *VD); 2964 2965 setAliasAttributes(D, GA); 2966 } 2967 2968 void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) { 2969 const auto *D = cast<ValueDecl>(GD.getDecl()); 2970 const IFuncAttr *IFA = D->getAttr<IFuncAttr>(); 2971 assert(IFA && "Not an ifunc?"); 2972 2973 StringRef MangledName = getMangledName(GD); 2974 2975 if (IFA->getResolver() == MangledName) { 2976 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 2977 return; 2978 } 2979 2980 // Report an error if some definition overrides ifunc. 2981 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 2982 if (Entry && !Entry->isDeclaration()) { 2983 GlobalDecl OtherGD; 2984 if (lookupRepresentativeDecl(MangledName, OtherGD) && 2985 DiagnosedConflictingDefinitions.insert(GD).second) { 2986 Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name); 2987 Diags.Report(OtherGD.getDecl()->getLocation(), 2988 diag::note_previous_definition); 2989 } 2990 return; 2991 } 2992 2993 Aliases.push_back(GD); 2994 2995 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 2996 llvm::Constant *Resolver = 2997 GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD, 2998 /*ForVTable=*/false); 2999 llvm::GlobalIFunc *GIF = 3000 llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage, 3001 "", Resolver, &getModule()); 3002 if (Entry) { 3003 if (GIF->getResolver() == Entry) { 3004 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 3005 return; 3006 } 3007 assert(Entry->isDeclaration()); 3008 3009 // If there is a declaration in the module, then we had an extern followed 3010 // by the ifunc, as in: 3011 // extern int test(); 3012 // ... 3013 // int test() __attribute__((ifunc("resolver"))); 3014 // 3015 // Remove it and replace uses of it with the ifunc. 3016 GIF->takeName(Entry); 3017 3018 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF, 3019 Entry->getType())); 3020 Entry->eraseFromParent(); 3021 } else 3022 GIF->setName(MangledName); 3023 3024 SetCommonAttributes(D, GIF); 3025 } 3026 3027 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, 3028 ArrayRef<llvm::Type*> Tys) { 3029 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, 3030 Tys); 3031 } 3032 3033 static llvm::StringMapEntry<llvm::GlobalVariable *> & 3034 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map, 3035 const StringLiteral *Literal, bool TargetIsLSB, 3036 bool &IsUTF16, unsigned &StringLength) { 3037 StringRef String = Literal->getString(); 3038 unsigned NumBytes = String.size(); 3039 3040 // Check for simple case. 3041 if (!Literal->containsNonAsciiOrNull()) { 3042 StringLength = NumBytes; 3043 return *Map.insert(std::make_pair(String, nullptr)).first; 3044 } 3045 3046 // Otherwise, convert the UTF8 literals into a string of shorts. 3047 IsUTF16 = true; 3048 3049 SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls. 3050 const UTF8 *FromPtr = (const UTF8 *)String.data(); 3051 UTF16 *ToPtr = &ToBuf[0]; 3052 3053 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 3054 &ToPtr, ToPtr + NumBytes, 3055 strictConversion); 3056 3057 // ConvertUTF8toUTF16 returns the length in ToPtr. 3058 StringLength = ToPtr - &ToBuf[0]; 3059 3060 // Add an explicit null. 3061 *ToPtr = 0; 3062 return *Map.insert(std::make_pair( 3063 StringRef(reinterpret_cast<const char *>(ToBuf.data()), 3064 (StringLength + 1) * 2), 3065 nullptr)).first; 3066 } 3067 3068 static llvm::StringMapEntry<llvm::GlobalVariable *> & 3069 GetConstantStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map, 3070 const StringLiteral *Literal, unsigned &StringLength) { 3071 StringRef String = Literal->getString(); 3072 StringLength = String.size(); 3073 return *Map.insert(std::make_pair(String, nullptr)).first; 3074 } 3075 3076 ConstantAddress 3077 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 3078 unsigned StringLength = 0; 3079 bool isUTF16 = false; 3080 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 3081 GetConstantCFStringEntry(CFConstantStringMap, Literal, 3082 getDataLayout().isLittleEndian(), isUTF16, 3083 StringLength); 3084 3085 if (auto *C = Entry.second) 3086 return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment())); 3087 3088 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 3089 llvm::Constant *Zeros[] = { Zero, Zero }; 3090 llvm::Value *V; 3091 3092 // If we don't already have it, get __CFConstantStringClassReference. 3093 if (!CFConstantStringClassRef) { 3094 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 3095 Ty = llvm::ArrayType::get(Ty, 0); 3096 llvm::Constant *GV = 3097 CreateRuntimeVariable(Ty, "__CFConstantStringClassReference"); 3098 3099 if (getTarget().getTriple().isOSBinFormatCOFF()) { 3100 IdentifierInfo &II = getContext().Idents.get(GV->getName()); 3101 TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl(); 3102 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 3103 llvm::GlobalValue *CGV = cast<llvm::GlobalValue>(GV); 3104 3105 const VarDecl *VD = nullptr; 3106 for (const auto &Result : DC->lookup(&II)) 3107 if ((VD = dyn_cast<VarDecl>(Result))) 3108 break; 3109 3110 if (!VD || !VD->hasAttr<DLLExportAttr>()) { 3111 CGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 3112 CGV->setLinkage(llvm::GlobalValue::ExternalLinkage); 3113 } else { 3114 CGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 3115 CGV->setLinkage(llvm::GlobalValue::ExternalLinkage); 3116 } 3117 } 3118 3119 // Decay array -> ptr 3120 V = llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros); 3121 CFConstantStringClassRef = V; 3122 } else { 3123 V = CFConstantStringClassRef; 3124 } 3125 3126 QualType CFTy = getContext().getCFConstantStringType(); 3127 3128 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 3129 3130 llvm::Constant *Fields[4]; 3131 3132 // Class pointer. 3133 Fields[0] = cast<llvm::ConstantExpr>(V); 3134 3135 // Flags. 3136 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 3137 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) 3138 : llvm::ConstantInt::get(Ty, 0x07C8); 3139 3140 // String pointer. 3141 llvm::Constant *C = nullptr; 3142 if (isUTF16) { 3143 auto Arr = llvm::makeArrayRef( 3144 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())), 3145 Entry.first().size() / 2); 3146 C = llvm::ConstantDataArray::get(VMContext, Arr); 3147 } else { 3148 C = llvm::ConstantDataArray::getString(VMContext, Entry.first()); 3149 } 3150 3151 // Note: -fwritable-strings doesn't make the backing store strings of 3152 // CFStrings writable. (See <rdar://problem/10657500>) 3153 auto *GV = 3154 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true, 3155 llvm::GlobalValue::PrivateLinkage, C, ".str"); 3156 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 3157 // Don't enforce the target's minimum global alignment, since the only use 3158 // of the string is via this class initializer. 3159 CharUnits Align = isUTF16 3160 ? getContext().getTypeAlignInChars(getContext().ShortTy) 3161 : getContext().getTypeAlignInChars(getContext().CharTy); 3162 GV->setAlignment(Align.getQuantity()); 3163 3164 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. 3165 // Without it LLVM can merge the string with a non unnamed_addr one during 3166 // LTO. Doing that changes the section it ends in, which surprises ld64. 3167 if (getTarget().getTriple().isOSBinFormatMachO()) 3168 GV->setSection(isUTF16 ? "__TEXT,__ustring" 3169 : "__TEXT,__cstring,cstring_literals"); 3170 3171 // String. 3172 Fields[2] = 3173 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros); 3174 3175 if (isUTF16) 3176 // Cast the UTF16 string to the correct type. 3177 Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy); 3178 3179 // String length. 3180 Ty = getTypes().ConvertType(getContext().LongTy); 3181 Fields[3] = llvm::ConstantInt::get(Ty, StringLength); 3182 3183 CharUnits Alignment = getPointerAlign(); 3184 3185 // The struct. 3186 C = llvm::ConstantStruct::get(STy, Fields); 3187 GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 3188 llvm::GlobalVariable::PrivateLinkage, C, 3189 "_unnamed_cfstring_"); 3190 GV->setAlignment(Alignment.getQuantity()); 3191 switch (getTarget().getTriple().getObjectFormat()) { 3192 case llvm::Triple::UnknownObjectFormat: 3193 llvm_unreachable("unknown file format"); 3194 case llvm::Triple::COFF: 3195 GV->setSection(".rdata.cfstring"); 3196 break; 3197 case llvm::Triple::ELF: 3198 GV->setSection(".rodata.cfstring"); 3199 break; 3200 case llvm::Triple::MachO: 3201 GV->setSection("__DATA,__cfstring"); 3202 break; 3203 } 3204 Entry.second = GV; 3205 3206 return ConstantAddress(GV, Alignment); 3207 } 3208 3209 ConstantAddress 3210 CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) { 3211 unsigned StringLength = 0; 3212 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 3213 GetConstantStringEntry(CFConstantStringMap, Literal, StringLength); 3214 3215 if (auto *C = Entry.second) 3216 return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment())); 3217 3218 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 3219 llvm::Constant *Zeros[] = { Zero, Zero }; 3220 llvm::Value *V; 3221 // If we don't already have it, get _NSConstantStringClassReference. 3222 if (!ConstantStringClassRef) { 3223 std::string StringClass(getLangOpts().ObjCConstantStringClass); 3224 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 3225 llvm::Constant *GV; 3226 if (LangOpts.ObjCRuntime.isNonFragile()) { 3227 std::string str = 3228 StringClass.empty() ? "OBJC_CLASS_$_NSConstantString" 3229 : "OBJC_CLASS_$_" + StringClass; 3230 GV = getObjCRuntime().GetClassGlobal(str); 3231 // Make sure the result is of the correct type. 3232 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 3233 V = llvm::ConstantExpr::getBitCast(GV, PTy); 3234 ConstantStringClassRef = V; 3235 } else { 3236 std::string str = 3237 StringClass.empty() ? "_NSConstantStringClassReference" 3238 : "_" + StringClass + "ClassReference"; 3239 llvm::Type *PTy = llvm::ArrayType::get(Ty, 0); 3240 GV = CreateRuntimeVariable(PTy, str); 3241 // Decay array -> ptr 3242 V = llvm::ConstantExpr::getGetElementPtr(PTy, GV, Zeros); 3243 ConstantStringClassRef = V; 3244 } 3245 } else 3246 V = ConstantStringClassRef; 3247 3248 if (!NSConstantStringType) { 3249 // Construct the type for a constant NSString. 3250 RecordDecl *D = Context.buildImplicitRecord("__builtin_NSString"); 3251 D->startDefinition(); 3252 3253 QualType FieldTypes[3]; 3254 3255 // const int *isa; 3256 FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst()); 3257 // const char *str; 3258 FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst()); 3259 // unsigned int length; 3260 FieldTypes[2] = Context.UnsignedIntTy; 3261 3262 // Create fields 3263 for (unsigned i = 0; i < 3; ++i) { 3264 FieldDecl *Field = FieldDecl::Create(Context, D, 3265 SourceLocation(), 3266 SourceLocation(), nullptr, 3267 FieldTypes[i], /*TInfo=*/nullptr, 3268 /*BitWidth=*/nullptr, 3269 /*Mutable=*/false, 3270 ICIS_NoInit); 3271 Field->setAccess(AS_public); 3272 D->addDecl(Field); 3273 } 3274 3275 D->completeDefinition(); 3276 QualType NSTy = Context.getTagDeclType(D); 3277 NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy)); 3278 } 3279 3280 llvm::Constant *Fields[3]; 3281 3282 // Class pointer. 3283 Fields[0] = cast<llvm::ConstantExpr>(V); 3284 3285 // String pointer. 3286 llvm::Constant *C = 3287 llvm::ConstantDataArray::getString(VMContext, Entry.first()); 3288 3289 llvm::GlobalValue::LinkageTypes Linkage; 3290 bool isConstant; 3291 Linkage = llvm::GlobalValue::PrivateLinkage; 3292 isConstant = !LangOpts.WritableStrings; 3293 3294 auto *GV = new llvm::GlobalVariable(getModule(), C->getType(), isConstant, 3295 Linkage, C, ".str"); 3296 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 3297 // Don't enforce the target's minimum global alignment, since the only use 3298 // of the string is via this class initializer. 3299 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy); 3300 GV->setAlignment(Align.getQuantity()); 3301 Fields[1] = 3302 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros); 3303 3304 // String length. 3305 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 3306 Fields[2] = llvm::ConstantInt::get(Ty, StringLength); 3307 3308 // The struct. 3309 CharUnits Alignment = getPointerAlign(); 3310 C = llvm::ConstantStruct::get(NSConstantStringType, Fields); 3311 GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 3312 llvm::GlobalVariable::PrivateLinkage, C, 3313 "_unnamed_nsstring_"); 3314 GV->setAlignment(Alignment.getQuantity()); 3315 const char *NSStringSection = "__OBJC,__cstring_object,regular,no_dead_strip"; 3316 const char *NSStringNonFragileABISection = 3317 "__DATA,__objc_stringobj,regular,no_dead_strip"; 3318 // FIXME. Fix section. 3319 GV->setSection(LangOpts.ObjCRuntime.isNonFragile() 3320 ? NSStringNonFragileABISection 3321 : NSStringSection); 3322 Entry.second = GV; 3323 3324 return ConstantAddress(GV, Alignment); 3325 } 3326 3327 QualType CodeGenModule::getObjCFastEnumerationStateType() { 3328 if (ObjCFastEnumerationStateType.isNull()) { 3329 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState"); 3330 D->startDefinition(); 3331 3332 QualType FieldTypes[] = { 3333 Context.UnsignedLongTy, 3334 Context.getPointerType(Context.getObjCIdType()), 3335 Context.getPointerType(Context.UnsignedLongTy), 3336 Context.getConstantArrayType(Context.UnsignedLongTy, 3337 llvm::APInt(32, 5), ArrayType::Normal, 0) 3338 }; 3339 3340 for (size_t i = 0; i < 4; ++i) { 3341 FieldDecl *Field = FieldDecl::Create(Context, 3342 D, 3343 SourceLocation(), 3344 SourceLocation(), nullptr, 3345 FieldTypes[i], /*TInfo=*/nullptr, 3346 /*BitWidth=*/nullptr, 3347 /*Mutable=*/false, 3348 ICIS_NoInit); 3349 Field->setAccess(AS_public); 3350 D->addDecl(Field); 3351 } 3352 3353 D->completeDefinition(); 3354 ObjCFastEnumerationStateType = Context.getTagDeclType(D); 3355 } 3356 3357 return ObjCFastEnumerationStateType; 3358 } 3359 3360 llvm::Constant * 3361 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) { 3362 assert(!E->getType()->isPointerType() && "Strings are always arrays"); 3363 3364 // Don't emit it as the address of the string, emit the string data itself 3365 // as an inline array. 3366 if (E->getCharByteWidth() == 1) { 3367 SmallString<64> Str(E->getString()); 3368 3369 // Resize the string to the right size, which is indicated by its type. 3370 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType()); 3371 Str.resize(CAT->getSize().getZExtValue()); 3372 return llvm::ConstantDataArray::getString(VMContext, Str, false); 3373 } 3374 3375 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType())); 3376 llvm::Type *ElemTy = AType->getElementType(); 3377 unsigned NumElements = AType->getNumElements(); 3378 3379 // Wide strings have either 2-byte or 4-byte elements. 3380 if (ElemTy->getPrimitiveSizeInBits() == 16) { 3381 SmallVector<uint16_t, 32> Elements; 3382 Elements.reserve(NumElements); 3383 3384 for(unsigned i = 0, e = E->getLength(); i != e; ++i) 3385 Elements.push_back(E->getCodeUnit(i)); 3386 Elements.resize(NumElements); 3387 return llvm::ConstantDataArray::get(VMContext, Elements); 3388 } 3389 3390 assert(ElemTy->getPrimitiveSizeInBits() == 32); 3391 SmallVector<uint32_t, 32> Elements; 3392 Elements.reserve(NumElements); 3393 3394 for(unsigned i = 0, e = E->getLength(); i != e; ++i) 3395 Elements.push_back(E->getCodeUnit(i)); 3396 Elements.resize(NumElements); 3397 return llvm::ConstantDataArray::get(VMContext, Elements); 3398 } 3399 3400 static llvm::GlobalVariable * 3401 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, 3402 CodeGenModule &CGM, StringRef GlobalName, 3403 CharUnits Alignment) { 3404 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space. 3405 unsigned AddrSpace = 0; 3406 if (CGM.getLangOpts().OpenCL) 3407 AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant); 3408 3409 llvm::Module &M = CGM.getModule(); 3410 // Create a global variable for this string 3411 auto *GV = new llvm::GlobalVariable( 3412 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName, 3413 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace); 3414 GV->setAlignment(Alignment.getQuantity()); 3415 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 3416 if (GV->isWeakForLinker()) { 3417 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals"); 3418 GV->setComdat(M.getOrInsertComdat(GV->getName())); 3419 } 3420 3421 return GV; 3422 } 3423 3424 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 3425 /// constant array for the given string literal. 3426 ConstantAddress 3427 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S, 3428 StringRef Name) { 3429 CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType()); 3430 3431 llvm::Constant *C = GetConstantArrayFromStringLiteral(S); 3432 llvm::GlobalVariable **Entry = nullptr; 3433 if (!LangOpts.WritableStrings) { 3434 Entry = &ConstantStringMap[C]; 3435 if (auto GV = *Entry) { 3436 if (Alignment.getQuantity() > GV->getAlignment()) 3437 GV->setAlignment(Alignment.getQuantity()); 3438 return ConstantAddress(GV, Alignment); 3439 } 3440 } 3441 3442 SmallString<256> MangledNameBuffer; 3443 StringRef GlobalVariableName; 3444 llvm::GlobalValue::LinkageTypes LT; 3445 3446 // Mangle the string literal if the ABI allows for it. However, we cannot 3447 // do this if we are compiling with ASan or -fwritable-strings because they 3448 // rely on strings having normal linkage. 3449 if (!LangOpts.WritableStrings && 3450 !LangOpts.Sanitize.has(SanitizerKind::Address) && 3451 getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) { 3452 llvm::raw_svector_ostream Out(MangledNameBuffer); 3453 getCXXABI().getMangleContext().mangleStringLiteral(S, Out); 3454 3455 LT = llvm::GlobalValue::LinkOnceODRLinkage; 3456 GlobalVariableName = MangledNameBuffer; 3457 } else { 3458 LT = llvm::GlobalValue::PrivateLinkage; 3459 GlobalVariableName = Name; 3460 } 3461 3462 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment); 3463 if (Entry) 3464 *Entry = GV; 3465 3466 SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>", 3467 QualType()); 3468 return ConstantAddress(GV, Alignment); 3469 } 3470 3471 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 3472 /// array for the given ObjCEncodeExpr node. 3473 ConstantAddress 3474 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 3475 std::string Str; 3476 getContext().getObjCEncodingForType(E->getEncodedType(), Str); 3477 3478 return GetAddrOfConstantCString(Str); 3479 } 3480 3481 /// GetAddrOfConstantCString - Returns a pointer to a character array containing 3482 /// the literal and a terminating '\0' character. 3483 /// The result has pointer to array type. 3484 ConstantAddress CodeGenModule::GetAddrOfConstantCString( 3485 const std::string &Str, const char *GlobalName) { 3486 StringRef StrWithNull(Str.c_str(), Str.size() + 1); 3487 CharUnits Alignment = 3488 getContext().getAlignOfGlobalVarInChars(getContext().CharTy); 3489 3490 llvm::Constant *C = 3491 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false); 3492 3493 // Don't share any string literals if strings aren't constant. 3494 llvm::GlobalVariable **Entry = nullptr; 3495 if (!LangOpts.WritableStrings) { 3496 Entry = &ConstantStringMap[C]; 3497 if (auto GV = *Entry) { 3498 if (Alignment.getQuantity() > GV->getAlignment()) 3499 GV->setAlignment(Alignment.getQuantity()); 3500 return ConstantAddress(GV, Alignment); 3501 } 3502 } 3503 3504 // Get the default prefix if a name wasn't specified. 3505 if (!GlobalName) 3506 GlobalName = ".str"; 3507 // Create a global variable for this. 3508 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this, 3509 GlobalName, Alignment); 3510 if (Entry) 3511 *Entry = GV; 3512 return ConstantAddress(GV, Alignment); 3513 } 3514 3515 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary( 3516 const MaterializeTemporaryExpr *E, const Expr *Init) { 3517 assert((E->getStorageDuration() == SD_Static || 3518 E->getStorageDuration() == SD_Thread) && "not a global temporary"); 3519 const auto *VD = cast<VarDecl>(E->getExtendingDecl()); 3520 3521 // If we're not materializing a subobject of the temporary, keep the 3522 // cv-qualifiers from the type of the MaterializeTemporaryExpr. 3523 QualType MaterializedType = Init->getType(); 3524 if (Init == E->GetTemporaryExpr()) 3525 MaterializedType = E->getType(); 3526 3527 CharUnits Align = getContext().getTypeAlignInChars(MaterializedType); 3528 3529 if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E]) 3530 return ConstantAddress(Slot, Align); 3531 3532 // FIXME: If an externally-visible declaration extends multiple temporaries, 3533 // we need to give each temporary the same name in every translation unit (and 3534 // we also need to make the temporaries externally-visible). 3535 SmallString<256> Name; 3536 llvm::raw_svector_ostream Out(Name); 3537 getCXXABI().getMangleContext().mangleReferenceTemporary( 3538 VD, E->getManglingNumber(), Out); 3539 3540 APValue *Value = nullptr; 3541 if (E->getStorageDuration() == SD_Static) { 3542 // We might have a cached constant initializer for this temporary. Note 3543 // that this might have a different value from the value computed by 3544 // evaluating the initializer if the surrounding constant expression 3545 // modifies the temporary. 3546 Value = getContext().getMaterializedTemporaryValue(E, false); 3547 if (Value && Value->isUninit()) 3548 Value = nullptr; 3549 } 3550 3551 // Try evaluating it now, it might have a constant initializer. 3552 Expr::EvalResult EvalResult; 3553 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) && 3554 !EvalResult.hasSideEffects()) 3555 Value = &EvalResult.Val; 3556 3557 llvm::Constant *InitialValue = nullptr; 3558 bool Constant = false; 3559 llvm::Type *Type; 3560 if (Value) { 3561 // The temporary has a constant initializer, use it. 3562 InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr); 3563 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value); 3564 Type = InitialValue->getType(); 3565 } else { 3566 // No initializer, the initialization will be provided when we 3567 // initialize the declaration which performed lifetime extension. 3568 Type = getTypes().ConvertTypeForMem(MaterializedType); 3569 } 3570 3571 // Create a global variable for this lifetime-extended temporary. 3572 llvm::GlobalValue::LinkageTypes Linkage = 3573 getLLVMLinkageVarDefinition(VD, Constant); 3574 if (Linkage == llvm::GlobalVariable::ExternalLinkage) { 3575 const VarDecl *InitVD; 3576 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) && 3577 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) { 3578 // Temporaries defined inside a class get linkonce_odr linkage because the 3579 // class can be defined in multipe translation units. 3580 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage; 3581 } else { 3582 // There is no need for this temporary to have external linkage if the 3583 // VarDecl has external linkage. 3584 Linkage = llvm::GlobalVariable::InternalLinkage; 3585 } 3586 } 3587 unsigned AddrSpace = GetGlobalVarAddressSpace( 3588 VD, getContext().getTargetAddressSpace(MaterializedType)); 3589 auto *GV = new llvm::GlobalVariable( 3590 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(), 3591 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, 3592 AddrSpace); 3593 setGlobalVisibility(GV, VD); 3594 GV->setAlignment(Align.getQuantity()); 3595 if (supportsCOMDAT() && GV->isWeakForLinker()) 3596 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 3597 if (VD->getTLSKind()) 3598 setTLSMode(GV, *VD); 3599 MaterializedGlobalTemporaryMap[E] = GV; 3600 return ConstantAddress(GV, Align); 3601 } 3602 3603 /// EmitObjCPropertyImplementations - Emit information for synthesized 3604 /// properties for an implementation. 3605 void CodeGenModule::EmitObjCPropertyImplementations(const 3606 ObjCImplementationDecl *D) { 3607 for (const auto *PID : D->property_impls()) { 3608 // Dynamic is just for type-checking. 3609 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 3610 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 3611 3612 // Determine which methods need to be implemented, some may have 3613 // been overridden. Note that ::isPropertyAccessor is not the method 3614 // we want, that just indicates if the decl came from a 3615 // property. What we want to know is if the method is defined in 3616 // this implementation. 3617 if (!D->getInstanceMethod(PD->getGetterName())) 3618 CodeGenFunction(*this).GenerateObjCGetter( 3619 const_cast<ObjCImplementationDecl *>(D), PID); 3620 if (!PD->isReadOnly() && 3621 !D->getInstanceMethod(PD->getSetterName())) 3622 CodeGenFunction(*this).GenerateObjCSetter( 3623 const_cast<ObjCImplementationDecl *>(D), PID); 3624 } 3625 } 3626 } 3627 3628 static bool needsDestructMethod(ObjCImplementationDecl *impl) { 3629 const ObjCInterfaceDecl *iface = impl->getClassInterface(); 3630 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 3631 ivar; ivar = ivar->getNextIvar()) 3632 if (ivar->getType().isDestructedType()) 3633 return true; 3634 3635 return false; 3636 } 3637 3638 static bool AllTrivialInitializers(CodeGenModule &CGM, 3639 ObjCImplementationDecl *D) { 3640 CodeGenFunction CGF(CGM); 3641 for (ObjCImplementationDecl::init_iterator B = D->init_begin(), 3642 E = D->init_end(); B != E; ++B) { 3643 CXXCtorInitializer *CtorInitExp = *B; 3644 Expr *Init = CtorInitExp->getInit(); 3645 if (!CGF.isTrivialInitializer(Init)) 3646 return false; 3647 } 3648 return true; 3649 } 3650 3651 /// EmitObjCIvarInitializations - Emit information for ivar initialization 3652 /// for an implementation. 3653 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 3654 // We might need a .cxx_destruct even if we don't have any ivar initializers. 3655 if (needsDestructMethod(D)) { 3656 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 3657 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 3658 ObjCMethodDecl *DTORMethod = 3659 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(), 3660 cxxSelector, getContext().VoidTy, nullptr, D, 3661 /*isInstance=*/true, /*isVariadic=*/false, 3662 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true, 3663 /*isDefined=*/false, ObjCMethodDecl::Required); 3664 D->addInstanceMethod(DTORMethod); 3665 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 3666 D->setHasDestructors(true); 3667 } 3668 3669 // If the implementation doesn't have any ivar initializers, we don't need 3670 // a .cxx_construct. 3671 if (D->getNumIvarInitializers() == 0 || 3672 AllTrivialInitializers(*this, D)) 3673 return; 3674 3675 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); 3676 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 3677 // The constructor returns 'self'. 3678 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(), 3679 D->getLocation(), 3680 D->getLocation(), 3681 cxxSelector, 3682 getContext().getObjCIdType(), 3683 nullptr, D, /*isInstance=*/true, 3684 /*isVariadic=*/false, 3685 /*isPropertyAccessor=*/true, 3686 /*isImplicitlyDeclared=*/true, 3687 /*isDefined=*/false, 3688 ObjCMethodDecl::Required); 3689 D->addInstanceMethod(CTORMethod); 3690 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 3691 D->setHasNonZeroConstructors(true); 3692 } 3693 3694 /// EmitNamespace - Emit all declarations in a namespace. 3695 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) { 3696 for (auto *I : ND->decls()) { 3697 if (const auto *VD = dyn_cast<VarDecl>(I)) 3698 if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization && 3699 VD->getTemplateSpecializationKind() != TSK_Undeclared) 3700 continue; 3701 EmitTopLevelDecl(I); 3702 } 3703 } 3704 3705 // EmitLinkageSpec - Emit all declarations in a linkage spec. 3706 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 3707 if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 3708 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 3709 ErrorUnsupported(LSD, "linkage spec"); 3710 return; 3711 } 3712 3713 for (auto *I : LSD->decls()) { 3714 // Meta-data for ObjC class includes references to implemented methods. 3715 // Generate class's method definitions first. 3716 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) { 3717 for (auto *M : OID->methods()) 3718 EmitTopLevelDecl(M); 3719 } 3720 EmitTopLevelDecl(I); 3721 } 3722 } 3723 3724 /// EmitTopLevelDecl - Emit code for a single top level declaration. 3725 void CodeGenModule::EmitTopLevelDecl(Decl *D) { 3726 // Ignore dependent declarations. 3727 if (D->getDeclContext() && D->getDeclContext()->isDependentContext()) 3728 return; 3729 3730 switch (D->getKind()) { 3731 case Decl::CXXConversion: 3732 case Decl::CXXMethod: 3733 case Decl::Function: 3734 // Skip function templates 3735 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 3736 cast<FunctionDecl>(D)->isLateTemplateParsed()) 3737 return; 3738 3739 EmitGlobal(cast<FunctionDecl>(D)); 3740 // Always provide some coverage mapping 3741 // even for the functions that aren't emitted. 3742 AddDeferredUnusedCoverageMapping(D); 3743 break; 3744 3745 case Decl::Var: 3746 // Skip variable templates 3747 if (cast<VarDecl>(D)->getDescribedVarTemplate()) 3748 return; 3749 case Decl::VarTemplateSpecialization: 3750 EmitGlobal(cast<VarDecl>(D)); 3751 break; 3752 3753 // Indirect fields from global anonymous structs and unions can be 3754 // ignored; only the actual variable requires IR gen support. 3755 case Decl::IndirectField: 3756 break; 3757 3758 // C++ Decls 3759 case Decl::Namespace: 3760 EmitNamespace(cast<NamespaceDecl>(D)); 3761 break; 3762 // No code generation needed. 3763 case Decl::UsingShadow: 3764 case Decl::ClassTemplate: 3765 case Decl::VarTemplate: 3766 case Decl::VarTemplatePartialSpecialization: 3767 case Decl::FunctionTemplate: 3768 case Decl::TypeAliasTemplate: 3769 case Decl::Block: 3770 case Decl::Empty: 3771 break; 3772 case Decl::Using: // using X; [C++] 3773 if (CGDebugInfo *DI = getModuleDebugInfo()) 3774 DI->EmitUsingDecl(cast<UsingDecl>(*D)); 3775 return; 3776 case Decl::NamespaceAlias: 3777 if (CGDebugInfo *DI = getModuleDebugInfo()) 3778 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D)); 3779 return; 3780 case Decl::UsingDirective: // using namespace X; [C++] 3781 if (CGDebugInfo *DI = getModuleDebugInfo()) 3782 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D)); 3783 return; 3784 case Decl::CXXConstructor: 3785 // Skip function templates 3786 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 3787 cast<FunctionDecl>(D)->isLateTemplateParsed()) 3788 return; 3789 3790 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 3791 break; 3792 case Decl::CXXDestructor: 3793 if (cast<FunctionDecl>(D)->isLateTemplateParsed()) 3794 return; 3795 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 3796 break; 3797 3798 case Decl::StaticAssert: 3799 // Nothing to do. 3800 break; 3801 3802 // Objective-C Decls 3803 3804 // Forward declarations, no (immediate) code generation. 3805 case Decl::ObjCInterface: 3806 case Decl::ObjCCategory: 3807 break; 3808 3809 case Decl::ObjCProtocol: { 3810 auto *Proto = cast<ObjCProtocolDecl>(D); 3811 if (Proto->isThisDeclarationADefinition()) 3812 ObjCRuntime->GenerateProtocol(Proto); 3813 break; 3814 } 3815 3816 case Decl::ObjCCategoryImpl: 3817 // Categories have properties but don't support synthesize so we 3818 // can ignore them here. 3819 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 3820 break; 3821 3822 case Decl::ObjCImplementation: { 3823 auto *OMD = cast<ObjCImplementationDecl>(D); 3824 EmitObjCPropertyImplementations(OMD); 3825 EmitObjCIvarInitializations(OMD); 3826 ObjCRuntime->GenerateClass(OMD); 3827 // Emit global variable debug information. 3828 if (CGDebugInfo *DI = getModuleDebugInfo()) 3829 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) 3830 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType( 3831 OMD->getClassInterface()), OMD->getLocation()); 3832 break; 3833 } 3834 case Decl::ObjCMethod: { 3835 auto *OMD = cast<ObjCMethodDecl>(D); 3836 // If this is not a prototype, emit the body. 3837 if (OMD->getBody()) 3838 CodeGenFunction(*this).GenerateObjCMethod(OMD); 3839 break; 3840 } 3841 case Decl::ObjCCompatibleAlias: 3842 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D)); 3843 break; 3844 3845 case Decl::PragmaComment: { 3846 const auto *PCD = cast<PragmaCommentDecl>(D); 3847 switch (PCD->getCommentKind()) { 3848 case PCK_Unknown: 3849 llvm_unreachable("unexpected pragma comment kind"); 3850 case PCK_Linker: 3851 AppendLinkerOptions(PCD->getArg()); 3852 break; 3853 case PCK_Lib: 3854 AddDependentLib(PCD->getArg()); 3855 break; 3856 case PCK_Compiler: 3857 case PCK_ExeStr: 3858 case PCK_User: 3859 break; // We ignore all of these. 3860 } 3861 break; 3862 } 3863 3864 case Decl::PragmaDetectMismatch: { 3865 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D); 3866 AddDetectMismatch(PDMD->getName(), PDMD->getValue()); 3867 break; 3868 } 3869 3870 case Decl::LinkageSpec: 3871 EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 3872 break; 3873 3874 case Decl::FileScopeAsm: { 3875 // File-scope asm is ignored during device-side CUDA compilation. 3876 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) 3877 break; 3878 // File-scope asm is ignored during device-side OpenMP compilation. 3879 if (LangOpts.OpenMPIsDevice) 3880 break; 3881 auto *AD = cast<FileScopeAsmDecl>(D); 3882 getModule().appendModuleInlineAsm(AD->getAsmString()->getString()); 3883 break; 3884 } 3885 3886 case Decl::Import: { 3887 auto *Import = cast<ImportDecl>(D); 3888 3889 // Ignore import declarations that come from imported modules. 3890 if (Import->getImportedOwningModule()) 3891 break; 3892 if (CGDebugInfo *DI = getModuleDebugInfo()) 3893 DI->EmitImportDecl(*Import); 3894 3895 ImportedModules.insert(Import->getImportedModule()); 3896 break; 3897 } 3898 3899 case Decl::OMPThreadPrivate: 3900 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D)); 3901 break; 3902 3903 case Decl::ClassTemplateSpecialization: { 3904 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D); 3905 if (DebugInfo && 3906 Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition && 3907 Spec->hasDefinition()) 3908 DebugInfo->completeTemplateDefinition(*Spec); 3909 break; 3910 } 3911 3912 case Decl::OMPDeclareReduction: 3913 EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D)); 3914 break; 3915 3916 default: 3917 // Make sure we handled everything we should, every other kind is a 3918 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 3919 // function. Need to recode Decl::Kind to do that easily. 3920 assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 3921 break; 3922 } 3923 } 3924 3925 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) { 3926 // Do we need to generate coverage mapping? 3927 if (!CodeGenOpts.CoverageMapping) 3928 return; 3929 switch (D->getKind()) { 3930 case Decl::CXXConversion: 3931 case Decl::CXXMethod: 3932 case Decl::Function: 3933 case Decl::ObjCMethod: 3934 case Decl::CXXConstructor: 3935 case Decl::CXXDestructor: { 3936 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody()) 3937 return; 3938 auto I = DeferredEmptyCoverageMappingDecls.find(D); 3939 if (I == DeferredEmptyCoverageMappingDecls.end()) 3940 DeferredEmptyCoverageMappingDecls[D] = true; 3941 break; 3942 } 3943 default: 3944 break; 3945 }; 3946 } 3947 3948 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) { 3949 // Do we need to generate coverage mapping? 3950 if (!CodeGenOpts.CoverageMapping) 3951 return; 3952 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) { 3953 if (Fn->isTemplateInstantiation()) 3954 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern()); 3955 } 3956 auto I = DeferredEmptyCoverageMappingDecls.find(D); 3957 if (I == DeferredEmptyCoverageMappingDecls.end()) 3958 DeferredEmptyCoverageMappingDecls[D] = false; 3959 else 3960 I->second = false; 3961 } 3962 3963 void CodeGenModule::EmitDeferredUnusedCoverageMappings() { 3964 std::vector<const Decl *> DeferredDecls; 3965 for (const auto &I : DeferredEmptyCoverageMappingDecls) { 3966 if (!I.second) 3967 continue; 3968 DeferredDecls.push_back(I.first); 3969 } 3970 // Sort the declarations by their location to make sure that the tests get a 3971 // predictable order for the coverage mapping for the unused declarations. 3972 if (CodeGenOpts.DumpCoverageMapping) 3973 std::sort(DeferredDecls.begin(), DeferredDecls.end(), 3974 [] (const Decl *LHS, const Decl *RHS) { 3975 return LHS->getLocStart() < RHS->getLocStart(); 3976 }); 3977 for (const auto *D : DeferredDecls) { 3978 switch (D->getKind()) { 3979 case Decl::CXXConversion: 3980 case Decl::CXXMethod: 3981 case Decl::Function: 3982 case Decl::ObjCMethod: { 3983 CodeGenPGO PGO(*this); 3984 GlobalDecl GD(cast<FunctionDecl>(D)); 3985 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 3986 getFunctionLinkage(GD)); 3987 break; 3988 } 3989 case Decl::CXXConstructor: { 3990 CodeGenPGO PGO(*this); 3991 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base); 3992 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 3993 getFunctionLinkage(GD)); 3994 break; 3995 } 3996 case Decl::CXXDestructor: { 3997 CodeGenPGO PGO(*this); 3998 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base); 3999 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 4000 getFunctionLinkage(GD)); 4001 break; 4002 } 4003 default: 4004 break; 4005 }; 4006 } 4007 } 4008 4009 /// Turns the given pointer into a constant. 4010 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 4011 const void *Ptr) { 4012 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 4013 llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 4014 return llvm::ConstantInt::get(i64, PtrInt); 4015 } 4016 4017 static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 4018 llvm::NamedMDNode *&GlobalMetadata, 4019 GlobalDecl D, 4020 llvm::GlobalValue *Addr) { 4021 if (!GlobalMetadata) 4022 GlobalMetadata = 4023 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 4024 4025 // TODO: should we report variant information for ctors/dtors? 4026 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr), 4027 llvm::ConstantAsMetadata::get(GetPointerConstant( 4028 CGM.getLLVMContext(), D.getDecl()))}; 4029 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 4030 } 4031 4032 /// For each function which is declared within an extern "C" region and marked 4033 /// as 'used', but has internal linkage, create an alias from the unmangled 4034 /// name to the mangled name if possible. People expect to be able to refer 4035 /// to such functions with an unmangled name from inline assembly within the 4036 /// same translation unit. 4037 void CodeGenModule::EmitStaticExternCAliases() { 4038 // Don't do anything if we're generating CUDA device code -- the NVPTX 4039 // assembly target doesn't support aliases. 4040 if (Context.getTargetInfo().getTriple().isNVPTX()) 4041 return; 4042 for (auto &I : StaticExternCValues) { 4043 IdentifierInfo *Name = I.first; 4044 llvm::GlobalValue *Val = I.second; 4045 if (Val && !getModule().getNamedValue(Name->getName())) 4046 addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val)); 4047 } 4048 } 4049 4050 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName, 4051 GlobalDecl &Result) const { 4052 auto Res = Manglings.find(MangledName); 4053 if (Res == Manglings.end()) 4054 return false; 4055 Result = Res->getValue(); 4056 return true; 4057 } 4058 4059 /// Emits metadata nodes associating all the global values in the 4060 /// current module with the Decls they came from. This is useful for 4061 /// projects using IR gen as a subroutine. 4062 /// 4063 /// Since there's currently no way to associate an MDNode directly 4064 /// with an llvm::GlobalValue, we create a global named metadata 4065 /// with the name 'clang.global.decl.ptrs'. 4066 void CodeGenModule::EmitDeclMetadata() { 4067 llvm::NamedMDNode *GlobalMetadata = nullptr; 4068 4069 for (auto &I : MangledDeclNames) { 4070 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second); 4071 // Some mangled names don't necessarily have an associated GlobalValue 4072 // in this module, e.g. if we mangled it for DebugInfo. 4073 if (Addr) 4074 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr); 4075 } 4076 } 4077 4078 /// Emits metadata nodes for all the local variables in the current 4079 /// function. 4080 void CodeGenFunction::EmitDeclMetadata() { 4081 if (LocalDeclMap.empty()) return; 4082 4083 llvm::LLVMContext &Context = getLLVMContext(); 4084 4085 // Find the unique metadata ID for this name. 4086 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 4087 4088 llvm::NamedMDNode *GlobalMetadata = nullptr; 4089 4090 for (auto &I : LocalDeclMap) { 4091 const Decl *D = I.first; 4092 llvm::Value *Addr = I.second.getPointer(); 4093 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 4094 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 4095 Alloca->setMetadata( 4096 DeclPtrKind, llvm::MDNode::get( 4097 Context, llvm::ValueAsMetadata::getConstant(DAddr))); 4098 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 4099 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 4100 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 4101 } 4102 } 4103 } 4104 4105 void CodeGenModule::EmitVersionIdentMetadata() { 4106 llvm::NamedMDNode *IdentMetadata = 4107 TheModule.getOrInsertNamedMetadata("llvm.ident"); 4108 std::string Version = getClangFullVersion(); 4109 llvm::LLVMContext &Ctx = TheModule.getContext(); 4110 4111 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)}; 4112 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode)); 4113 } 4114 4115 void CodeGenModule::EmitTargetMetadata() { 4116 // Warning, new MangledDeclNames may be appended within this loop. 4117 // We rely on MapVector insertions adding new elements to the end 4118 // of the container. 4119 // FIXME: Move this loop into the one target that needs it, and only 4120 // loop over those declarations for which we couldn't emit the target 4121 // metadata when we emitted the declaration. 4122 for (unsigned I = 0; I != MangledDeclNames.size(); ++I) { 4123 auto Val = *(MangledDeclNames.begin() + I); 4124 const Decl *D = Val.first.getDecl()->getMostRecentDecl(); 4125 llvm::GlobalValue *GV = GetGlobalValue(Val.second); 4126 getTargetCodeGenInfo().emitTargetMD(D, GV, *this); 4127 } 4128 } 4129 4130 void CodeGenModule::EmitCoverageFile() { 4131 if (!getCodeGenOpts().CoverageFile.empty()) { 4132 if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) { 4133 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); 4134 llvm::LLVMContext &Ctx = TheModule.getContext(); 4135 llvm::MDString *CoverageFile = 4136 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile); 4137 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { 4138 llvm::MDNode *CU = CUNode->getOperand(i); 4139 llvm::Metadata *Elts[] = {CoverageFile, CU}; 4140 GCov->addOperand(llvm::MDNode::get(Ctx, Elts)); 4141 } 4142 } 4143 } 4144 } 4145 4146 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) { 4147 // Sema has checked that all uuid strings are of the form 4148 // "12345678-1234-1234-1234-1234567890ab". 4149 assert(Uuid.size() == 36); 4150 for (unsigned i = 0; i < 36; ++i) { 4151 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-'); 4152 else assert(isHexDigit(Uuid[i])); 4153 } 4154 4155 // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab". 4156 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 }; 4157 4158 llvm::Constant *Field3[8]; 4159 for (unsigned Idx = 0; Idx < 8; ++Idx) 4160 Field3[Idx] = llvm::ConstantInt::get( 4161 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16); 4162 4163 llvm::Constant *Fields[4] = { 4164 llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16), 4165 llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16), 4166 llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16), 4167 llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3) 4168 }; 4169 4170 return llvm::ConstantStruct::getAnon(Fields); 4171 } 4172 4173 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty, 4174 bool ForEH) { 4175 // Return a bogus pointer if RTTI is disabled, unless it's for EH. 4176 // FIXME: should we even be calling this method if RTTI is disabled 4177 // and it's not for EH? 4178 if (!ForEH && !getLangOpts().RTTI) 4179 return llvm::Constant::getNullValue(Int8PtrTy); 4180 4181 if (ForEH && Ty->isObjCObjectPointerType() && 4182 LangOpts.ObjCRuntime.isGNUFamily()) 4183 return ObjCRuntime->GetEHType(Ty); 4184 4185 return getCXXABI().getAddrOfRTTIDescriptor(Ty); 4186 } 4187 4188 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) { 4189 for (auto RefExpr : D->varlists()) { 4190 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl()); 4191 bool PerformInit = 4192 VD->getAnyInitializer() && 4193 !VD->getAnyInitializer()->isConstantInitializer(getContext(), 4194 /*ForRef=*/false); 4195 4196 Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD)); 4197 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition( 4198 VD, Addr, RefExpr->getLocStart(), PerformInit)) 4199 CXXGlobalInits.push_back(InitFunction); 4200 } 4201 } 4202 4203 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) { 4204 llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()]; 4205 if (InternalId) 4206 return InternalId; 4207 4208 if (isExternallyVisible(T->getLinkage())) { 4209 std::string OutName; 4210 llvm::raw_string_ostream Out(OutName); 4211 getCXXABI().getMangleContext().mangleTypeName(T, Out); 4212 4213 InternalId = llvm::MDString::get(getLLVMContext(), Out.str()); 4214 } else { 4215 InternalId = llvm::MDNode::getDistinct(getLLVMContext(), 4216 llvm::ArrayRef<llvm::Metadata *>()); 4217 } 4218 4219 return InternalId; 4220 } 4221 4222 /// Returns whether this module needs the "all-vtables" bitset. 4223 bool CodeGenModule::NeedAllVtablesBitSet() const { 4224 // Returns true if at least one of vtable-based CFI checkers is enabled and 4225 // is not in the trapping mode. 4226 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) && 4227 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) || 4228 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) && 4229 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) || 4230 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) && 4231 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) || 4232 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) && 4233 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast))); 4234 } 4235 4236 void CodeGenModule::CreateVTableBitSetEntry(llvm::NamedMDNode *BitsetsMD, 4237 llvm::GlobalVariable *VTable, 4238 CharUnits Offset, 4239 const CXXRecordDecl *RD) { 4240 llvm::Metadata *MD = 4241 CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)); 4242 llvm::Metadata *BitsetOps[] = { 4243 MD, llvm::ConstantAsMetadata::get(VTable), 4244 llvm::ConstantAsMetadata::get( 4245 llvm::ConstantInt::get(Int64Ty, Offset.getQuantity()))}; 4246 BitsetsMD->addOperand(llvm::MDTuple::get(getLLVMContext(), BitsetOps)); 4247 4248 if (CodeGenOpts.SanitizeCfiCrossDso) { 4249 if (auto TypeId = CreateCfiIdForTypeMetadata(MD)) { 4250 llvm::Metadata *BitsetOps2[] = { 4251 llvm::ConstantAsMetadata::get(TypeId), 4252 llvm::ConstantAsMetadata::get(VTable), 4253 llvm::ConstantAsMetadata::get( 4254 llvm::ConstantInt::get(Int64Ty, Offset.getQuantity()))}; 4255 BitsetsMD->addOperand(llvm::MDTuple::get(getLLVMContext(), BitsetOps2)); 4256 } 4257 } 4258 4259 if (NeedAllVtablesBitSet()) { 4260 llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables"); 4261 llvm::Metadata *BitsetOps[] = { 4262 MD, llvm::ConstantAsMetadata::get(VTable), 4263 llvm::ConstantAsMetadata::get( 4264 llvm::ConstantInt::get(Int64Ty, Offset.getQuantity()))}; 4265 // Avoid adding a node to BitsetsMD twice. 4266 if (!llvm::MDTuple::getIfExists(getLLVMContext(), BitsetOps)) 4267 BitsetsMD->addOperand(llvm::MDTuple::get(getLLVMContext(), BitsetOps)); 4268 } 4269 } 4270 4271 // Fills in the supplied string map with the set of target features for the 4272 // passed in function. 4273 void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 4274 const FunctionDecl *FD) { 4275 StringRef TargetCPU = Target.getTargetOpts().CPU; 4276 if (const auto *TD = FD->getAttr<TargetAttr>()) { 4277 // If we have a TargetAttr build up the feature map based on that. 4278 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse(); 4279 4280 // Make a copy of the features as passed on the command line into the 4281 // beginning of the additional features from the function to override. 4282 ParsedAttr.first.insert(ParsedAttr.first.begin(), 4283 Target.getTargetOpts().FeaturesAsWritten.begin(), 4284 Target.getTargetOpts().FeaturesAsWritten.end()); 4285 4286 if (ParsedAttr.second != "") 4287 TargetCPU = ParsedAttr.second; 4288 4289 // Now populate the feature map, first with the TargetCPU which is either 4290 // the default or a new one from the target attribute string. Then we'll use 4291 // the passed in features (FeaturesAsWritten) along with the new ones from 4292 // the attribute. 4293 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, ParsedAttr.first); 4294 } else { 4295 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, 4296 Target.getTargetOpts().Features); 4297 } 4298 } 4299 4300 llvm::SanitizerStatReport &CodeGenModule::getSanStats() { 4301 if (!SanStats) 4302 SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule()); 4303 4304 return *SanStats; 4305 } 4306