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