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