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