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