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