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