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