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