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