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