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