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