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