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