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