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