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