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