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