1 //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This coordinates the per-module state used while generating code.
12 //===----------------------------------------------------------------------===//
14 #include "CodeGenModule.h"
15 #include "CGDebugInfo.h"
16 #include "CodeGenFunction.h"
17 #include "CodeGenTBAA.h"
20 #include "CGObjCRuntime.h"
21 #include "TargetInfo.h"
22 #include "clang/Frontend/CodeGenOptions.h"
23 #include "clang/AST/ASTContext.h"
24 #include "clang/AST/CharUnits.h"
25 #include "clang/AST/DeclObjC.h"
26 #include "clang/AST/DeclCXX.h"
27 #include "clang/AST/DeclTemplate.h"
28 #include "clang/AST/Mangle.h"
29 #include "clang/AST/RecordLayout.h"
30 #include "clang/Basic/Builtins.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;
47 static CGCXXABI &createCXXABI(CodeGenModule &CGM) {
48 switch (CGM.getContext().Target.getCXXABI()) {
49 case CXXABI_ARM: return *CreateARMCXXABI(CGM);
50 case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM);
51 case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM);
54 llvm_unreachable("invalid C++ ABI kind");
55 return *CreateItaniumCXXABI(CGM);
59 CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
60 llvm::Module &M, const llvm::TargetData &TD,
62 : Context(C), Features(C.getLangOptions()), CodeGenOpts(CGO), TheModule(M),
63 TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags),
64 ABI(createCXXABI(*this)),
65 Types(C, M, TD, getTargetCodeGenInfo().getABIInfo(), ABI),
67 VTables(*this), Runtime(0), DebugInfo(0),
68 CFConstantStringClassRef(0), ConstantStringClassRef(0),
69 VMContext(M.getContext()),
70 NSConcreteGlobalBlockDecl(0), NSConcreteStackBlockDecl(0),
71 NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
72 BlockObjectAssignDecl(0), BlockObjectDisposeDecl(0),
73 BlockObjectAssign(0), BlockObjectDispose(0),
74 BlockDescriptorType(0), GenericBlockLiteralType(0) {
78 // Enable TBAA unless it's suppressed.
79 if (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)
80 TBAA = new CodeGenTBAA(Context, VMContext, getLangOptions(),
81 ABI.getMangleContext());
83 // If debug info or coverage generation is enabled, create the CGDebugInfo
85 if (CodeGenOpts.DebugInfo || CodeGenOpts.EmitGcovArcs ||
86 CodeGenOpts.EmitGcovNotes)
87 DebugInfo = new CGDebugInfo(*this);
89 Block.GlobalUniqueCount = 0;
91 // Initialize the type cache.
92 llvm::LLVMContext &LLVMContext = M.getContext();
93 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
94 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
95 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
96 PointerWidthInBits = C.Target.getPointerWidth(0);
98 C.toCharUnitsFromBits(C.Target.getPointerAlign(0)).getQuantity();
99 IntTy = llvm::IntegerType::get(LLVMContext, C.Target.getIntWidth());
100 IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
101 Int8PtrTy = Int8Ty->getPointerTo(0);
102 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
105 CodeGenModule::~CodeGenModule() {
112 void CodeGenModule::createObjCRuntime() {
113 if (!Features.NeXTRuntime)
114 Runtime = CreateGNUObjCRuntime(*this);
116 Runtime = CreateMacObjCRuntime(*this);
119 void CodeGenModule::Release() {
121 EmitCXXGlobalInitFunc();
122 EmitCXXGlobalDtorFunc();
124 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
125 AddGlobalCtor(ObjCInitFunction);
126 EmitCtorList(GlobalCtors, "llvm.global_ctors");
127 EmitCtorList(GlobalDtors, "llvm.global_dtors");
131 SimplifyPersonality();
133 if (getCodeGenOpts().EmitDeclMetadata)
137 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
138 // Make sure that this type is translated.
139 Types.UpdateCompletedType(TD);
141 DebugInfo->UpdateCompletedType(TD);
144 llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
147 return TBAA->getTBAAInfo(QTy);
150 void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
151 llvm::MDNode *TBAAInfo) {
152 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
155 bool CodeGenModule::isTargetDarwin() const {
156 return getContext().Target.getTriple().isOSDarwin();
159 void CodeGenModule::Error(SourceLocation loc, llvm::StringRef error) {
160 unsigned diagID = getDiags().getCustomDiagID(Diagnostic::Error, error);
161 getDiags().Report(Context.getFullLoc(loc), diagID);
164 /// ErrorUnsupported - Print out an error that codegen doesn't support the
165 /// specified stmt yet.
166 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
168 if (OmitOnError && getDiags().hasErrorOccurred())
170 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
171 "cannot compile this %0 yet");
172 std::string Msg = Type;
173 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
174 << Msg << S->getSourceRange();
177 /// ErrorUnsupported - Print out an error that codegen doesn't support the
178 /// specified decl yet.
179 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
181 if (OmitOnError && getDiags().hasErrorOccurred())
183 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
184 "cannot compile this %0 yet");
185 std::string Msg = Type;
186 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
189 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
190 const NamedDecl *D) const {
191 // Internal definitions always have default visibility.
192 if (GV->hasLocalLinkage()) {
193 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
197 // Set visibility for definitions.
198 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
199 if (LV.visibilityExplicit() || !GV->hasAvailableExternallyLinkage())
200 GV->setVisibility(GetLLVMVisibility(LV.visibility()));
203 /// Set the symbol visibility of type information (vtable and RTTI)
204 /// associated with the given type.
205 void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
206 const CXXRecordDecl *RD,
207 TypeVisibilityKind TVK) const {
208 setGlobalVisibility(GV, RD);
210 if (!CodeGenOpts.HiddenWeakVTables)
213 // We never want to drop the visibility for RTTI names.
214 if (TVK == TVK_ForRTTIName)
217 // We want to drop the visibility to hidden for weak type symbols.
218 // This isn't possible if there might be unresolved references
219 // elsewhere that rely on this symbol being visible.
221 // This should be kept roughly in sync with setThunkVisibility
225 if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
226 GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
229 // Don't override an explicit visibility attribute.
230 if (RD->getExplicitVisibility())
233 switch (RD->getTemplateSpecializationKind()) {
234 // We have to disable the optimization if this is an EI definition
235 // because there might be EI declarations in other shared objects.
236 case TSK_ExplicitInstantiationDefinition:
237 case TSK_ExplicitInstantiationDeclaration:
240 // Every use of a non-template class's type information has to emit it.
244 // In theory, implicit instantiations can ignore the possibility of
245 // an explicit instantiation declaration because there necessarily
246 // must be an EI definition somewhere with default visibility. In
247 // practice, it's possible to have an explicit instantiation for
248 // an arbitrary template class, and linkers aren't necessarily able
249 // to deal with mixed-visibility symbols.
250 case TSK_ExplicitSpecialization:
251 case TSK_ImplicitInstantiation:
252 if (!CodeGenOpts.HiddenWeakTemplateVTables)
257 // If there's a key function, there may be translation units
258 // that don't have the key function's definition. But ignore
259 // this if we're emitting RTTI under -fno-rtti.
260 if (!(TVK != TVK_ForRTTI) || Features.RTTI) {
261 if (Context.getKeyFunction(RD))
265 // Otherwise, drop the visibility to hidden.
266 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
267 GV->setUnnamedAddr(true);
270 llvm::StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
271 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
273 llvm::StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
277 if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
278 IdentifierInfo *II = ND->getIdentifier();
279 assert(II && "Attempt to mangle unnamed decl.");
285 llvm::SmallString<256> Buffer;
286 llvm::raw_svector_ostream Out(Buffer);
287 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
288 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
289 else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
290 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
291 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
292 getCXXABI().getMangleContext().mangleBlock(BD, Out);
294 getCXXABI().getMangleContext().mangleName(ND, Out);
296 // Allocate space for the mangled name.
298 size_t Length = Buffer.size();
299 char *Name = MangledNamesAllocator.Allocate<char>(Length);
300 std::copy(Buffer.begin(), Buffer.end(), Name);
302 Str = llvm::StringRef(Name, Length);
307 void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
308 const BlockDecl *BD) {
309 MangleContext &MangleCtx = getCXXABI().getMangleContext();
310 const Decl *D = GD.getDecl();
311 llvm::raw_svector_ostream Out(Buffer.getBuffer());
313 MangleCtx.mangleGlobalBlock(BD, Out);
314 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
315 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
316 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
317 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
319 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
322 llvm::GlobalValue *CodeGenModule::GetGlobalValue(llvm::StringRef Name) {
323 return getModule().getNamedValue(Name);
326 /// AddGlobalCtor - Add a function to the list that will be called before
328 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
329 // FIXME: Type coercion of void()* types.
330 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
333 /// AddGlobalDtor - Add a function to the list that will be called
334 /// when the module is unloaded.
335 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
336 // FIXME: Type coercion of void()* types.
337 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
340 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
341 // Ctor function type is void()*.
342 llvm::FunctionType* CtorFTy =
343 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false);
344 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
346 // Get the type of a ctor entry, { i32, void ()* }.
347 llvm::StructType* CtorStructTy =
348 llvm::StructType::get(VMContext, llvm::Type::getInt32Ty(VMContext),
349 llvm::PointerType::getUnqual(CtorFTy), NULL);
351 // Construct the constructor and destructor arrays.
352 std::vector<llvm::Constant*> Ctors;
353 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
354 std::vector<llvm::Constant*> S;
355 S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
357 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
358 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
361 if (!Ctors.empty()) {
362 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
363 new llvm::GlobalVariable(TheModule, AT, false,
364 llvm::GlobalValue::AppendingLinkage,
365 llvm::ConstantArray::get(AT, Ctors),
370 void CodeGenModule::EmitAnnotations() {
371 if (Annotations.empty())
374 // Create a new global variable for the ConstantStruct in the Module.
375 llvm::Constant *Array =
376 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
379 llvm::GlobalValue *gv =
380 new llvm::GlobalVariable(TheModule, Array->getType(), false,
381 llvm::GlobalValue::AppendingLinkage, Array,
382 "llvm.global.annotations");
383 gv->setSection("llvm.metadata");
386 llvm::GlobalValue::LinkageTypes
387 CodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
388 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
390 if (Linkage == GVA_Internal)
391 return llvm::Function::InternalLinkage;
393 if (D->hasAttr<DLLExportAttr>())
394 return llvm::Function::DLLExportLinkage;
396 if (D->hasAttr<WeakAttr>())
397 return llvm::Function::WeakAnyLinkage;
399 // In C99 mode, 'inline' functions are guaranteed to have a strong
400 // definition somewhere else, so we can use available_externally linkage.
401 if (Linkage == GVA_C99Inline)
402 return llvm::Function::AvailableExternallyLinkage;
404 // In C++, the compiler has to emit a definition in every translation unit
405 // that references the function. We should use linkonce_odr because
406 // a) if all references in this translation unit are optimized away, we
407 // don't need to codegen it. b) if the function persists, it needs to be
408 // merged with other definitions. c) C++ has the ODR, so we know the
409 // definition is dependable.
410 if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
411 return !Context.getLangOptions().AppleKext
412 ? llvm::Function::LinkOnceODRLinkage
413 : llvm::Function::InternalLinkage;
415 // An explicit instantiation of a template has weak linkage, since
416 // explicit instantiations can occur in multiple translation units
417 // and must all be equivalent. However, we are not allowed to
418 // throw away these explicit instantiations.
419 if (Linkage == GVA_ExplicitTemplateInstantiation)
420 return !Context.getLangOptions().AppleKext
421 ? llvm::Function::WeakODRLinkage
422 : llvm::Function::InternalLinkage;
424 // Otherwise, we have strong external linkage.
425 assert(Linkage == GVA_StrongExternal);
426 return llvm::Function::ExternalLinkage;
430 /// SetFunctionDefinitionAttributes - Set attributes for a global.
432 /// FIXME: This is currently only done for aliases and functions, but not for
433 /// variables (these details are set in EmitGlobalVarDefinition for variables).
434 void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
435 llvm::GlobalValue *GV) {
436 SetCommonAttributes(D, GV);
439 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
440 const CGFunctionInfo &Info,
442 unsigned CallingConv;
443 AttributeListType AttributeList;
444 ConstructAttributeList(Info, D, AttributeList, CallingConv);
445 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
446 AttributeList.size()));
447 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
450 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
452 if (!Features.Exceptions && !Features.ObjCNonFragileABI)
453 F->addFnAttr(llvm::Attribute::NoUnwind);
455 if (D->hasAttr<AlwaysInlineAttr>())
456 F->addFnAttr(llvm::Attribute::AlwaysInline);
458 if (D->hasAttr<NakedAttr>())
459 F->addFnAttr(llvm::Attribute::Naked);
461 if (D->hasAttr<NoInlineAttr>())
462 F->addFnAttr(llvm::Attribute::NoInline);
464 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
465 F->setUnnamedAddr(true);
467 if (Features.getStackProtectorMode() == LangOptions::SSPOn)
468 F->addFnAttr(llvm::Attribute::StackProtect);
469 else if (Features.getStackProtectorMode() == LangOptions::SSPReq)
470 F->addFnAttr(llvm::Attribute::StackProtectReq);
472 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
474 F->setAlignment(alignment);
476 // C++ ABI requires 2-byte alignment for member functions.
477 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
481 void CodeGenModule::SetCommonAttributes(const Decl *D,
482 llvm::GlobalValue *GV) {
483 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
484 setGlobalVisibility(GV, ND);
486 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
488 if (D->hasAttr<UsedAttr>())
491 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
492 GV->setSection(SA->getName());
494 getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
497 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
499 const CGFunctionInfo &FI) {
500 SetLLVMFunctionAttributes(D, FI, F);
501 SetLLVMFunctionAttributesForDefinition(D, F);
503 F->setLinkage(llvm::Function::InternalLinkage);
505 SetCommonAttributes(D, F);
508 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
510 bool IsIncompleteFunction) {
511 if (unsigned IID = F->getIntrinsicID()) {
512 // If this is an intrinsic function, set the function's attributes
513 // to the intrinsic's attributes.
514 F->setAttributes(llvm::Intrinsic::getAttributes((llvm::Intrinsic::ID)IID));
518 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
520 if (!IsIncompleteFunction)
521 SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(GD), F);
523 // Only a few attributes are set on declarations; these may later be
524 // overridden by a definition.
526 if (FD->hasAttr<DLLImportAttr>()) {
527 F->setLinkage(llvm::Function::DLLImportLinkage);
528 } else if (FD->hasAttr<WeakAttr>() ||
529 FD->isWeakImported()) {
530 // "extern_weak" is overloaded in LLVM; we probably should have
531 // separate linkage types for this.
532 F->setLinkage(llvm::Function::ExternalWeakLinkage);
534 F->setLinkage(llvm::Function::ExternalLinkage);
536 NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility();
537 if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) {
538 F->setVisibility(GetLLVMVisibility(LV.visibility()));
542 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
543 F->setSection(SA->getName());
546 void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
547 assert(!GV->isDeclaration() &&
548 "Only globals with definition can force usage.");
549 LLVMUsed.push_back(GV);
552 void CodeGenModule::EmitLLVMUsed() {
553 // Don't create llvm.used if there is no need.
554 if (LLVMUsed.empty())
557 const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext);
559 // Convert LLVMUsed to what ConstantArray needs.
560 std::vector<llvm::Constant*> UsedArray;
561 UsedArray.resize(LLVMUsed.size());
562 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
564 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
568 if (UsedArray.empty())
570 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size());
572 llvm::GlobalVariable *GV =
573 new llvm::GlobalVariable(getModule(), ATy, false,
574 llvm::GlobalValue::AppendingLinkage,
575 llvm::ConstantArray::get(ATy, UsedArray),
578 GV->setSection("llvm.metadata");
581 void CodeGenModule::EmitDeferred() {
582 // Emit code for any potentially referenced deferred decls. Since a
583 // previously unused static decl may become used during the generation of code
584 // for a static function, iterate until no changes are made.
586 while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) {
587 if (!DeferredVTables.empty()) {
588 const CXXRecordDecl *RD = DeferredVTables.back();
589 DeferredVTables.pop_back();
590 getVTables().GenerateClassData(getVTableLinkage(RD), RD);
594 GlobalDecl D = DeferredDeclsToEmit.back();
595 DeferredDeclsToEmit.pop_back();
597 // Check to see if we've already emitted this. This is necessary
598 // for a couple of reasons: first, decls can end up in the
599 // deferred-decls queue multiple times, and second, decls can end
600 // up with definitions in unusual ways (e.g. by an extern inline
601 // function acquiring a strong function redefinition). Just
602 // ignore these cases.
604 // TODO: That said, looking this up multiple times is very wasteful.
605 llvm::StringRef Name = getMangledName(D);
606 llvm::GlobalValue *CGRef = GetGlobalValue(Name);
607 assert(CGRef && "Deferred decl wasn't referenced?");
609 if (!CGRef->isDeclaration())
612 // GlobalAlias::isDeclaration() defers to the aliasee, but for our
613 // purposes an alias counts as a definition.
614 if (isa<llvm::GlobalAlias>(CGRef))
617 // Otherwise, emit the definition and move on to the next one.
618 EmitGlobalDefinition(D);
622 /// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
623 /// annotation information for a given GlobalValue. The annotation struct is
624 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
625 /// GlobalValue being annotated. The second field is the constant string
626 /// created from the AnnotateAttr's annotation. The third field is a constant
627 /// string containing the name of the translation unit. The fourth field is
628 /// the line number in the file of the annotated value declaration.
630 /// FIXME: this does not unique the annotation string constants, as llvm-gcc
633 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
634 const AnnotateAttr *AA,
636 llvm::Module *M = &getModule();
638 // get [N x i8] constants for the annotation string, and the filename string
639 // which are the 2nd and 3rd elements of the global annotation structure.
640 const llvm::Type *SBP = llvm::Type::getInt8PtrTy(VMContext);
641 llvm::Constant *anno = llvm::ConstantArray::get(VMContext,
642 AA->getAnnotation(), true);
643 llvm::Constant *unit = llvm::ConstantArray::get(VMContext,
644 M->getModuleIdentifier(),
647 // Get the two global values corresponding to the ConstantArrays we just
648 // created to hold the bytes of the strings.
649 llvm::GlobalValue *annoGV =
650 new llvm::GlobalVariable(*M, anno->getType(), false,
651 llvm::GlobalValue::PrivateLinkage, anno,
653 // translation unit name string, emitted into the llvm.metadata section.
654 llvm::GlobalValue *unitGV =
655 new llvm::GlobalVariable(*M, unit->getType(), false,
656 llvm::GlobalValue::PrivateLinkage, unit,
658 unitGV->setUnnamedAddr(true);
660 // Create the ConstantStruct for the global annotation.
661 llvm::Constant *Fields[4] = {
662 llvm::ConstantExpr::getBitCast(GV, SBP),
663 llvm::ConstantExpr::getBitCast(annoGV, SBP),
664 llvm::ConstantExpr::getBitCast(unitGV, SBP),
665 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo)
667 return llvm::ConstantStruct::get(VMContext, Fields, 4, false);
670 bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
671 // Never defer when EmitAllDecls is specified.
672 if (Features.EmitAllDecls)
675 return !getContext().DeclMustBeEmitted(Global);
678 llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
679 const AliasAttr *AA = VD->getAttr<AliasAttr>();
680 assert(AA && "No alias?");
682 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
684 // See if there is already something with the target's name in the module.
685 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
687 llvm::Constant *Aliasee;
688 if (isa<llvm::FunctionType>(DeclTy))
689 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
690 /*ForVTable=*/false);
692 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
693 llvm::PointerType::getUnqual(DeclTy), 0);
695 llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
696 F->setLinkage(llvm::Function::ExternalWeakLinkage);
697 WeakRefReferences.insert(F);
703 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
704 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
706 // Weak references don't produce any output by themselves.
707 if (Global->hasAttr<WeakRefAttr>())
710 // If this is an alias definition (which otherwise looks like a declaration)
712 if (Global->hasAttr<AliasAttr>())
713 return EmitAliasDefinition(GD);
715 // Ignore declarations, they will be emitted on their first use.
716 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
717 if (FD->getIdentifier()) {
718 llvm::StringRef Name = FD->getName();
719 if (Name == "_Block_object_assign") {
720 BlockObjectAssignDecl = FD;
721 } else if (Name == "_Block_object_dispose") {
722 BlockObjectDisposeDecl = FD;
726 // Forward declarations are emitted lazily on first use.
727 if (!FD->isThisDeclarationADefinition())
730 const VarDecl *VD = cast<VarDecl>(Global);
731 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
733 if (VD->getIdentifier()) {
734 llvm::StringRef Name = VD->getName();
735 if (Name == "_NSConcreteGlobalBlock") {
736 NSConcreteGlobalBlockDecl = VD;
737 } else if (Name == "_NSConcreteStackBlock") {
738 NSConcreteStackBlockDecl = VD;
743 if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
747 // Defer code generation when possible if this is a static definition, inline
748 // function etc. These we only want to emit if they are used.
749 if (!MayDeferGeneration(Global)) {
750 // Emit the definition if it can't be deferred.
751 EmitGlobalDefinition(GD);
755 // If we're deferring emission of a C++ variable with an
756 // initializer, remember the order in which it appeared in the file.
757 if (getLangOptions().CPlusPlus && isa<VarDecl>(Global) &&
758 cast<VarDecl>(Global)->hasInit()) {
759 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
760 CXXGlobalInits.push_back(0);
763 // If the value has already been used, add it directly to the
764 // DeferredDeclsToEmit list.
765 llvm::StringRef MangledName = getMangledName(GD);
766 if (GetGlobalValue(MangledName))
767 DeferredDeclsToEmit.push_back(GD);
769 // Otherwise, remember that we saw a deferred decl with this name. The
770 // first use of the mangled name will cause it to move into
771 // DeferredDeclsToEmit.
772 DeferredDecls[MangledName] = GD;
776 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
777 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
779 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
780 Context.getSourceManager(),
781 "Generating code for declaration");
783 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
784 // At -O0, don't generate IR for functions with available_externally
786 if (CodeGenOpts.OptimizationLevel == 0 &&
787 !Function->hasAttr<AlwaysInlineAttr>() &&
788 getFunctionLinkage(Function)
789 == llvm::Function::AvailableExternallyLinkage)
792 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
793 if (Method->isVirtual())
794 getVTables().EmitThunks(GD);
796 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
797 return EmitCXXConstructor(CD, GD.getCtorType());
799 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(Method))
800 return EmitCXXDestructor(DD, GD.getDtorType());
803 return EmitGlobalFunctionDefinition(GD);
806 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
807 return EmitGlobalVarDefinition(VD);
809 assert(0 && "Invalid argument to EmitGlobalDefinition()");
812 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
813 /// module, create and return an llvm Function with the specified type. If there
814 /// is something in the module with the specified name, return it potentially
815 /// bitcasted to the right type.
817 /// If D is non-null, it specifies a decl that correspond to this. This is used
818 /// to set the attributes on the function when it is first created.
820 CodeGenModule::GetOrCreateLLVMFunction(llvm::StringRef MangledName,
821 const llvm::Type *Ty,
822 GlobalDecl D, bool ForVTable) {
823 // Lookup the entry, lazily creating it if necessary.
824 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
826 if (WeakRefReferences.count(Entry)) {
827 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
828 if (FD && !FD->hasAttr<WeakAttr>())
829 Entry->setLinkage(llvm::Function::ExternalLinkage);
831 WeakRefReferences.erase(Entry);
834 if (Entry->getType()->getElementType() == Ty)
837 // Make sure the result is of the correct type.
838 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
839 return llvm::ConstantExpr::getBitCast(Entry, PTy);
842 // This function doesn't have a complete type (for example, the return
843 // type is an incomplete struct). Use a fake type instead, and make
844 // sure not to try to set attributes.
845 bool IsIncompleteFunction = false;
847 const llvm::FunctionType *FTy;
848 if (isa<llvm::FunctionType>(Ty)) {
849 FTy = cast<llvm::FunctionType>(Ty);
851 FTy = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false);
852 IsIncompleteFunction = true;
855 llvm::Function *F = llvm::Function::Create(FTy,
856 llvm::Function::ExternalLinkage,
857 MangledName, &getModule());
858 assert(F->getName() == MangledName && "name was uniqued!");
860 SetFunctionAttributes(D, F, IsIncompleteFunction);
862 // This is the first use or definition of a mangled name. If there is a
863 // deferred decl with this name, remember that we need to emit it at the end
865 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
866 if (DDI != DeferredDecls.end()) {
867 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
868 // list, and remove it from DeferredDecls (since we don't need it anymore).
869 DeferredDeclsToEmit.push_back(DDI->second);
870 DeferredDecls.erase(DDI);
872 // Otherwise, there are cases we have to worry about where we're
873 // using a declaration for which we must emit a definition but where
874 // we might not find a top-level definition:
875 // - member functions defined inline in their classes
876 // - friend functions defined inline in some class
877 // - special member functions with implicit definitions
878 // If we ever change our AST traversal to walk into class methods,
879 // this will be unnecessary.
881 // We also don't emit a definition for a function if it's going to be an entry
882 // in a vtable, unless it's already marked as used.
883 } else if (getLangOptions().CPlusPlus && D.getDecl()) {
884 // Look for a declaration that's lexically in a record.
885 const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl());
887 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
888 if (FD->isImplicit() && !ForVTable) {
889 assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
890 DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
892 } else if (FD->isThisDeclarationADefinition()) {
893 DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
897 FD = FD->getPreviousDeclaration();
901 // Make sure the result is of the requested type.
902 if (!IsIncompleteFunction) {
903 assert(F->getType()->getElementType() == Ty);
907 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
908 return llvm::ConstantExpr::getBitCast(F, PTy);
911 /// GetAddrOfFunction - Return the address of the given function. If Ty is
912 /// non-null, then this function will use the specified type if it has to
913 /// create it (this occurs when we see a definition of the function).
914 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
915 const llvm::Type *Ty,
917 // If there was no specific requested type, just convert it now.
919 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
921 llvm::StringRef MangledName = getMangledName(GD);
922 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable);
925 /// CreateRuntimeFunction - Create a new runtime function with the specified
928 CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
929 llvm::StringRef Name) {
930 return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false);
933 static bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D) {
934 if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType())
936 if (Context.getLangOptions().CPlusPlus &&
937 Context.getBaseElementType(D->getType())->getAs<RecordType>()) {
938 // FIXME: We should do something fancier here!
944 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
945 /// create and return an llvm GlobalVariable with the specified type. If there
946 /// is something in the module with the specified name, return it potentially
947 /// bitcasted to the right type.
949 /// If D is non-null, it specifies a decl that correspond to this. This is used
950 /// to set the attributes on the global when it is first created.
952 CodeGenModule::GetOrCreateLLVMGlobal(llvm::StringRef MangledName,
953 const llvm::PointerType *Ty,
956 // Lookup the entry, lazily creating it if necessary.
957 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
959 if (WeakRefReferences.count(Entry)) {
960 if (D && !D->hasAttr<WeakAttr>())
961 Entry->setLinkage(llvm::Function::ExternalLinkage);
963 WeakRefReferences.erase(Entry);
967 Entry->setUnnamedAddr(true);
969 if (Entry->getType() == Ty)
972 // Make sure the result is of the correct type.
973 return llvm::ConstantExpr::getBitCast(Entry, Ty);
976 // This is the first use or definition of a mangled name. If there is a
977 // deferred decl with this name, remember that we need to emit it at the end
979 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
980 if (DDI != DeferredDecls.end()) {
981 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
982 // list, and remove it from DeferredDecls (since we don't need it anymore).
983 DeferredDeclsToEmit.push_back(DDI->second);
984 DeferredDecls.erase(DDI);
987 llvm::GlobalVariable *GV =
988 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
989 llvm::GlobalValue::ExternalLinkage,
991 false, Ty->getAddressSpace());
993 // Handle things which are present even on external declarations.
995 // FIXME: This code is overly simple and should be merged with other global
997 GV->setConstant(DeclIsConstantGlobal(Context, D));
999 // Set linkage and visibility in case we never see a definition.
1000 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
1001 if (LV.linkage() != ExternalLinkage) {
1002 // Don't set internal linkage on declarations.
1004 if (D->hasAttr<DLLImportAttr>())
1005 GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
1006 else if (D->hasAttr<WeakAttr>() || D->isWeakImported())
1007 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1009 // Set visibility on a declaration only if it's explicit.
1010 if (LV.visibilityExplicit())
1011 GV->setVisibility(GetLLVMVisibility(LV.visibility()));
1014 GV->setThreadLocal(D->isThreadSpecified());
1021 llvm::GlobalVariable *
1022 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(llvm::StringRef Name,
1023 const llvm::Type *Ty,
1024 llvm::GlobalValue::LinkageTypes Linkage) {
1025 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
1026 llvm::GlobalVariable *OldGV = 0;
1030 // Check if the variable has the right type.
1031 if (GV->getType()->getElementType() == Ty)
1034 // Because C++ name mangling, the only way we can end up with an already
1035 // existing global with the same name is if it has been declared extern "C".
1036 assert(GV->isDeclaration() && "Declaration has wrong type!");
1040 // Create a new variable.
1041 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
1045 // Replace occurrences of the old variable if needed.
1046 GV->takeName(OldGV);
1048 if (!OldGV->use_empty()) {
1049 llvm::Constant *NewPtrForOldDecl =
1050 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1051 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1054 OldGV->eraseFromParent();
1060 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1061 /// given global variable. If Ty is non-null and if the global doesn't exist,
1062 /// then it will be greated with the specified type instead of whatever the
1063 /// normal requested type would be.
1064 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
1065 const llvm::Type *Ty) {
1066 assert(D->hasGlobalStorage() && "Not a global variable");
1067 QualType ASTTy = D->getType();
1069 Ty = getTypes().ConvertTypeForMem(ASTTy);
1071 const llvm::PointerType *PTy =
1072 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
1074 llvm::StringRef MangledName = getMangledName(D);
1075 return GetOrCreateLLVMGlobal(MangledName, PTy, D);
1078 /// CreateRuntimeVariable - Create a new runtime global variable with the
1079 /// specified type and name.
1081 CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
1082 llvm::StringRef Name) {
1083 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
1087 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1088 assert(!D->getInit() && "Cannot emit definite definitions here!");
1090 if (MayDeferGeneration(D)) {
1091 // If we have not seen a reference to this variable yet, place it
1092 // into the deferred declarations table to be emitted if needed
1094 llvm::StringRef MangledName = getMangledName(D);
1095 if (!GetGlobalValue(MangledName)) {
1096 DeferredDecls[MangledName] = D;
1101 // The tentative definition is the only definition.
1102 EmitGlobalVarDefinition(D);
1105 void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) {
1106 if (DefinitionRequired)
1107 getVTables().GenerateClassData(getVTableLinkage(Class), Class);
1110 llvm::GlobalVariable::LinkageTypes
1111 CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
1112 if (RD->isInAnonymousNamespace() || !RD->hasLinkage())
1113 return llvm::GlobalVariable::InternalLinkage;
1115 if (const CXXMethodDecl *KeyFunction
1116 = RD->getASTContext().getKeyFunction(RD)) {
1117 // If this class has a key function, use that to determine the linkage of
1119 const FunctionDecl *Def = 0;
1120 if (KeyFunction->hasBody(Def))
1121 KeyFunction = cast<CXXMethodDecl>(Def);
1123 switch (KeyFunction->getTemplateSpecializationKind()) {
1124 case TSK_Undeclared:
1125 case TSK_ExplicitSpecialization:
1126 // When compiling with optimizations turned on, we emit all vtables,
1127 // even if the key function is not defined in the current translation
1128 // unit. If this is the case, use available_externally linkage.
1129 if (!Def && CodeGenOpts.OptimizationLevel)
1130 return llvm::GlobalVariable::AvailableExternallyLinkage;
1132 if (KeyFunction->isInlined())
1133 return !Context.getLangOptions().AppleKext ?
1134 llvm::GlobalVariable::LinkOnceODRLinkage :
1135 llvm::Function::InternalLinkage;
1137 return llvm::GlobalVariable::ExternalLinkage;
1139 case TSK_ImplicitInstantiation:
1140 return !Context.getLangOptions().AppleKext ?
1141 llvm::GlobalVariable::LinkOnceODRLinkage :
1142 llvm::Function::InternalLinkage;
1144 case TSK_ExplicitInstantiationDefinition:
1145 return !Context.getLangOptions().AppleKext ?
1146 llvm::GlobalVariable::WeakODRLinkage :
1147 llvm::Function::InternalLinkage;
1149 case TSK_ExplicitInstantiationDeclaration:
1150 // FIXME: Use available_externally linkage. However, this currently
1151 // breaks LLVM's build due to undefined symbols.
1152 // return llvm::GlobalVariable::AvailableExternallyLinkage;
1153 return !Context.getLangOptions().AppleKext ?
1154 llvm::GlobalVariable::LinkOnceODRLinkage :
1155 llvm::Function::InternalLinkage;
1159 if (Context.getLangOptions().AppleKext)
1160 return llvm::Function::InternalLinkage;
1162 switch (RD->getTemplateSpecializationKind()) {
1163 case TSK_Undeclared:
1164 case TSK_ExplicitSpecialization:
1165 case TSK_ImplicitInstantiation:
1166 // FIXME: Use available_externally linkage. However, this currently
1167 // breaks LLVM's build due to undefined symbols.
1168 // return llvm::GlobalVariable::AvailableExternallyLinkage;
1169 case TSK_ExplicitInstantiationDeclaration:
1170 return llvm::GlobalVariable::LinkOnceODRLinkage;
1172 case TSK_ExplicitInstantiationDefinition:
1173 return llvm::GlobalVariable::WeakODRLinkage;
1176 // Silence GCC warning.
1177 return llvm::GlobalVariable::LinkOnceODRLinkage;
1180 CharUnits CodeGenModule::GetTargetTypeStoreSize(const llvm::Type *Ty) const {
1181 return Context.toCharUnitsFromBits(
1182 TheTargetData.getTypeStoreSizeInBits(Ty));
1185 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
1186 llvm::Constant *Init = 0;
1187 QualType ASTTy = D->getType();
1188 bool NonConstInit = false;
1190 const Expr *InitExpr = D->getAnyInitializer();
1193 // This is a tentative definition; tentative definitions are
1194 // implicitly initialized with { 0 }.
1196 // Note that tentative definitions are only emitted at the end of
1197 // a translation unit, so they should never have incomplete
1198 // type. In addition, EmitTentativeDefinition makes sure that we
1199 // never attempt to emit a tentative definition if a real one
1200 // exists. A use may still exists, however, so we still may need
1202 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
1203 Init = EmitNullConstant(D->getType());
1205 Init = EmitConstantExpr(InitExpr, D->getType());
1207 QualType T = InitExpr->getType();
1208 if (D->getType()->isReferenceType())
1211 if (getLangOptions().CPlusPlus) {
1212 Init = EmitNullConstant(T);
1213 NonConstInit = true;
1215 ErrorUnsupported(D, "static initializer");
1216 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1219 // We don't need an initializer, so remove the entry for the delayed
1220 // initializer position (just in case this entry was delayed).
1221 if (getLangOptions().CPlusPlus)
1222 DelayedCXXInitPosition.erase(D);
1226 const llvm::Type* InitType = Init->getType();
1227 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
1229 // Strip off a bitcast if we got one back.
1230 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1231 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1232 // all zero index gep.
1233 CE->getOpcode() == llvm::Instruction::GetElementPtr);
1234 Entry = CE->getOperand(0);
1237 // Entry is now either a Function or GlobalVariable.
1238 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
1240 // We have a definition after a declaration with the wrong type.
1241 // We must make a new GlobalVariable* and update everything that used OldGV
1242 // (a declaration or tentative definition) with the new GlobalVariable*
1243 // (which will be a definition).
1245 // This happens if there is a prototype for a global (e.g.
1246 // "extern int x[];") and then a definition of a different type (e.g.
1247 // "int x[10];"). This also happens when an initializer has a different type
1248 // from the type of the global (this happens with unions).
1250 GV->getType()->getElementType() != InitType ||
1251 GV->getType()->getAddressSpace() !=
1252 getContext().getTargetAddressSpace(ASTTy)) {
1254 // Move the old entry aside so that we'll create a new one.
1255 Entry->setName(llvm::StringRef());
1257 // Make a new global with the correct type, this is now guaranteed to work.
1258 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
1260 // Replace all uses of the old global with the new global
1261 llvm::Constant *NewPtrForOldDecl =
1262 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
1263 Entry->replaceAllUsesWith(NewPtrForOldDecl);
1265 // Erase the old global, since it is no longer used.
1266 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
1269 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
1270 SourceManager &SM = Context.getSourceManager();
1271 AddAnnotation(EmitAnnotateAttr(GV, AA,
1272 SM.getInstantiationLineNumber(D->getLocation())));
1275 GV->setInitializer(Init);
1277 // If it is safe to mark the global 'constant', do so now.
1278 GV->setConstant(false);
1279 if (!NonConstInit && DeclIsConstantGlobal(Context, D))
1280 GV->setConstant(true);
1282 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
1284 // Set the llvm linkage type as appropriate.
1285 llvm::GlobalValue::LinkageTypes Linkage =
1286 GetLLVMLinkageVarDefinition(D, GV);
1287 GV->setLinkage(Linkage);
1288 if (Linkage == llvm::GlobalVariable::CommonLinkage)
1289 // common vars aren't constant even if declared const.
1290 GV->setConstant(false);
1292 SetCommonAttributes(D, GV);
1294 // Emit the initializer function if necessary.
1296 EmitCXXGlobalVarDeclInitFunc(D, GV);
1298 // Emit global variable debug information.
1299 if (CGDebugInfo *DI = getModuleDebugInfo()) {
1300 DI->setLocation(D->getLocation());
1301 DI->EmitGlobalVariable(GV, D);
1305 llvm::GlobalValue::LinkageTypes
1306 CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
1307 llvm::GlobalVariable *GV) {
1308 GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1309 if (Linkage == GVA_Internal)
1310 return llvm::Function::InternalLinkage;
1311 else if (D->hasAttr<DLLImportAttr>())
1312 return llvm::Function::DLLImportLinkage;
1313 else if (D->hasAttr<DLLExportAttr>())
1314 return llvm::Function::DLLExportLinkage;
1315 else if (D->hasAttr<WeakAttr>()) {
1316 if (GV->isConstant())
1317 return llvm::GlobalVariable::WeakODRLinkage;
1319 return llvm::GlobalVariable::WeakAnyLinkage;
1320 } else if (Linkage == GVA_TemplateInstantiation ||
1321 Linkage == GVA_ExplicitTemplateInstantiation)
1322 return llvm::GlobalVariable::WeakODRLinkage;
1323 else if (!getLangOptions().CPlusPlus &&
1324 ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
1325 D->getAttr<CommonAttr>()) &&
1326 !D->hasExternalStorage() && !D->getInit() &&
1327 !D->getAttr<SectionAttr>() && !D->isThreadSpecified()) {
1328 // Thread local vars aren't considered common linkage.
1329 return llvm::GlobalVariable::CommonLinkage;
1331 return llvm::GlobalVariable::ExternalLinkage;
1334 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
1335 /// implement a function with no prototype, e.g. "int foo() {}". If there are
1336 /// existing call uses of the old function in the module, this adjusts them to
1337 /// call the new function directly.
1339 /// This is not just a cleanup: the always_inline pass requires direct calls to
1340 /// functions to be able to inline them. If there is a bitcast in the way, it
1341 /// won't inline them. Instcombine normally deletes these calls, but it isn't
1343 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1344 llvm::Function *NewFn) {
1345 // If we're redefining a global as a function, don't transform it.
1346 llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
1347 if (OldFn == 0) return;
1349 const llvm::Type *NewRetTy = NewFn->getReturnType();
1350 llvm::SmallVector<llvm::Value*, 4> ArgList;
1352 for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
1354 // TODO: Do invokes ever occur in C code? If so, we should handle them too.
1355 llvm::Value::use_iterator I = UI++; // Increment before the CI is erased.
1356 llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I);
1357 if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I)
1358 llvm::CallSite CS(CI);
1359 if (!CI || !CS.isCallee(I)) continue;
1361 // If the return types don't match exactly, and if the call isn't dead, then
1362 // we can't transform this call.
1363 if (CI->getType() != NewRetTy && !CI->use_empty())
1366 // If the function was passed too few arguments, don't transform. If extra
1367 // arguments were passed, we silently drop them. If any of the types
1368 // mismatch, we don't transform.
1370 bool DontTransform = false;
1371 for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
1372 E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
1373 if (CS.arg_size() == ArgNo ||
1374 CS.getArgument(ArgNo)->getType() != AI->getType()) {
1375 DontTransform = true;
1382 // Okay, we can transform this. Create the new call instruction and copy
1383 // over the required information.
1384 ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo);
1385 llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(),
1386 ArgList.end(), "", CI);
1388 if (!NewCall->getType()->isVoidTy())
1389 NewCall->takeName(CI);
1390 NewCall->setAttributes(CI->getAttributes());
1391 NewCall->setCallingConv(CI->getCallingConv());
1393 // Finally, remove the old call, replacing any uses with the new one.
1394 if (!CI->use_empty())
1395 CI->replaceAllUsesWith(NewCall);
1397 // Copy debug location attached to CI.
1398 if (!CI->getDebugLoc().isUnknown())
1399 NewCall->setDebugLoc(CI->getDebugLoc());
1400 CI->eraseFromParent();
1405 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
1406 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
1408 // Compute the function info and LLVM type.
1409 const CGFunctionInfo &FI = getTypes().getFunctionInfo(GD);
1410 bool variadic = false;
1411 if (const FunctionProtoType *fpt = D->getType()->getAs<FunctionProtoType>())
1412 variadic = fpt->isVariadic();
1413 const llvm::FunctionType *Ty = getTypes().GetFunctionType(FI, variadic, false);
1415 // Get or create the prototype for the function.
1416 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
1418 // Strip off a bitcast if we got one back.
1419 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1420 assert(CE->getOpcode() == llvm::Instruction::BitCast);
1421 Entry = CE->getOperand(0);
1425 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
1426 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
1428 // If the types mismatch then we have to rewrite the definition.
1429 assert(OldFn->isDeclaration() &&
1430 "Shouldn't replace non-declaration");
1432 // F is the Function* for the one with the wrong type, we must make a new
1433 // Function* and update everything that used F (a declaration) with the new
1434 // Function* (which will be a definition).
1436 // This happens if there is a prototype for a function
1437 // (e.g. "int f()") and then a definition of a different type
1438 // (e.g. "int f(int x)"). Move the old function aside so that it
1439 // doesn't interfere with GetAddrOfFunction.
1440 OldFn->setName(llvm::StringRef());
1441 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
1443 // If this is an implementation of a function without a prototype, try to
1444 // replace any existing uses of the function (which may be calls) with uses
1445 // of the new function
1446 if (D->getType()->isFunctionNoProtoType()) {
1447 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
1448 OldFn->removeDeadConstantUsers();
1451 // Replace uses of F with the Function we will endow with a body.
1452 if (!Entry->use_empty()) {
1453 llvm::Constant *NewPtrForOldDecl =
1454 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
1455 Entry->replaceAllUsesWith(NewPtrForOldDecl);
1458 // Ok, delete the old function now, which is dead.
1459 OldFn->eraseFromParent();
1464 // We need to set linkage and visibility on the function before
1465 // generating code for it because various parts of IR generation
1466 // want to propagate this information down (e.g. to local static
1468 llvm::Function *Fn = cast<llvm::Function>(Entry);
1469 setFunctionLinkage(D, Fn);
1471 // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
1472 setGlobalVisibility(Fn, D);
1474 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
1476 SetFunctionDefinitionAttributes(D, Fn);
1477 SetLLVMFunctionAttributesForDefinition(D, Fn);
1479 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
1480 AddGlobalCtor(Fn, CA->getPriority());
1481 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
1482 AddGlobalDtor(Fn, DA->getPriority());
1485 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
1486 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
1487 const AliasAttr *AA = D->getAttr<AliasAttr>();
1488 assert(AA && "Not an alias?");
1490 llvm::StringRef MangledName = getMangledName(GD);
1492 // If there is a definition in the module, then it wins over the alias.
1493 // This is dubious, but allow it to be safe. Just ignore the alias.
1494 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1495 if (Entry && !Entry->isDeclaration())
1498 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
1500 // Create a reference to the named value. This ensures that it is emitted
1501 // if a deferred decl.
1502 llvm::Constant *Aliasee;
1503 if (isa<llvm::FunctionType>(DeclTy))
1504 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
1505 /*ForVTable=*/false);
1507 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1508 llvm::PointerType::getUnqual(DeclTy), 0);
1510 // Create the new alias itself, but don't set a name yet.
1511 llvm::GlobalValue *GA =
1512 new llvm::GlobalAlias(Aliasee->getType(),
1513 llvm::Function::ExternalLinkage,
1514 "", Aliasee, &getModule());
1517 assert(Entry->isDeclaration());
1519 // If there is a declaration in the module, then we had an extern followed
1520 // by the alias, as in:
1521 // extern int test6();
1523 // int test6() __attribute__((alias("test7")));
1525 // Remove it and replace uses of it with the alias.
1526 GA->takeName(Entry);
1528 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
1530 Entry->eraseFromParent();
1532 GA->setName(MangledName);
1535 // Set attributes which are particular to an alias; this is a
1536 // specialization of the attributes which may be set on a global
1537 // variable/function.
1538 if (D->hasAttr<DLLExportAttr>()) {
1539 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1540 // The dllexport attribute is ignored for undefined symbols.
1542 GA->setLinkage(llvm::Function::DLLExportLinkage);
1544 GA->setLinkage(llvm::Function::DLLExportLinkage);
1546 } else if (D->hasAttr<WeakAttr>() ||
1547 D->hasAttr<WeakRefAttr>() ||
1548 D->isWeakImported()) {
1549 GA->setLinkage(llvm::Function::WeakAnyLinkage);
1552 SetCommonAttributes(D, GA);
1555 /// getBuiltinLibFunction - Given a builtin id for a function like
1556 /// "__builtin_fabsf", return a Function* for "fabsf".
1557 llvm::Value *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD,
1558 unsigned BuiltinID) {
1559 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
1560 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
1563 // Get the name, skip over the __builtin_ prefix (if necessary).
1564 const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
1565 if (Context.BuiltinInfo.isLibFunction(BuiltinID))
1568 const llvm::FunctionType *Ty =
1569 cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType()));
1571 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl(FD), /*ForVTable=*/false);
1574 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
1576 return llvm::Intrinsic::getDeclaration(&getModule(),
1577 (llvm::Intrinsic::ID)IID, Tys, NumTys);
1580 static llvm::StringMapEntry<llvm::Constant*> &
1581 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1582 const StringLiteral *Literal,
1585 unsigned &StringLength) {
1586 llvm::StringRef String = Literal->getString();
1587 unsigned NumBytes = String.size();
1589 // Check for simple case.
1590 if (!Literal->containsNonAsciiOrNull()) {
1591 StringLength = NumBytes;
1592 return Map.GetOrCreateValue(String);
1595 // Otherwise, convert the UTF8 literals into a byte string.
1596 llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
1597 const UTF8 *FromPtr = (UTF8 *)String.data();
1598 UTF16 *ToPtr = &ToBuf[0];
1600 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1601 &ToPtr, ToPtr + NumBytes,
1604 // ConvertUTF8toUTF16 returns the length in ToPtr.
1605 StringLength = ToPtr - &ToBuf[0];
1607 // Render the UTF-16 string into a byte array and convert to the target byte
1610 // FIXME: This isn't something we should need to do here.
1611 llvm::SmallString<128> AsBytes;
1612 AsBytes.reserve(StringLength * 2);
1613 for (unsigned i = 0; i != StringLength; ++i) {
1614 unsigned short Val = ToBuf[i];
1616 AsBytes.push_back(Val & 0xFF);
1617 AsBytes.push_back(Val >> 8);
1619 AsBytes.push_back(Val >> 8);
1620 AsBytes.push_back(Val & 0xFF);
1623 // Append one extra null character, the second is automatically added by our
1625 AsBytes.push_back(0);
1628 return Map.GetOrCreateValue(llvm::StringRef(AsBytes.data(), AsBytes.size()));
1632 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
1633 unsigned StringLength = 0;
1634 bool isUTF16 = false;
1635 llvm::StringMapEntry<llvm::Constant*> &Entry =
1636 GetConstantCFStringEntry(CFConstantStringMap, Literal,
1637 getTargetData().isLittleEndian(),
1638 isUTF16, StringLength);
1640 if (llvm::Constant *C = Entry.getValue())
1643 llvm::Constant *Zero =
1644 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
1645 llvm::Constant *Zeros[] = { Zero, Zero };
1647 // If we don't already have it, get __CFConstantStringClassReference.
1648 if (!CFConstantStringClassRef) {
1649 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1650 Ty = llvm::ArrayType::get(Ty, 0);
1651 llvm::Constant *GV = CreateRuntimeVariable(Ty,
1652 "__CFConstantStringClassReference");
1653 // Decay array -> ptr
1654 CFConstantStringClassRef =
1655 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1658 QualType CFTy = getContext().getCFConstantStringType();
1660 const llvm::StructType *STy =
1661 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1663 std::vector<llvm::Constant*> Fields(4);
1666 Fields[0] = CFConstantStringClassRef;
1669 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1670 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
1671 llvm::ConstantInt::get(Ty, 0x07C8);
1674 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1676 llvm::GlobalValue::LinkageTypes Linkage;
1679 // FIXME: why do utf strings get "_" labels instead of "L" labels?
1680 Linkage = llvm::GlobalValue::InternalLinkage;
1681 // Note: -fwritable-strings doesn't make unicode CFStrings writable, but
1682 // does make plain ascii ones writable.
1685 // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error
1686 // when using private linkage. It is not clear if this is a bug in ld
1687 // or a reasonable new restriction.
1688 Linkage = llvm::GlobalValue::LinkerPrivateLinkage;
1689 isConstant = !Features.WritableStrings;
1692 llvm::GlobalVariable *GV =
1693 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1695 GV->setUnnamedAddr(true);
1697 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1698 GV->setAlignment(Align.getQuantity());
1700 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
1701 GV->setAlignment(Align.getQuantity());
1703 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1706 Ty = getTypes().ConvertType(getContext().LongTy);
1707 Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
1710 C = llvm::ConstantStruct::get(STy, Fields);
1711 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1712 llvm::GlobalVariable::PrivateLinkage, C,
1713 "_unnamed_cfstring_");
1714 if (const char *Sect = getContext().Target.getCFStringSection())
1715 GV->setSection(Sect);
1722 CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
1723 unsigned StringLength = 0;
1724 bool isUTF16 = false;
1725 llvm::StringMapEntry<llvm::Constant*> &Entry =
1726 GetConstantCFStringEntry(CFConstantStringMap, Literal,
1727 getTargetData().isLittleEndian(),
1728 isUTF16, StringLength);
1730 if (llvm::Constant *C = Entry.getValue())
1733 llvm::Constant *Zero =
1734 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
1735 llvm::Constant *Zeros[] = { Zero, Zero };
1737 // If we don't already have it, get _NSConstantStringClassReference.
1738 if (!ConstantStringClassRef) {
1739 std::string StringClass(getLangOptions().ObjCConstantStringClass);
1740 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1741 Ty = llvm::ArrayType::get(Ty, 0);
1743 if (StringClass.empty())
1744 GV = CreateRuntimeVariable(Ty,
1745 Features.ObjCNonFragileABI ?
1746 "OBJC_CLASS_$_NSConstantString" :
1747 "_NSConstantStringClassReference");
1750 if (Features.ObjCNonFragileABI)
1751 str = "OBJC_CLASS_$_" + StringClass;
1753 str = "_" + StringClass + "ClassReference";
1754 GV = CreateRuntimeVariable(Ty, str);
1756 // Decay array -> ptr
1757 ConstantStringClassRef =
1758 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1761 QualType NSTy = getContext().getNSConstantStringType();
1763 const llvm::StructType *STy =
1764 cast<llvm::StructType>(getTypes().ConvertType(NSTy));
1766 std::vector<llvm::Constant*> Fields(3);
1769 Fields[0] = ConstantStringClassRef;
1772 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1774 llvm::GlobalValue::LinkageTypes Linkage;
1777 // FIXME: why do utf strings get "_" labels instead of "L" labels?
1778 Linkage = llvm::GlobalValue::InternalLinkage;
1779 // Note: -fwritable-strings doesn't make unicode NSStrings writable, but
1780 // does make plain ascii ones writable.
1783 Linkage = llvm::GlobalValue::PrivateLinkage;
1784 isConstant = !Features.WritableStrings;
1787 llvm::GlobalVariable *GV =
1788 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1790 GV->setUnnamedAddr(true);
1792 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1793 GV->setAlignment(Align.getQuantity());
1795 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
1796 GV->setAlignment(Align.getQuantity());
1798 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1801 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1802 Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
1805 C = llvm::ConstantStruct::get(STy, Fields);
1806 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1807 llvm::GlobalVariable::PrivateLinkage, C,
1808 "_unnamed_nsstring_");
1809 // FIXME. Fix section.
1810 if (const char *Sect =
1811 Features.ObjCNonFragileABI
1812 ? getContext().Target.getNSStringNonFragileABISection()
1813 : getContext().Target.getNSStringSection())
1814 GV->setSection(Sect);
1820 /// GetStringForStringLiteral - Return the appropriate bytes for a
1821 /// string literal, properly padded to match the literal type.
1822 std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
1823 const ASTContext &Context = getContext();
1824 const ConstantArrayType *CAT =
1825 Context.getAsConstantArrayType(E->getType());
1826 assert(CAT && "String isn't pointer or array!");
1828 // Resize the string to the right size.
1829 uint64_t RealLen = CAT->getSize().getZExtValue();
1832 RealLen *= Context.Target.getWCharWidth() / Context.getCharWidth();
1834 std::string Str = E->getString().str();
1835 Str.resize(RealLen, '\0');
1840 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1841 /// constant array for the given string literal.
1843 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1844 // FIXME: This can be more efficient.
1845 // FIXME: We shouldn't need to bitcast the constant in the wide string case.
1846 llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S));
1848 llvm::Type *DestTy =
1849 llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType()));
1850 C = llvm::ConstantExpr::getBitCast(C, DestTy);
1855 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1856 /// array for the given ObjCEncodeExpr node.
1858 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1860 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
1862 return GetAddrOfConstantCString(Str);
1866 /// GenerateWritableString -- Creates storage for a string literal.
1867 static llvm::Constant *GenerateStringLiteral(llvm::StringRef str,
1870 const char *GlobalName) {
1871 // Create Constant for this string literal. Don't add a '\0'.
1873 llvm::ConstantArray::get(CGM.getLLVMContext(), str, false);
1875 // Create a global variable for this string
1876 llvm::GlobalVariable *GV =
1877 new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
1878 llvm::GlobalValue::PrivateLinkage,
1880 GV->setUnnamedAddr(true);
1884 /// GetAddrOfConstantString - Returns a pointer to a character array
1885 /// containing the literal. This contents are exactly that of the
1886 /// given string, i.e. it will not be null terminated automatically;
1887 /// see GetAddrOfConstantCString. Note that whether the result is
1888 /// actually a pointer to an LLVM constant depends on
1889 /// Feature.WriteableStrings.
1891 /// The result has pointer to array type.
1892 llvm::Constant *CodeGenModule::GetAddrOfConstantString(llvm::StringRef Str,
1893 const char *GlobalName) {
1894 bool IsConstant = !Features.WritableStrings;
1896 // Get the default prefix if a name wasn't specified.
1898 GlobalName = ".str";
1900 // Don't share any string literals if strings aren't constant.
1902 return GenerateStringLiteral(Str, false, *this, GlobalName);
1904 llvm::StringMapEntry<llvm::Constant *> &Entry =
1905 ConstantStringMap.GetOrCreateValue(Str);
1907 if (Entry.getValue())
1908 return Entry.getValue();
1910 // Create a global variable for this.
1911 llvm::Constant *C = GenerateStringLiteral(Str, true, *this, GlobalName);
1916 /// GetAddrOfConstantCString - Returns a pointer to a character
1917 /// array containing the literal and a terminating '\0'
1918 /// character. The result has pointer to array type.
1919 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
1920 const char *GlobalName){
1921 llvm::StringRef StrWithNull(Str.c_str(), Str.size() + 1);
1922 return GetAddrOfConstantString(StrWithNull, GlobalName);
1925 /// EmitObjCPropertyImplementations - Emit information for synthesized
1926 /// properties for an implementation.
1927 void CodeGenModule::EmitObjCPropertyImplementations(const
1928 ObjCImplementationDecl *D) {
1929 for (ObjCImplementationDecl::propimpl_iterator
1930 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
1931 ObjCPropertyImplDecl *PID = *i;
1933 // Dynamic is just for type-checking.
1934 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1935 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1937 // Determine which methods need to be implemented, some may have
1938 // been overridden. Note that ::isSynthesized is not the method
1939 // we want, that just indicates if the decl came from a
1940 // property. What we want to know is if the method is defined in
1941 // this implementation.
1942 if (!D->getInstanceMethod(PD->getGetterName()))
1943 CodeGenFunction(*this).GenerateObjCGetter(
1944 const_cast<ObjCImplementationDecl *>(D), PID);
1945 if (!PD->isReadOnly() &&
1946 !D->getInstanceMethod(PD->getSetterName()))
1947 CodeGenFunction(*this).GenerateObjCSetter(
1948 const_cast<ObjCImplementationDecl *>(D), PID);
1953 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
1954 ObjCInterfaceDecl *iface
1955 = const_cast<ObjCInterfaceDecl*>(impl->getClassInterface());
1956 for (ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
1957 ivar; ivar = ivar->getNextIvar())
1958 if (ivar->getType().isDestructedType())
1964 /// EmitObjCIvarInitializations - Emit information for ivar initialization
1965 /// for an implementation.
1966 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
1967 // We might need a .cxx_destruct even if we don't have any ivar initializers.
1968 if (needsDestructMethod(D)) {
1969 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
1970 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
1971 ObjCMethodDecl *DTORMethod =
1972 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
1973 cxxSelector, getContext().VoidTy, 0, D, true,
1974 false, true, false, ObjCMethodDecl::Required);
1975 D->addInstanceMethod(DTORMethod);
1976 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
1979 // If the implementation doesn't have any ivar initializers, we don't need
1980 // a .cxx_construct.
1981 if (D->getNumIvarInitializers() == 0)
1984 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
1985 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
1986 // The constructor returns 'self'.
1987 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
1989 D->getLocation(), cxxSelector,
1990 getContext().getObjCIdType(), 0,
1991 D, true, false, true, false,
1992 ObjCMethodDecl::Required);
1993 D->addInstanceMethod(CTORMethod);
1994 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
1997 /// EmitNamespace - Emit all declarations in a namespace.
1998 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
1999 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
2001 EmitTopLevelDecl(*I);
2004 // EmitLinkageSpec - Emit all declarations in a linkage spec.
2005 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
2006 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
2007 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
2008 ErrorUnsupported(LSD, "linkage spec");
2012 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
2014 EmitTopLevelDecl(*I);
2017 /// EmitTopLevelDecl - Emit code for a single top level declaration.
2018 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
2019 // If an error has occurred, stop code generation, but continue
2020 // parsing and semantic analysis (to ensure all warnings and errors
2022 if (Diags.hasErrorOccurred())
2025 // Ignore dependent declarations.
2026 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
2029 switch (D->getKind()) {
2030 case Decl::CXXConversion:
2031 case Decl::CXXMethod:
2032 case Decl::Function:
2033 // Skip function templates
2034 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2035 cast<FunctionDecl>(D)->isLateTemplateParsed())
2038 EmitGlobal(cast<FunctionDecl>(D));
2042 EmitGlobal(cast<VarDecl>(D));
2045 // Indirect fields from global anonymous structs and unions can be
2046 // ignored; only the actual variable requires IR gen support.
2047 case Decl::IndirectField:
2051 case Decl::Namespace:
2052 EmitNamespace(cast<NamespaceDecl>(D));
2054 // No code generation needed.
2055 case Decl::UsingShadow:
2057 case Decl::UsingDirective:
2058 case Decl::ClassTemplate:
2059 case Decl::FunctionTemplate:
2060 case Decl::NamespaceAlias:
2062 case Decl::CXXConstructor:
2063 // Skip function templates
2064 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2065 cast<FunctionDecl>(D)->isLateTemplateParsed())
2068 EmitCXXConstructors(cast<CXXConstructorDecl>(D));
2070 case Decl::CXXDestructor:
2071 if (cast<FunctionDecl>(D)->isLateTemplateParsed())
2073 EmitCXXDestructors(cast<CXXDestructorDecl>(D));
2076 case Decl::StaticAssert:
2080 // Objective-C Decls
2082 // Forward declarations, no (immediate) code generation.
2083 case Decl::ObjCClass:
2084 case Decl::ObjCForwardProtocol:
2085 case Decl::ObjCInterface:
2088 case Decl::ObjCCategory: {
2089 ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D);
2090 if (CD->IsClassExtension() && CD->hasSynthBitfield())
2091 Context.ResetObjCLayout(CD->getClassInterface());
2095 case Decl::ObjCProtocol:
2096 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
2099 case Decl::ObjCCategoryImpl:
2100 // Categories have properties but don't support synthesize so we
2101 // can ignore them here.
2102 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
2105 case Decl::ObjCImplementation: {
2106 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
2107 if (Features.ObjCNonFragileABI2 && OMD->hasSynthBitfield())
2108 Context.ResetObjCLayout(OMD->getClassInterface());
2109 EmitObjCPropertyImplementations(OMD);
2110 EmitObjCIvarInitializations(OMD);
2111 Runtime->GenerateClass(OMD);
2114 case Decl::ObjCMethod: {
2115 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
2116 // If this is not a prototype, emit the body.
2118 CodeGenFunction(*this).GenerateObjCMethod(OMD);
2121 case Decl::ObjCCompatibleAlias:
2122 // compatibility-alias is a directive and has no code gen.
2125 case Decl::LinkageSpec:
2126 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
2129 case Decl::FileScopeAsm: {
2130 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
2131 llvm::StringRef AsmString = AD->getAsmString()->getString();
2133 const std::string &S = getModule().getModuleInlineAsm();
2135 getModule().setModuleInlineAsm(AsmString);
2137 getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
2142 // Make sure we handled everything we should, every other kind is a
2143 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
2144 // function. Need to recode Decl::Kind to do that easily.
2145 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
2149 /// Turns the given pointer into a constant.
2150 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
2152 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
2153 const llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
2154 return llvm::ConstantInt::get(i64, PtrInt);
2157 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
2158 llvm::NamedMDNode *&GlobalMetadata,
2160 llvm::GlobalValue *Addr) {
2161 if (!GlobalMetadata)
2163 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
2165 // TODO: should we report variant information for ctors/dtors?
2166 llvm::Value *Ops[] = {
2168 GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
2170 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2173 /// Emits metadata nodes associating all the global values in the
2174 /// current module with the Decls they came from. This is useful for
2175 /// projects using IR gen as a subroutine.
2177 /// Since there's currently no way to associate an MDNode directly
2178 /// with an llvm::GlobalValue, we create a global named metadata
2179 /// with the name 'clang.global.decl.ptrs'.
2180 void CodeGenModule::EmitDeclMetadata() {
2181 llvm::NamedMDNode *GlobalMetadata = 0;
2183 // StaticLocalDeclMap
2184 for (llvm::DenseMap<GlobalDecl,llvm::StringRef>::iterator
2185 I = MangledDeclNames.begin(), E = MangledDeclNames.end();
2187 llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
2188 EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
2192 /// Emits metadata nodes for all the local variables in the current
2194 void CodeGenFunction::EmitDeclMetadata() {
2195 if (LocalDeclMap.empty()) return;
2197 llvm::LLVMContext &Context = getLLVMContext();
2199 // Find the unique metadata ID for this name.
2200 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
2202 llvm::NamedMDNode *GlobalMetadata = 0;
2204 for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
2205 I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
2206 const Decl *D = I->first;
2207 llvm::Value *Addr = I->second;
2209 if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
2210 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
2211 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
2212 } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
2213 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
2214 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
2219 ///@name Custom Runtime Function Interfaces
2222 // FIXME: These can be eliminated once we can have clients just get the required
2223 // AST nodes from the builtin tables.
2225 llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2226 if (BlockObjectDispose)
2227 return BlockObjectDispose;
2229 // If we saw an explicit decl, use that.
2230 if (BlockObjectDisposeDecl) {
2231 return BlockObjectDispose = GetAddrOfFunction(
2232 BlockObjectDisposeDecl,
2233 getTypes().GetFunctionType(BlockObjectDisposeDecl));
2236 // Otherwise construct the function by hand.
2237 const llvm::FunctionType *FTy;
2238 std::vector<const llvm::Type*> ArgTys;
2239 const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
2240 ArgTys.push_back(Int8PtrTy);
2241 ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
2242 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
2243 return BlockObjectDispose =
2244 CreateRuntimeFunction(FTy, "_Block_object_dispose");
2247 llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2248 if (BlockObjectAssign)
2249 return BlockObjectAssign;
2251 // If we saw an explicit decl, use that.
2252 if (BlockObjectAssignDecl) {
2253 return BlockObjectAssign = GetAddrOfFunction(
2254 BlockObjectAssignDecl,
2255 getTypes().GetFunctionType(BlockObjectAssignDecl));
2258 // Otherwise construct the function by hand.
2259 const llvm::FunctionType *FTy;
2260 std::vector<const llvm::Type*> ArgTys;
2261 const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
2262 ArgTys.push_back(Int8PtrTy);
2263 ArgTys.push_back(Int8PtrTy);
2264 ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
2265 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
2266 return BlockObjectAssign =
2267 CreateRuntimeFunction(FTy, "_Block_object_assign");
2270 llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2271 if (NSConcreteGlobalBlock)
2272 return NSConcreteGlobalBlock;
2274 // If we saw an explicit decl, use that.
2275 if (NSConcreteGlobalBlockDecl) {
2276 return NSConcreteGlobalBlock = GetAddrOfGlobalVar(
2277 NSConcreteGlobalBlockDecl,
2278 getTypes().ConvertType(NSConcreteGlobalBlockDecl->getType()));
2281 // Otherwise construct the variable by hand.
2282 return NSConcreteGlobalBlock =
2283 CreateRuntimeVariable(Int8PtrTy, "_NSConcreteGlobalBlock");
2286 llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2287 if (NSConcreteStackBlock)
2288 return NSConcreteStackBlock;
2290 // If we saw an explicit decl, use that.
2291 if (NSConcreteStackBlockDecl) {
2292 return NSConcreteStackBlock = GetAddrOfGlobalVar(
2293 NSConcreteStackBlockDecl,
2294 getTypes().ConvertType(NSConcreteStackBlockDecl->getType()));
2297 // Otherwise construct the variable by hand.
2298 return NSConcreteStackBlock =
2299 CreateRuntimeVariable(Int8PtrTy, "_NSConcreteStackBlock");