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 static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV, 776 const NamedDecl *ND) { 777 // Set linkage and visibility in case we never see a definition. 778 LinkageInfo LV = ND->getLinkageAndVisibility(); 779 if (LV.getLinkage() != ExternalLinkage) { 780 // Don't set internal linkage on declarations. 781 } else { 782 if (ND->hasAttr<DLLImportAttr>()) { 783 GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 784 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 785 } else if (ND->hasAttr<DLLExportAttr>()) { 786 GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 787 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 788 } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) { 789 // "extern_weak" is overloaded in LLVM; we probably should have 790 // separate linkage types for this. 791 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 792 } 793 794 // Set visibility on a declaration only if it's explicit. 795 if (LV.isVisibilityExplicit()) 796 GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility())); 797 } 798 } 799 800 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, 801 llvm::Function *F, 802 bool IsIncompleteFunction) { 803 if (unsigned IID = F->getIntrinsicID()) { 804 // If this is an intrinsic function, set the function's attributes 805 // to the intrinsic's attributes. 806 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), 807 (llvm::Intrinsic::ID)IID)); 808 return; 809 } 810 811 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 812 813 if (!IsIncompleteFunction) 814 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F); 815 816 // Add the Returned attribute for "this", except for iOS 5 and earlier 817 // where substantial code, including the libstdc++ dylib, was compiled with 818 // GCC and does not actually return "this". 819 if (getCXXABI().HasThisReturn(GD) && 820 !(getTarget().getTriple().isiOS() && 821 getTarget().getTriple().isOSVersionLT(6))) { 822 assert(!F->arg_empty() && 823 F->arg_begin()->getType() 824 ->canLosslesslyBitCastTo(F->getReturnType()) && 825 "unexpected this return"); 826 F->addAttribute(1, llvm::Attribute::Returned); 827 } 828 829 // Only a few attributes are set on declarations; these may later be 830 // overridden by a definition. 831 832 setLinkageAndVisibilityForGV(F, FD); 833 834 if (const SectionAttr *SA = FD->getAttr<SectionAttr>()) 835 F->setSection(SA->getName()); 836 837 // A replaceable global allocation function does not act like a builtin by 838 // default, only if it is invoked by a new-expression or delete-expression. 839 if (FD->isReplaceableGlobalAllocationFunction()) 840 F->addAttribute(llvm::AttributeSet::FunctionIndex, 841 llvm::Attribute::NoBuiltin); 842 } 843 844 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) { 845 assert(!GV->isDeclaration() && 846 "Only globals with definition can force usage."); 847 LLVMUsed.push_back(GV); 848 } 849 850 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) { 851 assert(!GV->isDeclaration() && 852 "Only globals with definition can force usage."); 853 LLVMCompilerUsed.push_back(GV); 854 } 855 856 static void emitUsed(CodeGenModule &CGM, StringRef Name, 857 std::vector<llvm::WeakVH> &List) { 858 // Don't create llvm.used if there is no need. 859 if (List.empty()) 860 return; 861 862 // Convert List to what ConstantArray needs. 863 SmallVector<llvm::Constant*, 8> UsedArray; 864 UsedArray.resize(List.size()); 865 for (unsigned i = 0, e = List.size(); i != e; ++i) { 866 UsedArray[i] = 867 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*List[i]), 868 CGM.Int8PtrTy); 869 } 870 871 if (UsedArray.empty()) 872 return; 873 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size()); 874 875 llvm::GlobalVariable *GV = 876 new llvm::GlobalVariable(CGM.getModule(), ATy, false, 877 llvm::GlobalValue::AppendingLinkage, 878 llvm::ConstantArray::get(ATy, UsedArray), 879 Name); 880 881 GV->setSection("llvm.metadata"); 882 } 883 884 void CodeGenModule::emitLLVMUsed() { 885 emitUsed(*this, "llvm.used", LLVMUsed); 886 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed); 887 } 888 889 void CodeGenModule::AppendLinkerOptions(StringRef Opts) { 890 llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opts); 891 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 892 } 893 894 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) { 895 llvm::SmallString<32> Opt; 896 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt); 897 llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 898 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 899 } 900 901 void CodeGenModule::AddDependentLib(StringRef Lib) { 902 llvm::SmallString<24> Opt; 903 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt); 904 llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 905 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 906 } 907 908 /// \brief Add link options implied by the given module, including modules 909 /// it depends on, using a postorder walk. 910 static void addLinkOptionsPostorder(CodeGenModule &CGM, 911 Module *Mod, 912 SmallVectorImpl<llvm::Value *> &Metadata, 913 llvm::SmallPtrSet<Module *, 16> &Visited) { 914 // Import this module's parent. 915 if (Mod->Parent && Visited.insert(Mod->Parent)) { 916 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited); 917 } 918 919 // Import this module's dependencies. 920 for (unsigned I = Mod->Imports.size(); I > 0; --I) { 921 if (Visited.insert(Mod->Imports[I-1])) 922 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited); 923 } 924 925 // Add linker options to link against the libraries/frameworks 926 // described by this module. 927 llvm::LLVMContext &Context = CGM.getLLVMContext(); 928 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) { 929 // Link against a framework. Frameworks are currently Darwin only, so we 930 // don't to ask TargetCodeGenInfo for the spelling of the linker option. 931 if (Mod->LinkLibraries[I-1].IsFramework) { 932 llvm::Value *Args[2] = { 933 llvm::MDString::get(Context, "-framework"), 934 llvm::MDString::get(Context, Mod->LinkLibraries[I-1].Library) 935 }; 936 937 Metadata.push_back(llvm::MDNode::get(Context, Args)); 938 continue; 939 } 940 941 // Link against a library. 942 llvm::SmallString<24> Opt; 943 CGM.getTargetCodeGenInfo().getDependentLibraryOption( 944 Mod->LinkLibraries[I-1].Library, Opt); 945 llvm::Value *OptString = llvm::MDString::get(Context, Opt); 946 Metadata.push_back(llvm::MDNode::get(Context, OptString)); 947 } 948 } 949 950 void CodeGenModule::EmitModuleLinkOptions() { 951 // Collect the set of all of the modules we want to visit to emit link 952 // options, which is essentially the imported modules and all of their 953 // non-explicit child modules. 954 llvm::SetVector<clang::Module *> LinkModules; 955 llvm::SmallPtrSet<clang::Module *, 16> Visited; 956 SmallVector<clang::Module *, 16> Stack; 957 958 // Seed the stack with imported modules. 959 for (llvm::SetVector<clang::Module *>::iterator M = ImportedModules.begin(), 960 MEnd = ImportedModules.end(); 961 M != MEnd; ++M) { 962 if (Visited.insert(*M)) 963 Stack.push_back(*M); 964 } 965 966 // Find all of the modules to import, making a little effort to prune 967 // non-leaf modules. 968 while (!Stack.empty()) { 969 clang::Module *Mod = Stack.pop_back_val(); 970 971 bool AnyChildren = false; 972 973 // Visit the submodules of this module. 974 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(), 975 SubEnd = Mod->submodule_end(); 976 Sub != SubEnd; ++Sub) { 977 // Skip explicit children; they need to be explicitly imported to be 978 // linked against. 979 if ((*Sub)->IsExplicit) 980 continue; 981 982 if (Visited.insert(*Sub)) { 983 Stack.push_back(*Sub); 984 AnyChildren = true; 985 } 986 } 987 988 // We didn't find any children, so add this module to the list of 989 // modules to link against. 990 if (!AnyChildren) { 991 LinkModules.insert(Mod); 992 } 993 } 994 995 // Add link options for all of the imported modules in reverse topological 996 // order. We don't do anything to try to order import link flags with respect 997 // to linker options inserted by things like #pragma comment(). 998 SmallVector<llvm::Value *, 16> MetadataArgs; 999 Visited.clear(); 1000 for (llvm::SetVector<clang::Module *>::iterator M = LinkModules.begin(), 1001 MEnd = LinkModules.end(); 1002 M != MEnd; ++M) { 1003 if (Visited.insert(*M)) 1004 addLinkOptionsPostorder(*this, *M, MetadataArgs, Visited); 1005 } 1006 std::reverse(MetadataArgs.begin(), MetadataArgs.end()); 1007 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end()); 1008 1009 // Add the linker options metadata flag. 1010 getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options", 1011 llvm::MDNode::get(getLLVMContext(), 1012 LinkerOptionsMetadata)); 1013 } 1014 1015 void CodeGenModule::EmitDeferred() { 1016 // Emit code for any potentially referenced deferred decls. Since a 1017 // previously unused static decl may become used during the generation of code 1018 // for a static function, iterate until no changes are made. 1019 1020 while (true) { 1021 if (!DeferredVTables.empty()) { 1022 EmitDeferredVTables(); 1023 1024 // Emitting a v-table doesn't directly cause more v-tables to 1025 // become deferred, although it can cause functions to be 1026 // emitted that then need those v-tables. 1027 assert(DeferredVTables.empty()); 1028 } 1029 1030 // Stop if we're out of both deferred v-tables and deferred declarations. 1031 if (DeferredDeclsToEmit.empty()) break; 1032 1033 DeferredGlobal &G = DeferredDeclsToEmit.back(); 1034 GlobalDecl D = G.GD; 1035 llvm::GlobalValue *GV = G.GV; 1036 DeferredDeclsToEmit.pop_back(); 1037 1038 assert(GV == GetGlobalValue(getMangledName(D))); 1039 // Check to see if we've already emitted this. This is necessary 1040 // for a couple of reasons: first, decls can end up in the 1041 // deferred-decls queue multiple times, and second, decls can end 1042 // up with definitions in unusual ways (e.g. by an extern inline 1043 // function acquiring a strong function redefinition). Just 1044 // ignore these cases. 1045 if(!GV->isDeclaration()) 1046 continue; 1047 1048 // Otherwise, emit the definition and move on to the next one. 1049 EmitGlobalDefinition(D, GV); 1050 } 1051 } 1052 1053 void CodeGenModule::EmitGlobalAnnotations() { 1054 if (Annotations.empty()) 1055 return; 1056 1057 // Create a new global variable for the ConstantStruct in the Module. 1058 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( 1059 Annotations[0]->getType(), Annotations.size()), Annotations); 1060 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), 1061 Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array, 1062 "llvm.global.annotations"); 1063 gv->setSection(AnnotationSection); 1064 } 1065 1066 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) { 1067 llvm::Constant *&AStr = AnnotationStrings[Str]; 1068 if (AStr) 1069 return AStr; 1070 1071 // Not found yet, create a new global. 1072 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str); 1073 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(), 1074 true, llvm::GlobalValue::PrivateLinkage, s, ".str"); 1075 gv->setSection(AnnotationSection); 1076 gv->setUnnamedAddr(true); 1077 AStr = gv; 1078 return gv; 1079 } 1080 1081 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { 1082 SourceManager &SM = getContext().getSourceManager(); 1083 PresumedLoc PLoc = SM.getPresumedLoc(Loc); 1084 if (PLoc.isValid()) 1085 return EmitAnnotationString(PLoc.getFilename()); 1086 return EmitAnnotationString(SM.getBufferName(Loc)); 1087 } 1088 1089 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { 1090 SourceManager &SM = getContext().getSourceManager(); 1091 PresumedLoc PLoc = SM.getPresumedLoc(L); 1092 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : 1093 SM.getExpansionLineNumber(L); 1094 return llvm::ConstantInt::get(Int32Ty, LineNo); 1095 } 1096 1097 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 1098 const AnnotateAttr *AA, 1099 SourceLocation L) { 1100 // Get the globals for file name, annotation, and the line number. 1101 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), 1102 *UnitGV = EmitAnnotationUnit(L), 1103 *LineNoCst = EmitAnnotationLineNo(L); 1104 1105 // Create the ConstantStruct for the global annotation. 1106 llvm::Constant *Fields[4] = { 1107 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy), 1108 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy), 1109 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy), 1110 LineNoCst 1111 }; 1112 return llvm::ConstantStruct::getAnon(Fields); 1113 } 1114 1115 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, 1116 llvm::GlobalValue *GV) { 1117 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 1118 // Get the struct elements for these annotations. 1119 for (const auto *I : D->specific_attrs<AnnotateAttr>()) 1120 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation())); 1121 } 1122 1123 bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) { 1124 // Never defer when EmitAllDecls is specified. 1125 if (LangOpts.EmitAllDecls) 1126 return false; 1127 1128 return !getContext().DeclMustBeEmitted(Global); 1129 } 1130 1131 llvm::Constant *CodeGenModule::GetAddrOfUuidDescriptor( 1132 const CXXUuidofExpr* E) { 1133 // Sema has verified that IIDSource has a __declspec(uuid()), and that its 1134 // well-formed. 1135 StringRef Uuid = E->getUuidAsStringRef(Context); 1136 std::string Name = "_GUID_" + Uuid.lower(); 1137 std::replace(Name.begin(), Name.end(), '-', '_'); 1138 1139 // Look for an existing global. 1140 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 1141 return GV; 1142 1143 llvm::Constant *Init = EmitUuidofInitializer(Uuid, E->getType()); 1144 assert(Init && "failed to initialize as constant"); 1145 1146 llvm::GlobalVariable *GV = new llvm::GlobalVariable( 1147 getModule(), Init->getType(), 1148 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); 1149 return GV; 1150 } 1151 1152 llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 1153 const AliasAttr *AA = VD->getAttr<AliasAttr>(); 1154 assert(AA && "No alias?"); 1155 1156 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 1157 1158 // See if there is already something with the target's name in the module. 1159 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 1160 if (Entry) { 1161 unsigned AS = getContext().getTargetAddressSpace(VD->getType()); 1162 return llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS)); 1163 } 1164 1165 llvm::Constant *Aliasee; 1166 if (isa<llvm::FunctionType>(DeclTy)) 1167 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, 1168 GlobalDecl(cast<FunctionDecl>(VD)), 1169 /*ForVTable=*/false); 1170 else 1171 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 1172 llvm::PointerType::getUnqual(DeclTy), 0); 1173 1174 llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee); 1175 F->setLinkage(llvm::Function::ExternalWeakLinkage); 1176 WeakRefReferences.insert(F); 1177 1178 return Aliasee; 1179 } 1180 1181 void CodeGenModule::EmitGlobal(GlobalDecl GD) { 1182 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl()); 1183 1184 // Weak references don't produce any output by themselves. 1185 if (Global->hasAttr<WeakRefAttr>()) 1186 return; 1187 1188 // If this is an alias definition (which otherwise looks like a declaration) 1189 // emit it now. 1190 if (Global->hasAttr<AliasAttr>()) 1191 return EmitAliasDefinition(GD); 1192 1193 // If this is CUDA, be selective about which declarations we emit. 1194 if (LangOpts.CUDA) { 1195 if (CodeGenOpts.CUDAIsDevice) { 1196 if (!Global->hasAttr<CUDADeviceAttr>() && 1197 !Global->hasAttr<CUDAGlobalAttr>() && 1198 !Global->hasAttr<CUDAConstantAttr>() && 1199 !Global->hasAttr<CUDASharedAttr>()) 1200 return; 1201 } else { 1202 if (!Global->hasAttr<CUDAHostAttr>() && ( 1203 Global->hasAttr<CUDADeviceAttr>() || 1204 Global->hasAttr<CUDAConstantAttr>() || 1205 Global->hasAttr<CUDASharedAttr>())) 1206 return; 1207 } 1208 } 1209 1210 // Ignore declarations, they will be emitted on their first use. 1211 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) { 1212 // Forward declarations are emitted lazily on first use. 1213 if (!FD->doesThisDeclarationHaveABody()) { 1214 if (!FD->doesDeclarationForceExternallyVisibleDefinition()) 1215 return; 1216 1217 StringRef MangledName = getMangledName(GD); 1218 1219 // Compute the function info and LLVM type. 1220 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 1221 llvm::Type *Ty = getTypes().GetFunctionType(FI); 1222 1223 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false, 1224 /*DontDefer=*/false); 1225 return; 1226 } 1227 } else { 1228 const VarDecl *VD = cast<VarDecl>(Global); 1229 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 1230 1231 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) 1232 return; 1233 } 1234 1235 // Defer code generation when possible if this is a static definition, inline 1236 // function etc. These we only want to emit if they are used. 1237 if (!MayDeferGeneration(Global)) { 1238 // Emit the definition if it can't be deferred. 1239 EmitGlobalDefinition(GD); 1240 return; 1241 } 1242 1243 // If we're deferring emission of a C++ variable with an 1244 // initializer, remember the order in which it appeared in the file. 1245 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) && 1246 cast<VarDecl>(Global)->hasInit()) { 1247 DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 1248 CXXGlobalInits.push_back(0); 1249 } 1250 1251 // If the value has already been used, add it directly to the 1252 // DeferredDeclsToEmit list. 1253 StringRef MangledName = getMangledName(GD); 1254 if (llvm::GlobalValue *GV = GetGlobalValue(MangledName)) 1255 addDeferredDeclToEmit(GV, GD); 1256 else { 1257 // Otherwise, remember that we saw a deferred decl with this name. The 1258 // first use of the mangled name will cause it to move into 1259 // DeferredDeclsToEmit. 1260 DeferredDecls[MangledName] = GD; 1261 } 1262 } 1263 1264 namespace { 1265 struct FunctionIsDirectlyRecursive : 1266 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> { 1267 const StringRef Name; 1268 const Builtin::Context &BI; 1269 bool Result; 1270 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) : 1271 Name(N), BI(C), Result(false) { 1272 } 1273 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base; 1274 1275 bool TraverseCallExpr(CallExpr *E) { 1276 const FunctionDecl *FD = E->getDirectCallee(); 1277 if (!FD) 1278 return true; 1279 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 1280 if (Attr && Name == Attr->getLabel()) { 1281 Result = true; 1282 return false; 1283 } 1284 unsigned BuiltinID = FD->getBuiltinID(); 1285 if (!BuiltinID) 1286 return true; 1287 StringRef BuiltinName = BI.GetName(BuiltinID); 1288 if (BuiltinName.startswith("__builtin_") && 1289 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) { 1290 Result = true; 1291 return false; 1292 } 1293 return true; 1294 } 1295 }; 1296 } 1297 1298 // isTriviallyRecursive - Check if this function calls another 1299 // decl that, because of the asm attribute or the other decl being a builtin, 1300 // ends up pointing to itself. 1301 bool 1302 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) { 1303 StringRef Name; 1304 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) { 1305 // asm labels are a special kind of mangling we have to support. 1306 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 1307 if (!Attr) 1308 return false; 1309 Name = Attr->getLabel(); 1310 } else { 1311 Name = FD->getName(); 1312 } 1313 1314 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo); 1315 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD)); 1316 return Walker.Result; 1317 } 1318 1319 bool 1320 CodeGenModule::shouldEmitFunction(GlobalDecl GD) { 1321 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage) 1322 return true; 1323 const FunctionDecl *F = cast<FunctionDecl>(GD.getDecl()); 1324 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>()) 1325 return false; 1326 // PR9614. Avoid cases where the source code is lying to us. An available 1327 // externally function should have an equivalent function somewhere else, 1328 // but a function that calls itself is clearly not equivalent to the real 1329 // implementation. 1330 // This happens in glibc's btowc and in some configure checks. 1331 return !isTriviallyRecursive(F); 1332 } 1333 1334 /// If the type for the method's class was generated by 1335 /// CGDebugInfo::createContextChain(), the cache contains only a 1336 /// limited DIType without any declarations. Since EmitFunctionStart() 1337 /// needs to find the canonical declaration for each method, we need 1338 /// to construct the complete type prior to emitting the method. 1339 void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) { 1340 if (!D->isInstance()) 1341 return; 1342 1343 if (CGDebugInfo *DI = getModuleDebugInfo()) 1344 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) { 1345 const PointerType *ThisPtr = 1346 cast<PointerType>(D->getThisType(getContext())); 1347 DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation()); 1348 } 1349 } 1350 1351 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) { 1352 const ValueDecl *D = cast<ValueDecl>(GD.getDecl()); 1353 1354 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 1355 Context.getSourceManager(), 1356 "Generating code for declaration"); 1357 1358 if (isa<FunctionDecl>(D)) { 1359 // At -O0, don't generate IR for functions with available_externally 1360 // linkage. 1361 if (!shouldEmitFunction(GD)) 1362 return; 1363 1364 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 1365 CompleteDIClassType(Method); 1366 // Make sure to emit the definition(s) before we emit the thunks. 1367 // This is necessary for the generation of certain thunks. 1368 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method)) 1369 EmitCXXConstructor(CD, GD.getCtorType()); 1370 else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method)) 1371 EmitCXXDestructor(DD, GD.getDtorType()); 1372 else 1373 EmitGlobalFunctionDefinition(GD, GV); 1374 1375 if (Method->isVirtual()) 1376 getVTables().EmitThunks(GD); 1377 1378 return; 1379 } 1380 1381 return EmitGlobalFunctionDefinition(GD, GV); 1382 } 1383 1384 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 1385 return EmitGlobalVarDefinition(VD); 1386 1387 llvm_unreachable("Invalid argument to EmitGlobalDefinition()"); 1388 } 1389 1390 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 1391 /// module, create and return an llvm Function with the specified type. If there 1392 /// is something in the module with the specified name, return it potentially 1393 /// bitcasted to the right type. 1394 /// 1395 /// If D is non-null, it specifies a decl that correspond to this. This is used 1396 /// to set the attributes on the function when it is first created. 1397 llvm::Constant * 1398 CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName, 1399 llvm::Type *Ty, 1400 GlobalDecl GD, bool ForVTable, 1401 bool DontDefer, 1402 llvm::AttributeSet ExtraAttrs) { 1403 const Decl *D = GD.getDecl(); 1404 1405 // Lookup the entry, lazily creating it if necessary. 1406 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1407 if (Entry) { 1408 if (WeakRefReferences.erase(Entry)) { 1409 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D); 1410 if (FD && !FD->hasAttr<WeakAttr>()) 1411 Entry->setLinkage(llvm::Function::ExternalLinkage); 1412 } 1413 1414 if (Entry->getType()->getElementType() == Ty) 1415 return Entry; 1416 1417 // Make sure the result is of the correct type. 1418 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo()); 1419 } 1420 1421 // This function doesn't have a complete type (for example, the return 1422 // type is an incomplete struct). Use a fake type instead, and make 1423 // sure not to try to set attributes. 1424 bool IsIncompleteFunction = false; 1425 1426 llvm::FunctionType *FTy; 1427 if (isa<llvm::FunctionType>(Ty)) { 1428 FTy = cast<llvm::FunctionType>(Ty); 1429 } else { 1430 FTy = llvm::FunctionType::get(VoidTy, false); 1431 IsIncompleteFunction = true; 1432 } 1433 1434 llvm::Function *F = llvm::Function::Create(FTy, 1435 llvm::Function::ExternalLinkage, 1436 MangledName, &getModule()); 1437 assert(F->getName() == MangledName && "name was uniqued!"); 1438 if (D) 1439 SetFunctionAttributes(GD, F, IsIncompleteFunction); 1440 if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) { 1441 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex); 1442 F->addAttributes(llvm::AttributeSet::FunctionIndex, 1443 llvm::AttributeSet::get(VMContext, 1444 llvm::AttributeSet::FunctionIndex, 1445 B)); 1446 } 1447 1448 if (!DontDefer) { 1449 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to 1450 // each other bottoming out with the base dtor. Therefore we emit non-base 1451 // dtors on usage, even if there is no dtor definition in the TU. 1452 if (D && isa<CXXDestructorDecl>(D) && 1453 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 1454 GD.getDtorType())) 1455 addDeferredDeclToEmit(F, GD); 1456 1457 // This is the first use or definition of a mangled name. If there is a 1458 // deferred decl with this name, remember that we need to emit it at the end 1459 // of the file. 1460 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName); 1461 if (DDI != DeferredDecls.end()) { 1462 // Move the potentially referenced deferred decl to the 1463 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we 1464 // don't need it anymore). 1465 addDeferredDeclToEmit(F, DDI->second); 1466 DeferredDecls.erase(DDI); 1467 1468 // Otherwise, if this is a sized deallocation function, emit a weak 1469 // definition 1470 // for it at the end of the translation unit. 1471 } else if (D && cast<FunctionDecl>(D) 1472 ->getCorrespondingUnsizedGlobalDeallocationFunction()) { 1473 addDeferredDeclToEmit(F, GD); 1474 1475 // Otherwise, there are cases we have to worry about where we're 1476 // using a declaration for which we must emit a definition but where 1477 // we might not find a top-level definition: 1478 // - member functions defined inline in their classes 1479 // - friend functions defined inline in some class 1480 // - special member functions with implicit definitions 1481 // If we ever change our AST traversal to walk into class methods, 1482 // this will be unnecessary. 1483 // 1484 // We also don't emit a definition for a function if it's going to be an 1485 // entry 1486 // in a vtable, unless it's already marked as used. 1487 } else if (getLangOpts().CPlusPlus && D) { 1488 // Look for a declaration that's lexically in a record. 1489 const FunctionDecl *FD = cast<FunctionDecl>(D); 1490 FD = FD->getMostRecentDecl(); 1491 do { 1492 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 1493 if (FD->isImplicit() && !ForVTable) { 1494 assert(FD->isUsed() && 1495 "Sema didn't mark implicit function as used!"); 1496 addDeferredDeclToEmit(F, GD.getWithDecl(FD)); 1497 break; 1498 } else if (FD->doesThisDeclarationHaveABody()) { 1499 addDeferredDeclToEmit(F, GD.getWithDecl(FD)); 1500 break; 1501 } 1502 } 1503 FD = FD->getPreviousDecl(); 1504 } while (FD); 1505 } 1506 } 1507 1508 // Make sure the result is of the requested type. 1509 if (!IsIncompleteFunction) { 1510 assert(F->getType()->getElementType() == Ty); 1511 return F; 1512 } 1513 1514 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 1515 return llvm::ConstantExpr::getBitCast(F, PTy); 1516 } 1517 1518 /// GetAddrOfFunction - Return the address of the given function. If Ty is 1519 /// non-null, then this function will use the specified type if it has to 1520 /// create it (this occurs when we see a definition of the function). 1521 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 1522 llvm::Type *Ty, 1523 bool ForVTable, 1524 bool DontDefer) { 1525 // If there was no specific requested type, just convert it now. 1526 if (!Ty) 1527 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType()); 1528 1529 StringRef MangledName = getMangledName(GD); 1530 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer); 1531 } 1532 1533 /// CreateRuntimeFunction - Create a new runtime function with the specified 1534 /// type and name. 1535 llvm::Constant * 1536 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, 1537 StringRef Name, 1538 llvm::AttributeSet ExtraAttrs) { 1539 llvm::Constant *C = 1540 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 1541 /*DontDefer=*/false, ExtraAttrs); 1542 if (llvm::Function *F = dyn_cast<llvm::Function>(C)) 1543 if (F->empty()) 1544 F->setCallingConv(getRuntimeCC()); 1545 return C; 1546 } 1547 1548 /// isTypeConstant - Determine whether an object of this type can be emitted 1549 /// as a constant. 1550 /// 1551 /// If ExcludeCtor is true, the duration when the object's constructor runs 1552 /// will not be considered. The caller will need to verify that the object is 1553 /// not written to during its construction. 1554 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) { 1555 if (!Ty.isConstant(Context) && !Ty->isReferenceType()) 1556 return false; 1557 1558 if (Context.getLangOpts().CPlusPlus) { 1559 if (const CXXRecordDecl *Record 1560 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl()) 1561 return ExcludeCtor && !Record->hasMutableFields() && 1562 Record->hasTrivialDestructor(); 1563 } 1564 1565 return true; 1566 } 1567 1568 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 1569 /// create and return an llvm GlobalVariable with the specified type. If there 1570 /// is something in the module with the specified name, return it potentially 1571 /// bitcasted to the right type. 1572 /// 1573 /// If D is non-null, it specifies a decl that correspond to this. This is used 1574 /// to set the attributes on the global when it is first created. 1575 llvm::Constant * 1576 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, 1577 llvm::PointerType *Ty, 1578 const VarDecl *D, 1579 bool UnnamedAddr) { 1580 // Lookup the entry, lazily creating it if necessary. 1581 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1582 if (Entry) { 1583 if (WeakRefReferences.erase(Entry)) { 1584 if (D && !D->hasAttr<WeakAttr>()) 1585 Entry->setLinkage(llvm::Function::ExternalLinkage); 1586 } 1587 1588 if (UnnamedAddr) 1589 Entry->setUnnamedAddr(true); 1590 1591 if (Entry->getType() == Ty) 1592 return Entry; 1593 1594 // Make sure the result is of the correct type. 1595 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace()) 1596 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty); 1597 1598 return llvm::ConstantExpr::getBitCast(Entry, Ty); 1599 } 1600 1601 unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace()); 1602 llvm::GlobalVariable *GV = 1603 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false, 1604 llvm::GlobalValue::ExternalLinkage, 1605 0, MangledName, 0, 1606 llvm::GlobalVariable::NotThreadLocal, AddrSpace); 1607 1608 // This is the first use or definition of a mangled name. If there is a 1609 // deferred decl with this name, remember that we need to emit it at the end 1610 // of the file. 1611 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName); 1612 if (DDI != DeferredDecls.end()) { 1613 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 1614 // list, and remove it from DeferredDecls (since we don't need it anymore). 1615 addDeferredDeclToEmit(GV, DDI->second); 1616 DeferredDecls.erase(DDI); 1617 } 1618 1619 // Handle things which are present even on external declarations. 1620 if (D) { 1621 // FIXME: This code is overly simple and should be merged with other global 1622 // handling. 1623 GV->setConstant(isTypeConstant(D->getType(), false)); 1624 1625 setLinkageAndVisibilityForGV(GV, D); 1626 1627 if (D->getTLSKind()) { 1628 if (D->getTLSKind() == VarDecl::TLS_Dynamic) 1629 CXXThreadLocals.push_back(std::make_pair(D, GV)); 1630 setTLSMode(GV, *D); 1631 } 1632 1633 // If required by the ABI, treat declarations of static data members with 1634 // inline initializers as definitions. 1635 if (getCXXABI().isInlineInitializedStaticDataMemberLinkOnce() && 1636 D->isStaticDataMember() && D->hasInit() && 1637 !D->isThisDeclarationADefinition()) 1638 EmitGlobalVarDefinition(D); 1639 } 1640 1641 if (AddrSpace != Ty->getAddressSpace()) 1642 return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty); 1643 1644 if (getTarget().getTriple().getArch() == llvm::Triple::xcore && 1645 D->getLanguageLinkage() == CLanguageLinkage && 1646 D->getType().isConstant(Context) && 1647 isExternallyVisible(D->getLinkageAndVisibility().getLinkage())) 1648 GV->setSection(".cp.rodata"); 1649 1650 return GV; 1651 } 1652 1653 1654 llvm::GlobalVariable * 1655 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name, 1656 llvm::Type *Ty, 1657 llvm::GlobalValue::LinkageTypes Linkage) { 1658 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); 1659 llvm::GlobalVariable *OldGV = 0; 1660 1661 1662 if (GV) { 1663 // Check if the variable has the right type. 1664 if (GV->getType()->getElementType() == Ty) 1665 return GV; 1666 1667 // Because C++ name mangling, the only way we can end up with an already 1668 // existing global with the same name is if it has been declared extern "C". 1669 assert(GV->isDeclaration() && "Declaration has wrong type!"); 1670 OldGV = GV; 1671 } 1672 1673 // Create a new variable. 1674 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, 1675 Linkage, 0, Name); 1676 1677 if (OldGV) { 1678 // Replace occurrences of the old variable if needed. 1679 GV->takeName(OldGV); 1680 1681 if (!OldGV->use_empty()) { 1682 llvm::Constant *NewPtrForOldDecl = 1683 llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 1684 OldGV->replaceAllUsesWith(NewPtrForOldDecl); 1685 } 1686 1687 OldGV->eraseFromParent(); 1688 } 1689 1690 return GV; 1691 } 1692 1693 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 1694 /// given global variable. If Ty is non-null and if the global doesn't exist, 1695 /// then it will be created with the specified type instead of whatever the 1696 /// normal requested type would be. 1697 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 1698 llvm::Type *Ty) { 1699 assert(D->hasGlobalStorage() && "Not a global variable"); 1700 QualType ASTTy = D->getType(); 1701 if (Ty == 0) 1702 Ty = getTypes().ConvertTypeForMem(ASTTy); 1703 1704 llvm::PointerType *PTy = 1705 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy)); 1706 1707 StringRef MangledName = getMangledName(D); 1708 return GetOrCreateLLVMGlobal(MangledName, PTy, D); 1709 } 1710 1711 /// CreateRuntimeVariable - Create a new runtime global variable with the 1712 /// specified type and name. 1713 llvm::Constant * 1714 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, 1715 StringRef Name) { 1716 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0, 1717 true); 1718 } 1719 1720 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 1721 assert(!D->getInit() && "Cannot emit definite definitions here!"); 1722 1723 if (MayDeferGeneration(D)) { 1724 // If we have not seen a reference to this variable yet, place it 1725 // into the deferred declarations table to be emitted if needed 1726 // later. 1727 StringRef MangledName = getMangledName(D); 1728 if (!GetGlobalValue(MangledName)) { 1729 DeferredDecls[MangledName] = D; 1730 return; 1731 } 1732 } 1733 1734 // The tentative definition is the only definition. 1735 EmitGlobalVarDefinition(D); 1736 } 1737 1738 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { 1739 return Context.toCharUnitsFromBits( 1740 TheDataLayout.getTypeStoreSizeInBits(Ty)); 1741 } 1742 1743 unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D, 1744 unsigned AddrSpace) { 1745 if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) { 1746 if (D->hasAttr<CUDAConstantAttr>()) 1747 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant); 1748 else if (D->hasAttr<CUDASharedAttr>()) 1749 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared); 1750 else 1751 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device); 1752 } 1753 1754 return AddrSpace; 1755 } 1756 1757 template<typename SomeDecl> 1758 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D, 1759 llvm::GlobalValue *GV) { 1760 if (!getLangOpts().CPlusPlus) 1761 return; 1762 1763 // Must have 'used' attribute, or else inline assembly can't rely on 1764 // the name existing. 1765 if (!D->template hasAttr<UsedAttr>()) 1766 return; 1767 1768 // Must have internal linkage and an ordinary name. 1769 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage) 1770 return; 1771 1772 // Must be in an extern "C" context. Entities declared directly within 1773 // a record are not extern "C" even if the record is in such a context. 1774 const SomeDecl *First = D->getFirstDecl(); 1775 if (First->getDeclContext()->isRecord() || !First->isInExternCContext()) 1776 return; 1777 1778 // OK, this is an internal linkage entity inside an extern "C" linkage 1779 // specification. Make a note of that so we can give it the "expected" 1780 // mangled name if nothing else is using that name. 1781 std::pair<StaticExternCMap::iterator, bool> R = 1782 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV)); 1783 1784 // If we have multiple internal linkage entities with the same name 1785 // in extern "C" regions, none of them gets that name. 1786 if (!R.second) 1787 R.first->second = 0; 1788 } 1789 1790 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { 1791 llvm::Constant *Init = 0; 1792 QualType ASTTy = D->getType(); 1793 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 1794 bool NeedsGlobalCtor = false; 1795 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor(); 1796 1797 const VarDecl *InitDecl; 1798 const Expr *InitExpr = D->getAnyInitializer(InitDecl); 1799 1800 if (!InitExpr) { 1801 // This is a tentative definition; tentative definitions are 1802 // implicitly initialized with { 0 }. 1803 // 1804 // Note that tentative definitions are only emitted at the end of 1805 // a translation unit, so they should never have incomplete 1806 // type. In addition, EmitTentativeDefinition makes sure that we 1807 // never attempt to emit a tentative definition if a real one 1808 // exists. A use may still exists, however, so we still may need 1809 // to do a RAUW. 1810 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 1811 Init = EmitNullConstant(D->getType()); 1812 } else { 1813 initializedGlobalDecl = GlobalDecl(D); 1814 Init = EmitConstantInit(*InitDecl); 1815 1816 if (!Init) { 1817 QualType T = InitExpr->getType(); 1818 if (D->getType()->isReferenceType()) 1819 T = D->getType(); 1820 1821 if (getLangOpts().CPlusPlus) { 1822 Init = EmitNullConstant(T); 1823 NeedsGlobalCtor = true; 1824 } else { 1825 ErrorUnsupported(D, "static initializer"); 1826 Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 1827 } 1828 } else { 1829 // We don't need an initializer, so remove the entry for the delayed 1830 // initializer position (just in case this entry was delayed) if we 1831 // also don't need to register a destructor. 1832 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor) 1833 DelayedCXXInitPosition.erase(D); 1834 } 1835 } 1836 1837 llvm::Type* InitType = Init->getType(); 1838 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType); 1839 1840 // Strip off a bitcast if we got one back. 1841 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 1842 assert(CE->getOpcode() == llvm::Instruction::BitCast || 1843 CE->getOpcode() == llvm::Instruction::AddrSpaceCast || 1844 // All zero index gep. 1845 CE->getOpcode() == llvm::Instruction::GetElementPtr); 1846 Entry = CE->getOperand(0); 1847 } 1848 1849 // Entry is now either a Function or GlobalVariable. 1850 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry); 1851 1852 // We have a definition after a declaration with the wrong type. 1853 // We must make a new GlobalVariable* and update everything that used OldGV 1854 // (a declaration or tentative definition) with the new GlobalVariable* 1855 // (which will be a definition). 1856 // 1857 // This happens if there is a prototype for a global (e.g. 1858 // "extern int x[];") and then a definition of a different type (e.g. 1859 // "int x[10];"). This also happens when an initializer has a different type 1860 // from the type of the global (this happens with unions). 1861 if (GV == 0 || 1862 GV->getType()->getElementType() != InitType || 1863 GV->getType()->getAddressSpace() != 1864 GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) { 1865 1866 // Move the old entry aside so that we'll create a new one. 1867 Entry->setName(StringRef()); 1868 1869 // Make a new global with the correct type, this is now guaranteed to work. 1870 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType)); 1871 1872 // Replace all uses of the old global with the new global 1873 llvm::Constant *NewPtrForOldDecl = 1874 llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 1875 Entry->replaceAllUsesWith(NewPtrForOldDecl); 1876 1877 // Erase the old global, since it is no longer used. 1878 cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 1879 } 1880 1881 MaybeHandleStaticInExternC(D, GV); 1882 1883 if (D->hasAttr<AnnotateAttr>()) 1884 AddGlobalAnnotations(D, GV); 1885 1886 GV->setInitializer(Init); 1887 1888 // If it is safe to mark the global 'constant', do so now. 1889 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor && 1890 isTypeConstant(D->getType(), true)); 1891 1892 GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 1893 1894 // Set the llvm linkage type as appropriate. 1895 llvm::GlobalValue::LinkageTypes Linkage = 1896 GetLLVMLinkageVarDefinition(D, GV->isConstant()); 1897 GV->setLinkage(Linkage); 1898 if (D->hasAttr<DLLImportAttr>()) 1899 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 1900 else if (D->hasAttr<DLLExportAttr>()) 1901 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 1902 1903 // If required by the ABI, give definitions of static data members with inline 1904 // initializers linkonce_odr linkage. 1905 if (getCXXABI().isInlineInitializedStaticDataMemberLinkOnce() && 1906 D->isStaticDataMember() && InitExpr && 1907 !InitDecl->isThisDeclarationADefinition()) 1908 GV->setLinkage(llvm::GlobalVariable::LinkOnceODRLinkage); 1909 1910 if (Linkage == llvm::GlobalVariable::CommonLinkage) 1911 // common vars aren't constant even if declared const. 1912 GV->setConstant(false); 1913 1914 SetCommonAttributes(D, GV); 1915 1916 // Emit the initializer function if necessary. 1917 if (NeedsGlobalCtor || NeedsGlobalDtor) 1918 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor); 1919 1920 // If we are compiling with ASan, add metadata indicating dynamically 1921 // initialized globals. 1922 if (SanOpts.Address && NeedsGlobalCtor) { 1923 llvm::Module &M = getModule(); 1924 1925 llvm::NamedMDNode *DynamicInitializers = 1926 M.getOrInsertNamedMetadata("llvm.asan.dynamically_initialized_globals"); 1927 llvm::Value *GlobalToAdd[] = { GV }; 1928 llvm::MDNode *ThisGlobal = llvm::MDNode::get(VMContext, GlobalToAdd); 1929 DynamicInitializers->addOperand(ThisGlobal); 1930 } 1931 1932 // Emit global variable debug information. 1933 if (CGDebugInfo *DI = getModuleDebugInfo()) 1934 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) 1935 DI->EmitGlobalVariable(GV, D); 1936 } 1937 1938 static bool isVarDeclStrongDefinition(const VarDecl *D, bool NoCommon) { 1939 // Don't give variables common linkage if -fno-common was specified unless it 1940 // was overridden by a NoCommon attribute. 1941 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>()) 1942 return true; 1943 1944 // C11 6.9.2/2: 1945 // A declaration of an identifier for an object that has file scope without 1946 // an initializer, and without a storage-class specifier or with the 1947 // storage-class specifier static, constitutes a tentative definition. 1948 if (D->getInit() || D->hasExternalStorage()) 1949 return true; 1950 1951 // A variable cannot be both common and exist in a section. 1952 if (D->hasAttr<SectionAttr>()) 1953 return true; 1954 1955 // Thread local vars aren't considered common linkage. 1956 if (D->getTLSKind()) 1957 return true; 1958 1959 // Tentative definitions marked with WeakImportAttr are true definitions. 1960 if (D->hasAttr<WeakImportAttr>()) 1961 return true; 1962 1963 return false; 1964 } 1965 1966 llvm::GlobalValue::LinkageTypes 1967 CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D, bool isConstant) { 1968 GVALinkage Linkage = getContext().GetGVALinkageForVariable(D); 1969 if (Linkage == GVA_Internal) 1970 return llvm::Function::InternalLinkage; 1971 else if (D->hasAttr<DLLImportAttr>()) 1972 return llvm::Function::ExternalLinkage; 1973 else if (D->hasAttr<DLLExportAttr>()) 1974 return llvm::Function::ExternalLinkage; 1975 else if (D->hasAttr<SelectAnyAttr>()) { 1976 // selectany symbols are externally visible, so use weak instead of 1977 // linkonce. MSVC optimizes away references to const selectany globals, so 1978 // all definitions should be the same and ODR linkage should be used. 1979 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx 1980 return llvm::GlobalVariable::WeakODRLinkage; 1981 } else if (D->hasAttr<WeakAttr>()) { 1982 if (isConstant) 1983 return llvm::GlobalVariable::WeakODRLinkage; 1984 else 1985 return llvm::GlobalVariable::WeakAnyLinkage; 1986 } else if (Linkage == GVA_TemplateInstantiation || Linkage == GVA_StrongODR) 1987 return llvm::GlobalVariable::WeakODRLinkage; 1988 else if (D->getTLSKind() == VarDecl::TLS_Dynamic && 1989 getTarget().getTriple().isMacOSX()) 1990 // On Darwin, the backing variable for a C++11 thread_local variable always 1991 // has internal linkage; all accesses should just be calls to the 1992 // Itanium-specified entry point, which has the normal linkage of the 1993 // variable. 1994 return llvm::GlobalValue::InternalLinkage; 1995 // C++ doesn't have tentative definitions and thus cannot have common linkage. 1996 else if (!getLangOpts().CPlusPlus && 1997 !isVarDeclStrongDefinition(D, CodeGenOpts.NoCommon)) 1998 return llvm::GlobalVariable::CommonLinkage; 1999 2000 return llvm::GlobalVariable::ExternalLinkage; 2001 } 2002 2003 /// Replace the uses of a function that was declared with a non-proto type. 2004 /// We want to silently drop extra arguments from call sites 2005 static void replaceUsesOfNonProtoConstant(llvm::Constant *old, 2006 llvm::Function *newFn) { 2007 // Fast path. 2008 if (old->use_empty()) return; 2009 2010 llvm::Type *newRetTy = newFn->getReturnType(); 2011 SmallVector<llvm::Value*, 4> newArgs; 2012 2013 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end(); 2014 ui != ue; ) { 2015 llvm::Value::use_iterator use = ui++; // Increment before the use is erased. 2016 llvm::User *user = use->getUser(); 2017 2018 // Recognize and replace uses of bitcasts. Most calls to 2019 // unprototyped functions will use bitcasts. 2020 if (llvm::ConstantExpr *bitcast = dyn_cast<llvm::ConstantExpr>(user)) { 2021 if (bitcast->getOpcode() == llvm::Instruction::BitCast) 2022 replaceUsesOfNonProtoConstant(bitcast, newFn); 2023 continue; 2024 } 2025 2026 // Recognize calls to the function. 2027 llvm::CallSite callSite(user); 2028 if (!callSite) continue; 2029 if (!callSite.isCallee(&*use)) continue; 2030 2031 // If the return types don't match exactly, then we can't 2032 // transform this call unless it's dead. 2033 if (callSite->getType() != newRetTy && !callSite->use_empty()) 2034 continue; 2035 2036 // Get the call site's attribute list. 2037 SmallVector<llvm::AttributeSet, 8> newAttrs; 2038 llvm::AttributeSet oldAttrs = callSite.getAttributes(); 2039 2040 // Collect any return attributes from the call. 2041 if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex)) 2042 newAttrs.push_back( 2043 llvm::AttributeSet::get(newFn->getContext(), 2044 oldAttrs.getRetAttributes())); 2045 2046 // If the function was passed too few arguments, don't transform. 2047 unsigned newNumArgs = newFn->arg_size(); 2048 if (callSite.arg_size() < newNumArgs) continue; 2049 2050 // If extra arguments were passed, we silently drop them. 2051 // If any of the types mismatch, we don't transform. 2052 unsigned argNo = 0; 2053 bool dontTransform = false; 2054 for (llvm::Function::arg_iterator ai = newFn->arg_begin(), 2055 ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) { 2056 if (callSite.getArgument(argNo)->getType() != ai->getType()) { 2057 dontTransform = true; 2058 break; 2059 } 2060 2061 // Add any parameter attributes. 2062 if (oldAttrs.hasAttributes(argNo + 1)) 2063 newAttrs. 2064 push_back(llvm:: 2065 AttributeSet::get(newFn->getContext(), 2066 oldAttrs.getParamAttributes(argNo + 1))); 2067 } 2068 if (dontTransform) 2069 continue; 2070 2071 if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) 2072 newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(), 2073 oldAttrs.getFnAttributes())); 2074 2075 // Okay, we can transform this. Create the new call instruction and copy 2076 // over the required information. 2077 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo); 2078 2079 llvm::CallSite newCall; 2080 if (callSite.isCall()) { 2081 newCall = llvm::CallInst::Create(newFn, newArgs, "", 2082 callSite.getInstruction()); 2083 } else { 2084 llvm::InvokeInst *oldInvoke = 2085 cast<llvm::InvokeInst>(callSite.getInstruction()); 2086 newCall = llvm::InvokeInst::Create(newFn, 2087 oldInvoke->getNormalDest(), 2088 oldInvoke->getUnwindDest(), 2089 newArgs, "", 2090 callSite.getInstruction()); 2091 } 2092 newArgs.clear(); // for the next iteration 2093 2094 if (!newCall->getType()->isVoidTy()) 2095 newCall->takeName(callSite.getInstruction()); 2096 newCall.setAttributes( 2097 llvm::AttributeSet::get(newFn->getContext(), newAttrs)); 2098 newCall.setCallingConv(callSite.getCallingConv()); 2099 2100 // Finally, remove the old call, replacing any uses with the new one. 2101 if (!callSite->use_empty()) 2102 callSite->replaceAllUsesWith(newCall.getInstruction()); 2103 2104 // Copy debug location attached to CI. 2105 if (!callSite->getDebugLoc().isUnknown()) 2106 newCall->setDebugLoc(callSite->getDebugLoc()); 2107 callSite->eraseFromParent(); 2108 } 2109 } 2110 2111 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 2112 /// implement a function with no prototype, e.g. "int foo() {}". If there are 2113 /// existing call uses of the old function in the module, this adjusts them to 2114 /// call the new function directly. 2115 /// 2116 /// This is not just a cleanup: the always_inline pass requires direct calls to 2117 /// functions to be able to inline them. If there is a bitcast in the way, it 2118 /// won't inline them. Instcombine normally deletes these calls, but it isn't 2119 /// run at -O0. 2120 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 2121 llvm::Function *NewFn) { 2122 // If we're redefining a global as a function, don't transform it. 2123 if (!isa<llvm::Function>(Old)) return; 2124 2125 replaceUsesOfNonProtoConstant(Old, NewFn); 2126 } 2127 2128 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) { 2129 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind(); 2130 // If we have a definition, this might be a deferred decl. If the 2131 // instantiation is explicit, make sure we emit it at the end. 2132 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition) 2133 GetAddrOfGlobalVar(VD); 2134 2135 EmitTopLevelDecl(VD); 2136 } 2137 2138 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD, 2139 llvm::GlobalValue *GV) { 2140 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl()); 2141 2142 // Compute the function info and LLVM type. 2143 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 2144 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 2145 2146 // Get or create the prototype for the function. 2147 llvm::Constant *Entry = 2148 GV ? GV 2149 : GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer*/ true); 2150 2151 // Strip off a bitcast if we got one back. 2152 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 2153 assert(CE->getOpcode() == llvm::Instruction::BitCast); 2154 Entry = CE->getOperand(0); 2155 } 2156 2157 if (!cast<llvm::GlobalValue>(Entry)->isDeclaration()) { 2158 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name); 2159 return; 2160 } 2161 2162 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) { 2163 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry); 2164 2165 // If the types mismatch then we have to rewrite the definition. 2166 assert(OldFn->isDeclaration() && 2167 "Shouldn't replace non-declaration"); 2168 2169 // F is the Function* for the one with the wrong type, we must make a new 2170 // Function* and update everything that used F (a declaration) with the new 2171 // Function* (which will be a definition). 2172 // 2173 // This happens if there is a prototype for a function 2174 // (e.g. "int f()") and then a definition of a different type 2175 // (e.g. "int f(int x)"). Move the old function aside so that it 2176 // doesn't interfere with GetAddrOfFunction. 2177 OldFn->setName(StringRef()); 2178 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty)); 2179 2180 // This might be an implementation of a function without a 2181 // prototype, in which case, try to do special replacement of 2182 // calls which match the new prototype. The really key thing here 2183 // is that we also potentially drop arguments from the call site 2184 // so as to make a direct call, which makes the inliner happier 2185 // and suppresses a number of optimizer warnings (!) about 2186 // dropping arguments. 2187 if (!OldFn->use_empty()) { 2188 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn); 2189 OldFn->removeDeadConstantUsers(); 2190 } 2191 2192 // Replace uses of F with the Function we will endow with a body. 2193 if (!Entry->use_empty()) { 2194 llvm::Constant *NewPtrForOldDecl = 2195 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType()); 2196 Entry->replaceAllUsesWith(NewPtrForOldDecl); 2197 } 2198 2199 // Ok, delete the old function now, which is dead. 2200 OldFn->eraseFromParent(); 2201 2202 Entry = NewFn; 2203 } 2204 2205 // We need to set linkage and visibility on the function before 2206 // generating code for it because various parts of IR generation 2207 // want to propagate this information down (e.g. to local static 2208 // declarations). 2209 llvm::Function *Fn = cast<llvm::Function>(Entry); 2210 setFunctionLinkage(GD, Fn); 2211 2212 // FIXME: this is redundant with part of SetFunctionDefinitionAttributes 2213 setGlobalVisibility(Fn, D); 2214 2215 MaybeHandleStaticInExternC(D, Fn); 2216 2217 CodeGenFunction(*this).GenerateCode(D, Fn, FI); 2218 2219 SetFunctionDefinitionAttributes(D, Fn); 2220 SetLLVMFunctionAttributesForDefinition(D, Fn); 2221 2222 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 2223 AddGlobalCtor(Fn, CA->getPriority()); 2224 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 2225 AddGlobalDtor(Fn, DA->getPriority()); 2226 if (D->hasAttr<AnnotateAttr>()) 2227 AddGlobalAnnotations(D, Fn); 2228 } 2229 2230 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 2231 const ValueDecl *D = cast<ValueDecl>(GD.getDecl()); 2232 const AliasAttr *AA = D->getAttr<AliasAttr>(); 2233 assert(AA && "Not an alias?"); 2234 2235 StringRef MangledName = getMangledName(GD); 2236 2237 // If there is a definition in the module, then it wins over the alias. 2238 // This is dubious, but allow it to be safe. Just ignore the alias. 2239 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 2240 if (Entry && !Entry->isDeclaration()) 2241 return; 2242 2243 Aliases.push_back(GD); 2244 2245 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 2246 2247 // Create a reference to the named value. This ensures that it is emitted 2248 // if a deferred decl. 2249 llvm::Constant *Aliasee; 2250 if (isa<llvm::FunctionType>(DeclTy)) 2251 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD, 2252 /*ForVTable=*/false); 2253 else 2254 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 2255 llvm::PointerType::getUnqual(DeclTy), 0); 2256 2257 // Create the new alias itself, but don't set a name yet. 2258 llvm::GlobalValue *GA = 2259 new llvm::GlobalAlias(Aliasee->getType(), 2260 llvm::Function::ExternalLinkage, 2261 "", Aliasee, &getModule()); 2262 2263 if (Entry) { 2264 assert(Entry->isDeclaration()); 2265 2266 // If there is a declaration in the module, then we had an extern followed 2267 // by the alias, as in: 2268 // extern int test6(); 2269 // ... 2270 // int test6() __attribute__((alias("test7"))); 2271 // 2272 // Remove it and replace uses of it with the alias. 2273 GA->takeName(Entry); 2274 2275 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 2276 Entry->getType())); 2277 Entry->eraseFromParent(); 2278 } else { 2279 GA->setName(MangledName); 2280 } 2281 2282 // Set attributes which are particular to an alias; this is a 2283 // specialization of the attributes which may be set on a global 2284 // variable/function. 2285 if (D->hasAttr<DLLExportAttr>()) { 2286 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2287 // The dllexport attribute is ignored for undefined symbols. 2288 if (FD->hasBody()) 2289 GA->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 2290 } else { 2291 GA->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 2292 } 2293 } else if (D->hasAttr<WeakAttr>() || 2294 D->hasAttr<WeakRefAttr>() || 2295 D->isWeakImported()) { 2296 GA->setLinkage(llvm::Function::WeakAnyLinkage); 2297 } 2298 2299 SetCommonAttributes(D, GA); 2300 } 2301 2302 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, 2303 ArrayRef<llvm::Type*> Tys) { 2304 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, 2305 Tys); 2306 } 2307 2308 static llvm::StringMapEntry<llvm::Constant*> & 2309 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map, 2310 const StringLiteral *Literal, 2311 bool TargetIsLSB, 2312 bool &IsUTF16, 2313 unsigned &StringLength) { 2314 StringRef String = Literal->getString(); 2315 unsigned NumBytes = String.size(); 2316 2317 // Check for simple case. 2318 if (!Literal->containsNonAsciiOrNull()) { 2319 StringLength = NumBytes; 2320 return Map.GetOrCreateValue(String); 2321 } 2322 2323 // Otherwise, convert the UTF8 literals into a string of shorts. 2324 IsUTF16 = true; 2325 2326 SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls. 2327 const UTF8 *FromPtr = (const UTF8 *)String.data(); 2328 UTF16 *ToPtr = &ToBuf[0]; 2329 2330 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 2331 &ToPtr, ToPtr + NumBytes, 2332 strictConversion); 2333 2334 // ConvertUTF8toUTF16 returns the length in ToPtr. 2335 StringLength = ToPtr - &ToBuf[0]; 2336 2337 // Add an explicit null. 2338 *ToPtr = 0; 2339 return Map. 2340 GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()), 2341 (StringLength + 1) * 2)); 2342 } 2343 2344 static llvm::StringMapEntry<llvm::Constant*> & 2345 GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map, 2346 const StringLiteral *Literal, 2347 unsigned &StringLength) { 2348 StringRef String = Literal->getString(); 2349 StringLength = String.size(); 2350 return Map.GetOrCreateValue(String); 2351 } 2352 2353 llvm::Constant * 2354 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 2355 unsigned StringLength = 0; 2356 bool isUTF16 = false; 2357 llvm::StringMapEntry<llvm::Constant*> &Entry = 2358 GetConstantCFStringEntry(CFConstantStringMap, Literal, 2359 getDataLayout().isLittleEndian(), 2360 isUTF16, StringLength); 2361 2362 if (llvm::Constant *C = Entry.getValue()) 2363 return C; 2364 2365 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 2366 llvm::Constant *Zeros[] = { Zero, Zero }; 2367 llvm::Value *V; 2368 2369 // If we don't already have it, get __CFConstantStringClassReference. 2370 if (!CFConstantStringClassRef) { 2371 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 2372 Ty = llvm::ArrayType::get(Ty, 0); 2373 llvm::Constant *GV = CreateRuntimeVariable(Ty, 2374 "__CFConstantStringClassReference"); 2375 // Decay array -> ptr 2376 V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 2377 CFConstantStringClassRef = V; 2378 } 2379 else 2380 V = CFConstantStringClassRef; 2381 2382 QualType CFTy = getContext().getCFConstantStringType(); 2383 2384 llvm::StructType *STy = 2385 cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 2386 2387 llvm::Constant *Fields[4]; 2388 2389 // Class pointer. 2390 Fields[0] = cast<llvm::ConstantExpr>(V); 2391 2392 // Flags. 2393 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 2394 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) : 2395 llvm::ConstantInt::get(Ty, 0x07C8); 2396 2397 // String pointer. 2398 llvm::Constant *C = 0; 2399 if (isUTF16) { 2400 ArrayRef<uint16_t> Arr = 2401 llvm::makeArrayRef<uint16_t>(reinterpret_cast<uint16_t*>( 2402 const_cast<char *>(Entry.getKey().data())), 2403 Entry.getKey().size() / 2); 2404 C = llvm::ConstantDataArray::get(VMContext, Arr); 2405 } else { 2406 C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey()); 2407 } 2408 2409 // Note: -fwritable-strings doesn't make the backing store strings of 2410 // CFStrings writable. (See <rdar://problem/10657500>) 2411 llvm::GlobalVariable *GV = 2412 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true, 2413 llvm::GlobalValue::PrivateLinkage, C, ".str"); 2414 GV->setUnnamedAddr(true); 2415 // Don't enforce the target's minimum global alignment, since the only use 2416 // of the string is via this class initializer. 2417 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. Without 2418 // it LLVM can merge the string with a non unnamed_addr one during LTO. Doing 2419 // that changes the section it ends in, which surprises ld64. 2420 if (isUTF16) { 2421 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy); 2422 GV->setAlignment(Align.getQuantity()); 2423 GV->setSection("__TEXT,__ustring"); 2424 } else { 2425 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy); 2426 GV->setAlignment(Align.getQuantity()); 2427 GV->setSection("__TEXT,__cstring,cstring_literals"); 2428 } 2429 2430 // String. 2431 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 2432 2433 if (isUTF16) 2434 // Cast the UTF16 string to the correct type. 2435 Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy); 2436 2437 // String length. 2438 Ty = getTypes().ConvertType(getContext().LongTy); 2439 Fields[3] = llvm::ConstantInt::get(Ty, StringLength); 2440 2441 // The struct. 2442 C = llvm::ConstantStruct::get(STy, Fields); 2443 GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 2444 llvm::GlobalVariable::PrivateLinkage, C, 2445 "_unnamed_cfstring_"); 2446 GV->setSection("__DATA,__cfstring"); 2447 Entry.setValue(GV); 2448 2449 return GV; 2450 } 2451 2452 llvm::Constant * 2453 CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) { 2454 unsigned StringLength = 0; 2455 llvm::StringMapEntry<llvm::Constant*> &Entry = 2456 GetConstantStringEntry(CFConstantStringMap, Literal, StringLength); 2457 2458 if (llvm::Constant *C = Entry.getValue()) 2459 return C; 2460 2461 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 2462 llvm::Constant *Zeros[] = { Zero, Zero }; 2463 llvm::Value *V; 2464 // If we don't already have it, get _NSConstantStringClassReference. 2465 if (!ConstantStringClassRef) { 2466 std::string StringClass(getLangOpts().ObjCConstantStringClass); 2467 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 2468 llvm::Constant *GV; 2469 if (LangOpts.ObjCRuntime.isNonFragile()) { 2470 std::string str = 2471 StringClass.empty() ? "OBJC_CLASS_$_NSConstantString" 2472 : "OBJC_CLASS_$_" + StringClass; 2473 GV = getObjCRuntime().GetClassGlobal(str); 2474 // Make sure the result is of the correct type. 2475 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 2476 V = llvm::ConstantExpr::getBitCast(GV, PTy); 2477 ConstantStringClassRef = V; 2478 } else { 2479 std::string str = 2480 StringClass.empty() ? "_NSConstantStringClassReference" 2481 : "_" + StringClass + "ClassReference"; 2482 llvm::Type *PTy = llvm::ArrayType::get(Ty, 0); 2483 GV = CreateRuntimeVariable(PTy, str); 2484 // Decay array -> ptr 2485 V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 2486 ConstantStringClassRef = V; 2487 } 2488 } 2489 else 2490 V = ConstantStringClassRef; 2491 2492 if (!NSConstantStringType) { 2493 // Construct the type for a constant NSString. 2494 RecordDecl *D = Context.buildImplicitRecord("__builtin_NSString"); 2495 D->startDefinition(); 2496 2497 QualType FieldTypes[3]; 2498 2499 // const int *isa; 2500 FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst()); 2501 // const char *str; 2502 FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst()); 2503 // unsigned int length; 2504 FieldTypes[2] = Context.UnsignedIntTy; 2505 2506 // Create fields 2507 for (unsigned i = 0; i < 3; ++i) { 2508 FieldDecl *Field = FieldDecl::Create(Context, D, 2509 SourceLocation(), 2510 SourceLocation(), 0, 2511 FieldTypes[i], /*TInfo=*/0, 2512 /*BitWidth=*/0, 2513 /*Mutable=*/false, 2514 ICIS_NoInit); 2515 Field->setAccess(AS_public); 2516 D->addDecl(Field); 2517 } 2518 2519 D->completeDefinition(); 2520 QualType NSTy = Context.getTagDeclType(D); 2521 NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy)); 2522 } 2523 2524 llvm::Constant *Fields[3]; 2525 2526 // Class pointer. 2527 Fields[0] = cast<llvm::ConstantExpr>(V); 2528 2529 // String pointer. 2530 llvm::Constant *C = 2531 llvm::ConstantDataArray::getString(VMContext, Entry.getKey()); 2532 2533 llvm::GlobalValue::LinkageTypes Linkage; 2534 bool isConstant; 2535 Linkage = llvm::GlobalValue::PrivateLinkage; 2536 isConstant = !LangOpts.WritableStrings; 2537 2538 llvm::GlobalVariable *GV = 2539 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C, 2540 ".str"); 2541 GV->setUnnamedAddr(true); 2542 // Don't enforce the target's minimum global alignment, since the only use 2543 // of the string is via this class initializer. 2544 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy); 2545 GV->setAlignment(Align.getQuantity()); 2546 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 2547 2548 // String length. 2549 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 2550 Fields[2] = llvm::ConstantInt::get(Ty, StringLength); 2551 2552 // The struct. 2553 C = llvm::ConstantStruct::get(NSConstantStringType, Fields); 2554 GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 2555 llvm::GlobalVariable::PrivateLinkage, C, 2556 "_unnamed_nsstring_"); 2557 const char *NSStringSection = "__OBJC,__cstring_object,regular,no_dead_strip"; 2558 const char *NSStringNonFragileABISection = 2559 "__DATA,__objc_stringobj,regular,no_dead_strip"; 2560 // FIXME. Fix section. 2561 GV->setSection(LangOpts.ObjCRuntime.isNonFragile() 2562 ? NSStringNonFragileABISection 2563 : NSStringSection); 2564 Entry.setValue(GV); 2565 2566 return GV; 2567 } 2568 2569 QualType CodeGenModule::getObjCFastEnumerationStateType() { 2570 if (ObjCFastEnumerationStateType.isNull()) { 2571 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState"); 2572 D->startDefinition(); 2573 2574 QualType FieldTypes[] = { 2575 Context.UnsignedLongTy, 2576 Context.getPointerType(Context.getObjCIdType()), 2577 Context.getPointerType(Context.UnsignedLongTy), 2578 Context.getConstantArrayType(Context.UnsignedLongTy, 2579 llvm::APInt(32, 5), ArrayType::Normal, 0) 2580 }; 2581 2582 for (size_t i = 0; i < 4; ++i) { 2583 FieldDecl *Field = FieldDecl::Create(Context, 2584 D, 2585 SourceLocation(), 2586 SourceLocation(), 0, 2587 FieldTypes[i], /*TInfo=*/0, 2588 /*BitWidth=*/0, 2589 /*Mutable=*/false, 2590 ICIS_NoInit); 2591 Field->setAccess(AS_public); 2592 D->addDecl(Field); 2593 } 2594 2595 D->completeDefinition(); 2596 ObjCFastEnumerationStateType = Context.getTagDeclType(D); 2597 } 2598 2599 return ObjCFastEnumerationStateType; 2600 } 2601 2602 llvm::Constant * 2603 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) { 2604 assert(!E->getType()->isPointerType() && "Strings are always arrays"); 2605 2606 // Don't emit it as the address of the string, emit the string data itself 2607 // as an inline array. 2608 if (E->getCharByteWidth() == 1) { 2609 SmallString<64> Str(E->getString()); 2610 2611 // Resize the string to the right size, which is indicated by its type. 2612 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType()); 2613 Str.resize(CAT->getSize().getZExtValue()); 2614 return llvm::ConstantDataArray::getString(VMContext, Str, false); 2615 } 2616 2617 llvm::ArrayType *AType = 2618 cast<llvm::ArrayType>(getTypes().ConvertType(E->getType())); 2619 llvm::Type *ElemTy = AType->getElementType(); 2620 unsigned NumElements = AType->getNumElements(); 2621 2622 // Wide strings have either 2-byte or 4-byte elements. 2623 if (ElemTy->getPrimitiveSizeInBits() == 16) { 2624 SmallVector<uint16_t, 32> Elements; 2625 Elements.reserve(NumElements); 2626 2627 for(unsigned i = 0, e = E->getLength(); i != e; ++i) 2628 Elements.push_back(E->getCodeUnit(i)); 2629 Elements.resize(NumElements); 2630 return llvm::ConstantDataArray::get(VMContext, Elements); 2631 } 2632 2633 assert(ElemTy->getPrimitiveSizeInBits() == 32); 2634 SmallVector<uint32_t, 32> Elements; 2635 Elements.reserve(NumElements); 2636 2637 for(unsigned i = 0, e = E->getLength(); i != e; ++i) 2638 Elements.push_back(E->getCodeUnit(i)); 2639 Elements.resize(NumElements); 2640 return llvm::ConstantDataArray::get(VMContext, Elements); 2641 } 2642 2643 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 2644 /// constant array for the given string literal. 2645 llvm::Constant * 2646 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) { 2647 CharUnits Align = getContext().getAlignOfGlobalVarInChars(S->getType()); 2648 2649 llvm::StringMapEntry<llvm::GlobalVariable *> *Entry = nullptr; 2650 llvm::GlobalVariable *GV = nullptr; 2651 if (!LangOpts.WritableStrings) { 2652 llvm::StringMap<llvm::GlobalVariable *> *ConstantStringMap = nullptr; 2653 switch (S->getCharByteWidth()) { 2654 case 1: 2655 ConstantStringMap = &Constant1ByteStringMap; 2656 break; 2657 case 2: 2658 ConstantStringMap = &Constant2ByteStringMap; 2659 break; 2660 case 4: 2661 ConstantStringMap = &Constant4ByteStringMap; 2662 break; 2663 default: 2664 llvm_unreachable("unhandled byte width!"); 2665 } 2666 Entry = &ConstantStringMap->GetOrCreateValue(S->getBytes()); 2667 GV = Entry->getValue(); 2668 } 2669 2670 if (!GV) { 2671 SmallString<256> MangledNameBuffer; 2672 StringRef GlobalVariableName; 2673 llvm::GlobalValue::LinkageTypes LT; 2674 2675 // Mangle the string literal if the ABI allows for it. However, we cannot 2676 // do this if we are compiling with ASan or -fwritable-strings because they 2677 // rely on strings having normal linkage. 2678 if (!LangOpts.WritableStrings && !SanOpts.Address && 2679 getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) { 2680 llvm::raw_svector_ostream Out(MangledNameBuffer); 2681 getCXXABI().getMangleContext().mangleStringLiteral(S, Out); 2682 Out.flush(); 2683 2684 LT = llvm::GlobalValue::LinkOnceODRLinkage; 2685 GlobalVariableName = MangledNameBuffer; 2686 } else { 2687 LT = llvm::GlobalValue::PrivateLinkage; 2688 GlobalVariableName = ".str"; 2689 } 2690 2691 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space. 2692 unsigned AddrSpace = 0; 2693 if (getLangOpts().OpenCL) 2694 AddrSpace = getContext().getTargetAddressSpace(LangAS::opencl_constant); 2695 2696 llvm::Constant *C = GetConstantArrayFromStringLiteral(S); 2697 GV = new llvm::GlobalVariable( 2698 getModule(), C->getType(), !LangOpts.WritableStrings, LT, C, 2699 GlobalVariableName, /*InsertBefore=*/nullptr, 2700 llvm::GlobalVariable::NotThreadLocal, AddrSpace); 2701 GV->setUnnamedAddr(true); 2702 if (Entry) 2703 Entry->setValue(GV); 2704 } 2705 2706 if (Align.getQuantity() > GV->getAlignment()) 2707 GV->setAlignment(Align.getQuantity()); 2708 2709 return GV; 2710 } 2711 2712 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 2713 /// array for the given ObjCEncodeExpr node. 2714 llvm::Constant * 2715 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 2716 std::string Str; 2717 getContext().getObjCEncodingForType(E->getEncodedType(), Str); 2718 2719 return GetAddrOfConstantCString(Str); 2720 } 2721 2722 2723 /// GenerateWritableString -- Creates storage for a string literal. 2724 static llvm::GlobalVariable *GenerateStringLiteral(StringRef str, 2725 bool constant, 2726 CodeGenModule &CGM, 2727 const char *GlobalName, 2728 unsigned Alignment) { 2729 // Create Constant for this string literal. Don't add a '\0'. 2730 llvm::Constant *C = 2731 llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false); 2732 2733 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space. 2734 unsigned AddrSpace = 0; 2735 if (CGM.getLangOpts().OpenCL) 2736 AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant); 2737 2738 // Create a global variable for this string 2739 llvm::GlobalVariable *GV = new llvm::GlobalVariable( 2740 CGM.getModule(), C->getType(), constant, 2741 llvm::GlobalValue::PrivateLinkage, C, GlobalName, 0, 2742 llvm::GlobalVariable::NotThreadLocal, AddrSpace); 2743 GV->setAlignment(Alignment); 2744 GV->setUnnamedAddr(true); 2745 return GV; 2746 } 2747 2748 /// GetAddrOfConstantString - Returns a pointer to a character array 2749 /// containing the literal. This contents are exactly that of the 2750 /// given string, i.e. it will not be null terminated automatically; 2751 /// see GetAddrOfConstantCString. Note that whether the result is 2752 /// actually a pointer to an LLVM constant depends on 2753 /// Feature.WriteableStrings. 2754 /// 2755 /// The result has pointer to array type. 2756 llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str, 2757 const char *GlobalName, 2758 unsigned Alignment) { 2759 // Get the default prefix if a name wasn't specified. 2760 if (!GlobalName) 2761 GlobalName = ".str"; 2762 2763 if (Alignment == 0) 2764 Alignment = getContext().getAlignOfGlobalVarInChars(getContext().CharTy) 2765 .getQuantity(); 2766 2767 // Don't share any string literals if strings aren't constant. 2768 if (LangOpts.WritableStrings) 2769 return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment); 2770 2771 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 2772 Constant1ByteStringMap.GetOrCreateValue(Str); 2773 2774 if (llvm::GlobalVariable *GV = Entry.getValue()) { 2775 if (Alignment > GV->getAlignment()) { 2776 GV->setAlignment(Alignment); 2777 } 2778 return GV; 2779 } 2780 2781 // Create a global variable for this. 2782 llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName, 2783 Alignment); 2784 Entry.setValue(GV); 2785 return GV; 2786 } 2787 2788 /// GetAddrOfConstantCString - Returns a pointer to a character 2789 /// array containing the literal and a terminating '\0' 2790 /// character. The result has pointer to array type. 2791 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str, 2792 const char *GlobalName, 2793 unsigned Alignment) { 2794 StringRef StrWithNull(Str.c_str(), Str.size() + 1); 2795 return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment); 2796 } 2797 2798 llvm::Constant *CodeGenModule::GetAddrOfGlobalTemporary( 2799 const MaterializeTemporaryExpr *E, const Expr *Init) { 2800 assert((E->getStorageDuration() == SD_Static || 2801 E->getStorageDuration() == SD_Thread) && "not a global temporary"); 2802 const VarDecl *VD = cast<VarDecl>(E->getExtendingDecl()); 2803 2804 // If we're not materializing a subobject of the temporary, keep the 2805 // cv-qualifiers from the type of the MaterializeTemporaryExpr. 2806 QualType MaterializedType = Init->getType(); 2807 if (Init == E->GetTemporaryExpr()) 2808 MaterializedType = E->getType(); 2809 2810 llvm::Constant *&Slot = MaterializedGlobalTemporaryMap[E]; 2811 if (Slot) 2812 return Slot; 2813 2814 // FIXME: If an externally-visible declaration extends multiple temporaries, 2815 // we need to give each temporary the same name in every translation unit (and 2816 // we also need to make the temporaries externally-visible). 2817 SmallString<256> Name; 2818 llvm::raw_svector_ostream Out(Name); 2819 getCXXABI().getMangleContext().mangleReferenceTemporary(VD, Out); 2820 Out.flush(); 2821 2822 APValue *Value = 0; 2823 if (E->getStorageDuration() == SD_Static) { 2824 // We might have a cached constant initializer for this temporary. Note 2825 // that this might have a different value from the value computed by 2826 // evaluating the initializer if the surrounding constant expression 2827 // modifies the temporary. 2828 Value = getContext().getMaterializedTemporaryValue(E, false); 2829 if (Value && Value->isUninit()) 2830 Value = 0; 2831 } 2832 2833 // Try evaluating it now, it might have a constant initializer. 2834 Expr::EvalResult EvalResult; 2835 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) && 2836 !EvalResult.hasSideEffects()) 2837 Value = &EvalResult.Val; 2838 2839 llvm::Constant *InitialValue = 0; 2840 bool Constant = false; 2841 llvm::Type *Type; 2842 if (Value) { 2843 // The temporary has a constant initializer, use it. 2844 InitialValue = EmitConstantValue(*Value, MaterializedType, 0); 2845 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value); 2846 Type = InitialValue->getType(); 2847 } else { 2848 // No initializer, the initialization will be provided when we 2849 // initialize the declaration which performed lifetime extension. 2850 Type = getTypes().ConvertTypeForMem(MaterializedType); 2851 } 2852 2853 // Create a global variable for this lifetime-extended temporary. 2854 llvm::GlobalVariable *GV = 2855 new llvm::GlobalVariable(getModule(), Type, Constant, 2856 llvm::GlobalValue::PrivateLinkage, 2857 InitialValue, Name.c_str()); 2858 GV->setAlignment( 2859 getContext().getTypeAlignInChars(MaterializedType).getQuantity()); 2860 if (VD->getTLSKind()) 2861 setTLSMode(GV, *VD); 2862 Slot = GV; 2863 return GV; 2864 } 2865 2866 /// EmitObjCPropertyImplementations - Emit information for synthesized 2867 /// properties for an implementation. 2868 void CodeGenModule::EmitObjCPropertyImplementations(const 2869 ObjCImplementationDecl *D) { 2870 for (const auto *PID : D->property_impls()) { 2871 // Dynamic is just for type-checking. 2872 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 2873 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 2874 2875 // Determine which methods need to be implemented, some may have 2876 // been overridden. Note that ::isPropertyAccessor is not the method 2877 // we want, that just indicates if the decl came from a 2878 // property. What we want to know is if the method is defined in 2879 // this implementation. 2880 if (!D->getInstanceMethod(PD->getGetterName())) 2881 CodeGenFunction(*this).GenerateObjCGetter( 2882 const_cast<ObjCImplementationDecl *>(D), PID); 2883 if (!PD->isReadOnly() && 2884 !D->getInstanceMethod(PD->getSetterName())) 2885 CodeGenFunction(*this).GenerateObjCSetter( 2886 const_cast<ObjCImplementationDecl *>(D), PID); 2887 } 2888 } 2889 } 2890 2891 static bool needsDestructMethod(ObjCImplementationDecl *impl) { 2892 const ObjCInterfaceDecl *iface = impl->getClassInterface(); 2893 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 2894 ivar; ivar = ivar->getNextIvar()) 2895 if (ivar->getType().isDestructedType()) 2896 return true; 2897 2898 return false; 2899 } 2900 2901 /// EmitObjCIvarInitializations - Emit information for ivar initialization 2902 /// for an implementation. 2903 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 2904 // We might need a .cxx_destruct even if we don't have any ivar initializers. 2905 if (needsDestructMethod(D)) { 2906 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 2907 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 2908 ObjCMethodDecl *DTORMethod = 2909 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(), 2910 cxxSelector, getContext().VoidTy, 0, D, 2911 /*isInstance=*/true, /*isVariadic=*/false, 2912 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true, 2913 /*isDefined=*/false, ObjCMethodDecl::Required); 2914 D->addInstanceMethod(DTORMethod); 2915 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 2916 D->setHasDestructors(true); 2917 } 2918 2919 // If the implementation doesn't have any ivar initializers, we don't need 2920 // a .cxx_construct. 2921 if (D->getNumIvarInitializers() == 0) 2922 return; 2923 2924 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); 2925 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 2926 // The constructor returns 'self'. 2927 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(), 2928 D->getLocation(), 2929 D->getLocation(), 2930 cxxSelector, 2931 getContext().getObjCIdType(), 0, 2932 D, /*isInstance=*/true, 2933 /*isVariadic=*/false, 2934 /*isPropertyAccessor=*/true, 2935 /*isImplicitlyDeclared=*/true, 2936 /*isDefined=*/false, 2937 ObjCMethodDecl::Required); 2938 D->addInstanceMethod(CTORMethod); 2939 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 2940 D->setHasNonZeroConstructors(true); 2941 } 2942 2943 /// EmitNamespace - Emit all declarations in a namespace. 2944 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) { 2945 for (auto *I : ND->decls()) { 2946 if (const auto *VD = dyn_cast<VarDecl>(I)) 2947 if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization && 2948 VD->getTemplateSpecializationKind() != TSK_Undeclared) 2949 continue; 2950 EmitTopLevelDecl(I); 2951 } 2952 } 2953 2954 // EmitLinkageSpec - Emit all declarations in a linkage spec. 2955 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 2956 if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 2957 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 2958 ErrorUnsupported(LSD, "linkage spec"); 2959 return; 2960 } 2961 2962 for (auto *I : LSD->decls()) { 2963 // Meta-data for ObjC class includes references to implemented methods. 2964 // Generate class's method definitions first. 2965 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) { 2966 for (auto *M : OID->methods()) 2967 EmitTopLevelDecl(M); 2968 } 2969 EmitTopLevelDecl(I); 2970 } 2971 } 2972 2973 /// EmitTopLevelDecl - Emit code for a single top level declaration. 2974 void CodeGenModule::EmitTopLevelDecl(Decl *D) { 2975 // Ignore dependent declarations. 2976 if (D->getDeclContext() && D->getDeclContext()->isDependentContext()) 2977 return; 2978 2979 switch (D->getKind()) { 2980 case Decl::CXXConversion: 2981 case Decl::CXXMethod: 2982 case Decl::Function: 2983 // Skip function templates 2984 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 2985 cast<FunctionDecl>(D)->isLateTemplateParsed()) 2986 return; 2987 2988 EmitGlobal(cast<FunctionDecl>(D)); 2989 break; 2990 2991 case Decl::Var: 2992 // Skip variable templates 2993 if (cast<VarDecl>(D)->getDescribedVarTemplate()) 2994 return; 2995 case Decl::VarTemplateSpecialization: 2996 EmitGlobal(cast<VarDecl>(D)); 2997 break; 2998 2999 // Indirect fields from global anonymous structs and unions can be 3000 // ignored; only the actual variable requires IR gen support. 3001 case Decl::IndirectField: 3002 break; 3003 3004 // C++ Decls 3005 case Decl::Namespace: 3006 EmitNamespace(cast<NamespaceDecl>(D)); 3007 break; 3008 // No code generation needed. 3009 case Decl::UsingShadow: 3010 case Decl::ClassTemplate: 3011 case Decl::VarTemplate: 3012 case Decl::VarTemplatePartialSpecialization: 3013 case Decl::FunctionTemplate: 3014 case Decl::TypeAliasTemplate: 3015 case Decl::Block: 3016 case Decl::Empty: 3017 break; 3018 case Decl::Using: // using X; [C++] 3019 if (CGDebugInfo *DI = getModuleDebugInfo()) 3020 DI->EmitUsingDecl(cast<UsingDecl>(*D)); 3021 return; 3022 case Decl::NamespaceAlias: 3023 if (CGDebugInfo *DI = getModuleDebugInfo()) 3024 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D)); 3025 return; 3026 case Decl::UsingDirective: // using namespace X; [C++] 3027 if (CGDebugInfo *DI = getModuleDebugInfo()) 3028 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D)); 3029 return; 3030 case Decl::CXXConstructor: 3031 // Skip function templates 3032 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 3033 cast<FunctionDecl>(D)->isLateTemplateParsed()) 3034 return; 3035 3036 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 3037 break; 3038 case Decl::CXXDestructor: 3039 if (cast<FunctionDecl>(D)->isLateTemplateParsed()) 3040 return; 3041 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 3042 break; 3043 3044 case Decl::StaticAssert: 3045 // Nothing to do. 3046 break; 3047 3048 // Objective-C Decls 3049 3050 // Forward declarations, no (immediate) code generation. 3051 case Decl::ObjCInterface: 3052 case Decl::ObjCCategory: 3053 break; 3054 3055 case Decl::ObjCProtocol: { 3056 ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(D); 3057 if (Proto->isThisDeclarationADefinition()) 3058 ObjCRuntime->GenerateProtocol(Proto); 3059 break; 3060 } 3061 3062 case Decl::ObjCCategoryImpl: 3063 // Categories have properties but don't support synthesize so we 3064 // can ignore them here. 3065 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 3066 break; 3067 3068 case Decl::ObjCImplementation: { 3069 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D); 3070 EmitObjCPropertyImplementations(OMD); 3071 EmitObjCIvarInitializations(OMD); 3072 ObjCRuntime->GenerateClass(OMD); 3073 // Emit global variable debug information. 3074 if (CGDebugInfo *DI = getModuleDebugInfo()) 3075 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) 3076 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType( 3077 OMD->getClassInterface()), OMD->getLocation()); 3078 break; 3079 } 3080 case Decl::ObjCMethod: { 3081 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D); 3082 // If this is not a prototype, emit the body. 3083 if (OMD->getBody()) 3084 CodeGenFunction(*this).GenerateObjCMethod(OMD); 3085 break; 3086 } 3087 case Decl::ObjCCompatibleAlias: 3088 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D)); 3089 break; 3090 3091 case Decl::LinkageSpec: 3092 EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 3093 break; 3094 3095 case Decl::FileScopeAsm: { 3096 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D); 3097 StringRef AsmString = AD->getAsmString()->getString(); 3098 3099 const std::string &S = getModule().getModuleInlineAsm(); 3100 if (S.empty()) 3101 getModule().setModuleInlineAsm(AsmString); 3102 else if (S.end()[-1] == '\n') 3103 getModule().setModuleInlineAsm(S + AsmString.str()); 3104 else 3105 getModule().setModuleInlineAsm(S + '\n' + AsmString.str()); 3106 break; 3107 } 3108 3109 case Decl::Import: { 3110 ImportDecl *Import = cast<ImportDecl>(D); 3111 3112 // Ignore import declarations that come from imported modules. 3113 if (clang::Module *Owner = Import->getOwningModule()) { 3114 if (getLangOpts().CurrentModule.empty() || 3115 Owner->getTopLevelModule()->Name == getLangOpts().CurrentModule) 3116 break; 3117 } 3118 3119 ImportedModules.insert(Import->getImportedModule()); 3120 break; 3121 } 3122 3123 case Decl::ClassTemplateSpecialization: { 3124 const ClassTemplateSpecializationDecl *Spec = 3125 cast<ClassTemplateSpecializationDecl>(D); 3126 if (DebugInfo && 3127 Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition) 3128 DebugInfo->completeTemplateDefinition(*Spec); 3129 } 3130 3131 default: 3132 // Make sure we handled everything we should, every other kind is a 3133 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 3134 // function. Need to recode Decl::Kind to do that easily. 3135 assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 3136 } 3137 } 3138 3139 /// Turns the given pointer into a constant. 3140 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 3141 const void *Ptr) { 3142 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 3143 llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 3144 return llvm::ConstantInt::get(i64, PtrInt); 3145 } 3146 3147 static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 3148 llvm::NamedMDNode *&GlobalMetadata, 3149 GlobalDecl D, 3150 llvm::GlobalValue *Addr) { 3151 if (!GlobalMetadata) 3152 GlobalMetadata = 3153 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 3154 3155 // TODO: should we report variant information for ctors/dtors? 3156 llvm::Value *Ops[] = { 3157 Addr, 3158 GetPointerConstant(CGM.getLLVMContext(), D.getDecl()) 3159 }; 3160 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 3161 } 3162 3163 /// For each function which is declared within an extern "C" region and marked 3164 /// as 'used', but has internal linkage, create an alias from the unmangled 3165 /// name to the mangled name if possible. People expect to be able to refer 3166 /// to such functions with an unmangled name from inline assembly within the 3167 /// same translation unit. 3168 void CodeGenModule::EmitStaticExternCAliases() { 3169 for (StaticExternCMap::iterator I = StaticExternCValues.begin(), 3170 E = StaticExternCValues.end(); 3171 I != E; ++I) { 3172 IdentifierInfo *Name = I->first; 3173 llvm::GlobalValue *Val = I->second; 3174 if (Val && !getModule().getNamedValue(Name->getName())) 3175 addUsedGlobal(new llvm::GlobalAlias(Val->getType(), Val->getLinkage(), 3176 Name->getName(), Val, &getModule())); 3177 } 3178 } 3179 3180 /// Emits metadata nodes associating all the global values in the 3181 /// current module with the Decls they came from. This is useful for 3182 /// projects using IR gen as a subroutine. 3183 /// 3184 /// Since there's currently no way to associate an MDNode directly 3185 /// with an llvm::GlobalValue, we create a global named metadata 3186 /// with the name 'clang.global.decl.ptrs'. 3187 void CodeGenModule::EmitDeclMetadata() { 3188 llvm::NamedMDNode *GlobalMetadata = 0; 3189 3190 // StaticLocalDeclMap 3191 for (llvm::DenseMap<GlobalDecl,StringRef>::iterator 3192 I = MangledDeclNames.begin(), E = MangledDeclNames.end(); 3193 I != E; ++I) { 3194 llvm::GlobalValue *Addr = getModule().getNamedValue(I->second); 3195 EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr); 3196 } 3197 } 3198 3199 /// Emits metadata nodes for all the local variables in the current 3200 /// function. 3201 void CodeGenFunction::EmitDeclMetadata() { 3202 if (LocalDeclMap.empty()) return; 3203 3204 llvm::LLVMContext &Context = getLLVMContext(); 3205 3206 // Find the unique metadata ID for this name. 3207 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 3208 3209 llvm::NamedMDNode *GlobalMetadata = 0; 3210 3211 for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator 3212 I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) { 3213 const Decl *D = I->first; 3214 llvm::Value *Addr = I->second; 3215 3216 if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 3217 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 3218 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr)); 3219 } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 3220 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 3221 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 3222 } 3223 } 3224 } 3225 3226 void CodeGenModule::EmitVersionIdentMetadata() { 3227 llvm::NamedMDNode *IdentMetadata = 3228 TheModule.getOrInsertNamedMetadata("llvm.ident"); 3229 std::string Version = getClangFullVersion(); 3230 llvm::LLVMContext &Ctx = TheModule.getContext(); 3231 3232 llvm::Value *IdentNode[] = { 3233 llvm::MDString::get(Ctx, Version) 3234 }; 3235 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode)); 3236 } 3237 3238 void CodeGenModule::EmitCoverageFile() { 3239 if (!getCodeGenOpts().CoverageFile.empty()) { 3240 if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) { 3241 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); 3242 llvm::LLVMContext &Ctx = TheModule.getContext(); 3243 llvm::MDString *CoverageFile = 3244 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile); 3245 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { 3246 llvm::MDNode *CU = CUNode->getOperand(i); 3247 llvm::Value *node[] = { CoverageFile, CU }; 3248 llvm::MDNode *N = llvm::MDNode::get(Ctx, node); 3249 GCov->addOperand(N); 3250 } 3251 } 3252 } 3253 } 3254 3255 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid, 3256 QualType GuidType) { 3257 // Sema has checked that all uuid strings are of the form 3258 // "12345678-1234-1234-1234-1234567890ab". 3259 assert(Uuid.size() == 36); 3260 for (unsigned i = 0; i < 36; ++i) { 3261 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-'); 3262 else assert(isHexDigit(Uuid[i])); 3263 } 3264 3265 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 }; 3266 3267 llvm::Constant *Field3[8]; 3268 for (unsigned Idx = 0; Idx < 8; ++Idx) 3269 Field3[Idx] = llvm::ConstantInt::get( 3270 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16); 3271 3272 llvm::Constant *Fields[4] = { 3273 llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16), 3274 llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16), 3275 llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16), 3276 llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3) 3277 }; 3278 3279 return llvm::ConstantStruct::getAnon(Fields); 3280 } 3281