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