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