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