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