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