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