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