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 "CGDebugInfo.h" 16 #include "CodeGenFunction.h" 17 #include "CodeGenTBAA.h" 18 #include "CGCall.h" 19 #include "CGCXXABI.h" 20 #include "CGObjCRuntime.h" 21 #include "CGOpenCLRuntime.h" 22 #include "TargetInfo.h" 23 #include "clang/Frontend/CodeGenOptions.h" 24 #include "clang/AST/ASTContext.h" 25 #include "clang/AST/CharUnits.h" 26 #include "clang/AST/DeclObjC.h" 27 #include "clang/AST/DeclCXX.h" 28 #include "clang/AST/DeclTemplate.h" 29 #include "clang/AST/Mangle.h" 30 #include "clang/AST/RecordLayout.h" 31 #include "clang/Basic/Diagnostic.h" 32 #include "clang/Basic/SourceManager.h" 33 #include "clang/Basic/TargetInfo.h" 34 #include "clang/Basic/ConvertUTF.h" 35 #include "llvm/CallingConv.h" 36 #include "llvm/Module.h" 37 #include "llvm/Intrinsics.h" 38 #include "llvm/LLVMContext.h" 39 #include "llvm/ADT/Triple.h" 40 #include "llvm/Target/Mangler.h" 41 #include "llvm/Target/TargetData.h" 42 #include "llvm/Support/CallSite.h" 43 #include "llvm/Support/ErrorHandling.h" 44 using namespace clang; 45 using namespace CodeGen; 46 47 static const char AnnotationSection[] = "llvm.metadata"; 48 49 static CGCXXABI &createCXXABI(CodeGenModule &CGM) { 50 switch (CGM.getContext().getTargetInfo().getCXXABI()) { 51 case CXXABI_ARM: return *CreateARMCXXABI(CGM); 52 case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM); 53 case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM); 54 } 55 56 llvm_unreachable("invalid C++ ABI kind"); 57 return *CreateItaniumCXXABI(CGM); 58 } 59 60 61 CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO, 62 llvm::Module &M, const llvm::TargetData &TD, 63 Diagnostic &diags) 64 : Context(C), Features(C.getLangOptions()), CodeGenOpts(CGO), TheModule(M), 65 TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags), 66 ABI(createCXXABI(*this)), 67 Types(C, M, TD, getTargetCodeGenInfo().getABIInfo(), ABI, CGO), 68 TBAA(0), 69 VTables(*this), ObjCRuntime(0), OpenCLRuntime(0), DebugInfo(0), ARCData(0), 70 RRData(0), CFConstantStringClassRef(0), ConstantStringClassRef(0), 71 NSConstantStringType(0), 72 VMContext(M.getContext()), 73 NSConcreteGlobalBlock(0), NSConcreteStackBlock(0), 74 BlockObjectAssign(0), BlockObjectDispose(0), 75 BlockDescriptorType(0), GenericBlockLiteralType(0) { 76 if (Features.ObjC1) 77 createObjCRuntime(); 78 if (Features.OpenCL) 79 createOpenCLRuntime(); 80 81 // Enable TBAA unless it's suppressed. 82 if (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0) 83 TBAA = new CodeGenTBAA(Context, VMContext, getLangOptions(), 84 ABI.getMangleContext()); 85 86 // If debug info or coverage generation is enabled, create the CGDebugInfo 87 // object. 88 if (CodeGenOpts.DebugInfo || CodeGenOpts.EmitGcovArcs || 89 CodeGenOpts.EmitGcovNotes) 90 DebugInfo = new CGDebugInfo(*this); 91 92 Block.GlobalUniqueCount = 0; 93 94 if (C.getLangOptions().ObjCAutoRefCount) 95 ARCData = new ARCEntrypoints(); 96 RRData = new RREntrypoints(); 97 98 // Initialize the type cache. 99 llvm::LLVMContext &LLVMContext = M.getContext(); 100 VoidTy = llvm::Type::getVoidTy(LLVMContext); 101 Int8Ty = llvm::Type::getInt8Ty(LLVMContext); 102 Int32Ty = llvm::Type::getInt32Ty(LLVMContext); 103 Int64Ty = llvm::Type::getInt64Ty(LLVMContext); 104 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0); 105 PointerAlignInBytes = 106 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity(); 107 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth()); 108 IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits); 109 Int8PtrTy = Int8Ty->getPointerTo(0); 110 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0); 111 } 112 113 CodeGenModule::~CodeGenModule() { 114 delete ObjCRuntime; 115 delete OpenCLRuntime; 116 delete &ABI; 117 delete TBAA; 118 delete DebugInfo; 119 delete ARCData; 120 delete RRData; 121 } 122 123 void CodeGenModule::createObjCRuntime() { 124 if (!Features.NeXTRuntime) 125 ObjCRuntime = CreateGNUObjCRuntime(*this); 126 else 127 ObjCRuntime = CreateMacObjCRuntime(*this); 128 } 129 130 void CodeGenModule::createOpenCLRuntime() { 131 OpenCLRuntime = new CGOpenCLRuntime(*this); 132 } 133 134 void CodeGenModule::Release() { 135 EmitDeferred(); 136 EmitCXXGlobalInitFunc(); 137 EmitCXXGlobalDtorFunc(); 138 if (ObjCRuntime) 139 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction()) 140 AddGlobalCtor(ObjCInitFunction); 141 EmitCtorList(GlobalCtors, "llvm.global_ctors"); 142 EmitCtorList(GlobalDtors, "llvm.global_dtors"); 143 EmitGlobalAnnotations(); 144 EmitLLVMUsed(); 145 146 SimplifyPersonality(); 147 148 if (getCodeGenOpts().EmitDeclMetadata) 149 EmitDeclMetadata(); 150 151 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes) 152 EmitCoverageFile(); 153 154 if (DebugInfo) 155 DebugInfo->finalize(); 156 } 157 158 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 159 // Make sure that this type is translated. 160 Types.UpdateCompletedType(TD); 161 if (DebugInfo) 162 DebugInfo->UpdateCompletedType(TD); 163 } 164 165 llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) { 166 if (!TBAA) 167 return 0; 168 return TBAA->getTBAAInfo(QTy); 169 } 170 171 void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst, 172 llvm::MDNode *TBAAInfo) { 173 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo); 174 } 175 176 bool CodeGenModule::isTargetDarwin() const { 177 return getContext().getTargetInfo().getTriple().isOSDarwin(); 178 } 179 180 void CodeGenModule::Error(SourceLocation loc, StringRef error) { 181 unsigned diagID = getDiags().getCustomDiagID(Diagnostic::Error, error); 182 getDiags().Report(Context.getFullLoc(loc), diagID); 183 } 184 185 /// ErrorUnsupported - Print out an error that codegen doesn't support the 186 /// specified stmt yet. 187 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type, 188 bool OmitOnError) { 189 if (OmitOnError && getDiags().hasErrorOccurred()) 190 return; 191 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error, 192 "cannot compile this %0 yet"); 193 std::string Msg = Type; 194 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID) 195 << Msg << S->getSourceRange(); 196 } 197 198 /// ErrorUnsupported - Print out an error that codegen doesn't support the 199 /// specified decl yet. 200 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type, 201 bool OmitOnError) { 202 if (OmitOnError && getDiags().hasErrorOccurred()) 203 return; 204 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error, 205 "cannot compile this %0 yet"); 206 std::string Msg = Type; 207 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 208 } 209 210 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) { 211 return llvm::ConstantInt::get(SizeTy, size.getQuantity()); 212 } 213 214 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 215 const NamedDecl *D) const { 216 // Internal definitions always have default visibility. 217 if (GV->hasLocalLinkage()) { 218 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 219 return; 220 } 221 222 // Set visibility for definitions. 223 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility(); 224 if (LV.visibilityExplicit() || !GV->hasAvailableExternallyLinkage()) 225 GV->setVisibility(GetLLVMVisibility(LV.visibility())); 226 } 227 228 /// Set the symbol visibility of type information (vtable and RTTI) 229 /// associated with the given type. 230 void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV, 231 const CXXRecordDecl *RD, 232 TypeVisibilityKind TVK) const { 233 setGlobalVisibility(GV, RD); 234 235 if (!CodeGenOpts.HiddenWeakVTables) 236 return; 237 238 // We never want to drop the visibility for RTTI names. 239 if (TVK == TVK_ForRTTIName) 240 return; 241 242 // We want to drop the visibility to hidden for weak type symbols. 243 // This isn't possible if there might be unresolved references 244 // elsewhere that rely on this symbol being visible. 245 246 // This should be kept roughly in sync with setThunkVisibility 247 // in CGVTables.cpp. 248 249 // Preconditions. 250 if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage || 251 GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility) 252 return; 253 254 // Don't override an explicit visibility attribute. 255 if (RD->getExplicitVisibility()) 256 return; 257 258 switch (RD->getTemplateSpecializationKind()) { 259 // We have to disable the optimization if this is an EI definition 260 // because there might be EI declarations in other shared objects. 261 case TSK_ExplicitInstantiationDefinition: 262 case TSK_ExplicitInstantiationDeclaration: 263 return; 264 265 // Every use of a non-template class's type information has to emit it. 266 case TSK_Undeclared: 267 break; 268 269 // In theory, implicit instantiations can ignore the possibility of 270 // an explicit instantiation declaration because there necessarily 271 // must be an EI definition somewhere with default visibility. In 272 // practice, it's possible to have an explicit instantiation for 273 // an arbitrary template class, and linkers aren't necessarily able 274 // to deal with mixed-visibility symbols. 275 case TSK_ExplicitSpecialization: 276 case TSK_ImplicitInstantiation: 277 if (!CodeGenOpts.HiddenWeakTemplateVTables) 278 return; 279 break; 280 } 281 282 // If there's a key function, there may be translation units 283 // that don't have the key function's definition. But ignore 284 // this if we're emitting RTTI under -fno-rtti. 285 if (!(TVK != TVK_ForRTTI) || Features.RTTI) { 286 if (Context.getKeyFunction(RD)) 287 return; 288 } 289 290 // Otherwise, drop the visibility to hidden. 291 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 292 GV->setUnnamedAddr(true); 293 } 294 295 StringRef CodeGenModule::getMangledName(GlobalDecl GD) { 296 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl()); 297 298 StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()]; 299 if (!Str.empty()) 300 return Str; 301 302 if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) { 303 IdentifierInfo *II = ND->getIdentifier(); 304 assert(II && "Attempt to mangle unnamed decl."); 305 306 Str = II->getName(); 307 return Str; 308 } 309 310 llvm::SmallString<256> Buffer; 311 llvm::raw_svector_ostream Out(Buffer); 312 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND)) 313 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out); 314 else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND)) 315 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out); 316 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND)) 317 getCXXABI().getMangleContext().mangleBlock(BD, Out); 318 else 319 getCXXABI().getMangleContext().mangleName(ND, Out); 320 321 // Allocate space for the mangled name. 322 Out.flush(); 323 size_t Length = Buffer.size(); 324 char *Name = MangledNamesAllocator.Allocate<char>(Length); 325 std::copy(Buffer.begin(), Buffer.end(), Name); 326 327 Str = StringRef(Name, Length); 328 329 return Str; 330 } 331 332 void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer, 333 const BlockDecl *BD) { 334 MangleContext &MangleCtx = getCXXABI().getMangleContext(); 335 const Decl *D = GD.getDecl(); 336 llvm::raw_svector_ostream Out(Buffer.getBuffer()); 337 if (D == 0) 338 MangleCtx.mangleGlobalBlock(BD, Out); 339 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 340 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out); 341 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D)) 342 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out); 343 else 344 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out); 345 } 346 347 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) { 348 return getModule().getNamedValue(Name); 349 } 350 351 /// AddGlobalCtor - Add a function to the list that will be called before 352 /// main() runs. 353 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) { 354 // FIXME: Type coercion of void()* types. 355 GlobalCtors.push_back(std::make_pair(Ctor, Priority)); 356 } 357 358 /// AddGlobalDtor - Add a function to the list that will be called 359 /// when the module is unloaded. 360 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) { 361 // FIXME: Type coercion of void()* types. 362 GlobalDtors.push_back(std::make_pair(Dtor, Priority)); 363 } 364 365 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) { 366 // Ctor function type is void()*. 367 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false); 368 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy); 369 370 // Get the type of a ctor entry, { i32, void ()* }. 371 llvm::StructType *CtorStructTy = 372 llvm::StructType::get(llvm::Type::getInt32Ty(VMContext), 373 llvm::PointerType::getUnqual(CtorFTy), NULL); 374 375 // Construct the constructor and destructor arrays. 376 std::vector<llvm::Constant*> Ctors; 377 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 378 std::vector<llvm::Constant*> S; 379 S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 380 I->second, false)); 381 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)); 382 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S)); 383 } 384 385 if (!Ctors.empty()) { 386 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size()); 387 new llvm::GlobalVariable(TheModule, AT, false, 388 llvm::GlobalValue::AppendingLinkage, 389 llvm::ConstantArray::get(AT, Ctors), 390 GlobalName); 391 } 392 } 393 394 llvm::GlobalValue::LinkageTypes 395 CodeGenModule::getFunctionLinkage(const FunctionDecl *D) { 396 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D); 397 398 if (Linkage == GVA_Internal) 399 return llvm::Function::InternalLinkage; 400 401 if (D->hasAttr<DLLExportAttr>()) 402 return llvm::Function::DLLExportLinkage; 403 404 if (D->hasAttr<WeakAttr>()) 405 return llvm::Function::WeakAnyLinkage; 406 407 // In C99 mode, 'inline' functions are guaranteed to have a strong 408 // definition somewhere else, so we can use available_externally linkage. 409 if (Linkage == GVA_C99Inline) 410 return llvm::Function::AvailableExternallyLinkage; 411 412 // Note that Apple's kernel linker doesn't support symbol 413 // coalescing, so we need to avoid linkonce and weak linkages there. 414 // Normally, this means we just map to internal, but for explicit 415 // instantiations we'll map to external. 416 417 // In C++, the compiler has to emit a definition in every translation unit 418 // that references the function. We should use linkonce_odr because 419 // a) if all references in this translation unit are optimized away, we 420 // don't need to codegen it. b) if the function persists, it needs to be 421 // merged with other definitions. c) C++ has the ODR, so we know the 422 // definition is dependable. 423 if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation) 424 return !Context.getLangOptions().AppleKext 425 ? llvm::Function::LinkOnceODRLinkage 426 : llvm::Function::InternalLinkage; 427 428 // An explicit instantiation of a template has weak linkage, since 429 // explicit instantiations can occur in multiple translation units 430 // and must all be equivalent. However, we are not allowed to 431 // throw away these explicit instantiations. 432 if (Linkage == GVA_ExplicitTemplateInstantiation) 433 return !Context.getLangOptions().AppleKext 434 ? llvm::Function::WeakODRLinkage 435 : llvm::Function::ExternalLinkage; 436 437 // Otherwise, we have strong external linkage. 438 assert(Linkage == GVA_StrongExternal); 439 return llvm::Function::ExternalLinkage; 440 } 441 442 443 /// SetFunctionDefinitionAttributes - Set attributes for a global. 444 /// 445 /// FIXME: This is currently only done for aliases and functions, but not for 446 /// variables (these details are set in EmitGlobalVarDefinition for variables). 447 void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D, 448 llvm::GlobalValue *GV) { 449 SetCommonAttributes(D, GV); 450 } 451 452 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D, 453 const CGFunctionInfo &Info, 454 llvm::Function *F) { 455 unsigned CallingConv; 456 AttributeListType AttributeList; 457 ConstructAttributeList(Info, D, AttributeList, CallingConv); 458 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(), 459 AttributeList.size())); 460 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 461 } 462 463 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 464 llvm::Function *F) { 465 if (CodeGenOpts.UnwindTables) 466 F->setHasUWTable(); 467 468 if (!Features.Exceptions && !Features.ObjCNonFragileABI) 469 F->addFnAttr(llvm::Attribute::NoUnwind); 470 471 if (D->hasAttr<NakedAttr>()) { 472 // Naked implies noinline: we should not be inlining such functions. 473 F->addFnAttr(llvm::Attribute::Naked); 474 F->addFnAttr(llvm::Attribute::NoInline); 475 } 476 477 if (D->hasAttr<NoInlineAttr>()) 478 F->addFnAttr(llvm::Attribute::NoInline); 479 480 // (noinline wins over always_inline, and we can't specify both in IR) 481 if (D->hasAttr<AlwaysInlineAttr>() && 482 !F->hasFnAttr(llvm::Attribute::NoInline)) 483 F->addFnAttr(llvm::Attribute::AlwaysInline); 484 485 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D)) 486 F->setUnnamedAddr(true); 487 488 if (Features.getStackProtector() == LangOptions::SSPOn) 489 F->addFnAttr(llvm::Attribute::StackProtect); 490 else if (Features.getStackProtector() == LangOptions::SSPReq) 491 F->addFnAttr(llvm::Attribute::StackProtectReq); 492 493 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth(); 494 if (alignment) 495 F->setAlignment(alignment); 496 497 // C++ ABI requires 2-byte alignment for member functions. 498 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) 499 F->setAlignment(2); 500 } 501 502 void CodeGenModule::SetCommonAttributes(const Decl *D, 503 llvm::GlobalValue *GV) { 504 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) 505 setGlobalVisibility(GV, ND); 506 else 507 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 508 509 if (D->hasAttr<UsedAttr>()) 510 AddUsedGlobal(GV); 511 512 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 513 GV->setSection(SA->getName()); 514 515 getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this); 516 } 517 518 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D, 519 llvm::Function *F, 520 const CGFunctionInfo &FI) { 521 SetLLVMFunctionAttributes(D, FI, F); 522 SetLLVMFunctionAttributesForDefinition(D, F); 523 524 F->setLinkage(llvm::Function::InternalLinkage); 525 526 SetCommonAttributes(D, F); 527 } 528 529 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, 530 llvm::Function *F, 531 bool IsIncompleteFunction) { 532 if (unsigned IID = F->getIntrinsicID()) { 533 // If this is an intrinsic function, set the function's attributes 534 // to the intrinsic's attributes. 535 F->setAttributes(llvm::Intrinsic::getAttributes((llvm::Intrinsic::ID)IID)); 536 return; 537 } 538 539 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 540 541 if (!IsIncompleteFunction) 542 SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(GD), F); 543 544 // Only a few attributes are set on declarations; these may later be 545 // overridden by a definition. 546 547 if (FD->hasAttr<DLLImportAttr>()) { 548 F->setLinkage(llvm::Function::DLLImportLinkage); 549 } else if (FD->hasAttr<WeakAttr>() || 550 FD->isWeakImported()) { 551 // "extern_weak" is overloaded in LLVM; we probably should have 552 // separate linkage types for this. 553 F->setLinkage(llvm::Function::ExternalWeakLinkage); 554 } else { 555 F->setLinkage(llvm::Function::ExternalLinkage); 556 557 NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility(); 558 if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) { 559 F->setVisibility(GetLLVMVisibility(LV.visibility())); 560 } 561 } 562 563 if (const SectionAttr *SA = FD->getAttr<SectionAttr>()) 564 F->setSection(SA->getName()); 565 } 566 567 void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) { 568 assert(!GV->isDeclaration() && 569 "Only globals with definition can force usage."); 570 LLVMUsed.push_back(GV); 571 } 572 573 void CodeGenModule::EmitLLVMUsed() { 574 // Don't create llvm.used if there is no need. 575 if (LLVMUsed.empty()) 576 return; 577 578 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext); 579 580 // Convert LLVMUsed to what ConstantArray needs. 581 std::vector<llvm::Constant*> UsedArray; 582 UsedArray.resize(LLVMUsed.size()); 583 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) { 584 UsedArray[i] = 585 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]), 586 i8PTy); 587 } 588 589 if (UsedArray.empty()) 590 return; 591 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size()); 592 593 llvm::GlobalVariable *GV = 594 new llvm::GlobalVariable(getModule(), ATy, false, 595 llvm::GlobalValue::AppendingLinkage, 596 llvm::ConstantArray::get(ATy, UsedArray), 597 "llvm.used"); 598 599 GV->setSection("llvm.metadata"); 600 } 601 602 void CodeGenModule::EmitDeferred() { 603 // Emit code for any potentially referenced deferred decls. Since a 604 // previously unused static decl may become used during the generation of code 605 // for a static function, iterate until no changes are made. 606 607 while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) { 608 if (!DeferredVTables.empty()) { 609 const CXXRecordDecl *RD = DeferredVTables.back(); 610 DeferredVTables.pop_back(); 611 getVTables().GenerateClassData(getVTableLinkage(RD), RD); 612 continue; 613 } 614 615 GlobalDecl D = DeferredDeclsToEmit.back(); 616 DeferredDeclsToEmit.pop_back(); 617 618 // Check to see if we've already emitted this. This is necessary 619 // for a couple of reasons: first, decls can end up in the 620 // deferred-decls queue multiple times, and second, decls can end 621 // up with definitions in unusual ways (e.g. by an extern inline 622 // function acquiring a strong function redefinition). Just 623 // ignore these cases. 624 // 625 // TODO: That said, looking this up multiple times is very wasteful. 626 StringRef Name = getMangledName(D); 627 llvm::GlobalValue *CGRef = GetGlobalValue(Name); 628 assert(CGRef && "Deferred decl wasn't referenced?"); 629 630 if (!CGRef->isDeclaration()) 631 continue; 632 633 // GlobalAlias::isDeclaration() defers to the aliasee, but for our 634 // purposes an alias counts as a definition. 635 if (isa<llvm::GlobalAlias>(CGRef)) 636 continue; 637 638 // Otherwise, emit the definition and move on to the next one. 639 EmitGlobalDefinition(D); 640 } 641 } 642 643 void CodeGenModule::EmitGlobalAnnotations() { 644 if (Annotations.empty()) 645 return; 646 647 // Create a new global variable for the ConstantStruct in the Module. 648 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( 649 Annotations[0]->getType(), Annotations.size()), Annotations); 650 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), 651 Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array, 652 "llvm.global.annotations"); 653 gv->setSection(AnnotationSection); 654 } 655 656 llvm::Constant *CodeGenModule::EmitAnnotationString(llvm::StringRef Str) { 657 llvm::StringMap<llvm::Constant*>::iterator i = AnnotationStrings.find(Str); 658 if (i != AnnotationStrings.end()) 659 return i->second; 660 661 // Not found yet, create a new global. 662 llvm::Constant *s = llvm::ConstantArray::get(getLLVMContext(), Str, true); 663 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(), 664 true, llvm::GlobalValue::PrivateLinkage, s, ".str"); 665 gv->setSection(AnnotationSection); 666 gv->setUnnamedAddr(true); 667 AnnotationStrings[Str] = gv; 668 return gv; 669 } 670 671 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { 672 SourceManager &SM = getContext().getSourceManager(); 673 PresumedLoc PLoc = SM.getPresumedLoc(Loc); 674 if (PLoc.isValid()) 675 return EmitAnnotationString(PLoc.getFilename()); 676 return EmitAnnotationString(SM.getBufferName(Loc)); 677 } 678 679 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { 680 SourceManager &SM = getContext().getSourceManager(); 681 PresumedLoc PLoc = SM.getPresumedLoc(L); 682 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : 683 SM.getExpansionLineNumber(L); 684 return llvm::ConstantInt::get(Int32Ty, LineNo); 685 } 686 687 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 688 const AnnotateAttr *AA, 689 SourceLocation L) { 690 // Get the globals for file name, annotation, and the line number. 691 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), 692 *UnitGV = EmitAnnotationUnit(L), 693 *LineNoCst = EmitAnnotationLineNo(L); 694 695 // Create the ConstantStruct for the global annotation. 696 llvm::Constant *Fields[4] = { 697 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy), 698 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy), 699 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy), 700 LineNoCst 701 }; 702 return llvm::ConstantStruct::getAnon(Fields); 703 } 704 705 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, 706 llvm::GlobalValue *GV) { 707 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 708 // Get the struct elements for these annotations. 709 for (specific_attr_iterator<AnnotateAttr> 710 ai = D->specific_attr_begin<AnnotateAttr>(), 711 ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai) 712 Annotations.push_back(EmitAnnotateAttr(GV, *ai, D->getLocation())); 713 } 714 715 bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) { 716 // Never defer when EmitAllDecls is specified. 717 if (Features.EmitAllDecls) 718 return false; 719 720 return !getContext().DeclMustBeEmitted(Global); 721 } 722 723 llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 724 const AliasAttr *AA = VD->getAttr<AliasAttr>(); 725 assert(AA && "No alias?"); 726 727 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 728 729 // See if there is already something with the target's name in the module. 730 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 731 732 llvm::Constant *Aliasee; 733 if (isa<llvm::FunctionType>(DeclTy)) 734 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(), 735 /*ForVTable=*/false); 736 else 737 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 738 llvm::PointerType::getUnqual(DeclTy), 0); 739 if (!Entry) { 740 llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee); 741 F->setLinkage(llvm::Function::ExternalWeakLinkage); 742 WeakRefReferences.insert(F); 743 } 744 745 return Aliasee; 746 } 747 748 void CodeGenModule::EmitGlobal(GlobalDecl GD) { 749 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl()); 750 751 // Weak references don't produce any output by themselves. 752 if (Global->hasAttr<WeakRefAttr>()) 753 return; 754 755 // If this is an alias definition (which otherwise looks like a declaration) 756 // emit it now. 757 if (Global->hasAttr<AliasAttr>()) 758 return EmitAliasDefinition(GD); 759 760 // Ignore declarations, they will be emitted on their first use. 761 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) { 762 // Forward declarations are emitted lazily on first use. 763 if (!FD->doesThisDeclarationHaveABody()) { 764 if (!FD->doesDeclarationForceExternallyVisibleDefinition()) 765 return; 766 767 const FunctionDecl *InlineDefinition = 0; 768 FD->getBody(InlineDefinition); 769 770 StringRef MangledName = getMangledName(GD); 771 llvm::StringMap<GlobalDecl>::iterator DDI = 772 DeferredDecls.find(MangledName); 773 if (DDI != DeferredDecls.end()) 774 DeferredDecls.erase(DDI); 775 EmitGlobalDefinition(InlineDefinition); 776 return; 777 } 778 } else { 779 const VarDecl *VD = cast<VarDecl>(Global); 780 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 781 782 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) 783 return; 784 } 785 786 // Defer code generation when possible if this is a static definition, inline 787 // function etc. These we only want to emit if they are used. 788 if (!MayDeferGeneration(Global)) { 789 // Emit the definition if it can't be deferred. 790 EmitGlobalDefinition(GD); 791 return; 792 } 793 794 // If we're deferring emission of a C++ variable with an 795 // initializer, remember the order in which it appeared in the file. 796 if (getLangOptions().CPlusPlus && isa<VarDecl>(Global) && 797 cast<VarDecl>(Global)->hasInit()) { 798 DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 799 CXXGlobalInits.push_back(0); 800 } 801 802 // If the value has already been used, add it directly to the 803 // DeferredDeclsToEmit list. 804 StringRef MangledName = getMangledName(GD); 805 if (GetGlobalValue(MangledName)) 806 DeferredDeclsToEmit.push_back(GD); 807 else { 808 // Otherwise, remember that we saw a deferred decl with this name. The 809 // first use of the mangled name will cause it to move into 810 // DeferredDeclsToEmit. 811 DeferredDecls[MangledName] = GD; 812 } 813 } 814 815 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) { 816 const ValueDecl *D = cast<ValueDecl>(GD.getDecl()); 817 818 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 819 Context.getSourceManager(), 820 "Generating code for declaration"); 821 822 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 823 // At -O0, don't generate IR for functions with available_externally 824 // linkage. 825 if (CodeGenOpts.OptimizationLevel == 0 && 826 !Function->hasAttr<AlwaysInlineAttr>() && 827 getFunctionLinkage(Function) 828 == llvm::Function::AvailableExternallyLinkage) 829 return; 830 831 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 832 // Make sure to emit the definition(s) before we emit the thunks. 833 // This is necessary for the generation of certain thunks. 834 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method)) 835 EmitCXXConstructor(CD, GD.getCtorType()); 836 else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method)) 837 EmitCXXDestructor(DD, GD.getDtorType()); 838 else 839 EmitGlobalFunctionDefinition(GD); 840 841 if (Method->isVirtual()) 842 getVTables().EmitThunks(GD); 843 844 return; 845 } 846 847 return EmitGlobalFunctionDefinition(GD); 848 } 849 850 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 851 return EmitGlobalVarDefinition(VD); 852 853 llvm_unreachable("Invalid argument to EmitGlobalDefinition()"); 854 } 855 856 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 857 /// module, create and return an llvm Function with the specified type. If there 858 /// is something in the module with the specified name, return it potentially 859 /// bitcasted to the right type. 860 /// 861 /// If D is non-null, it specifies a decl that correspond to this. This is used 862 /// to set the attributes on the function when it is first created. 863 llvm::Constant * 864 CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName, 865 llvm::Type *Ty, 866 GlobalDecl D, bool ForVTable, 867 llvm::Attributes ExtraAttrs) { 868 // Lookup the entry, lazily creating it if necessary. 869 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 870 if (Entry) { 871 if (WeakRefReferences.count(Entry)) { 872 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl()); 873 if (FD && !FD->hasAttr<WeakAttr>()) 874 Entry->setLinkage(llvm::Function::ExternalLinkage); 875 876 WeakRefReferences.erase(Entry); 877 } 878 879 if (Entry->getType()->getElementType() == Ty) 880 return Entry; 881 882 // Make sure the result is of the correct type. 883 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo()); 884 } 885 886 // This function doesn't have a complete type (for example, the return 887 // type is an incomplete struct). Use a fake type instead, and make 888 // sure not to try to set attributes. 889 bool IsIncompleteFunction = false; 890 891 llvm::FunctionType *FTy; 892 if (isa<llvm::FunctionType>(Ty)) { 893 FTy = cast<llvm::FunctionType>(Ty); 894 } else { 895 FTy = llvm::FunctionType::get(VoidTy, false); 896 IsIncompleteFunction = true; 897 } 898 899 llvm::Function *F = llvm::Function::Create(FTy, 900 llvm::Function::ExternalLinkage, 901 MangledName, &getModule()); 902 assert(F->getName() == MangledName && "name was uniqued!"); 903 if (D.getDecl()) 904 SetFunctionAttributes(D, F, IsIncompleteFunction); 905 if (ExtraAttrs != llvm::Attribute::None) 906 F->addFnAttr(ExtraAttrs); 907 908 // This is the first use or definition of a mangled name. If there is a 909 // deferred decl with this name, remember that we need to emit it at the end 910 // of the file. 911 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName); 912 if (DDI != DeferredDecls.end()) { 913 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 914 // list, and remove it from DeferredDecls (since we don't need it anymore). 915 DeferredDeclsToEmit.push_back(DDI->second); 916 DeferredDecls.erase(DDI); 917 918 // Otherwise, there are cases we have to worry about where we're 919 // using a declaration for which we must emit a definition but where 920 // we might not find a top-level definition: 921 // - member functions defined inline in their classes 922 // - friend functions defined inline in some class 923 // - special member functions with implicit definitions 924 // If we ever change our AST traversal to walk into class methods, 925 // this will be unnecessary. 926 // 927 // We also don't emit a definition for a function if it's going to be an entry 928 // in a vtable, unless it's already marked as used. 929 } else if (getLangOptions().CPlusPlus && D.getDecl()) { 930 // Look for a declaration that's lexically in a record. 931 const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl()); 932 do { 933 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 934 if (FD->isImplicit() && !ForVTable) { 935 assert(FD->isUsed() && "Sema didn't mark implicit function as used!"); 936 DeferredDeclsToEmit.push_back(D.getWithDecl(FD)); 937 break; 938 } else if (FD->doesThisDeclarationHaveABody()) { 939 DeferredDeclsToEmit.push_back(D.getWithDecl(FD)); 940 break; 941 } 942 } 943 FD = FD->getPreviousDeclaration(); 944 } while (FD); 945 } 946 947 // Make sure the result is of the requested type. 948 if (!IsIncompleteFunction) { 949 assert(F->getType()->getElementType() == Ty); 950 return F; 951 } 952 953 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 954 return llvm::ConstantExpr::getBitCast(F, PTy); 955 } 956 957 /// GetAddrOfFunction - Return the address of the given function. If Ty is 958 /// non-null, then this function will use the specified type if it has to 959 /// create it (this occurs when we see a definition of the function). 960 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 961 llvm::Type *Ty, 962 bool ForVTable) { 963 // If there was no specific requested type, just convert it now. 964 if (!Ty) 965 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType()); 966 967 StringRef MangledName = getMangledName(GD); 968 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable); 969 } 970 971 /// CreateRuntimeFunction - Create a new runtime function with the specified 972 /// type and name. 973 llvm::Constant * 974 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, 975 StringRef Name, 976 llvm::Attributes ExtraAttrs) { 977 return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 978 ExtraAttrs); 979 } 980 981 static bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D, 982 bool ConstantInit) { 983 if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType()) 984 return false; 985 986 if (Context.getLangOptions().CPlusPlus) { 987 if (const RecordType *Record 988 = Context.getBaseElementType(D->getType())->getAs<RecordType>()) 989 return ConstantInit && 990 cast<CXXRecordDecl>(Record->getDecl())->isPOD() && 991 !cast<CXXRecordDecl>(Record->getDecl())->hasMutableFields(); 992 } 993 994 return true; 995 } 996 997 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 998 /// create and return an llvm GlobalVariable with the specified type. If there 999 /// is something in the module with the specified name, return it potentially 1000 /// bitcasted to the right type. 1001 /// 1002 /// If D is non-null, it specifies a decl that correspond to this. This is used 1003 /// to set the attributes on the global when it is first created. 1004 llvm::Constant * 1005 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, 1006 llvm::PointerType *Ty, 1007 const VarDecl *D, 1008 bool UnnamedAddr) { 1009 // Lookup the entry, lazily creating it if necessary. 1010 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1011 if (Entry) { 1012 if (WeakRefReferences.count(Entry)) { 1013 if (D && !D->hasAttr<WeakAttr>()) 1014 Entry->setLinkage(llvm::Function::ExternalLinkage); 1015 1016 WeakRefReferences.erase(Entry); 1017 } 1018 1019 if (UnnamedAddr) 1020 Entry->setUnnamedAddr(true); 1021 1022 if (Entry->getType() == Ty) 1023 return Entry; 1024 1025 // Make sure the result is of the correct type. 1026 return llvm::ConstantExpr::getBitCast(Entry, Ty); 1027 } 1028 1029 // This is the first use or definition of a mangled name. If there is a 1030 // deferred decl with this name, remember that we need to emit it at the end 1031 // of the file. 1032 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName); 1033 if (DDI != DeferredDecls.end()) { 1034 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 1035 // list, and remove it from DeferredDecls (since we don't need it anymore). 1036 DeferredDeclsToEmit.push_back(DDI->second); 1037 DeferredDecls.erase(DDI); 1038 } 1039 1040 llvm::GlobalVariable *GV = 1041 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false, 1042 llvm::GlobalValue::ExternalLinkage, 1043 0, MangledName, 0, 1044 false, Ty->getAddressSpace()); 1045 1046 // Handle things which are present even on external declarations. 1047 if (D) { 1048 // FIXME: This code is overly simple and should be merged with other global 1049 // handling. 1050 GV->setConstant(DeclIsConstantGlobal(Context, D, false)); 1051 1052 // Set linkage and visibility in case we never see a definition. 1053 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility(); 1054 if (LV.linkage() != ExternalLinkage) { 1055 // Don't set internal linkage on declarations. 1056 } else { 1057 if (D->hasAttr<DLLImportAttr>()) 1058 GV->setLinkage(llvm::GlobalValue::DLLImportLinkage); 1059 else if (D->hasAttr<WeakAttr>() || D->isWeakImported()) 1060 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 1061 1062 // Set visibility on a declaration only if it's explicit. 1063 if (LV.visibilityExplicit()) 1064 GV->setVisibility(GetLLVMVisibility(LV.visibility())); 1065 } 1066 1067 GV->setThreadLocal(D->isThreadSpecified()); 1068 } 1069 1070 return GV; 1071 } 1072 1073 1074 llvm::GlobalVariable * 1075 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name, 1076 llvm::Type *Ty, 1077 llvm::GlobalValue::LinkageTypes Linkage) { 1078 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); 1079 llvm::GlobalVariable *OldGV = 0; 1080 1081 1082 if (GV) { 1083 // Check if the variable has the right type. 1084 if (GV->getType()->getElementType() == Ty) 1085 return GV; 1086 1087 // Because C++ name mangling, the only way we can end up with an already 1088 // existing global with the same name is if it has been declared extern "C". 1089 assert(GV->isDeclaration() && "Declaration has wrong type!"); 1090 OldGV = GV; 1091 } 1092 1093 // Create a new variable. 1094 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, 1095 Linkage, 0, Name); 1096 1097 if (OldGV) { 1098 // Replace occurrences of the old variable if needed. 1099 GV->takeName(OldGV); 1100 1101 if (!OldGV->use_empty()) { 1102 llvm::Constant *NewPtrForOldDecl = 1103 llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 1104 OldGV->replaceAllUsesWith(NewPtrForOldDecl); 1105 } 1106 1107 OldGV->eraseFromParent(); 1108 } 1109 1110 return GV; 1111 } 1112 1113 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 1114 /// given global variable. If Ty is non-null and if the global doesn't exist, 1115 /// then it will be greated with the specified type instead of whatever the 1116 /// normal requested type would be. 1117 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 1118 llvm::Type *Ty) { 1119 assert(D->hasGlobalStorage() && "Not a global variable"); 1120 QualType ASTTy = D->getType(); 1121 if (Ty == 0) 1122 Ty = getTypes().ConvertTypeForMem(ASTTy); 1123 1124 llvm::PointerType *PTy = 1125 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy)); 1126 1127 StringRef MangledName = getMangledName(D); 1128 return GetOrCreateLLVMGlobal(MangledName, PTy, D); 1129 } 1130 1131 /// CreateRuntimeVariable - Create a new runtime global variable with the 1132 /// specified type and name. 1133 llvm::Constant * 1134 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, 1135 StringRef Name) { 1136 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0, 1137 true); 1138 } 1139 1140 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 1141 assert(!D->getInit() && "Cannot emit definite definitions here!"); 1142 1143 if (MayDeferGeneration(D)) { 1144 // If we have not seen a reference to this variable yet, place it 1145 // into the deferred declarations table to be emitted if needed 1146 // later. 1147 StringRef MangledName = getMangledName(D); 1148 if (!GetGlobalValue(MangledName)) { 1149 DeferredDecls[MangledName] = D; 1150 return; 1151 } 1152 } 1153 1154 // The tentative definition is the only definition. 1155 EmitGlobalVarDefinition(D); 1156 } 1157 1158 void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) { 1159 if (DefinitionRequired) 1160 getVTables().GenerateClassData(getVTableLinkage(Class), Class); 1161 } 1162 1163 llvm::GlobalVariable::LinkageTypes 1164 CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) { 1165 if (RD->getLinkage() != ExternalLinkage) 1166 return llvm::GlobalVariable::InternalLinkage; 1167 1168 if (const CXXMethodDecl *KeyFunction 1169 = RD->getASTContext().getKeyFunction(RD)) { 1170 // If this class has a key function, use that to determine the linkage of 1171 // the vtable. 1172 const FunctionDecl *Def = 0; 1173 if (KeyFunction->hasBody(Def)) 1174 KeyFunction = cast<CXXMethodDecl>(Def); 1175 1176 switch (KeyFunction->getTemplateSpecializationKind()) { 1177 case TSK_Undeclared: 1178 case TSK_ExplicitSpecialization: 1179 // When compiling with optimizations turned on, we emit all vtables, 1180 // even if the key function is not defined in the current translation 1181 // unit. If this is the case, use available_externally linkage. 1182 if (!Def && CodeGenOpts.OptimizationLevel) 1183 return llvm::GlobalVariable::AvailableExternallyLinkage; 1184 1185 if (KeyFunction->isInlined()) 1186 return !Context.getLangOptions().AppleKext ? 1187 llvm::GlobalVariable::LinkOnceODRLinkage : 1188 llvm::Function::InternalLinkage; 1189 1190 return llvm::GlobalVariable::ExternalLinkage; 1191 1192 case TSK_ImplicitInstantiation: 1193 return !Context.getLangOptions().AppleKext ? 1194 llvm::GlobalVariable::LinkOnceODRLinkage : 1195 llvm::Function::InternalLinkage; 1196 1197 case TSK_ExplicitInstantiationDefinition: 1198 return !Context.getLangOptions().AppleKext ? 1199 llvm::GlobalVariable::WeakODRLinkage : 1200 llvm::Function::InternalLinkage; 1201 1202 case TSK_ExplicitInstantiationDeclaration: 1203 // FIXME: Use available_externally linkage. However, this currently 1204 // breaks LLVM's build due to undefined symbols. 1205 // return llvm::GlobalVariable::AvailableExternallyLinkage; 1206 return !Context.getLangOptions().AppleKext ? 1207 llvm::GlobalVariable::LinkOnceODRLinkage : 1208 llvm::Function::InternalLinkage; 1209 } 1210 } 1211 1212 if (Context.getLangOptions().AppleKext) 1213 return llvm::Function::InternalLinkage; 1214 1215 switch (RD->getTemplateSpecializationKind()) { 1216 case TSK_Undeclared: 1217 case TSK_ExplicitSpecialization: 1218 case TSK_ImplicitInstantiation: 1219 // FIXME: Use available_externally linkage. However, this currently 1220 // breaks LLVM's build due to undefined symbols. 1221 // return llvm::GlobalVariable::AvailableExternallyLinkage; 1222 case TSK_ExplicitInstantiationDeclaration: 1223 return llvm::GlobalVariable::LinkOnceODRLinkage; 1224 1225 case TSK_ExplicitInstantiationDefinition: 1226 return llvm::GlobalVariable::WeakODRLinkage; 1227 } 1228 1229 // Silence GCC warning. 1230 return llvm::GlobalVariable::LinkOnceODRLinkage; 1231 } 1232 1233 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { 1234 return Context.toCharUnitsFromBits( 1235 TheTargetData.getTypeStoreSizeInBits(Ty)); 1236 } 1237 1238 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { 1239 llvm::Constant *Init = 0; 1240 QualType ASTTy = D->getType(); 1241 bool NonConstInit = false; 1242 1243 const Expr *InitExpr = D->getAnyInitializer(); 1244 1245 if (!InitExpr) { 1246 // This is a tentative definition; tentative definitions are 1247 // implicitly initialized with { 0 }. 1248 // 1249 // Note that tentative definitions are only emitted at the end of 1250 // a translation unit, so they should never have incomplete 1251 // type. In addition, EmitTentativeDefinition makes sure that we 1252 // never attempt to emit a tentative definition if a real one 1253 // exists. A use may still exists, however, so we still may need 1254 // to do a RAUW. 1255 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 1256 Init = EmitNullConstant(D->getType()); 1257 } else { 1258 Init = EmitConstantExpr(InitExpr, D->getType()); 1259 if (!Init) { 1260 QualType T = InitExpr->getType(); 1261 if (D->getType()->isReferenceType()) 1262 T = D->getType(); 1263 1264 if (getLangOptions().CPlusPlus) { 1265 Init = EmitNullConstant(T); 1266 NonConstInit = true; 1267 } else { 1268 ErrorUnsupported(D, "static initializer"); 1269 Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 1270 } 1271 } else { 1272 // We don't need an initializer, so remove the entry for the delayed 1273 // initializer position (just in case this entry was delayed). 1274 if (getLangOptions().CPlusPlus) 1275 DelayedCXXInitPosition.erase(D); 1276 } 1277 } 1278 1279 llvm::Type* InitType = Init->getType(); 1280 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType); 1281 1282 // Strip off a bitcast if we got one back. 1283 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 1284 assert(CE->getOpcode() == llvm::Instruction::BitCast || 1285 // all zero index gep. 1286 CE->getOpcode() == llvm::Instruction::GetElementPtr); 1287 Entry = CE->getOperand(0); 1288 } 1289 1290 // Entry is now either a Function or GlobalVariable. 1291 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry); 1292 1293 // We have a definition after a declaration with the wrong type. 1294 // We must make a new GlobalVariable* and update everything that used OldGV 1295 // (a declaration or tentative definition) with the new GlobalVariable* 1296 // (which will be a definition). 1297 // 1298 // This happens if there is a prototype for a global (e.g. 1299 // "extern int x[];") and then a definition of a different type (e.g. 1300 // "int x[10];"). This also happens when an initializer has a different type 1301 // from the type of the global (this happens with unions). 1302 if (GV == 0 || 1303 GV->getType()->getElementType() != InitType || 1304 GV->getType()->getAddressSpace() != 1305 getContext().getTargetAddressSpace(ASTTy)) { 1306 1307 // Move the old entry aside so that we'll create a new one. 1308 Entry->setName(StringRef()); 1309 1310 // Make a new global with the correct type, this is now guaranteed to work. 1311 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType)); 1312 1313 // Replace all uses of the old global with the new global 1314 llvm::Constant *NewPtrForOldDecl = 1315 llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 1316 Entry->replaceAllUsesWith(NewPtrForOldDecl); 1317 1318 // Erase the old global, since it is no longer used. 1319 cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 1320 } 1321 1322 if (D->hasAttr<AnnotateAttr>()) 1323 AddGlobalAnnotations(D, GV); 1324 1325 GV->setInitializer(Init); 1326 1327 // If it is safe to mark the global 'constant', do so now. 1328 GV->setConstant(false); 1329 if (!NonConstInit && DeclIsConstantGlobal(Context, D, true)) 1330 GV->setConstant(true); 1331 1332 GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 1333 1334 // Set the llvm linkage type as appropriate. 1335 llvm::GlobalValue::LinkageTypes Linkage = 1336 GetLLVMLinkageVarDefinition(D, GV); 1337 GV->setLinkage(Linkage); 1338 if (Linkage == llvm::GlobalVariable::CommonLinkage) 1339 // common vars aren't constant even if declared const. 1340 GV->setConstant(false); 1341 1342 SetCommonAttributes(D, GV); 1343 1344 // Emit the initializer function if necessary. 1345 if (NonConstInit) 1346 EmitCXXGlobalVarDeclInitFunc(D, GV); 1347 1348 // Emit global variable debug information. 1349 if (CGDebugInfo *DI = getModuleDebugInfo()) { 1350 DI->setLocation(D->getLocation()); 1351 DI->EmitGlobalVariable(GV, D); 1352 } 1353 } 1354 1355 llvm::GlobalValue::LinkageTypes 1356 CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D, 1357 llvm::GlobalVariable *GV) { 1358 GVALinkage Linkage = getContext().GetGVALinkageForVariable(D); 1359 if (Linkage == GVA_Internal) 1360 return llvm::Function::InternalLinkage; 1361 else if (D->hasAttr<DLLImportAttr>()) 1362 return llvm::Function::DLLImportLinkage; 1363 else if (D->hasAttr<DLLExportAttr>()) 1364 return llvm::Function::DLLExportLinkage; 1365 else if (D->hasAttr<WeakAttr>()) { 1366 if (GV->isConstant()) 1367 return llvm::GlobalVariable::WeakODRLinkage; 1368 else 1369 return llvm::GlobalVariable::WeakAnyLinkage; 1370 } else if (Linkage == GVA_TemplateInstantiation || 1371 Linkage == GVA_ExplicitTemplateInstantiation) 1372 return llvm::GlobalVariable::WeakODRLinkage; 1373 else if (!getLangOptions().CPlusPlus && 1374 ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) || 1375 D->getAttr<CommonAttr>()) && 1376 !D->hasExternalStorage() && !D->getInit() && 1377 !D->getAttr<SectionAttr>() && !D->isThreadSpecified() && 1378 !D->getAttr<WeakImportAttr>()) { 1379 // Thread local vars aren't considered common linkage. 1380 return llvm::GlobalVariable::CommonLinkage; 1381 } 1382 return llvm::GlobalVariable::ExternalLinkage; 1383 } 1384 1385 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 1386 /// implement a function with no prototype, e.g. "int foo() {}". If there are 1387 /// existing call uses of the old function in the module, this adjusts them to 1388 /// call the new function directly. 1389 /// 1390 /// This is not just a cleanup: the always_inline pass requires direct calls to 1391 /// functions to be able to inline them. If there is a bitcast in the way, it 1392 /// won't inline them. Instcombine normally deletes these calls, but it isn't 1393 /// run at -O0. 1394 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 1395 llvm::Function *NewFn) { 1396 // If we're redefining a global as a function, don't transform it. 1397 llvm::Function *OldFn = dyn_cast<llvm::Function>(Old); 1398 if (OldFn == 0) return; 1399 1400 llvm::Type *NewRetTy = NewFn->getReturnType(); 1401 SmallVector<llvm::Value*, 4> ArgList; 1402 1403 for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end(); 1404 UI != E; ) { 1405 // TODO: Do invokes ever occur in C code? If so, we should handle them too. 1406 llvm::Value::use_iterator I = UI++; // Increment before the CI is erased. 1407 llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I); 1408 if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I) 1409 llvm::CallSite CS(CI); 1410 if (!CI || !CS.isCallee(I)) continue; 1411 1412 // If the return types don't match exactly, and if the call isn't dead, then 1413 // we can't transform this call. 1414 if (CI->getType() != NewRetTy && !CI->use_empty()) 1415 continue; 1416 1417 // Get the attribute list. 1418 llvm::SmallVector<llvm::AttributeWithIndex, 8> AttrVec; 1419 llvm::AttrListPtr AttrList = CI->getAttributes(); 1420 1421 // Get any return attributes. 1422 llvm::Attributes RAttrs = AttrList.getRetAttributes(); 1423 1424 // Add the return attributes. 1425 if (RAttrs) 1426 AttrVec.push_back(llvm::AttributeWithIndex::get(0, RAttrs)); 1427 1428 // If the function was passed too few arguments, don't transform. If extra 1429 // arguments were passed, we silently drop them. If any of the types 1430 // mismatch, we don't transform. 1431 unsigned ArgNo = 0; 1432 bool DontTransform = false; 1433 for (llvm::Function::arg_iterator AI = NewFn->arg_begin(), 1434 E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) { 1435 if (CS.arg_size() == ArgNo || 1436 CS.getArgument(ArgNo)->getType() != AI->getType()) { 1437 DontTransform = true; 1438 break; 1439 } 1440 1441 // Add any parameter attributes. 1442 if (llvm::Attributes PAttrs = AttrList.getParamAttributes(ArgNo + 1)) 1443 AttrVec.push_back(llvm::AttributeWithIndex::get(ArgNo + 1, PAttrs)); 1444 } 1445 if (DontTransform) 1446 continue; 1447 1448 if (llvm::Attributes FnAttrs = AttrList.getFnAttributes()) 1449 AttrVec.push_back(llvm::AttributeWithIndex::get(~0, FnAttrs)); 1450 1451 // Okay, we can transform this. Create the new call instruction and copy 1452 // over the required information. 1453 ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo); 1454 llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList, "", CI); 1455 ArgList.clear(); 1456 if (!NewCall->getType()->isVoidTy()) 1457 NewCall->takeName(CI); 1458 NewCall->setAttributes(llvm::AttrListPtr::get(AttrVec.begin(), 1459 AttrVec.end())); 1460 NewCall->setCallingConv(CI->getCallingConv()); 1461 1462 // Finally, remove the old call, replacing any uses with the new one. 1463 if (!CI->use_empty()) 1464 CI->replaceAllUsesWith(NewCall); 1465 1466 // Copy debug location attached to CI. 1467 if (!CI->getDebugLoc().isUnknown()) 1468 NewCall->setDebugLoc(CI->getDebugLoc()); 1469 CI->eraseFromParent(); 1470 } 1471 } 1472 1473 1474 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) { 1475 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl()); 1476 1477 // Compute the function info and LLVM type. 1478 const CGFunctionInfo &FI = getTypes().getFunctionInfo(GD); 1479 bool variadic = false; 1480 if (const FunctionProtoType *fpt = D->getType()->getAs<FunctionProtoType>()) 1481 variadic = fpt->isVariadic(); 1482 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI, variadic); 1483 1484 // Get or create the prototype for the function. 1485 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty); 1486 1487 // Strip off a bitcast if we got one back. 1488 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 1489 assert(CE->getOpcode() == llvm::Instruction::BitCast); 1490 Entry = CE->getOperand(0); 1491 } 1492 1493 1494 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) { 1495 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry); 1496 1497 // If the types mismatch then we have to rewrite the definition. 1498 assert(OldFn->isDeclaration() && 1499 "Shouldn't replace non-declaration"); 1500 1501 // F is the Function* for the one with the wrong type, we must make a new 1502 // Function* and update everything that used F (a declaration) with the new 1503 // Function* (which will be a definition). 1504 // 1505 // This happens if there is a prototype for a function 1506 // (e.g. "int f()") and then a definition of a different type 1507 // (e.g. "int f(int x)"). Move the old function aside so that it 1508 // doesn't interfere with GetAddrOfFunction. 1509 OldFn->setName(StringRef()); 1510 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty)); 1511 1512 // If this is an implementation of a function without a prototype, try to 1513 // replace any existing uses of the function (which may be calls) with uses 1514 // of the new function 1515 if (D->getType()->isFunctionNoProtoType()) { 1516 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn); 1517 OldFn->removeDeadConstantUsers(); 1518 } 1519 1520 // Replace uses of F with the Function we will endow with a body. 1521 if (!Entry->use_empty()) { 1522 llvm::Constant *NewPtrForOldDecl = 1523 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType()); 1524 Entry->replaceAllUsesWith(NewPtrForOldDecl); 1525 } 1526 1527 // Ok, delete the old function now, which is dead. 1528 OldFn->eraseFromParent(); 1529 1530 Entry = NewFn; 1531 } 1532 1533 // We need to set linkage and visibility on the function before 1534 // generating code for it because various parts of IR generation 1535 // want to propagate this information down (e.g. to local static 1536 // declarations). 1537 llvm::Function *Fn = cast<llvm::Function>(Entry); 1538 setFunctionLinkage(D, Fn); 1539 1540 // FIXME: this is redundant with part of SetFunctionDefinitionAttributes 1541 setGlobalVisibility(Fn, D); 1542 1543 CodeGenFunction(*this).GenerateCode(D, Fn, FI); 1544 1545 SetFunctionDefinitionAttributes(D, Fn); 1546 SetLLVMFunctionAttributesForDefinition(D, Fn); 1547 1548 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 1549 AddGlobalCtor(Fn, CA->getPriority()); 1550 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 1551 AddGlobalDtor(Fn, DA->getPriority()); 1552 if (D->hasAttr<AnnotateAttr>()) 1553 AddGlobalAnnotations(D, Fn); 1554 } 1555 1556 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 1557 const ValueDecl *D = cast<ValueDecl>(GD.getDecl()); 1558 const AliasAttr *AA = D->getAttr<AliasAttr>(); 1559 assert(AA && "Not an alias?"); 1560 1561 StringRef MangledName = getMangledName(GD); 1562 1563 // If there is a definition in the module, then it wins over the alias. 1564 // This is dubious, but allow it to be safe. Just ignore the alias. 1565 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1566 if (Entry && !Entry->isDeclaration()) 1567 return; 1568 1569 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 1570 1571 // Create a reference to the named value. This ensures that it is emitted 1572 // if a deferred decl. 1573 llvm::Constant *Aliasee; 1574 if (isa<llvm::FunctionType>(DeclTy)) 1575 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(), 1576 /*ForVTable=*/false); 1577 else 1578 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 1579 llvm::PointerType::getUnqual(DeclTy), 0); 1580 1581 // Create the new alias itself, but don't set a name yet. 1582 llvm::GlobalValue *GA = 1583 new llvm::GlobalAlias(Aliasee->getType(), 1584 llvm::Function::ExternalLinkage, 1585 "", Aliasee, &getModule()); 1586 1587 if (Entry) { 1588 assert(Entry->isDeclaration()); 1589 1590 // If there is a declaration in the module, then we had an extern followed 1591 // by the alias, as in: 1592 // extern int test6(); 1593 // ... 1594 // int test6() __attribute__((alias("test7"))); 1595 // 1596 // Remove it and replace uses of it with the alias. 1597 GA->takeName(Entry); 1598 1599 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 1600 Entry->getType())); 1601 Entry->eraseFromParent(); 1602 } else { 1603 GA->setName(MangledName); 1604 } 1605 1606 // Set attributes which are particular to an alias; this is a 1607 // specialization of the attributes which may be set on a global 1608 // variable/function. 1609 if (D->hasAttr<DLLExportAttr>()) { 1610 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1611 // The dllexport attribute is ignored for undefined symbols. 1612 if (FD->hasBody()) 1613 GA->setLinkage(llvm::Function::DLLExportLinkage); 1614 } else { 1615 GA->setLinkage(llvm::Function::DLLExportLinkage); 1616 } 1617 } else if (D->hasAttr<WeakAttr>() || 1618 D->hasAttr<WeakRefAttr>() || 1619 D->isWeakImported()) { 1620 GA->setLinkage(llvm::Function::WeakAnyLinkage); 1621 } 1622 1623 SetCommonAttributes(D, GA); 1624 } 1625 1626 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, 1627 ArrayRef<llvm::Type*> Tys) { 1628 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, 1629 Tys); 1630 } 1631 1632 static llvm::StringMapEntry<llvm::Constant*> & 1633 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map, 1634 const StringLiteral *Literal, 1635 bool TargetIsLSB, 1636 bool &IsUTF16, 1637 unsigned &StringLength) { 1638 StringRef String = Literal->getString(); 1639 unsigned NumBytes = String.size(); 1640 1641 // Check for simple case. 1642 if (!Literal->containsNonAsciiOrNull()) { 1643 StringLength = NumBytes; 1644 return Map.GetOrCreateValue(String); 1645 } 1646 1647 // Otherwise, convert the UTF8 literals into a byte string. 1648 SmallVector<UTF16, 128> ToBuf(NumBytes); 1649 const UTF8 *FromPtr = (UTF8 *)String.data(); 1650 UTF16 *ToPtr = &ToBuf[0]; 1651 1652 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 1653 &ToPtr, ToPtr + NumBytes, 1654 strictConversion); 1655 1656 // ConvertUTF8toUTF16 returns the length in ToPtr. 1657 StringLength = ToPtr - &ToBuf[0]; 1658 1659 // Render the UTF-16 string into a byte array and convert to the target byte 1660 // order. 1661 // 1662 // FIXME: This isn't something we should need to do here. 1663 llvm::SmallString<128> AsBytes; 1664 AsBytes.reserve(StringLength * 2); 1665 for (unsigned i = 0; i != StringLength; ++i) { 1666 unsigned short Val = ToBuf[i]; 1667 if (TargetIsLSB) { 1668 AsBytes.push_back(Val & 0xFF); 1669 AsBytes.push_back(Val >> 8); 1670 } else { 1671 AsBytes.push_back(Val >> 8); 1672 AsBytes.push_back(Val & 0xFF); 1673 } 1674 } 1675 // Append one extra null character, the second is automatically added by our 1676 // caller. 1677 AsBytes.push_back(0); 1678 1679 IsUTF16 = true; 1680 return Map.GetOrCreateValue(StringRef(AsBytes.data(), AsBytes.size())); 1681 } 1682 1683 static llvm::StringMapEntry<llvm::Constant*> & 1684 GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map, 1685 const StringLiteral *Literal, 1686 unsigned &StringLength) 1687 { 1688 StringRef String = Literal->getString(); 1689 StringLength = String.size(); 1690 return Map.GetOrCreateValue(String); 1691 } 1692 1693 llvm::Constant * 1694 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 1695 unsigned StringLength = 0; 1696 bool isUTF16 = false; 1697 llvm::StringMapEntry<llvm::Constant*> &Entry = 1698 GetConstantCFStringEntry(CFConstantStringMap, Literal, 1699 getTargetData().isLittleEndian(), 1700 isUTF16, StringLength); 1701 1702 if (llvm::Constant *C = Entry.getValue()) 1703 return C; 1704 1705 llvm::Constant *Zero = 1706 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)); 1707 llvm::Constant *Zeros[] = { Zero, Zero }; 1708 1709 // If we don't already have it, get __CFConstantStringClassReference. 1710 if (!CFConstantStringClassRef) { 1711 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 1712 Ty = llvm::ArrayType::get(Ty, 0); 1713 llvm::Constant *GV = CreateRuntimeVariable(Ty, 1714 "__CFConstantStringClassReference"); 1715 // Decay array -> ptr 1716 CFConstantStringClassRef = 1717 llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 1718 } 1719 1720 QualType CFTy = getContext().getCFConstantStringType(); 1721 1722 llvm::StructType *STy = 1723 cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 1724 1725 std::vector<llvm::Constant*> Fields(4); 1726 1727 // Class pointer. 1728 Fields[0] = CFConstantStringClassRef; 1729 1730 // Flags. 1731 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 1732 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) : 1733 llvm::ConstantInt::get(Ty, 0x07C8); 1734 1735 // String pointer. 1736 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str()); 1737 1738 llvm::GlobalValue::LinkageTypes Linkage; 1739 bool isConstant; 1740 if (isUTF16) { 1741 // FIXME: why do utf strings get "_" labels instead of "L" labels? 1742 Linkage = llvm::GlobalValue::InternalLinkage; 1743 // Note: -fwritable-strings doesn't make unicode CFStrings writable, but 1744 // does make plain ascii ones writable. 1745 isConstant = true; 1746 } else { 1747 // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error 1748 // when using private linkage. It is not clear if this is a bug in ld 1749 // or a reasonable new restriction. 1750 Linkage = llvm::GlobalValue::LinkerPrivateLinkage; 1751 isConstant = !Features.WritableStrings; 1752 } 1753 1754 llvm::GlobalVariable *GV = 1755 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C, 1756 ".str"); 1757 GV->setUnnamedAddr(true); 1758 if (isUTF16) { 1759 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy); 1760 GV->setAlignment(Align.getQuantity()); 1761 } else { 1762 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy); 1763 GV->setAlignment(Align.getQuantity()); 1764 } 1765 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 1766 1767 // String length. 1768 Ty = getTypes().ConvertType(getContext().LongTy); 1769 Fields[3] = llvm::ConstantInt::get(Ty, StringLength); 1770 1771 // The struct. 1772 C = llvm::ConstantStruct::get(STy, Fields); 1773 GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 1774 llvm::GlobalVariable::PrivateLinkage, C, 1775 "_unnamed_cfstring_"); 1776 if (const char *Sect = getContext().getTargetInfo().getCFStringSection()) 1777 GV->setSection(Sect); 1778 Entry.setValue(GV); 1779 1780 return GV; 1781 } 1782 1783 static RecordDecl * 1784 CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK, 1785 DeclContext *DC, IdentifierInfo *Id) { 1786 SourceLocation Loc; 1787 if (Ctx.getLangOptions().CPlusPlus) 1788 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id); 1789 else 1790 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id); 1791 } 1792 1793 llvm::Constant * 1794 CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) { 1795 unsigned StringLength = 0; 1796 llvm::StringMapEntry<llvm::Constant*> &Entry = 1797 GetConstantStringEntry(CFConstantStringMap, Literal, StringLength); 1798 1799 if (llvm::Constant *C = Entry.getValue()) 1800 return C; 1801 1802 llvm::Constant *Zero = 1803 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)); 1804 llvm::Constant *Zeros[] = { Zero, Zero }; 1805 1806 // If we don't already have it, get _NSConstantStringClassReference. 1807 if (!ConstantStringClassRef) { 1808 std::string StringClass(getLangOptions().ObjCConstantStringClass); 1809 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 1810 llvm::Constant *GV; 1811 if (Features.ObjCNonFragileABI) { 1812 std::string str = 1813 StringClass.empty() ? "OBJC_CLASS_$_NSConstantString" 1814 : "OBJC_CLASS_$_" + StringClass; 1815 GV = getObjCRuntime().GetClassGlobal(str); 1816 // Make sure the result is of the correct type. 1817 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 1818 ConstantStringClassRef = 1819 llvm::ConstantExpr::getBitCast(GV, PTy); 1820 } else { 1821 std::string str = 1822 StringClass.empty() ? "_NSConstantStringClassReference" 1823 : "_" + StringClass + "ClassReference"; 1824 llvm::Type *PTy = llvm::ArrayType::get(Ty, 0); 1825 GV = CreateRuntimeVariable(PTy, str); 1826 // Decay array -> ptr 1827 ConstantStringClassRef = 1828 llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 1829 } 1830 } 1831 1832 if (!NSConstantStringType) { 1833 // Construct the type for a constant NSString. 1834 RecordDecl *D = CreateRecordDecl(Context, TTK_Struct, 1835 Context.getTranslationUnitDecl(), 1836 &Context.Idents.get("__builtin_NSString")); 1837 D->startDefinition(); 1838 1839 QualType FieldTypes[3]; 1840 1841 // const int *isa; 1842 FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst()); 1843 // const char *str; 1844 FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst()); 1845 // unsigned int length; 1846 FieldTypes[2] = Context.UnsignedIntTy; 1847 1848 // Create fields 1849 for (unsigned i = 0; i < 3; ++i) { 1850 FieldDecl *Field = FieldDecl::Create(Context, D, 1851 SourceLocation(), 1852 SourceLocation(), 0, 1853 FieldTypes[i], /*TInfo=*/0, 1854 /*BitWidth=*/0, 1855 /*Mutable=*/false, 1856 /*HasInit=*/false); 1857 Field->setAccess(AS_public); 1858 D->addDecl(Field); 1859 } 1860 1861 D->completeDefinition(); 1862 QualType NSTy = Context.getTagDeclType(D); 1863 NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy)); 1864 } 1865 1866 std::vector<llvm::Constant*> Fields(3); 1867 1868 // Class pointer. 1869 Fields[0] = ConstantStringClassRef; 1870 1871 // String pointer. 1872 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str()); 1873 1874 llvm::GlobalValue::LinkageTypes Linkage; 1875 bool isConstant; 1876 Linkage = llvm::GlobalValue::PrivateLinkage; 1877 isConstant = !Features.WritableStrings; 1878 1879 llvm::GlobalVariable *GV = 1880 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C, 1881 ".str"); 1882 GV->setUnnamedAddr(true); 1883 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy); 1884 GV->setAlignment(Align.getQuantity()); 1885 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 1886 1887 // String length. 1888 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 1889 Fields[2] = llvm::ConstantInt::get(Ty, StringLength); 1890 1891 // The struct. 1892 C = llvm::ConstantStruct::get(NSConstantStringType, Fields); 1893 GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 1894 llvm::GlobalVariable::PrivateLinkage, C, 1895 "_unnamed_nsstring_"); 1896 // FIXME. Fix section. 1897 if (const char *Sect = 1898 Features.ObjCNonFragileABI 1899 ? getContext().getTargetInfo().getNSStringNonFragileABISection() 1900 : getContext().getTargetInfo().getNSStringSection()) 1901 GV->setSection(Sect); 1902 Entry.setValue(GV); 1903 1904 return GV; 1905 } 1906 1907 QualType CodeGenModule::getObjCFastEnumerationStateType() { 1908 if (ObjCFastEnumerationStateType.isNull()) { 1909 RecordDecl *D = CreateRecordDecl(Context, TTK_Struct, 1910 Context.getTranslationUnitDecl(), 1911 &Context.Idents.get("__objcFastEnumerationState")); 1912 D->startDefinition(); 1913 1914 QualType FieldTypes[] = { 1915 Context.UnsignedLongTy, 1916 Context.getPointerType(Context.getObjCIdType()), 1917 Context.getPointerType(Context.UnsignedLongTy), 1918 Context.getConstantArrayType(Context.UnsignedLongTy, 1919 llvm::APInt(32, 5), ArrayType::Normal, 0) 1920 }; 1921 1922 for (size_t i = 0; i < 4; ++i) { 1923 FieldDecl *Field = FieldDecl::Create(Context, 1924 D, 1925 SourceLocation(), 1926 SourceLocation(), 0, 1927 FieldTypes[i], /*TInfo=*/0, 1928 /*BitWidth=*/0, 1929 /*Mutable=*/false, 1930 /*HasInit=*/false); 1931 Field->setAccess(AS_public); 1932 D->addDecl(Field); 1933 } 1934 1935 D->completeDefinition(); 1936 ObjCFastEnumerationStateType = Context.getTagDeclType(D); 1937 } 1938 1939 return ObjCFastEnumerationStateType; 1940 } 1941 1942 /// GetStringForStringLiteral - Return the appropriate bytes for a 1943 /// string literal, properly padded to match the literal type. 1944 std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) { 1945 const ASTContext &Context = getContext(); 1946 const ConstantArrayType *CAT = 1947 Context.getAsConstantArrayType(E->getType()); 1948 assert(CAT && "String isn't pointer or array!"); 1949 1950 // Resize the string to the right size. 1951 uint64_t RealLen = CAT->getSize().getZExtValue(); 1952 1953 switch (E->getKind()) { 1954 case StringLiteral::Ascii: 1955 case StringLiteral::UTF8: 1956 break; 1957 case StringLiteral::Wide: 1958 RealLen *= Context.getTargetInfo().getWCharWidth() / Context.getCharWidth(); 1959 break; 1960 case StringLiteral::UTF16: 1961 RealLen *= Context.getTargetInfo().getChar16Width() / Context.getCharWidth(); 1962 break; 1963 case StringLiteral::UTF32: 1964 RealLen *= Context.getTargetInfo().getChar32Width() / Context.getCharWidth(); 1965 break; 1966 } 1967 1968 std::string Str = E->getString().str(); 1969 Str.resize(RealLen, '\0'); 1970 1971 return Str; 1972 } 1973 1974 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 1975 /// constant array for the given string literal. 1976 llvm::Constant * 1977 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) { 1978 // FIXME: This can be more efficient. 1979 // FIXME: We shouldn't need to bitcast the constant in the wide string case. 1980 CharUnits Align = getContext().getTypeAlignInChars(S->getType()); 1981 llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S), 1982 /* GlobalName */ 0, 1983 Align.getQuantity()); 1984 if (S->isWide() || S->isUTF16() || S->isUTF32()) { 1985 llvm::Type *DestTy = 1986 llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType())); 1987 C = llvm::ConstantExpr::getBitCast(C, DestTy); 1988 } 1989 return C; 1990 } 1991 1992 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 1993 /// array for the given ObjCEncodeExpr node. 1994 llvm::Constant * 1995 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 1996 std::string Str; 1997 getContext().getObjCEncodingForType(E->getEncodedType(), Str); 1998 1999 return GetAddrOfConstantCString(Str); 2000 } 2001 2002 2003 /// GenerateWritableString -- Creates storage for a string literal. 2004 static llvm::GlobalVariable *GenerateStringLiteral(StringRef str, 2005 bool constant, 2006 CodeGenModule &CGM, 2007 const char *GlobalName, 2008 unsigned Alignment) { 2009 // Create Constant for this string literal. Don't add a '\0'. 2010 llvm::Constant *C = 2011 llvm::ConstantArray::get(CGM.getLLVMContext(), str, false); 2012 2013 // Create a global variable for this string 2014 llvm::GlobalVariable *GV = 2015 new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant, 2016 llvm::GlobalValue::PrivateLinkage, 2017 C, GlobalName); 2018 GV->setAlignment(Alignment); 2019 GV->setUnnamedAddr(true); 2020 return GV; 2021 } 2022 2023 /// GetAddrOfConstantString - Returns a pointer to a character array 2024 /// containing the literal. This contents are exactly that of the 2025 /// given string, i.e. it will not be null terminated automatically; 2026 /// see GetAddrOfConstantCString. Note that whether the result is 2027 /// actually a pointer to an LLVM constant depends on 2028 /// Feature.WriteableStrings. 2029 /// 2030 /// The result has pointer to array type. 2031 llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str, 2032 const char *GlobalName, 2033 unsigned Alignment) { 2034 bool IsConstant = !Features.WritableStrings; 2035 2036 // Get the default prefix if a name wasn't specified. 2037 if (!GlobalName) 2038 GlobalName = ".str"; 2039 2040 // Don't share any string literals if strings aren't constant. 2041 if (!IsConstant) 2042 return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment); 2043 2044 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 2045 ConstantStringMap.GetOrCreateValue(Str); 2046 2047 if (llvm::GlobalVariable *GV = Entry.getValue()) { 2048 if (Alignment > GV->getAlignment()) { 2049 GV->setAlignment(Alignment); 2050 } 2051 return GV; 2052 } 2053 2054 // Create a global variable for this. 2055 llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName, Alignment); 2056 Entry.setValue(GV); 2057 return GV; 2058 } 2059 2060 /// GetAddrOfConstantCString - Returns a pointer to a character 2061 /// array containing the literal and a terminating '\0' 2062 /// character. The result has pointer to array type. 2063 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str, 2064 const char *GlobalName, 2065 unsigned Alignment) { 2066 StringRef StrWithNull(Str.c_str(), Str.size() + 1); 2067 return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment); 2068 } 2069 2070 /// EmitObjCPropertyImplementations - Emit information for synthesized 2071 /// properties for an implementation. 2072 void CodeGenModule::EmitObjCPropertyImplementations(const 2073 ObjCImplementationDecl *D) { 2074 for (ObjCImplementationDecl::propimpl_iterator 2075 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) { 2076 ObjCPropertyImplDecl *PID = *i; 2077 2078 // Dynamic is just for type-checking. 2079 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 2080 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 2081 2082 // Determine which methods need to be implemented, some may have 2083 // been overridden. Note that ::isSynthesized is not the method 2084 // we want, that just indicates if the decl came from a 2085 // property. What we want to know is if the method is defined in 2086 // this implementation. 2087 if (!D->getInstanceMethod(PD->getGetterName())) 2088 CodeGenFunction(*this).GenerateObjCGetter( 2089 const_cast<ObjCImplementationDecl *>(D), PID); 2090 if (!PD->isReadOnly() && 2091 !D->getInstanceMethod(PD->getSetterName())) 2092 CodeGenFunction(*this).GenerateObjCSetter( 2093 const_cast<ObjCImplementationDecl *>(D), PID); 2094 } 2095 } 2096 } 2097 2098 static bool needsDestructMethod(ObjCImplementationDecl *impl) { 2099 const ObjCInterfaceDecl *iface = impl->getClassInterface(); 2100 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 2101 ivar; ivar = ivar->getNextIvar()) 2102 if (ivar->getType().isDestructedType()) 2103 return true; 2104 2105 return false; 2106 } 2107 2108 /// EmitObjCIvarInitializations - Emit information for ivar initialization 2109 /// for an implementation. 2110 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 2111 // We might need a .cxx_destruct even if we don't have any ivar initializers. 2112 if (needsDestructMethod(D)) { 2113 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 2114 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 2115 ObjCMethodDecl *DTORMethod = 2116 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(), 2117 cxxSelector, getContext().VoidTy, 0, D, 2118 /*isInstance=*/true, /*isVariadic=*/false, 2119 /*isSynthesized=*/true, /*isImplicitlyDeclared=*/true, 2120 /*isDefined=*/false, ObjCMethodDecl::Required); 2121 D->addInstanceMethod(DTORMethod); 2122 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 2123 D->setHasCXXStructors(true); 2124 } 2125 2126 // If the implementation doesn't have any ivar initializers, we don't need 2127 // a .cxx_construct. 2128 if (D->getNumIvarInitializers() == 0) 2129 return; 2130 2131 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); 2132 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 2133 // The constructor returns 'self'. 2134 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(), 2135 D->getLocation(), 2136 D->getLocation(), cxxSelector, 2137 getContext().getObjCIdType(), 0, 2138 D, /*isInstance=*/true, 2139 /*isVariadic=*/false, 2140 /*isSynthesized=*/true, 2141 /*isImplicitlyDeclared=*/true, 2142 /*isDefined=*/false, 2143 ObjCMethodDecl::Required); 2144 D->addInstanceMethod(CTORMethod); 2145 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 2146 D->setHasCXXStructors(true); 2147 } 2148 2149 /// EmitNamespace - Emit all declarations in a namespace. 2150 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) { 2151 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end(); 2152 I != E; ++I) 2153 EmitTopLevelDecl(*I); 2154 } 2155 2156 // EmitLinkageSpec - Emit all declarations in a linkage spec. 2157 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 2158 if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 2159 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 2160 ErrorUnsupported(LSD, "linkage spec"); 2161 return; 2162 } 2163 2164 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end(); 2165 I != E; ++I) 2166 EmitTopLevelDecl(*I); 2167 } 2168 2169 /// EmitTopLevelDecl - Emit code for a single top level declaration. 2170 void CodeGenModule::EmitTopLevelDecl(Decl *D) { 2171 // If an error has occurred, stop code generation, but continue 2172 // parsing and semantic analysis (to ensure all warnings and errors 2173 // are emitted). 2174 if (Diags.hasErrorOccurred()) 2175 return; 2176 2177 // Ignore dependent declarations. 2178 if (D->getDeclContext() && D->getDeclContext()->isDependentContext()) 2179 return; 2180 2181 switch (D->getKind()) { 2182 case Decl::CXXConversion: 2183 case Decl::CXXMethod: 2184 case Decl::Function: 2185 // Skip function templates 2186 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 2187 cast<FunctionDecl>(D)->isLateTemplateParsed()) 2188 return; 2189 2190 EmitGlobal(cast<FunctionDecl>(D)); 2191 break; 2192 2193 case Decl::Var: 2194 EmitGlobal(cast<VarDecl>(D)); 2195 break; 2196 2197 // Indirect fields from global anonymous structs and unions can be 2198 // ignored; only the actual variable requires IR gen support. 2199 case Decl::IndirectField: 2200 break; 2201 2202 // C++ Decls 2203 case Decl::Namespace: 2204 EmitNamespace(cast<NamespaceDecl>(D)); 2205 break; 2206 // No code generation needed. 2207 case Decl::UsingShadow: 2208 case Decl::Using: 2209 case Decl::UsingDirective: 2210 case Decl::ClassTemplate: 2211 case Decl::FunctionTemplate: 2212 case Decl::TypeAliasTemplate: 2213 case Decl::NamespaceAlias: 2214 case Decl::Block: 2215 break; 2216 case Decl::CXXConstructor: 2217 // Skip function templates 2218 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 2219 cast<FunctionDecl>(D)->isLateTemplateParsed()) 2220 return; 2221 2222 EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 2223 break; 2224 case Decl::CXXDestructor: 2225 if (cast<FunctionDecl>(D)->isLateTemplateParsed()) 2226 return; 2227 EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 2228 break; 2229 2230 case Decl::StaticAssert: 2231 // Nothing to do. 2232 break; 2233 2234 // Objective-C Decls 2235 2236 // Forward declarations, no (immediate) code generation. 2237 case Decl::ObjCClass: 2238 case Decl::ObjCForwardProtocol: 2239 case Decl::ObjCInterface: 2240 break; 2241 2242 case Decl::ObjCCategory: { 2243 ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D); 2244 if (CD->IsClassExtension() && CD->hasSynthBitfield()) 2245 Context.ResetObjCLayout(CD->getClassInterface()); 2246 break; 2247 } 2248 2249 case Decl::ObjCProtocol: 2250 ObjCRuntime->GenerateProtocol(cast<ObjCProtocolDecl>(D)); 2251 break; 2252 2253 case Decl::ObjCCategoryImpl: 2254 // Categories have properties but don't support synthesize so we 2255 // can ignore them here. 2256 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 2257 break; 2258 2259 case Decl::ObjCImplementation: { 2260 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D); 2261 if (Features.ObjCNonFragileABI2 && OMD->hasSynthBitfield()) 2262 Context.ResetObjCLayout(OMD->getClassInterface()); 2263 EmitObjCPropertyImplementations(OMD); 2264 EmitObjCIvarInitializations(OMD); 2265 ObjCRuntime->GenerateClass(OMD); 2266 break; 2267 } 2268 case Decl::ObjCMethod: { 2269 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D); 2270 // If this is not a prototype, emit the body. 2271 if (OMD->getBody()) 2272 CodeGenFunction(*this).GenerateObjCMethod(OMD); 2273 break; 2274 } 2275 case Decl::ObjCCompatibleAlias: 2276 // compatibility-alias is a directive and has no code gen. 2277 break; 2278 2279 case Decl::LinkageSpec: 2280 EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 2281 break; 2282 2283 case Decl::FileScopeAsm: { 2284 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D); 2285 StringRef AsmString = AD->getAsmString()->getString(); 2286 2287 const std::string &S = getModule().getModuleInlineAsm(); 2288 if (S.empty()) 2289 getModule().setModuleInlineAsm(AsmString); 2290 else if (*--S.end() == '\n') 2291 getModule().setModuleInlineAsm(S + AsmString.str()); 2292 else 2293 getModule().setModuleInlineAsm(S + '\n' + AsmString.str()); 2294 break; 2295 } 2296 2297 default: 2298 // Make sure we handled everything we should, every other kind is a 2299 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 2300 // function. Need to recode Decl::Kind to do that easily. 2301 assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 2302 } 2303 } 2304 2305 /// Turns the given pointer into a constant. 2306 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 2307 const void *Ptr) { 2308 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 2309 llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 2310 return llvm::ConstantInt::get(i64, PtrInt); 2311 } 2312 2313 static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 2314 llvm::NamedMDNode *&GlobalMetadata, 2315 GlobalDecl D, 2316 llvm::GlobalValue *Addr) { 2317 if (!GlobalMetadata) 2318 GlobalMetadata = 2319 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 2320 2321 // TODO: should we report variant information for ctors/dtors? 2322 llvm::Value *Ops[] = { 2323 Addr, 2324 GetPointerConstant(CGM.getLLVMContext(), D.getDecl()) 2325 }; 2326 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 2327 } 2328 2329 /// Emits metadata nodes associating all the global values in the 2330 /// current module with the Decls they came from. This is useful for 2331 /// projects using IR gen as a subroutine. 2332 /// 2333 /// Since there's currently no way to associate an MDNode directly 2334 /// with an llvm::GlobalValue, we create a global named metadata 2335 /// with the name 'clang.global.decl.ptrs'. 2336 void CodeGenModule::EmitDeclMetadata() { 2337 llvm::NamedMDNode *GlobalMetadata = 0; 2338 2339 // StaticLocalDeclMap 2340 for (llvm::DenseMap<GlobalDecl,StringRef>::iterator 2341 I = MangledDeclNames.begin(), E = MangledDeclNames.end(); 2342 I != E; ++I) { 2343 llvm::GlobalValue *Addr = getModule().getNamedValue(I->second); 2344 EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr); 2345 } 2346 } 2347 2348 /// Emits metadata nodes for all the local variables in the current 2349 /// function. 2350 void CodeGenFunction::EmitDeclMetadata() { 2351 if (LocalDeclMap.empty()) return; 2352 2353 llvm::LLVMContext &Context = getLLVMContext(); 2354 2355 // Find the unique metadata ID for this name. 2356 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 2357 2358 llvm::NamedMDNode *GlobalMetadata = 0; 2359 2360 for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator 2361 I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) { 2362 const Decl *D = I->first; 2363 llvm::Value *Addr = I->second; 2364 2365 if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 2366 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 2367 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr)); 2368 } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 2369 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 2370 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 2371 } 2372 } 2373 } 2374 2375 void CodeGenModule::EmitCoverageFile() { 2376 if (!getCodeGenOpts().CoverageFile.empty()) { 2377 if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) { 2378 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); 2379 llvm::LLVMContext &Ctx = TheModule.getContext(); 2380 llvm::MDString *CoverageFile = 2381 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile); 2382 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { 2383 llvm::MDNode *CU = CUNode->getOperand(i); 2384 llvm::Value *node[] = { CoverageFile, CU }; 2385 llvm::MDNode *N = llvm::MDNode::get(Ctx, node); 2386 GCov->addOperand(N); 2387 } 2388 } 2389 } 2390 } 2391