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