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