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