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