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