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