1f22ef01cSRoman Divacky //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2f22ef01cSRoman Divacky //
3f22ef01cSRoman Divacky //                     The LLVM Compiler Infrastructure
4f22ef01cSRoman Divacky //
5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source
6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details.
7f22ef01cSRoman Divacky //
8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
9f22ef01cSRoman Divacky //
10f22ef01cSRoman Divacky // This coordinates the per-module state used while generating code.
11f22ef01cSRoman Divacky //
12f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
13f22ef01cSRoman Divacky 
14f22ef01cSRoman Divacky #include "CodeGenModule.h"
15f22ef01cSRoman Divacky #include "CGDebugInfo.h"
16f22ef01cSRoman Divacky #include "CodeGenFunction.h"
17f22ef01cSRoman Divacky #include "CGCall.h"
18f22ef01cSRoman Divacky #include "CGObjCRuntime.h"
19f22ef01cSRoman Divacky #include "Mangle.h"
20f22ef01cSRoman Divacky #include "TargetInfo.h"
21f22ef01cSRoman Divacky #include "clang/CodeGen/CodeGenOptions.h"
22f22ef01cSRoman Divacky #include "clang/AST/ASTContext.h"
23f22ef01cSRoman Divacky #include "clang/AST/CharUnits.h"
24f22ef01cSRoman Divacky #include "clang/AST/DeclObjC.h"
25f22ef01cSRoman Divacky #include "clang/AST/DeclCXX.h"
26f22ef01cSRoman Divacky #include "clang/AST/RecordLayout.h"
27f22ef01cSRoman Divacky #include "clang/Basic/Builtins.h"
28f22ef01cSRoman Divacky #include "clang/Basic/Diagnostic.h"
29f22ef01cSRoman Divacky #include "clang/Basic/SourceManager.h"
30f22ef01cSRoman Divacky #include "clang/Basic/TargetInfo.h"
31f22ef01cSRoman Divacky #include "clang/Basic/ConvertUTF.h"
32f22ef01cSRoman Divacky #include "llvm/CallingConv.h"
33f22ef01cSRoman Divacky #include "llvm/Module.h"
34f22ef01cSRoman Divacky #include "llvm/Intrinsics.h"
35f22ef01cSRoman Divacky #include "llvm/LLVMContext.h"
36f22ef01cSRoman Divacky #include "llvm/ADT/Triple.h"
37f22ef01cSRoman Divacky #include "llvm/Target/TargetData.h"
38f22ef01cSRoman Divacky #include "llvm/Support/CallSite.h"
39f22ef01cSRoman Divacky #include "llvm/Support/ErrorHandling.h"
40f22ef01cSRoman Divacky using namespace clang;
41f22ef01cSRoman Divacky using namespace CodeGen;
42f22ef01cSRoman Divacky 
43f22ef01cSRoman Divacky 
44f22ef01cSRoman Divacky CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
45f22ef01cSRoman Divacky                              llvm::Module &M, const llvm::TargetData &TD,
46f22ef01cSRoman Divacky                              Diagnostic &diags)
47f22ef01cSRoman Divacky   : BlockModule(C, M, TD, Types, *this), Context(C),
48f22ef01cSRoman Divacky     Features(C.getLangOptions()), CodeGenOpts(CGO), TheModule(M),
49f22ef01cSRoman Divacky     TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags),
50f22ef01cSRoman Divacky     Types(C, M, TD, getTargetCodeGenInfo().getABIInfo()),
51f22ef01cSRoman Divacky     VTables(*this), Runtime(0), ABI(0),
52f22ef01cSRoman Divacky     CFConstantStringClassRef(0),
53f22ef01cSRoman Divacky     NSConstantStringClassRef(0),
54f22ef01cSRoman Divacky     VMContext(M.getContext()) {
55f22ef01cSRoman Divacky 
56f22ef01cSRoman Divacky   if (!Features.ObjC1)
57f22ef01cSRoman Divacky     Runtime = 0;
58f22ef01cSRoman Divacky   else if (!Features.NeXTRuntime)
59f22ef01cSRoman Divacky     Runtime = CreateGNUObjCRuntime(*this);
60f22ef01cSRoman Divacky   else if (Features.ObjCNonFragileABI)
61f22ef01cSRoman Divacky     Runtime = CreateMacNonFragileABIObjCRuntime(*this);
62f22ef01cSRoman Divacky   else
63f22ef01cSRoman Divacky     Runtime = CreateMacObjCRuntime(*this);
64f22ef01cSRoman Divacky 
65f22ef01cSRoman Divacky   if (!Features.CPlusPlus)
66f22ef01cSRoman Divacky     ABI = 0;
67f22ef01cSRoman Divacky   else createCXXABI();
68f22ef01cSRoman Divacky 
69f22ef01cSRoman Divacky   // If debug info generation is enabled, create the CGDebugInfo object.
70f22ef01cSRoman Divacky   DebugInfo = CodeGenOpts.DebugInfo ? new CGDebugInfo(*this) : 0;
71f22ef01cSRoman Divacky }
72f22ef01cSRoman Divacky 
73f22ef01cSRoman Divacky CodeGenModule::~CodeGenModule() {
74f22ef01cSRoman Divacky   delete Runtime;
75f22ef01cSRoman Divacky   delete ABI;
76f22ef01cSRoman Divacky   delete DebugInfo;
77f22ef01cSRoman Divacky }
78f22ef01cSRoman Divacky 
79f22ef01cSRoman Divacky void CodeGenModule::createObjCRuntime() {
80f22ef01cSRoman Divacky   if (!Features.NeXTRuntime)
81f22ef01cSRoman Divacky     Runtime = CreateGNUObjCRuntime(*this);
82f22ef01cSRoman Divacky   else if (Features.ObjCNonFragileABI)
83f22ef01cSRoman Divacky     Runtime = CreateMacNonFragileABIObjCRuntime(*this);
84f22ef01cSRoman Divacky   else
85f22ef01cSRoman Divacky     Runtime = CreateMacObjCRuntime(*this);
86f22ef01cSRoman Divacky }
87f22ef01cSRoman Divacky 
88f22ef01cSRoman Divacky void CodeGenModule::createCXXABI() {
89f22ef01cSRoman Divacky   // For now, just create an Itanium ABI.
90f22ef01cSRoman Divacky   ABI = CreateItaniumCXXABI(*this);
91f22ef01cSRoman Divacky }
92f22ef01cSRoman Divacky 
93f22ef01cSRoman Divacky void CodeGenModule::Release() {
94f22ef01cSRoman Divacky   EmitDeferred();
95f22ef01cSRoman Divacky   EmitCXXGlobalInitFunc();
96f22ef01cSRoman Divacky   EmitCXXGlobalDtorFunc();
97f22ef01cSRoman Divacky   if (Runtime)
98f22ef01cSRoman Divacky     if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
99f22ef01cSRoman Divacky       AddGlobalCtor(ObjCInitFunction);
100f22ef01cSRoman Divacky   EmitCtorList(GlobalCtors, "llvm.global_ctors");
101f22ef01cSRoman Divacky   EmitCtorList(GlobalDtors, "llvm.global_dtors");
102f22ef01cSRoman Divacky   EmitAnnotations();
103f22ef01cSRoman Divacky   EmitLLVMUsed();
104f22ef01cSRoman Divacky }
105f22ef01cSRoman Divacky 
106f22ef01cSRoman Divacky bool CodeGenModule::isTargetDarwin() const {
107f22ef01cSRoman Divacky   return getContext().Target.getTriple().getOS() == llvm::Triple::Darwin;
108f22ef01cSRoman Divacky }
109f22ef01cSRoman Divacky 
110f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the
111f22ef01cSRoman Divacky /// specified stmt yet.
112f22ef01cSRoman Divacky void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
113f22ef01cSRoman Divacky                                      bool OmitOnError) {
114f22ef01cSRoman Divacky   if (OmitOnError && getDiags().hasErrorOccurred())
115f22ef01cSRoman Divacky     return;
116f22ef01cSRoman Divacky   unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
117f22ef01cSRoman Divacky                                                "cannot compile this %0 yet");
118f22ef01cSRoman Divacky   std::string Msg = Type;
119f22ef01cSRoman Divacky   getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
120f22ef01cSRoman Divacky     << Msg << S->getSourceRange();
121f22ef01cSRoman Divacky }
122f22ef01cSRoman Divacky 
123f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the
124f22ef01cSRoman Divacky /// specified decl yet.
125f22ef01cSRoman Divacky void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
126f22ef01cSRoman Divacky                                      bool OmitOnError) {
127f22ef01cSRoman Divacky   if (OmitOnError && getDiags().hasErrorOccurred())
128f22ef01cSRoman Divacky     return;
129f22ef01cSRoman Divacky   unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
130f22ef01cSRoman Divacky                                                "cannot compile this %0 yet");
131f22ef01cSRoman Divacky   std::string Msg = Type;
132f22ef01cSRoman Divacky   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
133f22ef01cSRoman Divacky }
134f22ef01cSRoman Divacky 
135f22ef01cSRoman Divacky LangOptions::VisibilityMode
136f22ef01cSRoman Divacky CodeGenModule::getDeclVisibilityMode(const Decl *D) const {
137f22ef01cSRoman Divacky   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
138f22ef01cSRoman Divacky     if (VD->getStorageClass() == VarDecl::PrivateExtern)
139f22ef01cSRoman Divacky       return LangOptions::Hidden;
140f22ef01cSRoman Divacky 
141f22ef01cSRoman Divacky   if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>()) {
142f22ef01cSRoman Divacky     switch (attr->getVisibility()) {
143f22ef01cSRoman Divacky     default: assert(0 && "Unknown visibility!");
144f22ef01cSRoman Divacky     case VisibilityAttr::DefaultVisibility:
145f22ef01cSRoman Divacky       return LangOptions::Default;
146f22ef01cSRoman Divacky     case VisibilityAttr::HiddenVisibility:
147f22ef01cSRoman Divacky       return LangOptions::Hidden;
148f22ef01cSRoman Divacky     case VisibilityAttr::ProtectedVisibility:
149f22ef01cSRoman Divacky       return LangOptions::Protected;
150f22ef01cSRoman Divacky     }
151f22ef01cSRoman Divacky   }
152f22ef01cSRoman Divacky 
153f22ef01cSRoman Divacky   // This decl should have the same visibility as its parent.
154f22ef01cSRoman Divacky   if (const DeclContext *DC = D->getDeclContext())
155f22ef01cSRoman Divacky     return getDeclVisibilityMode(cast<Decl>(DC));
156f22ef01cSRoman Divacky 
157f22ef01cSRoman Divacky   return getLangOptions().getVisibilityMode();
158f22ef01cSRoman Divacky }
159f22ef01cSRoman Divacky 
160f22ef01cSRoman Divacky void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
161f22ef01cSRoman Divacky                                         const Decl *D) const {
162f22ef01cSRoman Divacky   // Internal definitions always have default visibility.
163f22ef01cSRoman Divacky   if (GV->hasLocalLinkage()) {
164f22ef01cSRoman Divacky     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
165f22ef01cSRoman Divacky     return;
166f22ef01cSRoman Divacky   }
167f22ef01cSRoman Divacky 
168f22ef01cSRoman Divacky   switch (getDeclVisibilityMode(D)) {
169f22ef01cSRoman Divacky   default: assert(0 && "Unknown visibility!");
170f22ef01cSRoman Divacky   case LangOptions::Default:
171f22ef01cSRoman Divacky     return GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
172f22ef01cSRoman Divacky   case LangOptions::Hidden:
173f22ef01cSRoman Divacky     return GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
174f22ef01cSRoman Divacky   case LangOptions::Protected:
175f22ef01cSRoman Divacky     return GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
176f22ef01cSRoman Divacky   }
177f22ef01cSRoman Divacky }
178f22ef01cSRoman Divacky 
179f22ef01cSRoman Divacky void CodeGenModule::getMangledName(MangleBuffer &Buffer, GlobalDecl GD) {
180f22ef01cSRoman Divacky   const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
181f22ef01cSRoman Divacky 
182f22ef01cSRoman Divacky   if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
183f22ef01cSRoman Divacky     return getMangledCXXCtorName(Buffer, D, GD.getCtorType());
184f22ef01cSRoman Divacky   if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
185f22ef01cSRoman Divacky     return getMangledCXXDtorName(Buffer, D, GD.getDtorType());
186f22ef01cSRoman Divacky 
187f22ef01cSRoman Divacky   return getMangledName(Buffer, ND);
188f22ef01cSRoman Divacky }
189f22ef01cSRoman Divacky 
190f22ef01cSRoman Divacky /// \brief Retrieves the mangled name for the given declaration.
191f22ef01cSRoman Divacky ///
192f22ef01cSRoman Divacky /// If the given declaration requires a mangled name, returns an
193f22ef01cSRoman Divacky /// const char* containing the mangled name.  Otherwise, returns
194f22ef01cSRoman Divacky /// the unmangled name.
195f22ef01cSRoman Divacky ///
196f22ef01cSRoman Divacky void CodeGenModule::getMangledName(MangleBuffer &Buffer,
197f22ef01cSRoman Divacky                                    const NamedDecl *ND) {
198f22ef01cSRoman Divacky   if (!getMangleContext().shouldMangleDeclName(ND)) {
199f22ef01cSRoman Divacky     assert(ND->getIdentifier() && "Attempt to mangle unnamed decl.");
200f22ef01cSRoman Divacky     Buffer.setString(ND->getNameAsCString());
201f22ef01cSRoman Divacky     return;
202f22ef01cSRoman Divacky   }
203f22ef01cSRoman Divacky 
204f22ef01cSRoman Divacky   getMangleContext().mangleName(ND, Buffer.getBuffer());
205f22ef01cSRoman Divacky }
206f22ef01cSRoman Divacky 
207f22ef01cSRoman Divacky llvm::GlobalValue *CodeGenModule::GetGlobalValue(llvm::StringRef Name) {
208f22ef01cSRoman Divacky   return getModule().getNamedValue(Name);
209f22ef01cSRoman Divacky }
210f22ef01cSRoman Divacky 
211f22ef01cSRoman Divacky /// AddGlobalCtor - Add a function to the list that will be called before
212f22ef01cSRoman Divacky /// main() runs.
213f22ef01cSRoman Divacky void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
214f22ef01cSRoman Divacky   // FIXME: Type coercion of void()* types.
215f22ef01cSRoman Divacky   GlobalCtors.push_back(std::make_pair(Ctor, Priority));
216f22ef01cSRoman Divacky }
217f22ef01cSRoman Divacky 
218f22ef01cSRoman Divacky /// AddGlobalDtor - Add a function to the list that will be called
219f22ef01cSRoman Divacky /// when the module is unloaded.
220f22ef01cSRoman Divacky void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
221f22ef01cSRoman Divacky   // FIXME: Type coercion of void()* types.
222f22ef01cSRoman Divacky   GlobalDtors.push_back(std::make_pair(Dtor, Priority));
223f22ef01cSRoman Divacky }
224f22ef01cSRoman Divacky 
225f22ef01cSRoman Divacky void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
226f22ef01cSRoman Divacky   // Ctor function type is void()*.
227f22ef01cSRoman Divacky   llvm::FunctionType* CtorFTy =
228f22ef01cSRoman Divacky     llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
229f22ef01cSRoman Divacky                             std::vector<const llvm::Type*>(),
230f22ef01cSRoman Divacky                             false);
231f22ef01cSRoman Divacky   llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
232f22ef01cSRoman Divacky 
233f22ef01cSRoman Divacky   // Get the type of a ctor entry, { i32, void ()* }.
234f22ef01cSRoman Divacky   llvm::StructType* CtorStructTy =
235f22ef01cSRoman Divacky     llvm::StructType::get(VMContext, llvm::Type::getInt32Ty(VMContext),
236f22ef01cSRoman Divacky                           llvm::PointerType::getUnqual(CtorFTy), NULL);
237f22ef01cSRoman Divacky 
238f22ef01cSRoman Divacky   // Construct the constructor and destructor arrays.
239f22ef01cSRoman Divacky   std::vector<llvm::Constant*> Ctors;
240f22ef01cSRoman Divacky   for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
241f22ef01cSRoman Divacky     std::vector<llvm::Constant*> S;
242f22ef01cSRoman Divacky     S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
243f22ef01cSRoman Divacky                 I->second, false));
244f22ef01cSRoman Divacky     S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
245f22ef01cSRoman Divacky     Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
246f22ef01cSRoman Divacky   }
247f22ef01cSRoman Divacky 
248f22ef01cSRoman Divacky   if (!Ctors.empty()) {
249f22ef01cSRoman Divacky     llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
250f22ef01cSRoman Divacky     new llvm::GlobalVariable(TheModule, AT, false,
251f22ef01cSRoman Divacky                              llvm::GlobalValue::AppendingLinkage,
252f22ef01cSRoman Divacky                              llvm::ConstantArray::get(AT, Ctors),
253f22ef01cSRoman Divacky                              GlobalName);
254f22ef01cSRoman Divacky   }
255f22ef01cSRoman Divacky }
256f22ef01cSRoman Divacky 
257f22ef01cSRoman Divacky void CodeGenModule::EmitAnnotations() {
258f22ef01cSRoman Divacky   if (Annotations.empty())
259f22ef01cSRoman Divacky     return;
260f22ef01cSRoman Divacky 
261f22ef01cSRoman Divacky   // Create a new global variable for the ConstantStruct in the Module.
262f22ef01cSRoman Divacky   llvm::Constant *Array =
263f22ef01cSRoman Divacky   llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
264f22ef01cSRoman Divacky                                                 Annotations.size()),
265f22ef01cSRoman Divacky                            Annotations);
266f22ef01cSRoman Divacky   llvm::GlobalValue *gv =
267f22ef01cSRoman Divacky   new llvm::GlobalVariable(TheModule, Array->getType(), false,
268f22ef01cSRoman Divacky                            llvm::GlobalValue::AppendingLinkage, Array,
269f22ef01cSRoman Divacky                            "llvm.global.annotations");
270f22ef01cSRoman Divacky   gv->setSection("llvm.metadata");
271f22ef01cSRoman Divacky }
272f22ef01cSRoman Divacky 
273f22ef01cSRoman Divacky static CodeGenModule::GVALinkage
274f22ef01cSRoman Divacky GetLinkageForFunction(ASTContext &Context, const FunctionDecl *FD,
275f22ef01cSRoman Divacky                       const LangOptions &Features) {
276f22ef01cSRoman Divacky   CodeGenModule::GVALinkage External = CodeGenModule::GVA_StrongExternal;
277f22ef01cSRoman Divacky 
278f22ef01cSRoman Divacky   Linkage L = FD->getLinkage();
279f22ef01cSRoman Divacky   if (L == ExternalLinkage && Context.getLangOptions().CPlusPlus &&
280f22ef01cSRoman Divacky       FD->getType()->getLinkage() == UniqueExternalLinkage)
281f22ef01cSRoman Divacky     L = UniqueExternalLinkage;
282f22ef01cSRoman Divacky 
283f22ef01cSRoman Divacky   switch (L) {
284f22ef01cSRoman Divacky   case NoLinkage:
285f22ef01cSRoman Divacky   case InternalLinkage:
286f22ef01cSRoman Divacky   case UniqueExternalLinkage:
287f22ef01cSRoman Divacky     return CodeGenModule::GVA_Internal;
288f22ef01cSRoman Divacky 
289f22ef01cSRoman Divacky   case ExternalLinkage:
290f22ef01cSRoman Divacky     switch (FD->getTemplateSpecializationKind()) {
291f22ef01cSRoman Divacky     case TSK_Undeclared:
292f22ef01cSRoman Divacky     case TSK_ExplicitSpecialization:
293f22ef01cSRoman Divacky       External = CodeGenModule::GVA_StrongExternal;
294f22ef01cSRoman Divacky       break;
295f22ef01cSRoman Divacky 
296f22ef01cSRoman Divacky     case TSK_ExplicitInstantiationDefinition:
297f22ef01cSRoman Divacky       return CodeGenModule::GVA_ExplicitTemplateInstantiation;
298f22ef01cSRoman Divacky 
299f22ef01cSRoman Divacky     case TSK_ExplicitInstantiationDeclaration:
300f22ef01cSRoman Divacky     case TSK_ImplicitInstantiation:
301f22ef01cSRoman Divacky       External = CodeGenModule::GVA_TemplateInstantiation;
302f22ef01cSRoman Divacky       break;
303f22ef01cSRoman Divacky     }
304f22ef01cSRoman Divacky   }
305f22ef01cSRoman Divacky 
306f22ef01cSRoman Divacky   if (!FD->isInlined())
307f22ef01cSRoman Divacky     return External;
308f22ef01cSRoman Divacky 
309f22ef01cSRoman Divacky   if (!Features.CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
310f22ef01cSRoman Divacky     // GNU or C99 inline semantics. Determine whether this symbol should be
311f22ef01cSRoman Divacky     // externally visible.
312f22ef01cSRoman Divacky     if (FD->isInlineDefinitionExternallyVisible())
313f22ef01cSRoman Divacky       return External;
314f22ef01cSRoman Divacky 
315f22ef01cSRoman Divacky     // C99 inline semantics, where the symbol is not externally visible.
316f22ef01cSRoman Divacky     return CodeGenModule::GVA_C99Inline;
317f22ef01cSRoman Divacky   }
318f22ef01cSRoman Divacky 
319f22ef01cSRoman Divacky   // C++0x [temp.explicit]p9:
320f22ef01cSRoman Divacky   //   [ Note: The intent is that an inline function that is the subject of
321f22ef01cSRoman Divacky   //   an explicit instantiation declaration will still be implicitly
322f22ef01cSRoman Divacky   //   instantiated when used so that the body can be considered for
323f22ef01cSRoman Divacky   //   inlining, but that no out-of-line copy of the inline function would be
324f22ef01cSRoman Divacky   //   generated in the translation unit. -- end note ]
325f22ef01cSRoman Divacky   if (FD->getTemplateSpecializationKind()
326f22ef01cSRoman Divacky                                        == TSK_ExplicitInstantiationDeclaration)
327f22ef01cSRoman Divacky     return CodeGenModule::GVA_C99Inline;
328f22ef01cSRoman Divacky 
329f22ef01cSRoman Divacky   return CodeGenModule::GVA_CXXInline;
330f22ef01cSRoman Divacky }
331f22ef01cSRoman Divacky 
332f22ef01cSRoman Divacky llvm::GlobalValue::LinkageTypes
333f22ef01cSRoman Divacky CodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
334f22ef01cSRoman Divacky   GVALinkage Linkage = GetLinkageForFunction(getContext(), D, Features);
335f22ef01cSRoman Divacky 
336f22ef01cSRoman Divacky   if (Linkage == GVA_Internal) {
337f22ef01cSRoman Divacky     return llvm::Function::InternalLinkage;
338f22ef01cSRoman Divacky   } else if (D->hasAttr<DLLExportAttr>()) {
339f22ef01cSRoman Divacky     return llvm::Function::DLLExportLinkage;
340f22ef01cSRoman Divacky   } else if (D->hasAttr<WeakAttr>()) {
341f22ef01cSRoman Divacky     return llvm::Function::WeakAnyLinkage;
342f22ef01cSRoman Divacky   } else if (Linkage == GVA_C99Inline) {
343f22ef01cSRoman Divacky     // In C99 mode, 'inline' functions are guaranteed to have a strong
344f22ef01cSRoman Divacky     // definition somewhere else, so we can use available_externally linkage.
345f22ef01cSRoman Divacky     return llvm::Function::AvailableExternallyLinkage;
346f22ef01cSRoman Divacky   } else if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation) {
347f22ef01cSRoman Divacky     // In C++, the compiler has to emit a definition in every translation unit
348f22ef01cSRoman Divacky     // that references the function.  We should use linkonce_odr because
349f22ef01cSRoman Divacky     // a) if all references in this translation unit are optimized away, we
350f22ef01cSRoman Divacky     // don't need to codegen it.  b) if the function persists, it needs to be
351f22ef01cSRoman Divacky     // merged with other definitions. c) C++ has the ODR, so we know the
352f22ef01cSRoman Divacky     // definition is dependable.
353f22ef01cSRoman Divacky     return llvm::Function::LinkOnceODRLinkage;
354f22ef01cSRoman Divacky   } else if (Linkage == GVA_ExplicitTemplateInstantiation) {
355f22ef01cSRoman Divacky     // An explicit instantiation of a template has weak linkage, since
356f22ef01cSRoman Divacky     // explicit instantiations can occur in multiple translation units
357f22ef01cSRoman Divacky     // and must all be equivalent. However, we are not allowed to
358f22ef01cSRoman Divacky     // throw away these explicit instantiations.
359f22ef01cSRoman Divacky     return llvm::Function::WeakODRLinkage;
360f22ef01cSRoman Divacky   } else {
361f22ef01cSRoman Divacky     assert(Linkage == GVA_StrongExternal);
362f22ef01cSRoman Divacky     // Otherwise, we have strong external linkage.
363f22ef01cSRoman Divacky     return llvm::Function::ExternalLinkage;
364f22ef01cSRoman Divacky   }
365f22ef01cSRoman Divacky }
366f22ef01cSRoman Divacky 
367f22ef01cSRoman Divacky 
368f22ef01cSRoman Divacky /// SetFunctionDefinitionAttributes - Set attributes for a global.
369f22ef01cSRoman Divacky ///
370f22ef01cSRoman Divacky /// FIXME: This is currently only done for aliases and functions, but not for
371f22ef01cSRoman Divacky /// variables (these details are set in EmitGlobalVarDefinition for variables).
372f22ef01cSRoman Divacky void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
373f22ef01cSRoman Divacky                                                     llvm::GlobalValue *GV) {
374f22ef01cSRoman Divacky   SetCommonAttributes(D, GV);
375f22ef01cSRoman Divacky }
376f22ef01cSRoman Divacky 
377f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
378f22ef01cSRoman Divacky                                               const CGFunctionInfo &Info,
379f22ef01cSRoman Divacky                                               llvm::Function *F) {
380f22ef01cSRoman Divacky   unsigned CallingConv;
381f22ef01cSRoman Divacky   AttributeListType AttributeList;
382f22ef01cSRoman Divacky   ConstructAttributeList(Info, D, AttributeList, CallingConv);
383f22ef01cSRoman Divacky   F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
384f22ef01cSRoman Divacky                                           AttributeList.size()));
385f22ef01cSRoman Divacky   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
386f22ef01cSRoman Divacky }
387f22ef01cSRoman Divacky 
388f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
389f22ef01cSRoman Divacky                                                            llvm::Function *F) {
390f22ef01cSRoman Divacky   if (!Features.Exceptions && !Features.ObjCNonFragileABI)
391f22ef01cSRoman Divacky     F->addFnAttr(llvm::Attribute::NoUnwind);
392f22ef01cSRoman Divacky 
393f22ef01cSRoman Divacky   if (D->hasAttr<AlwaysInlineAttr>())
394f22ef01cSRoman Divacky     F->addFnAttr(llvm::Attribute::AlwaysInline);
395f22ef01cSRoman Divacky 
396f22ef01cSRoman Divacky   if (D->hasAttr<NoInlineAttr>())
397f22ef01cSRoman Divacky     F->addFnAttr(llvm::Attribute::NoInline);
398f22ef01cSRoman Divacky 
399f22ef01cSRoman Divacky   if (Features.getStackProtectorMode() == LangOptions::SSPOn)
400f22ef01cSRoman Divacky     F->addFnAttr(llvm::Attribute::StackProtect);
401f22ef01cSRoman Divacky   else if (Features.getStackProtectorMode() == LangOptions::SSPReq)
402f22ef01cSRoman Divacky     F->addFnAttr(llvm::Attribute::StackProtectReq);
403f22ef01cSRoman Divacky 
404f22ef01cSRoman Divacky   if (const AlignedAttr *AA = D->getAttr<AlignedAttr>()) {
405f22ef01cSRoman Divacky     unsigned width = Context.Target.getCharWidth();
406f22ef01cSRoman Divacky     F->setAlignment(AA->getAlignment() / width);
407f22ef01cSRoman Divacky     while ((AA = AA->getNext<AlignedAttr>()))
408f22ef01cSRoman Divacky       F->setAlignment(std::max(F->getAlignment(), AA->getAlignment() / width));
409f22ef01cSRoman Divacky   }
410f22ef01cSRoman Divacky   // C++ ABI requires 2-byte alignment for member functions.
411f22ef01cSRoman Divacky   if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
412f22ef01cSRoman Divacky     F->setAlignment(2);
413f22ef01cSRoman Divacky }
414f22ef01cSRoman Divacky 
415f22ef01cSRoman Divacky void CodeGenModule::SetCommonAttributes(const Decl *D,
416f22ef01cSRoman Divacky                                         llvm::GlobalValue *GV) {
417f22ef01cSRoman Divacky   setGlobalVisibility(GV, D);
418f22ef01cSRoman Divacky 
419f22ef01cSRoman Divacky   if (D->hasAttr<UsedAttr>())
420f22ef01cSRoman Divacky     AddUsedGlobal(GV);
421f22ef01cSRoman Divacky 
422f22ef01cSRoman Divacky   if (const SectionAttr *SA = D->getAttr<SectionAttr>())
423f22ef01cSRoman Divacky     GV->setSection(SA->getName());
424f22ef01cSRoman Divacky 
425f22ef01cSRoman Divacky   getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
426f22ef01cSRoman Divacky }
427f22ef01cSRoman Divacky 
428f22ef01cSRoman Divacky void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
429f22ef01cSRoman Divacky                                                   llvm::Function *F,
430f22ef01cSRoman Divacky                                                   const CGFunctionInfo &FI) {
431f22ef01cSRoman Divacky   SetLLVMFunctionAttributes(D, FI, F);
432f22ef01cSRoman Divacky   SetLLVMFunctionAttributesForDefinition(D, F);
433f22ef01cSRoman Divacky 
434f22ef01cSRoman Divacky   F->setLinkage(llvm::Function::InternalLinkage);
435f22ef01cSRoman Divacky 
436f22ef01cSRoman Divacky   SetCommonAttributes(D, F);
437f22ef01cSRoman Divacky }
438f22ef01cSRoman Divacky 
439f22ef01cSRoman Divacky void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
440f22ef01cSRoman Divacky                                           llvm::Function *F,
441f22ef01cSRoman Divacky                                           bool IsIncompleteFunction) {
442f22ef01cSRoman Divacky   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
443f22ef01cSRoman Divacky 
444f22ef01cSRoman Divacky   if (!IsIncompleteFunction)
445f22ef01cSRoman Divacky     SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(GD), F);
446f22ef01cSRoman Divacky 
447f22ef01cSRoman Divacky   // Only a few attributes are set on declarations; these may later be
448f22ef01cSRoman Divacky   // overridden by a definition.
449f22ef01cSRoman Divacky 
450f22ef01cSRoman Divacky   if (FD->hasAttr<DLLImportAttr>()) {
451f22ef01cSRoman Divacky     F->setLinkage(llvm::Function::DLLImportLinkage);
452f22ef01cSRoman Divacky   } else if (FD->hasAttr<WeakAttr>() ||
453f22ef01cSRoman Divacky              FD->hasAttr<WeakImportAttr>()) {
454f22ef01cSRoman Divacky     // "extern_weak" is overloaded in LLVM; we probably should have
455f22ef01cSRoman Divacky     // separate linkage types for this.
456f22ef01cSRoman Divacky     F->setLinkage(llvm::Function::ExternalWeakLinkage);
457f22ef01cSRoman Divacky   } else {
458f22ef01cSRoman Divacky     F->setLinkage(llvm::Function::ExternalLinkage);
459f22ef01cSRoman Divacky   }
460f22ef01cSRoman Divacky 
461f22ef01cSRoman Divacky   if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
462f22ef01cSRoman Divacky     F->setSection(SA->getName());
463f22ef01cSRoman Divacky }
464f22ef01cSRoman Divacky 
465f22ef01cSRoman Divacky void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
466f22ef01cSRoman Divacky   assert(!GV->isDeclaration() &&
467f22ef01cSRoman Divacky          "Only globals with definition can force usage.");
468f22ef01cSRoman Divacky   LLVMUsed.push_back(GV);
469f22ef01cSRoman Divacky }
470f22ef01cSRoman Divacky 
471f22ef01cSRoman Divacky void CodeGenModule::EmitLLVMUsed() {
472f22ef01cSRoman Divacky   // Don't create llvm.used if there is no need.
473f22ef01cSRoman Divacky   if (LLVMUsed.empty())
474f22ef01cSRoman Divacky     return;
475f22ef01cSRoman Divacky 
476f22ef01cSRoman Divacky   const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext);
477f22ef01cSRoman Divacky 
478f22ef01cSRoman Divacky   // Convert LLVMUsed to what ConstantArray needs.
479f22ef01cSRoman Divacky   std::vector<llvm::Constant*> UsedArray;
480f22ef01cSRoman Divacky   UsedArray.resize(LLVMUsed.size());
481f22ef01cSRoman Divacky   for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
482f22ef01cSRoman Divacky     UsedArray[i] =
483f22ef01cSRoman Divacky      llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
484f22ef01cSRoman Divacky                                       i8PTy);
485f22ef01cSRoman Divacky   }
486f22ef01cSRoman Divacky 
487f22ef01cSRoman Divacky   if (UsedArray.empty())
488f22ef01cSRoman Divacky     return;
489f22ef01cSRoman Divacky   llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size());
490f22ef01cSRoman Divacky 
491f22ef01cSRoman Divacky   llvm::GlobalVariable *GV =
492f22ef01cSRoman Divacky     new llvm::GlobalVariable(getModule(), ATy, false,
493f22ef01cSRoman Divacky                              llvm::GlobalValue::AppendingLinkage,
494f22ef01cSRoman Divacky                              llvm::ConstantArray::get(ATy, UsedArray),
495f22ef01cSRoman Divacky                              "llvm.used");
496f22ef01cSRoman Divacky 
497f22ef01cSRoman Divacky   GV->setSection("llvm.metadata");
498f22ef01cSRoman Divacky }
499f22ef01cSRoman Divacky 
500f22ef01cSRoman Divacky void CodeGenModule::EmitDeferred() {
501f22ef01cSRoman Divacky   // Emit code for any potentially referenced deferred decls.  Since a
502f22ef01cSRoman Divacky   // previously unused static decl may become used during the generation of code
503f22ef01cSRoman Divacky   // for a static function, iterate until no  changes are made.
504f22ef01cSRoman Divacky 
505f22ef01cSRoman Divacky   while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) {
506f22ef01cSRoman Divacky     if (!DeferredVTables.empty()) {
507f22ef01cSRoman Divacky       const CXXRecordDecl *RD = DeferredVTables.back();
508f22ef01cSRoman Divacky       DeferredVTables.pop_back();
509f22ef01cSRoman Divacky       getVTables().GenerateClassData(getVTableLinkage(RD), RD);
510f22ef01cSRoman Divacky       continue;
511f22ef01cSRoman Divacky     }
512f22ef01cSRoman Divacky 
513f22ef01cSRoman Divacky     GlobalDecl D = DeferredDeclsToEmit.back();
514f22ef01cSRoman Divacky     DeferredDeclsToEmit.pop_back();
515f22ef01cSRoman Divacky 
516f22ef01cSRoman Divacky     // Check to see if we've already emitted this.  This is necessary
517f22ef01cSRoman Divacky     // for a couple of reasons: first, decls can end up in the
518f22ef01cSRoman Divacky     // deferred-decls queue multiple times, and second, decls can end
519f22ef01cSRoman Divacky     // up with definitions in unusual ways (e.g. by an extern inline
520f22ef01cSRoman Divacky     // function acquiring a strong function redefinition).  Just
521f22ef01cSRoman Divacky     // ignore these cases.
522f22ef01cSRoman Divacky     //
523f22ef01cSRoman Divacky     // TODO: That said, looking this up multiple times is very wasteful.
524f22ef01cSRoman Divacky     MangleBuffer Name;
525f22ef01cSRoman Divacky     getMangledName(Name, D);
526f22ef01cSRoman Divacky     llvm::GlobalValue *CGRef = GetGlobalValue(Name);
527f22ef01cSRoman Divacky     assert(CGRef && "Deferred decl wasn't referenced?");
528f22ef01cSRoman Divacky 
529f22ef01cSRoman Divacky     if (!CGRef->isDeclaration())
530f22ef01cSRoman Divacky       continue;
531f22ef01cSRoman Divacky 
532f22ef01cSRoman Divacky     // GlobalAlias::isDeclaration() defers to the aliasee, but for our
533f22ef01cSRoman Divacky     // purposes an alias counts as a definition.
534f22ef01cSRoman Divacky     if (isa<llvm::GlobalAlias>(CGRef))
535f22ef01cSRoman Divacky       continue;
536f22ef01cSRoman Divacky 
537f22ef01cSRoman Divacky     // Otherwise, emit the definition and move on to the next one.
538f22ef01cSRoman Divacky     EmitGlobalDefinition(D);
539f22ef01cSRoman Divacky   }
540f22ef01cSRoman Divacky }
541f22ef01cSRoman Divacky 
542f22ef01cSRoman Divacky /// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
543f22ef01cSRoman Divacky /// annotation information for a given GlobalValue.  The annotation struct is
544f22ef01cSRoman Divacky /// {i8 *, i8 *, i8 *, i32}.  The first field is a constant expression, the
545f22ef01cSRoman Divacky /// GlobalValue being annotated.  The second field is the constant string
546f22ef01cSRoman Divacky /// created from the AnnotateAttr's annotation.  The third field is a constant
547f22ef01cSRoman Divacky /// string containing the name of the translation unit.  The fourth field is
548f22ef01cSRoman Divacky /// the line number in the file of the annotated value declaration.
549f22ef01cSRoman Divacky ///
550f22ef01cSRoman Divacky /// FIXME: this does not unique the annotation string constants, as llvm-gcc
551f22ef01cSRoman Divacky ///        appears to.
552f22ef01cSRoman Divacky ///
553f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
554f22ef01cSRoman Divacky                                                 const AnnotateAttr *AA,
555f22ef01cSRoman Divacky                                                 unsigned LineNo) {
556f22ef01cSRoman Divacky   llvm::Module *M = &getModule();
557f22ef01cSRoman Divacky 
558f22ef01cSRoman Divacky   // get [N x i8] constants for the annotation string, and the filename string
559f22ef01cSRoman Divacky   // which are the 2nd and 3rd elements of the global annotation structure.
560f22ef01cSRoman Divacky   const llvm::Type *SBP = llvm::Type::getInt8PtrTy(VMContext);
561f22ef01cSRoman Divacky   llvm::Constant *anno = llvm::ConstantArray::get(VMContext,
562f22ef01cSRoman Divacky                                                   AA->getAnnotation(), true);
563f22ef01cSRoman Divacky   llvm::Constant *unit = llvm::ConstantArray::get(VMContext,
564f22ef01cSRoman Divacky                                                   M->getModuleIdentifier(),
565f22ef01cSRoman Divacky                                                   true);
566f22ef01cSRoman Divacky 
567f22ef01cSRoman Divacky   // Get the two global values corresponding to the ConstantArrays we just
568f22ef01cSRoman Divacky   // created to hold the bytes of the strings.
569f22ef01cSRoman Divacky   llvm::GlobalValue *annoGV =
570f22ef01cSRoman Divacky     new llvm::GlobalVariable(*M, anno->getType(), false,
571f22ef01cSRoman Divacky                              llvm::GlobalValue::PrivateLinkage, anno,
572f22ef01cSRoman Divacky                              GV->getName());
573f22ef01cSRoman Divacky   // translation unit name string, emitted into the llvm.metadata section.
574f22ef01cSRoman Divacky   llvm::GlobalValue *unitGV =
575f22ef01cSRoman Divacky     new llvm::GlobalVariable(*M, unit->getType(), false,
576f22ef01cSRoman Divacky                              llvm::GlobalValue::PrivateLinkage, unit,
577f22ef01cSRoman Divacky                              ".str");
578f22ef01cSRoman Divacky 
579f22ef01cSRoman Divacky   // Create the ConstantStruct for the global annotation.
580f22ef01cSRoman Divacky   llvm::Constant *Fields[4] = {
581f22ef01cSRoman Divacky     llvm::ConstantExpr::getBitCast(GV, SBP),
582f22ef01cSRoman Divacky     llvm::ConstantExpr::getBitCast(annoGV, SBP),
583f22ef01cSRoman Divacky     llvm::ConstantExpr::getBitCast(unitGV, SBP),
584f22ef01cSRoman Divacky     llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo)
585f22ef01cSRoman Divacky   };
586f22ef01cSRoman Divacky   return llvm::ConstantStruct::get(VMContext, Fields, 4, false);
587f22ef01cSRoman Divacky }
588f22ef01cSRoman Divacky 
589f22ef01cSRoman Divacky bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
590f22ef01cSRoman Divacky   // Never defer when EmitAllDecls is specified or the decl has
591f22ef01cSRoman Divacky   // attribute used.
592f22ef01cSRoman Divacky   if (Features.EmitAllDecls || Global->hasAttr<UsedAttr>())
593f22ef01cSRoman Divacky     return false;
594f22ef01cSRoman Divacky 
595f22ef01cSRoman Divacky   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
596f22ef01cSRoman Divacky     // Constructors and destructors should never be deferred.
597f22ef01cSRoman Divacky     if (FD->hasAttr<ConstructorAttr>() ||
598f22ef01cSRoman Divacky         FD->hasAttr<DestructorAttr>())
599f22ef01cSRoman Divacky       return false;
600f22ef01cSRoman Divacky 
601f22ef01cSRoman Divacky     // The key function for a class must never be deferred.
602f22ef01cSRoman Divacky     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Global)) {
603f22ef01cSRoman Divacky       const CXXRecordDecl *RD = MD->getParent();
604f22ef01cSRoman Divacky       if (MD->isOutOfLine() && RD->isDynamicClass()) {
605f22ef01cSRoman Divacky         const CXXMethodDecl *KeyFunction = getContext().getKeyFunction(RD);
606f22ef01cSRoman Divacky         if (KeyFunction &&
607f22ef01cSRoman Divacky             KeyFunction->getCanonicalDecl() == MD->getCanonicalDecl())
608f22ef01cSRoman Divacky           return false;
609f22ef01cSRoman Divacky       }
610f22ef01cSRoman Divacky     }
611f22ef01cSRoman Divacky 
612f22ef01cSRoman Divacky     GVALinkage Linkage = GetLinkageForFunction(getContext(), FD, Features);
613f22ef01cSRoman Divacky 
614f22ef01cSRoman Divacky     // static, static inline, always_inline, and extern inline functions can
615f22ef01cSRoman Divacky     // always be deferred.  Normal inline functions can be deferred in C99/C++.
616f22ef01cSRoman Divacky     // Implicit template instantiations can also be deferred in C++.
617f22ef01cSRoman Divacky     if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
618f22ef01cSRoman Divacky         Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
619f22ef01cSRoman Divacky       return true;
620f22ef01cSRoman Divacky     return false;
621f22ef01cSRoman Divacky   }
622f22ef01cSRoman Divacky 
623f22ef01cSRoman Divacky   const VarDecl *VD = cast<VarDecl>(Global);
624f22ef01cSRoman Divacky   assert(VD->isFileVarDecl() && "Invalid decl");
625f22ef01cSRoman Divacky 
626f22ef01cSRoman Divacky   // We never want to defer structs that have non-trivial constructors or
627f22ef01cSRoman Divacky   // destructors.
628f22ef01cSRoman Divacky 
629f22ef01cSRoman Divacky   // FIXME: Handle references.
630f22ef01cSRoman Divacky   if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
631f22ef01cSRoman Divacky     if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
632f22ef01cSRoman Divacky       if (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor())
633f22ef01cSRoman Divacky         return false;
634f22ef01cSRoman Divacky     }
635f22ef01cSRoman Divacky   }
636f22ef01cSRoman Divacky 
637f22ef01cSRoman Divacky   // Static data may be deferred, but out-of-line static data members
638f22ef01cSRoman Divacky   // cannot be.
639f22ef01cSRoman Divacky   Linkage L = VD->getLinkage();
640f22ef01cSRoman Divacky   if (L == ExternalLinkage && getContext().getLangOptions().CPlusPlus &&
641f22ef01cSRoman Divacky       VD->getType()->getLinkage() == UniqueExternalLinkage)
642f22ef01cSRoman Divacky     L = UniqueExternalLinkage;
643f22ef01cSRoman Divacky 
644f22ef01cSRoman Divacky   switch (L) {
645f22ef01cSRoman Divacky   case NoLinkage:
646f22ef01cSRoman Divacky   case InternalLinkage:
647f22ef01cSRoman Divacky   case UniqueExternalLinkage:
648f22ef01cSRoman Divacky     // Initializer has side effects?
649f22ef01cSRoman Divacky     if (VD->getInit() && VD->getInit()->HasSideEffects(Context))
650f22ef01cSRoman Divacky       return false;
651f22ef01cSRoman Divacky     return !(VD->isStaticDataMember() && VD->isOutOfLine());
652f22ef01cSRoman Divacky 
653f22ef01cSRoman Divacky   case ExternalLinkage:
654f22ef01cSRoman Divacky     break;
655f22ef01cSRoman Divacky   }
656f22ef01cSRoman Divacky 
657f22ef01cSRoman Divacky   return false;
658f22ef01cSRoman Divacky }
659f22ef01cSRoman Divacky 
660f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
661f22ef01cSRoman Divacky   const AliasAttr *AA = VD->getAttr<AliasAttr>();
662f22ef01cSRoman Divacky   assert(AA && "No alias?");
663f22ef01cSRoman Divacky 
664f22ef01cSRoman Divacky   const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
665f22ef01cSRoman Divacky 
666f22ef01cSRoman Divacky   // See if there is already something with the target's name in the module.
667f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
668f22ef01cSRoman Divacky 
669f22ef01cSRoman Divacky   llvm::Constant *Aliasee;
670f22ef01cSRoman Divacky   if (isa<llvm::FunctionType>(DeclTy))
671f22ef01cSRoman Divacky     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl());
672f22ef01cSRoman Divacky   else
673f22ef01cSRoman Divacky     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
674f22ef01cSRoman Divacky                                     llvm::PointerType::getUnqual(DeclTy), 0);
675f22ef01cSRoman Divacky   if (!Entry) {
676f22ef01cSRoman Divacky     llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
677f22ef01cSRoman Divacky     F->setLinkage(llvm::Function::ExternalWeakLinkage);
678f22ef01cSRoman Divacky     WeakRefReferences.insert(F);
679f22ef01cSRoman Divacky   }
680f22ef01cSRoman Divacky 
681f22ef01cSRoman Divacky   return Aliasee;
682f22ef01cSRoman Divacky }
683f22ef01cSRoman Divacky 
684f22ef01cSRoman Divacky void CodeGenModule::EmitGlobal(GlobalDecl GD) {
685f22ef01cSRoman Divacky   const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
686f22ef01cSRoman Divacky 
687f22ef01cSRoman Divacky   // Weak references don't produce any output by themselves.
688f22ef01cSRoman Divacky   if (Global->hasAttr<WeakRefAttr>())
689f22ef01cSRoman Divacky     return;
690f22ef01cSRoman Divacky 
691f22ef01cSRoman Divacky   // If this is an alias definition (which otherwise looks like a declaration)
692f22ef01cSRoman Divacky   // emit it now.
693f22ef01cSRoman Divacky   if (Global->hasAttr<AliasAttr>())
694f22ef01cSRoman Divacky     return EmitAliasDefinition(GD);
695f22ef01cSRoman Divacky 
696f22ef01cSRoman Divacky   // Ignore declarations, they will be emitted on their first use.
697f22ef01cSRoman Divacky   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
698f22ef01cSRoman Divacky     // Forward declarations are emitted lazily on first use.
699f22ef01cSRoman Divacky     if (!FD->isThisDeclarationADefinition())
700f22ef01cSRoman Divacky       return;
701f22ef01cSRoman Divacky   } else {
702f22ef01cSRoman Divacky     const VarDecl *VD = cast<VarDecl>(Global);
703f22ef01cSRoman Divacky     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
704f22ef01cSRoman Divacky 
705f22ef01cSRoman Divacky     if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
706f22ef01cSRoman Divacky       return;
707f22ef01cSRoman Divacky   }
708f22ef01cSRoman Divacky 
709f22ef01cSRoman Divacky   // Defer code generation when possible if this is a static definition, inline
710f22ef01cSRoman Divacky   // function etc.  These we only want to emit if they are used.
711f22ef01cSRoman Divacky   if (!MayDeferGeneration(Global)) {
712f22ef01cSRoman Divacky     // Emit the definition if it can't be deferred.
713f22ef01cSRoman Divacky     EmitGlobalDefinition(GD);
714f22ef01cSRoman Divacky     return;
715f22ef01cSRoman Divacky   }
716f22ef01cSRoman Divacky 
717f22ef01cSRoman Divacky   // If the value has already been used, add it directly to the
718f22ef01cSRoman Divacky   // DeferredDeclsToEmit list.
719f22ef01cSRoman Divacky   MangleBuffer MangledName;
720f22ef01cSRoman Divacky   getMangledName(MangledName, GD);
721f22ef01cSRoman Divacky   if (GetGlobalValue(MangledName))
722f22ef01cSRoman Divacky     DeferredDeclsToEmit.push_back(GD);
723f22ef01cSRoman Divacky   else {
724f22ef01cSRoman Divacky     // Otherwise, remember that we saw a deferred decl with this name.  The
725f22ef01cSRoman Divacky     // first use of the mangled name will cause it to move into
726f22ef01cSRoman Divacky     // DeferredDeclsToEmit.
727f22ef01cSRoman Divacky     DeferredDecls[MangledName] = GD;
728f22ef01cSRoman Divacky   }
729f22ef01cSRoman Divacky }
730f22ef01cSRoman Divacky 
731f22ef01cSRoman Divacky void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
732f22ef01cSRoman Divacky   const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
733f22ef01cSRoman Divacky 
734f22ef01cSRoman Divacky   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
735f22ef01cSRoman Divacky                                  Context.getSourceManager(),
736f22ef01cSRoman Divacky                                  "Generating code for declaration");
737f22ef01cSRoman Divacky 
738f22ef01cSRoman Divacky   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
739f22ef01cSRoman Divacky     if (Method->isVirtual())
740f22ef01cSRoman Divacky       getVTables().EmitThunks(GD);
741f22ef01cSRoman Divacky 
742f22ef01cSRoman Divacky   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
743f22ef01cSRoman Divacky     return EmitCXXConstructor(CD, GD.getCtorType());
744f22ef01cSRoman Divacky 
745f22ef01cSRoman Divacky   if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
746f22ef01cSRoman Divacky     return EmitCXXDestructor(DD, GD.getDtorType());
747f22ef01cSRoman Divacky 
748f22ef01cSRoman Divacky   if (isa<FunctionDecl>(D))
749f22ef01cSRoman Divacky     return EmitGlobalFunctionDefinition(GD);
750f22ef01cSRoman Divacky 
751f22ef01cSRoman Divacky   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
752f22ef01cSRoman Divacky     return EmitGlobalVarDefinition(VD);
753f22ef01cSRoman Divacky 
754f22ef01cSRoman Divacky   assert(0 && "Invalid argument to EmitGlobalDefinition()");
755f22ef01cSRoman Divacky }
756f22ef01cSRoman Divacky 
757f22ef01cSRoman Divacky /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
758f22ef01cSRoman Divacky /// module, create and return an llvm Function with the specified type. If there
759f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially
760f22ef01cSRoman Divacky /// bitcasted to the right type.
761f22ef01cSRoman Divacky ///
762f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this.  This is used
763f22ef01cSRoman Divacky /// to set the attributes on the function when it is first created.
764f22ef01cSRoman Divacky llvm::Constant *
765f22ef01cSRoman Divacky CodeGenModule::GetOrCreateLLVMFunction(llvm::StringRef MangledName,
766f22ef01cSRoman Divacky                                        const llvm::Type *Ty,
767f22ef01cSRoman Divacky                                        GlobalDecl D) {
768f22ef01cSRoman Divacky   // Lookup the entry, lazily creating it if necessary.
769f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
770f22ef01cSRoman Divacky   if (Entry) {
771f22ef01cSRoman Divacky     if (WeakRefReferences.count(Entry)) {
772f22ef01cSRoman Divacky       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
773f22ef01cSRoman Divacky       if (FD && !FD->hasAttr<WeakAttr>())
774f22ef01cSRoman Divacky         Entry->setLinkage(llvm::Function::ExternalLinkage);
775f22ef01cSRoman Divacky 
776f22ef01cSRoman Divacky       WeakRefReferences.erase(Entry);
777f22ef01cSRoman Divacky     }
778f22ef01cSRoman Divacky 
779f22ef01cSRoman Divacky     if (Entry->getType()->getElementType() == Ty)
780f22ef01cSRoman Divacky       return Entry;
781f22ef01cSRoman Divacky 
782f22ef01cSRoman Divacky     // Make sure the result is of the correct type.
783f22ef01cSRoman Divacky     const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
784f22ef01cSRoman Divacky     return llvm::ConstantExpr::getBitCast(Entry, PTy);
785f22ef01cSRoman Divacky   }
786f22ef01cSRoman Divacky 
787f22ef01cSRoman Divacky   // This function doesn't have a complete type (for example, the return
788f22ef01cSRoman Divacky   // type is an incomplete struct). Use a fake type instead, and make
789f22ef01cSRoman Divacky   // sure not to try to set attributes.
790f22ef01cSRoman Divacky   bool IsIncompleteFunction = false;
791f22ef01cSRoman Divacky 
792f22ef01cSRoman Divacky   const llvm::FunctionType *FTy;
793f22ef01cSRoman Divacky   if (isa<llvm::FunctionType>(Ty)) {
794f22ef01cSRoman Divacky     FTy = cast<llvm::FunctionType>(Ty);
795f22ef01cSRoman Divacky   } else {
796f22ef01cSRoman Divacky     FTy = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
797f22ef01cSRoman Divacky                                   std::vector<const llvm::Type*>(), false);
798f22ef01cSRoman Divacky     IsIncompleteFunction = true;
799f22ef01cSRoman Divacky   }
800f22ef01cSRoman Divacky   llvm::Function *F = llvm::Function::Create(FTy,
801f22ef01cSRoman Divacky                                              llvm::Function::ExternalLinkage,
802f22ef01cSRoman Divacky                                              MangledName, &getModule());
803f22ef01cSRoman Divacky   assert(F->getName() == MangledName && "name was uniqued!");
804f22ef01cSRoman Divacky   if (D.getDecl())
805f22ef01cSRoman Divacky     SetFunctionAttributes(D, F, IsIncompleteFunction);
806f22ef01cSRoman Divacky 
807f22ef01cSRoman Divacky   // This is the first use or definition of a mangled name.  If there is a
808f22ef01cSRoman Divacky   // deferred decl with this name, remember that we need to emit it at the end
809f22ef01cSRoman Divacky   // of the file.
810f22ef01cSRoman Divacky   llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
811f22ef01cSRoman Divacky   if (DDI != DeferredDecls.end()) {
812f22ef01cSRoman Divacky     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
813f22ef01cSRoman Divacky     // list, and remove it from DeferredDecls (since we don't need it anymore).
814f22ef01cSRoman Divacky     DeferredDeclsToEmit.push_back(DDI->second);
815f22ef01cSRoman Divacky     DeferredDecls.erase(DDI);
816f22ef01cSRoman Divacky   } else if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl())) {
817f22ef01cSRoman Divacky     // If this the first reference to a C++ inline function in a class, queue up
818f22ef01cSRoman Divacky     // the deferred function body for emission.  These are not seen as
819f22ef01cSRoman Divacky     // top-level declarations.
820f22ef01cSRoman Divacky     if (FD->isThisDeclarationADefinition() && MayDeferGeneration(FD))
821f22ef01cSRoman Divacky       DeferredDeclsToEmit.push_back(D);
822f22ef01cSRoman Divacky     // A called constructor which has no definition or declaration need be
823f22ef01cSRoman Divacky     // synthesized.
824f22ef01cSRoman Divacky     else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
825f22ef01cSRoman Divacky       if (CD->isImplicit()) {
826f22ef01cSRoman Divacky         assert(CD->isUsed() && "Sema doesn't consider constructor as used.");
827f22ef01cSRoman Divacky         DeferredDeclsToEmit.push_back(D);
828f22ef01cSRoman Divacky       }
829f22ef01cSRoman Divacky     } else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD)) {
830f22ef01cSRoman Divacky       if (DD->isImplicit()) {
831f22ef01cSRoman Divacky         assert(DD->isUsed() && "Sema doesn't consider destructor as used.");
832f22ef01cSRoman Divacky         DeferredDeclsToEmit.push_back(D);
833f22ef01cSRoman Divacky       }
834f22ef01cSRoman Divacky     } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
835f22ef01cSRoman Divacky       if (MD->isCopyAssignment() && MD->isImplicit()) {
836f22ef01cSRoman Divacky         assert(MD->isUsed() && "Sema doesn't consider CopyAssignment as used.");
837f22ef01cSRoman Divacky         DeferredDeclsToEmit.push_back(D);
838f22ef01cSRoman Divacky       }
839f22ef01cSRoman Divacky     }
840f22ef01cSRoman Divacky   }
841f22ef01cSRoman Divacky 
842f22ef01cSRoman Divacky   // Make sure the result is of the requested type.
843f22ef01cSRoman Divacky   if (!IsIncompleteFunction) {
844f22ef01cSRoman Divacky     assert(F->getType()->getElementType() == Ty);
845f22ef01cSRoman Divacky     return F;
846f22ef01cSRoman Divacky   }
847f22ef01cSRoman Divacky 
848f22ef01cSRoman Divacky   const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
849f22ef01cSRoman Divacky   return llvm::ConstantExpr::getBitCast(F, PTy);
850f22ef01cSRoman Divacky }
851f22ef01cSRoman Divacky 
852f22ef01cSRoman Divacky /// GetAddrOfFunction - Return the address of the given function.  If Ty is
853f22ef01cSRoman Divacky /// non-null, then this function will use the specified type if it has to
854f22ef01cSRoman Divacky /// create it (this occurs when we see a definition of the function).
855f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
856f22ef01cSRoman Divacky                                                  const llvm::Type *Ty) {
857f22ef01cSRoman Divacky   // If there was no specific requested type, just convert it now.
858f22ef01cSRoman Divacky   if (!Ty)
859f22ef01cSRoman Divacky     Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
860f22ef01cSRoman Divacky   MangleBuffer MangledName;
861f22ef01cSRoman Divacky   getMangledName(MangledName, GD);
862f22ef01cSRoman Divacky   return GetOrCreateLLVMFunction(MangledName, Ty, GD);
863f22ef01cSRoman Divacky }
864f22ef01cSRoman Divacky 
865f22ef01cSRoman Divacky /// CreateRuntimeFunction - Create a new runtime function with the specified
866f22ef01cSRoman Divacky /// type and name.
867f22ef01cSRoman Divacky llvm::Constant *
868f22ef01cSRoman Divacky CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
869f22ef01cSRoman Divacky                                      llvm::StringRef Name) {
870f22ef01cSRoman Divacky   return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl());
871f22ef01cSRoman Divacky }
872f22ef01cSRoman Divacky 
873f22ef01cSRoman Divacky static bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D) {
874f22ef01cSRoman Divacky   if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType())
875f22ef01cSRoman Divacky     return false;
876f22ef01cSRoman Divacky   if (Context.getLangOptions().CPlusPlus &&
877f22ef01cSRoman Divacky       Context.getBaseElementType(D->getType())->getAs<RecordType>()) {
878f22ef01cSRoman Divacky     // FIXME: We should do something fancier here!
879f22ef01cSRoman Divacky     return false;
880f22ef01cSRoman Divacky   }
881f22ef01cSRoman Divacky   return true;
882f22ef01cSRoman Divacky }
883f22ef01cSRoman Divacky 
884f22ef01cSRoman Divacky /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
885f22ef01cSRoman Divacky /// create and return an llvm GlobalVariable with the specified type.  If there
886f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially
887f22ef01cSRoman Divacky /// bitcasted to the right type.
888f22ef01cSRoman Divacky ///
889f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this.  This is used
890f22ef01cSRoman Divacky /// to set the attributes on the global when it is first created.
891f22ef01cSRoman Divacky llvm::Constant *
892f22ef01cSRoman Divacky CodeGenModule::GetOrCreateLLVMGlobal(llvm::StringRef MangledName,
893f22ef01cSRoman Divacky                                      const llvm::PointerType *Ty,
894f22ef01cSRoman Divacky                                      const VarDecl *D) {
895f22ef01cSRoman Divacky   // Lookup the entry, lazily creating it if necessary.
896f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
897f22ef01cSRoman Divacky   if (Entry) {
898f22ef01cSRoman Divacky     if (WeakRefReferences.count(Entry)) {
899f22ef01cSRoman Divacky       if (D && !D->hasAttr<WeakAttr>())
900f22ef01cSRoman Divacky         Entry->setLinkage(llvm::Function::ExternalLinkage);
901f22ef01cSRoman Divacky 
902f22ef01cSRoman Divacky       WeakRefReferences.erase(Entry);
903f22ef01cSRoman Divacky     }
904f22ef01cSRoman Divacky 
905f22ef01cSRoman Divacky     if (Entry->getType() == Ty)
906f22ef01cSRoman Divacky       return Entry;
907f22ef01cSRoman Divacky 
908f22ef01cSRoman Divacky     // Make sure the result is of the correct type.
909f22ef01cSRoman Divacky     return llvm::ConstantExpr::getBitCast(Entry, Ty);
910f22ef01cSRoman Divacky   }
911f22ef01cSRoman Divacky 
912f22ef01cSRoman Divacky   // This is the first use or definition of a mangled name.  If there is a
913f22ef01cSRoman Divacky   // deferred decl with this name, remember that we need to emit it at the end
914f22ef01cSRoman Divacky   // of the file.
915f22ef01cSRoman Divacky   llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
916f22ef01cSRoman Divacky   if (DDI != DeferredDecls.end()) {
917f22ef01cSRoman Divacky     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
918f22ef01cSRoman Divacky     // list, and remove it from DeferredDecls (since we don't need it anymore).
919f22ef01cSRoman Divacky     DeferredDeclsToEmit.push_back(DDI->second);
920f22ef01cSRoman Divacky     DeferredDecls.erase(DDI);
921f22ef01cSRoman Divacky   }
922f22ef01cSRoman Divacky 
923f22ef01cSRoman Divacky   llvm::GlobalVariable *GV =
924f22ef01cSRoman Divacky     new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
925f22ef01cSRoman Divacky                              llvm::GlobalValue::ExternalLinkage,
926f22ef01cSRoman Divacky                              0, MangledName, 0,
927f22ef01cSRoman Divacky                              false, Ty->getAddressSpace());
928f22ef01cSRoman Divacky 
929f22ef01cSRoman Divacky   // Handle things which are present even on external declarations.
930f22ef01cSRoman Divacky   if (D) {
931f22ef01cSRoman Divacky     // FIXME: This code is overly simple and should be merged with other global
932f22ef01cSRoman Divacky     // handling.
933f22ef01cSRoman Divacky     GV->setConstant(DeclIsConstantGlobal(Context, D));
934f22ef01cSRoman Divacky 
935f22ef01cSRoman Divacky     // FIXME: Merge with other attribute handling code.
936f22ef01cSRoman Divacky     if (D->getStorageClass() == VarDecl::PrivateExtern)
937f22ef01cSRoman Divacky       GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
938f22ef01cSRoman Divacky 
939f22ef01cSRoman Divacky     if (D->hasAttr<WeakAttr>() ||
940f22ef01cSRoman Divacky         D->hasAttr<WeakImportAttr>())
941f22ef01cSRoman Divacky       GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
942f22ef01cSRoman Divacky 
943f22ef01cSRoman Divacky     GV->setThreadLocal(D->isThreadSpecified());
944f22ef01cSRoman Divacky   }
945f22ef01cSRoman Divacky 
946f22ef01cSRoman Divacky   return GV;
947f22ef01cSRoman Divacky }
948f22ef01cSRoman Divacky 
949f22ef01cSRoman Divacky 
950f22ef01cSRoman Divacky /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
951f22ef01cSRoman Divacky /// given global variable.  If Ty is non-null and if the global doesn't exist,
952f22ef01cSRoman Divacky /// then it will be greated with the specified type instead of whatever the
953f22ef01cSRoman Divacky /// normal requested type would be.
954f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
955f22ef01cSRoman Divacky                                                   const llvm::Type *Ty) {
956f22ef01cSRoman Divacky   assert(D->hasGlobalStorage() && "Not a global variable");
957f22ef01cSRoman Divacky   QualType ASTTy = D->getType();
958f22ef01cSRoman Divacky   if (Ty == 0)
959f22ef01cSRoman Divacky     Ty = getTypes().ConvertTypeForMem(ASTTy);
960f22ef01cSRoman Divacky 
961f22ef01cSRoman Divacky   const llvm::PointerType *PTy =
962f22ef01cSRoman Divacky     llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
963f22ef01cSRoman Divacky 
964f22ef01cSRoman Divacky   MangleBuffer MangledName;
965f22ef01cSRoman Divacky   getMangledName(MangledName, D);
966f22ef01cSRoman Divacky   return GetOrCreateLLVMGlobal(MangledName, PTy, D);
967f22ef01cSRoman Divacky }
968f22ef01cSRoman Divacky 
969f22ef01cSRoman Divacky /// CreateRuntimeVariable - Create a new runtime global variable with the
970f22ef01cSRoman Divacky /// specified type and name.
971f22ef01cSRoman Divacky llvm::Constant *
972f22ef01cSRoman Divacky CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
973f22ef01cSRoman Divacky                                      llvm::StringRef Name) {
974f22ef01cSRoman Divacky   return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0);
975f22ef01cSRoman Divacky }
976f22ef01cSRoman Divacky 
977f22ef01cSRoman Divacky void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
978f22ef01cSRoman Divacky   assert(!D->getInit() && "Cannot emit definite definitions here!");
979f22ef01cSRoman Divacky 
980f22ef01cSRoman Divacky   if (MayDeferGeneration(D)) {
981f22ef01cSRoman Divacky     // If we have not seen a reference to this variable yet, place it
982f22ef01cSRoman Divacky     // into the deferred declarations table to be emitted if needed
983f22ef01cSRoman Divacky     // later.
984f22ef01cSRoman Divacky     MangleBuffer MangledName;
985f22ef01cSRoman Divacky     getMangledName(MangledName, D);
986f22ef01cSRoman Divacky     if (!GetGlobalValue(MangledName)) {
987f22ef01cSRoman Divacky       DeferredDecls[MangledName] = D;
988f22ef01cSRoman Divacky       return;
989f22ef01cSRoman Divacky     }
990f22ef01cSRoman Divacky   }
991f22ef01cSRoman Divacky 
992f22ef01cSRoman Divacky   // The tentative definition is the only definition.
993f22ef01cSRoman Divacky   EmitGlobalVarDefinition(D);
994f22ef01cSRoman Divacky }
995f22ef01cSRoman Divacky 
996f22ef01cSRoman Divacky void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) {
997f22ef01cSRoman Divacky   if (DefinitionRequired)
998f22ef01cSRoman Divacky     getVTables().GenerateClassData(getVTableLinkage(Class), Class);
999f22ef01cSRoman Divacky }
1000f22ef01cSRoman Divacky 
1001f22ef01cSRoman Divacky llvm::GlobalVariable::LinkageTypes
1002f22ef01cSRoman Divacky CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
1003f22ef01cSRoman Divacky   if (RD->isInAnonymousNamespace() || !RD->hasLinkage())
1004f22ef01cSRoman Divacky     return llvm::GlobalVariable::InternalLinkage;
1005f22ef01cSRoman Divacky 
1006f22ef01cSRoman Divacky   if (const CXXMethodDecl *KeyFunction
1007f22ef01cSRoman Divacky                                     = RD->getASTContext().getKeyFunction(RD)) {
1008f22ef01cSRoman Divacky     // If this class has a key function, use that to determine the linkage of
1009f22ef01cSRoman Divacky     // the vtable.
1010f22ef01cSRoman Divacky     const FunctionDecl *Def = 0;
1011f22ef01cSRoman Divacky     if (KeyFunction->getBody(Def))
1012f22ef01cSRoman Divacky       KeyFunction = cast<CXXMethodDecl>(Def);
1013f22ef01cSRoman Divacky 
1014f22ef01cSRoman Divacky     switch (KeyFunction->getTemplateSpecializationKind()) {
1015f22ef01cSRoman Divacky       case TSK_Undeclared:
1016f22ef01cSRoman Divacky       case TSK_ExplicitSpecialization:
1017f22ef01cSRoman Divacky         if (KeyFunction->isInlined())
1018f22ef01cSRoman Divacky           return llvm::GlobalVariable::WeakODRLinkage;
1019f22ef01cSRoman Divacky 
1020f22ef01cSRoman Divacky         return llvm::GlobalVariable::ExternalLinkage;
1021f22ef01cSRoman Divacky 
1022f22ef01cSRoman Divacky       case TSK_ImplicitInstantiation:
1023f22ef01cSRoman Divacky       case TSK_ExplicitInstantiationDefinition:
1024f22ef01cSRoman Divacky         return llvm::GlobalVariable::WeakODRLinkage;
1025f22ef01cSRoman Divacky 
1026f22ef01cSRoman Divacky       case TSK_ExplicitInstantiationDeclaration:
1027f22ef01cSRoman Divacky         // FIXME: Use available_externally linkage. However, this currently
1028f22ef01cSRoman Divacky         // breaks LLVM's build due to undefined symbols.
1029f22ef01cSRoman Divacky         //      return llvm::GlobalVariable::AvailableExternallyLinkage;
1030f22ef01cSRoman Divacky         return llvm::GlobalVariable::WeakODRLinkage;
1031f22ef01cSRoman Divacky     }
1032f22ef01cSRoman Divacky   }
1033f22ef01cSRoman Divacky 
1034f22ef01cSRoman Divacky   switch (RD->getTemplateSpecializationKind()) {
1035f22ef01cSRoman Divacky   case TSK_Undeclared:
1036f22ef01cSRoman Divacky   case TSK_ExplicitSpecialization:
1037f22ef01cSRoman Divacky   case TSK_ImplicitInstantiation:
1038f22ef01cSRoman Divacky   case TSK_ExplicitInstantiationDefinition:
1039f22ef01cSRoman Divacky     return llvm::GlobalVariable::WeakODRLinkage;
1040f22ef01cSRoman Divacky 
1041f22ef01cSRoman Divacky   case TSK_ExplicitInstantiationDeclaration:
1042f22ef01cSRoman Divacky     // FIXME: Use available_externally linkage. However, this currently
1043f22ef01cSRoman Divacky     // breaks LLVM's build due to undefined symbols.
1044f22ef01cSRoman Divacky     //   return llvm::GlobalVariable::AvailableExternallyLinkage;
1045f22ef01cSRoman Divacky     return llvm::GlobalVariable::WeakODRLinkage;
1046f22ef01cSRoman Divacky   }
1047f22ef01cSRoman Divacky 
1048f22ef01cSRoman Divacky   // Silence GCC warning.
1049f22ef01cSRoman Divacky   return llvm::GlobalVariable::WeakODRLinkage;
1050f22ef01cSRoman Divacky }
1051f22ef01cSRoman Divacky 
1052f22ef01cSRoman Divacky static CodeGenModule::GVALinkage
1053f22ef01cSRoman Divacky GetLinkageForVariable(ASTContext &Context, const VarDecl *VD) {
1054f22ef01cSRoman Divacky   // If this is a static data member, compute the kind of template
1055f22ef01cSRoman Divacky   // specialization. Otherwise, this variable is not part of a
1056f22ef01cSRoman Divacky   // template.
1057f22ef01cSRoman Divacky   TemplateSpecializationKind TSK = TSK_Undeclared;
1058f22ef01cSRoman Divacky   if (VD->isStaticDataMember())
1059f22ef01cSRoman Divacky     TSK = VD->getTemplateSpecializationKind();
1060f22ef01cSRoman Divacky 
1061f22ef01cSRoman Divacky   Linkage L = VD->getLinkage();
1062f22ef01cSRoman Divacky   if (L == ExternalLinkage && Context.getLangOptions().CPlusPlus &&
1063f22ef01cSRoman Divacky       VD->getType()->getLinkage() == UniqueExternalLinkage)
1064f22ef01cSRoman Divacky     L = UniqueExternalLinkage;
1065f22ef01cSRoman Divacky 
1066f22ef01cSRoman Divacky   switch (L) {
1067f22ef01cSRoman Divacky   case NoLinkage:
1068f22ef01cSRoman Divacky   case InternalLinkage:
1069f22ef01cSRoman Divacky   case UniqueExternalLinkage:
1070f22ef01cSRoman Divacky     return CodeGenModule::GVA_Internal;
1071f22ef01cSRoman Divacky 
1072f22ef01cSRoman Divacky   case ExternalLinkage:
1073f22ef01cSRoman Divacky     switch (TSK) {
1074f22ef01cSRoman Divacky     case TSK_Undeclared:
1075f22ef01cSRoman Divacky     case TSK_ExplicitSpecialization:
1076f22ef01cSRoman Divacky       return CodeGenModule::GVA_StrongExternal;
1077f22ef01cSRoman Divacky 
1078f22ef01cSRoman Divacky     case TSK_ExplicitInstantiationDeclaration:
1079f22ef01cSRoman Divacky       llvm_unreachable("Variable should not be instantiated");
1080f22ef01cSRoman Divacky       // Fall through to treat this like any other instantiation.
1081f22ef01cSRoman Divacky 
1082f22ef01cSRoman Divacky     case TSK_ExplicitInstantiationDefinition:
1083f22ef01cSRoman Divacky       return CodeGenModule::GVA_ExplicitTemplateInstantiation;
1084f22ef01cSRoman Divacky 
1085f22ef01cSRoman Divacky     case TSK_ImplicitInstantiation:
1086f22ef01cSRoman Divacky       return CodeGenModule::GVA_TemplateInstantiation;
1087f22ef01cSRoman Divacky     }
1088f22ef01cSRoman Divacky   }
1089f22ef01cSRoman Divacky 
1090f22ef01cSRoman Divacky   return CodeGenModule::GVA_StrongExternal;
1091f22ef01cSRoman Divacky }
1092f22ef01cSRoman Divacky 
1093f22ef01cSRoman Divacky CharUnits CodeGenModule::GetTargetTypeStoreSize(const llvm::Type *Ty) const {
1094f22ef01cSRoman Divacky     return CharUnits::fromQuantity(
1095f22ef01cSRoman Divacky       TheTargetData.getTypeStoreSizeInBits(Ty) / Context.getCharWidth());
1096f22ef01cSRoman Divacky }
1097f22ef01cSRoman Divacky 
1098f22ef01cSRoman Divacky void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
1099f22ef01cSRoman Divacky   llvm::Constant *Init = 0;
1100f22ef01cSRoman Divacky   QualType ASTTy = D->getType();
1101f22ef01cSRoman Divacky   bool NonConstInit = false;
1102f22ef01cSRoman Divacky 
1103f22ef01cSRoman Divacky   const Expr *InitExpr = D->getAnyInitializer();
1104f22ef01cSRoman Divacky 
1105f22ef01cSRoman Divacky   if (!InitExpr) {
1106f22ef01cSRoman Divacky     // This is a tentative definition; tentative definitions are
1107f22ef01cSRoman Divacky     // implicitly initialized with { 0 }.
1108f22ef01cSRoman Divacky     //
1109f22ef01cSRoman Divacky     // Note that tentative definitions are only emitted at the end of
1110f22ef01cSRoman Divacky     // a translation unit, so they should never have incomplete
1111f22ef01cSRoman Divacky     // type. In addition, EmitTentativeDefinition makes sure that we
1112f22ef01cSRoman Divacky     // never attempt to emit a tentative definition if a real one
1113f22ef01cSRoman Divacky     // exists. A use may still exists, however, so we still may need
1114f22ef01cSRoman Divacky     // to do a RAUW.
1115f22ef01cSRoman Divacky     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
1116f22ef01cSRoman Divacky     Init = EmitNullConstant(D->getType());
1117f22ef01cSRoman Divacky   } else {
1118f22ef01cSRoman Divacky     Init = EmitConstantExpr(InitExpr, D->getType());
1119f22ef01cSRoman Divacky     if (!Init) {
1120f22ef01cSRoman Divacky       QualType T = InitExpr->getType();
1121f22ef01cSRoman Divacky       if (D->getType()->isReferenceType())
1122f22ef01cSRoman Divacky         T = D->getType();
1123f22ef01cSRoman Divacky 
1124f22ef01cSRoman Divacky       if (getLangOptions().CPlusPlus) {
1125f22ef01cSRoman Divacky         EmitCXXGlobalVarDeclInitFunc(D);
1126f22ef01cSRoman Divacky         Init = EmitNullConstant(T);
1127f22ef01cSRoman Divacky         NonConstInit = true;
1128f22ef01cSRoman Divacky       } else {
1129f22ef01cSRoman Divacky         ErrorUnsupported(D, "static initializer");
1130f22ef01cSRoman Divacky         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1131f22ef01cSRoman Divacky       }
1132f22ef01cSRoman Divacky     }
1133f22ef01cSRoman Divacky   }
1134f22ef01cSRoman Divacky 
1135f22ef01cSRoman Divacky   const llvm::Type* InitType = Init->getType();
1136f22ef01cSRoman Divacky   llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
1137f22ef01cSRoman Divacky 
1138f22ef01cSRoman Divacky   // Strip off a bitcast if we got one back.
1139f22ef01cSRoman Divacky   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1140f22ef01cSRoman Divacky     assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1141f22ef01cSRoman Divacky            // all zero index gep.
1142f22ef01cSRoman Divacky            CE->getOpcode() == llvm::Instruction::GetElementPtr);
1143f22ef01cSRoman Divacky     Entry = CE->getOperand(0);
1144f22ef01cSRoman Divacky   }
1145f22ef01cSRoman Divacky 
1146f22ef01cSRoman Divacky   // Entry is now either a Function or GlobalVariable.
1147f22ef01cSRoman Divacky   llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
1148f22ef01cSRoman Divacky 
1149f22ef01cSRoman Divacky   // We have a definition after a declaration with the wrong type.
1150f22ef01cSRoman Divacky   // We must make a new GlobalVariable* and update everything that used OldGV
1151f22ef01cSRoman Divacky   // (a declaration or tentative definition) with the new GlobalVariable*
1152f22ef01cSRoman Divacky   // (which will be a definition).
1153f22ef01cSRoman Divacky   //
1154f22ef01cSRoman Divacky   // This happens if there is a prototype for a global (e.g.
1155f22ef01cSRoman Divacky   // "extern int x[];") and then a definition of a different type (e.g.
1156f22ef01cSRoman Divacky   // "int x[10];"). This also happens when an initializer has a different type
1157f22ef01cSRoman Divacky   // from the type of the global (this happens with unions).
1158f22ef01cSRoman Divacky   if (GV == 0 ||
1159f22ef01cSRoman Divacky       GV->getType()->getElementType() != InitType ||
1160f22ef01cSRoman Divacky       GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) {
1161f22ef01cSRoman Divacky 
1162f22ef01cSRoman Divacky     // Move the old entry aside so that we'll create a new one.
1163f22ef01cSRoman Divacky     Entry->setName(llvm::StringRef());
1164f22ef01cSRoman Divacky 
1165f22ef01cSRoman Divacky     // Make a new global with the correct type, this is now guaranteed to work.
1166f22ef01cSRoman Divacky     GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
1167f22ef01cSRoman Divacky 
1168f22ef01cSRoman Divacky     // Replace all uses of the old global with the new global
1169f22ef01cSRoman Divacky     llvm::Constant *NewPtrForOldDecl =
1170f22ef01cSRoman Divacky         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
1171f22ef01cSRoman Divacky     Entry->replaceAllUsesWith(NewPtrForOldDecl);
1172f22ef01cSRoman Divacky 
1173f22ef01cSRoman Divacky     // Erase the old global, since it is no longer used.
1174f22ef01cSRoman Divacky     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
1175f22ef01cSRoman Divacky   }
1176f22ef01cSRoman Divacky 
1177f22ef01cSRoman Divacky   if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
1178f22ef01cSRoman Divacky     SourceManager &SM = Context.getSourceManager();
1179f22ef01cSRoman Divacky     AddAnnotation(EmitAnnotateAttr(GV, AA,
1180f22ef01cSRoman Divacky                               SM.getInstantiationLineNumber(D->getLocation())));
1181f22ef01cSRoman Divacky   }
1182f22ef01cSRoman Divacky 
1183f22ef01cSRoman Divacky   GV->setInitializer(Init);
1184f22ef01cSRoman Divacky 
1185f22ef01cSRoman Divacky   // If it is safe to mark the global 'constant', do so now.
1186f22ef01cSRoman Divacky   GV->setConstant(false);
1187f22ef01cSRoman Divacky   if (!NonConstInit && DeclIsConstantGlobal(Context, D))
1188f22ef01cSRoman Divacky     GV->setConstant(true);
1189f22ef01cSRoman Divacky 
1190f22ef01cSRoman Divacky   GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
1191f22ef01cSRoman Divacky 
1192f22ef01cSRoman Divacky   // Set the llvm linkage type as appropriate.
1193f22ef01cSRoman Divacky   GVALinkage Linkage = GetLinkageForVariable(getContext(), D);
1194f22ef01cSRoman Divacky   if (Linkage == GVA_Internal)
1195f22ef01cSRoman Divacky     GV->setLinkage(llvm::Function::InternalLinkage);
1196f22ef01cSRoman Divacky   else if (D->hasAttr<DLLImportAttr>())
1197f22ef01cSRoman Divacky     GV->setLinkage(llvm::Function::DLLImportLinkage);
1198f22ef01cSRoman Divacky   else if (D->hasAttr<DLLExportAttr>())
1199f22ef01cSRoman Divacky     GV->setLinkage(llvm::Function::DLLExportLinkage);
1200f22ef01cSRoman Divacky   else if (D->hasAttr<WeakAttr>()) {
1201f22ef01cSRoman Divacky     if (GV->isConstant())
1202f22ef01cSRoman Divacky       GV->setLinkage(llvm::GlobalVariable::WeakODRLinkage);
1203f22ef01cSRoman Divacky     else
1204f22ef01cSRoman Divacky       GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
1205f22ef01cSRoman Divacky   } else if (Linkage == GVA_TemplateInstantiation ||
1206f22ef01cSRoman Divacky              Linkage == GVA_ExplicitTemplateInstantiation)
1207f22ef01cSRoman Divacky     // FIXME: It seems like we can provide more specific linkage here
1208f22ef01cSRoman Divacky     // (LinkOnceODR, WeakODR).
1209f22ef01cSRoman Divacky     GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
1210f22ef01cSRoman Divacky   else if (!getLangOptions().CPlusPlus && !CodeGenOpts.NoCommon &&
1211f22ef01cSRoman Divacky            !D->hasExternalStorage() && !D->getInit() &&
1212f22ef01cSRoman Divacky            !D->getAttr<SectionAttr>()) {
1213f22ef01cSRoman Divacky     GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
1214f22ef01cSRoman Divacky     // common vars aren't constant even if declared const.
1215f22ef01cSRoman Divacky     GV->setConstant(false);
1216f22ef01cSRoman Divacky   } else
1217f22ef01cSRoman Divacky     GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
1218f22ef01cSRoman Divacky 
1219f22ef01cSRoman Divacky   SetCommonAttributes(D, GV);
1220f22ef01cSRoman Divacky 
1221f22ef01cSRoman Divacky   // Emit global variable debug information.
1222f22ef01cSRoman Divacky   if (CGDebugInfo *DI = getDebugInfo()) {
1223f22ef01cSRoman Divacky     DI->setLocation(D->getLocation());
1224f22ef01cSRoman Divacky     DI->EmitGlobalVariable(GV, D);
1225f22ef01cSRoman Divacky   }
1226f22ef01cSRoman Divacky }
1227f22ef01cSRoman Divacky 
1228f22ef01cSRoman Divacky /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
1229f22ef01cSRoman Divacky /// implement a function with no prototype, e.g. "int foo() {}".  If there are
1230f22ef01cSRoman Divacky /// existing call uses of the old function in the module, this adjusts them to
1231f22ef01cSRoman Divacky /// call the new function directly.
1232f22ef01cSRoman Divacky ///
1233f22ef01cSRoman Divacky /// This is not just a cleanup: the always_inline pass requires direct calls to
1234f22ef01cSRoman Divacky /// functions to be able to inline them.  If there is a bitcast in the way, it
1235f22ef01cSRoman Divacky /// won't inline them.  Instcombine normally deletes these calls, but it isn't
1236f22ef01cSRoman Divacky /// run at -O0.
1237f22ef01cSRoman Divacky static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1238f22ef01cSRoman Divacky                                                       llvm::Function *NewFn) {
1239f22ef01cSRoman Divacky   // If we're redefining a global as a function, don't transform it.
1240f22ef01cSRoman Divacky   llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
1241f22ef01cSRoman Divacky   if (OldFn == 0) return;
1242f22ef01cSRoman Divacky 
1243f22ef01cSRoman Divacky   const llvm::Type *NewRetTy = NewFn->getReturnType();
1244f22ef01cSRoman Divacky   llvm::SmallVector<llvm::Value*, 4> ArgList;
1245f22ef01cSRoman Divacky 
1246f22ef01cSRoman Divacky   for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
1247f22ef01cSRoman Divacky        UI != E; ) {
1248f22ef01cSRoman Divacky     // TODO: Do invokes ever occur in C code?  If so, we should handle them too.
1249f22ef01cSRoman Divacky     llvm::Value::use_iterator I = UI++; // Increment before the CI is erased.
1250f22ef01cSRoman Divacky     llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I);
1251f22ef01cSRoman Divacky     llvm::CallSite CS(CI);
1252f22ef01cSRoman Divacky     if (!CI || !CS.isCallee(I)) continue;
1253f22ef01cSRoman Divacky 
1254f22ef01cSRoman Divacky     // If the return types don't match exactly, and if the call isn't dead, then
1255f22ef01cSRoman Divacky     // we can't transform this call.
1256f22ef01cSRoman Divacky     if (CI->getType() != NewRetTy && !CI->use_empty())
1257f22ef01cSRoman Divacky       continue;
1258f22ef01cSRoman Divacky 
1259f22ef01cSRoman Divacky     // If the function was passed too few arguments, don't transform.  If extra
1260f22ef01cSRoman Divacky     // arguments were passed, we silently drop them.  If any of the types
1261f22ef01cSRoman Divacky     // mismatch, we don't transform.
1262f22ef01cSRoman Divacky     unsigned ArgNo = 0;
1263f22ef01cSRoman Divacky     bool DontTransform = false;
1264f22ef01cSRoman Divacky     for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
1265f22ef01cSRoman Divacky          E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
1266f22ef01cSRoman Divacky       if (CS.arg_size() == ArgNo ||
1267f22ef01cSRoman Divacky           CS.getArgument(ArgNo)->getType() != AI->getType()) {
1268f22ef01cSRoman Divacky         DontTransform = true;
1269f22ef01cSRoman Divacky         break;
1270f22ef01cSRoman Divacky       }
1271f22ef01cSRoman Divacky     }
1272f22ef01cSRoman Divacky     if (DontTransform)
1273f22ef01cSRoman Divacky       continue;
1274f22ef01cSRoman Divacky 
1275f22ef01cSRoman Divacky     // Okay, we can transform this.  Create the new call instruction and copy
1276f22ef01cSRoman Divacky     // over the required information.
1277f22ef01cSRoman Divacky     ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo);
1278f22ef01cSRoman Divacky     llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(),
1279f22ef01cSRoman Divacky                                                      ArgList.end(), "", CI);
1280f22ef01cSRoman Divacky     ArgList.clear();
1281f22ef01cSRoman Divacky     if (!NewCall->getType()->isVoidTy())
1282f22ef01cSRoman Divacky       NewCall->takeName(CI);
1283f22ef01cSRoman Divacky     NewCall->setAttributes(CI->getAttributes());
1284f22ef01cSRoman Divacky     NewCall->setCallingConv(CI->getCallingConv());
1285f22ef01cSRoman Divacky 
1286f22ef01cSRoman Divacky     // Finally, remove the old call, replacing any uses with the new one.
1287f22ef01cSRoman Divacky     if (!CI->use_empty())
1288f22ef01cSRoman Divacky       CI->replaceAllUsesWith(NewCall);
1289f22ef01cSRoman Divacky 
1290f22ef01cSRoman Divacky     // Copy debug location attached to CI.
1291f22ef01cSRoman Divacky     if (!CI->getDebugLoc().isUnknown())
1292f22ef01cSRoman Divacky       NewCall->setDebugLoc(CI->getDebugLoc());
1293f22ef01cSRoman Divacky     CI->eraseFromParent();
1294f22ef01cSRoman Divacky   }
1295f22ef01cSRoman Divacky }
1296f22ef01cSRoman Divacky 
1297f22ef01cSRoman Divacky 
1298f22ef01cSRoman Divacky void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
1299f22ef01cSRoman Divacky   const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
1300f22ef01cSRoman Divacky   const llvm::FunctionType *Ty = getTypes().GetFunctionType(GD);
1301f22ef01cSRoman Divacky   getMangleContext().mangleInitDiscriminator();
1302f22ef01cSRoman Divacky   // Get or create the prototype for the function.
1303f22ef01cSRoman Divacky   llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
1304f22ef01cSRoman Divacky 
1305f22ef01cSRoman Divacky   // Strip off a bitcast if we got one back.
1306f22ef01cSRoman Divacky   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1307f22ef01cSRoman Divacky     assert(CE->getOpcode() == llvm::Instruction::BitCast);
1308f22ef01cSRoman Divacky     Entry = CE->getOperand(0);
1309f22ef01cSRoman Divacky   }
1310f22ef01cSRoman Divacky 
1311f22ef01cSRoman Divacky 
1312f22ef01cSRoman Divacky   if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
1313f22ef01cSRoman Divacky     llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
1314f22ef01cSRoman Divacky 
1315f22ef01cSRoman Divacky     // If the types mismatch then we have to rewrite the definition.
1316f22ef01cSRoman Divacky     assert(OldFn->isDeclaration() &&
1317f22ef01cSRoman Divacky            "Shouldn't replace non-declaration");
1318f22ef01cSRoman Divacky 
1319f22ef01cSRoman Divacky     // F is the Function* for the one with the wrong type, we must make a new
1320f22ef01cSRoman Divacky     // Function* and update everything that used F (a declaration) with the new
1321f22ef01cSRoman Divacky     // Function* (which will be a definition).
1322f22ef01cSRoman Divacky     //
1323f22ef01cSRoman Divacky     // This happens if there is a prototype for a function
1324f22ef01cSRoman Divacky     // (e.g. "int f()") and then a definition of a different type
1325f22ef01cSRoman Divacky     // (e.g. "int f(int x)").  Move the old function aside so that it
1326f22ef01cSRoman Divacky     // doesn't interfere with GetAddrOfFunction.
1327f22ef01cSRoman Divacky     OldFn->setName(llvm::StringRef());
1328f22ef01cSRoman Divacky     llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
1329f22ef01cSRoman Divacky 
1330f22ef01cSRoman Divacky     // If this is an implementation of a function without a prototype, try to
1331f22ef01cSRoman Divacky     // replace any existing uses of the function (which may be calls) with uses
1332f22ef01cSRoman Divacky     // of the new function
1333f22ef01cSRoman Divacky     if (D->getType()->isFunctionNoProtoType()) {
1334f22ef01cSRoman Divacky       ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
1335f22ef01cSRoman Divacky       OldFn->removeDeadConstantUsers();
1336f22ef01cSRoman Divacky     }
1337f22ef01cSRoman Divacky 
1338f22ef01cSRoman Divacky     // Replace uses of F with the Function we will endow with a body.
1339f22ef01cSRoman Divacky     if (!Entry->use_empty()) {
1340f22ef01cSRoman Divacky       llvm::Constant *NewPtrForOldDecl =
1341f22ef01cSRoman Divacky         llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
1342f22ef01cSRoman Divacky       Entry->replaceAllUsesWith(NewPtrForOldDecl);
1343f22ef01cSRoman Divacky     }
1344f22ef01cSRoman Divacky 
1345f22ef01cSRoman Divacky     // Ok, delete the old function now, which is dead.
1346f22ef01cSRoman Divacky     OldFn->eraseFromParent();
1347f22ef01cSRoman Divacky 
1348f22ef01cSRoman Divacky     Entry = NewFn;
1349f22ef01cSRoman Divacky   }
1350f22ef01cSRoman Divacky 
1351f22ef01cSRoman Divacky   llvm::Function *Fn = cast<llvm::Function>(Entry);
1352f22ef01cSRoman Divacky   setFunctionLinkage(D, Fn);
1353f22ef01cSRoman Divacky 
1354f22ef01cSRoman Divacky   CodeGenFunction(*this).GenerateCode(D, Fn);
1355f22ef01cSRoman Divacky 
1356f22ef01cSRoman Divacky   SetFunctionDefinitionAttributes(D, Fn);
1357f22ef01cSRoman Divacky   SetLLVMFunctionAttributesForDefinition(D, Fn);
1358f22ef01cSRoman Divacky 
1359f22ef01cSRoman Divacky   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
1360f22ef01cSRoman Divacky     AddGlobalCtor(Fn, CA->getPriority());
1361f22ef01cSRoman Divacky   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
1362f22ef01cSRoman Divacky     AddGlobalDtor(Fn, DA->getPriority());
1363f22ef01cSRoman Divacky }
1364f22ef01cSRoman Divacky 
1365f22ef01cSRoman Divacky void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
1366f22ef01cSRoman Divacky   const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
1367f22ef01cSRoman Divacky   const AliasAttr *AA = D->getAttr<AliasAttr>();
1368f22ef01cSRoman Divacky   assert(AA && "Not an alias?");
1369f22ef01cSRoman Divacky 
1370f22ef01cSRoman Divacky   MangleBuffer MangledName;
1371f22ef01cSRoman Divacky   getMangledName(MangledName, GD);
1372f22ef01cSRoman Divacky 
1373f22ef01cSRoman Divacky   // If there is a definition in the module, then it wins over the alias.
1374f22ef01cSRoman Divacky   // This is dubious, but allow it to be safe.  Just ignore the alias.
1375f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1376f22ef01cSRoman Divacky   if (Entry && !Entry->isDeclaration())
1377f22ef01cSRoman Divacky     return;
1378f22ef01cSRoman Divacky 
1379f22ef01cSRoman Divacky   const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
1380f22ef01cSRoman Divacky 
1381f22ef01cSRoman Divacky   // Create a reference to the named value.  This ensures that it is emitted
1382f22ef01cSRoman Divacky   // if a deferred decl.
1383f22ef01cSRoman Divacky   llvm::Constant *Aliasee;
1384f22ef01cSRoman Divacky   if (isa<llvm::FunctionType>(DeclTy))
1385f22ef01cSRoman Divacky     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl());
1386f22ef01cSRoman Divacky   else
1387f22ef01cSRoman Divacky     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1388f22ef01cSRoman Divacky                                     llvm::PointerType::getUnqual(DeclTy), 0);
1389f22ef01cSRoman Divacky 
1390f22ef01cSRoman Divacky   // Create the new alias itself, but don't set a name yet.
1391f22ef01cSRoman Divacky   llvm::GlobalValue *GA =
1392f22ef01cSRoman Divacky     new llvm::GlobalAlias(Aliasee->getType(),
1393f22ef01cSRoman Divacky                           llvm::Function::ExternalLinkage,
1394f22ef01cSRoman Divacky                           "", Aliasee, &getModule());
1395f22ef01cSRoman Divacky 
1396f22ef01cSRoman Divacky   if (Entry) {
1397f22ef01cSRoman Divacky     assert(Entry->isDeclaration());
1398f22ef01cSRoman Divacky 
1399f22ef01cSRoman Divacky     // If there is a declaration in the module, then we had an extern followed
1400f22ef01cSRoman Divacky     // by the alias, as in:
1401f22ef01cSRoman Divacky     //   extern int test6();
1402f22ef01cSRoman Divacky     //   ...
1403f22ef01cSRoman Divacky     //   int test6() __attribute__((alias("test7")));
1404f22ef01cSRoman Divacky     //
1405f22ef01cSRoman Divacky     // Remove it and replace uses of it with the alias.
1406f22ef01cSRoman Divacky     GA->takeName(Entry);
1407f22ef01cSRoman Divacky 
1408f22ef01cSRoman Divacky     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
1409f22ef01cSRoman Divacky                                                           Entry->getType()));
1410f22ef01cSRoman Divacky     Entry->eraseFromParent();
1411f22ef01cSRoman Divacky   } else {
1412f22ef01cSRoman Divacky     GA->setName(MangledName.getString());
1413f22ef01cSRoman Divacky   }
1414f22ef01cSRoman Divacky 
1415f22ef01cSRoman Divacky   // Set attributes which are particular to an alias; this is a
1416f22ef01cSRoman Divacky   // specialization of the attributes which may be set on a global
1417f22ef01cSRoman Divacky   // variable/function.
1418f22ef01cSRoman Divacky   if (D->hasAttr<DLLExportAttr>()) {
1419f22ef01cSRoman Divacky     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1420f22ef01cSRoman Divacky       // The dllexport attribute is ignored for undefined symbols.
1421f22ef01cSRoman Divacky       if (FD->getBody())
1422f22ef01cSRoman Divacky         GA->setLinkage(llvm::Function::DLLExportLinkage);
1423f22ef01cSRoman Divacky     } else {
1424f22ef01cSRoman Divacky       GA->setLinkage(llvm::Function::DLLExportLinkage);
1425f22ef01cSRoman Divacky     }
1426f22ef01cSRoman Divacky   } else if (D->hasAttr<WeakAttr>() ||
1427f22ef01cSRoman Divacky              D->hasAttr<WeakRefAttr>() ||
1428f22ef01cSRoman Divacky              D->hasAttr<WeakImportAttr>()) {
1429f22ef01cSRoman Divacky     GA->setLinkage(llvm::Function::WeakAnyLinkage);
1430f22ef01cSRoman Divacky   }
1431f22ef01cSRoman Divacky 
1432f22ef01cSRoman Divacky   SetCommonAttributes(D, GA);
1433f22ef01cSRoman Divacky }
1434f22ef01cSRoman Divacky 
1435f22ef01cSRoman Divacky /// getBuiltinLibFunction - Given a builtin id for a function like
1436f22ef01cSRoman Divacky /// "__builtin_fabsf", return a Function* for "fabsf".
1437f22ef01cSRoman Divacky llvm::Value *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD,
1438f22ef01cSRoman Divacky                                                   unsigned BuiltinID) {
1439f22ef01cSRoman Divacky   assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
1440f22ef01cSRoman Divacky           Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
1441f22ef01cSRoman Divacky          "isn't a lib fn");
1442f22ef01cSRoman Divacky 
1443f22ef01cSRoman Divacky   // Get the name, skip over the __builtin_ prefix (if necessary).
1444f22ef01cSRoman Divacky   const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
1445f22ef01cSRoman Divacky   if (Context.BuiltinInfo.isLibFunction(BuiltinID))
1446f22ef01cSRoman Divacky     Name += 10;
1447f22ef01cSRoman Divacky 
1448f22ef01cSRoman Divacky   const llvm::FunctionType *Ty =
1449f22ef01cSRoman Divacky     cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType()));
1450f22ef01cSRoman Divacky 
1451f22ef01cSRoman Divacky   return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl(FD));
1452f22ef01cSRoman Divacky }
1453f22ef01cSRoman Divacky 
1454f22ef01cSRoman Divacky llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
1455f22ef01cSRoman Divacky                                             unsigned NumTys) {
1456f22ef01cSRoman Divacky   return llvm::Intrinsic::getDeclaration(&getModule(),
1457f22ef01cSRoman Divacky                                          (llvm::Intrinsic::ID)IID, Tys, NumTys);
1458f22ef01cSRoman Divacky }
1459f22ef01cSRoman Divacky 
1460f22ef01cSRoman Divacky 
1461f22ef01cSRoman Divacky llvm::Function *CodeGenModule::getMemCpyFn(const llvm::Type *DestType,
1462f22ef01cSRoman Divacky                                            const llvm::Type *SrcType,
1463f22ef01cSRoman Divacky                                            const llvm::Type *SizeType) {
1464f22ef01cSRoman Divacky   const llvm::Type *ArgTypes[3] = {DestType, SrcType, SizeType };
1465f22ef01cSRoman Divacky   return getIntrinsic(llvm::Intrinsic::memcpy, ArgTypes, 3);
1466f22ef01cSRoman Divacky }
1467f22ef01cSRoman Divacky 
1468f22ef01cSRoman Divacky llvm::Function *CodeGenModule::getMemMoveFn(const llvm::Type *DestType,
1469f22ef01cSRoman Divacky                                             const llvm::Type *SrcType,
1470f22ef01cSRoman Divacky                                             const llvm::Type *SizeType) {
1471f22ef01cSRoman Divacky   const llvm::Type *ArgTypes[3] = {DestType, SrcType, SizeType };
1472f22ef01cSRoman Divacky   return getIntrinsic(llvm::Intrinsic::memmove, ArgTypes, 3);
1473f22ef01cSRoman Divacky }
1474f22ef01cSRoman Divacky 
1475f22ef01cSRoman Divacky llvm::Function *CodeGenModule::getMemSetFn(const llvm::Type *DestType,
1476f22ef01cSRoman Divacky                                            const llvm::Type *SizeType) {
1477f22ef01cSRoman Divacky   const llvm::Type *ArgTypes[2] = { DestType, SizeType };
1478f22ef01cSRoman Divacky   return getIntrinsic(llvm::Intrinsic::memset, ArgTypes, 2);
1479f22ef01cSRoman Divacky }
1480f22ef01cSRoman Divacky 
1481f22ef01cSRoman Divacky static llvm::StringMapEntry<llvm::Constant*> &
1482f22ef01cSRoman Divacky GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1483f22ef01cSRoman Divacky                          const StringLiteral *Literal,
1484f22ef01cSRoman Divacky                          bool TargetIsLSB,
1485f22ef01cSRoman Divacky                          bool &IsUTF16,
1486f22ef01cSRoman Divacky                          unsigned &StringLength) {
1487f22ef01cSRoman Divacky   unsigned NumBytes = Literal->getByteLength();
1488f22ef01cSRoman Divacky 
1489f22ef01cSRoman Divacky   // Check for simple case.
1490f22ef01cSRoman Divacky   if (!Literal->containsNonAsciiOrNull()) {
1491f22ef01cSRoman Divacky     StringLength = NumBytes;
1492f22ef01cSRoman Divacky     return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(),
1493f22ef01cSRoman Divacky                                                 StringLength));
1494f22ef01cSRoman Divacky   }
1495f22ef01cSRoman Divacky 
1496f22ef01cSRoman Divacky   // Otherwise, convert the UTF8 literals into a byte string.
1497f22ef01cSRoman Divacky   llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
1498f22ef01cSRoman Divacky   const UTF8 *FromPtr = (UTF8 *)Literal->getStrData();
1499f22ef01cSRoman Divacky   UTF16 *ToPtr = &ToBuf[0];
1500f22ef01cSRoman Divacky 
1501f22ef01cSRoman Divacky   ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1502f22ef01cSRoman Divacky                                                &ToPtr, ToPtr + NumBytes,
1503f22ef01cSRoman Divacky                                                strictConversion);
1504f22ef01cSRoman Divacky 
1505f22ef01cSRoman Divacky   // Check for conversion failure.
1506f22ef01cSRoman Divacky   if (Result != conversionOK) {
1507f22ef01cSRoman Divacky     // FIXME: Have Sema::CheckObjCString() validate the UTF-8 string and remove
1508f22ef01cSRoman Divacky     // this duplicate code.
1509f22ef01cSRoman Divacky     assert(Result == sourceIllegal && "UTF-8 to UTF-16 conversion failed");
1510f22ef01cSRoman Divacky     StringLength = NumBytes;
1511f22ef01cSRoman Divacky     return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(),
1512f22ef01cSRoman Divacky                                                 StringLength));
1513f22ef01cSRoman Divacky   }
1514f22ef01cSRoman Divacky 
1515f22ef01cSRoman Divacky   // ConvertUTF8toUTF16 returns the length in ToPtr.
1516f22ef01cSRoman Divacky   StringLength = ToPtr - &ToBuf[0];
1517f22ef01cSRoman Divacky 
1518f22ef01cSRoman Divacky   // Render the UTF-16 string into a byte array and convert to the target byte
1519f22ef01cSRoman Divacky   // order.
1520f22ef01cSRoman Divacky   //
1521f22ef01cSRoman Divacky   // FIXME: This isn't something we should need to do here.
1522f22ef01cSRoman Divacky   llvm::SmallString<128> AsBytes;
1523f22ef01cSRoman Divacky   AsBytes.reserve(StringLength * 2);
1524f22ef01cSRoman Divacky   for (unsigned i = 0; i != StringLength; ++i) {
1525f22ef01cSRoman Divacky     unsigned short Val = ToBuf[i];
1526f22ef01cSRoman Divacky     if (TargetIsLSB) {
1527f22ef01cSRoman Divacky       AsBytes.push_back(Val & 0xFF);
1528f22ef01cSRoman Divacky       AsBytes.push_back(Val >> 8);
1529f22ef01cSRoman Divacky     } else {
1530f22ef01cSRoman Divacky       AsBytes.push_back(Val >> 8);
1531f22ef01cSRoman Divacky       AsBytes.push_back(Val & 0xFF);
1532f22ef01cSRoman Divacky     }
1533f22ef01cSRoman Divacky   }
1534f22ef01cSRoman Divacky   // Append one extra null character, the second is automatically added by our
1535f22ef01cSRoman Divacky   // caller.
1536f22ef01cSRoman Divacky   AsBytes.push_back(0);
1537f22ef01cSRoman Divacky 
1538f22ef01cSRoman Divacky   IsUTF16 = true;
1539f22ef01cSRoman Divacky   return Map.GetOrCreateValue(llvm::StringRef(AsBytes.data(), AsBytes.size()));
1540f22ef01cSRoman Divacky }
1541f22ef01cSRoman Divacky 
1542f22ef01cSRoman Divacky llvm::Constant *
1543f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
1544f22ef01cSRoman Divacky   unsigned StringLength = 0;
1545f22ef01cSRoman Divacky   bool isUTF16 = false;
1546f22ef01cSRoman Divacky   llvm::StringMapEntry<llvm::Constant*> &Entry =
1547f22ef01cSRoman Divacky     GetConstantCFStringEntry(CFConstantStringMap, Literal,
1548f22ef01cSRoman Divacky                              getTargetData().isLittleEndian(),
1549f22ef01cSRoman Divacky                              isUTF16, StringLength);
1550f22ef01cSRoman Divacky 
1551f22ef01cSRoman Divacky   if (llvm::Constant *C = Entry.getValue())
1552f22ef01cSRoman Divacky     return C;
1553f22ef01cSRoman Divacky 
1554f22ef01cSRoman Divacky   llvm::Constant *Zero =
1555f22ef01cSRoman Divacky       llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
1556f22ef01cSRoman Divacky   llvm::Constant *Zeros[] = { Zero, Zero };
1557f22ef01cSRoman Divacky 
1558f22ef01cSRoman Divacky   // If we don't already have it, get __CFConstantStringClassReference.
1559f22ef01cSRoman Divacky   if (!CFConstantStringClassRef) {
1560f22ef01cSRoman Divacky     const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1561f22ef01cSRoman Divacky     Ty = llvm::ArrayType::get(Ty, 0);
1562f22ef01cSRoman Divacky     llvm::Constant *GV = CreateRuntimeVariable(Ty,
1563f22ef01cSRoman Divacky                                            "__CFConstantStringClassReference");
1564f22ef01cSRoman Divacky     // Decay array -> ptr
1565f22ef01cSRoman Divacky     CFConstantStringClassRef =
1566f22ef01cSRoman Divacky       llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1567f22ef01cSRoman Divacky   }
1568f22ef01cSRoman Divacky 
1569f22ef01cSRoman Divacky   QualType CFTy = getContext().getCFConstantStringType();
1570f22ef01cSRoman Divacky 
1571f22ef01cSRoman Divacky   const llvm::StructType *STy =
1572f22ef01cSRoman Divacky     cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1573f22ef01cSRoman Divacky 
1574f22ef01cSRoman Divacky   std::vector<llvm::Constant*> Fields(4);
1575f22ef01cSRoman Divacky 
1576f22ef01cSRoman Divacky   // Class pointer.
1577f22ef01cSRoman Divacky   Fields[0] = CFConstantStringClassRef;
1578f22ef01cSRoman Divacky 
1579f22ef01cSRoman Divacky   // Flags.
1580f22ef01cSRoman Divacky   const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1581f22ef01cSRoman Divacky   Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
1582f22ef01cSRoman Divacky     llvm::ConstantInt::get(Ty, 0x07C8);
1583f22ef01cSRoman Divacky 
1584f22ef01cSRoman Divacky   // String pointer.
1585f22ef01cSRoman Divacky   llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1586f22ef01cSRoman Divacky 
1587f22ef01cSRoman Divacky   llvm::GlobalValue::LinkageTypes Linkage;
1588f22ef01cSRoman Divacky   bool isConstant;
1589f22ef01cSRoman Divacky   if (isUTF16) {
1590f22ef01cSRoman Divacky     // FIXME: why do utf strings get "_" labels instead of "L" labels?
1591f22ef01cSRoman Divacky     Linkage = llvm::GlobalValue::InternalLinkage;
1592f22ef01cSRoman Divacky     // Note: -fwritable-strings doesn't make unicode CFStrings writable, but
1593f22ef01cSRoman Divacky     // does make plain ascii ones writable.
1594f22ef01cSRoman Divacky     isConstant = true;
1595f22ef01cSRoman Divacky   } else {
1596f22ef01cSRoman Divacky     Linkage = llvm::GlobalValue::PrivateLinkage;
1597f22ef01cSRoman Divacky     isConstant = !Features.WritableStrings;
1598f22ef01cSRoman Divacky   }
1599f22ef01cSRoman Divacky 
1600f22ef01cSRoman Divacky   llvm::GlobalVariable *GV =
1601f22ef01cSRoman Divacky     new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1602f22ef01cSRoman Divacky                              ".str");
1603f22ef01cSRoman Divacky   if (isUTF16) {
1604f22ef01cSRoman Divacky     CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1605f22ef01cSRoman Divacky     GV->setAlignment(Align.getQuantity());
1606f22ef01cSRoman Divacky   }
1607f22ef01cSRoman Divacky   Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1608f22ef01cSRoman Divacky 
1609f22ef01cSRoman Divacky   // String length.
1610f22ef01cSRoman Divacky   Ty = getTypes().ConvertType(getContext().LongTy);
1611f22ef01cSRoman Divacky   Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
1612f22ef01cSRoman Divacky 
1613f22ef01cSRoman Divacky   // The struct.
1614f22ef01cSRoman Divacky   C = llvm::ConstantStruct::get(STy, Fields);
1615f22ef01cSRoman Divacky   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1616f22ef01cSRoman Divacky                                 llvm::GlobalVariable::PrivateLinkage, C,
1617f22ef01cSRoman Divacky                                 "_unnamed_cfstring_");
1618f22ef01cSRoman Divacky   if (const char *Sect = getContext().Target.getCFStringSection())
1619f22ef01cSRoman Divacky     GV->setSection(Sect);
1620f22ef01cSRoman Divacky   Entry.setValue(GV);
1621f22ef01cSRoman Divacky 
1622f22ef01cSRoman Divacky   return GV;
1623f22ef01cSRoman Divacky }
1624f22ef01cSRoman Divacky 
1625f22ef01cSRoman Divacky llvm::Constant *
1626f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantNSString(const StringLiteral *Literal) {
1627f22ef01cSRoman Divacky   unsigned StringLength = 0;
1628f22ef01cSRoman Divacky   bool isUTF16 = false;
1629f22ef01cSRoman Divacky   llvm::StringMapEntry<llvm::Constant*> &Entry =
1630f22ef01cSRoman Divacky     GetConstantCFStringEntry(CFConstantStringMap, Literal,
1631f22ef01cSRoman Divacky                              getTargetData().isLittleEndian(),
1632f22ef01cSRoman Divacky                              isUTF16, StringLength);
1633f22ef01cSRoman Divacky 
1634f22ef01cSRoman Divacky   if (llvm::Constant *C = Entry.getValue())
1635f22ef01cSRoman Divacky     return C;
1636f22ef01cSRoman Divacky 
1637f22ef01cSRoman Divacky   llvm::Constant *Zero =
1638f22ef01cSRoman Divacky   llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
1639f22ef01cSRoman Divacky   llvm::Constant *Zeros[] = { Zero, Zero };
1640f22ef01cSRoman Divacky 
1641f22ef01cSRoman Divacky   // If we don't already have it, get _NSConstantStringClassReference.
1642f22ef01cSRoman Divacky   if (!NSConstantStringClassRef) {
1643f22ef01cSRoman Divacky     const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1644f22ef01cSRoman Divacky     Ty = llvm::ArrayType::get(Ty, 0);
1645f22ef01cSRoman Divacky     llvm::Constant *GV = CreateRuntimeVariable(Ty,
1646f22ef01cSRoman Divacky                                         Features.ObjCNonFragileABI ?
1647f22ef01cSRoman Divacky                                         "OBJC_CLASS_$_NSConstantString" :
1648f22ef01cSRoman Divacky                                         "_NSConstantStringClassReference");
1649f22ef01cSRoman Divacky     // Decay array -> ptr
1650f22ef01cSRoman Divacky     NSConstantStringClassRef =
1651f22ef01cSRoman Divacky       llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1652f22ef01cSRoman Divacky   }
1653f22ef01cSRoman Divacky 
1654f22ef01cSRoman Divacky   QualType NSTy = getContext().getNSConstantStringType();
1655f22ef01cSRoman Divacky 
1656f22ef01cSRoman Divacky   const llvm::StructType *STy =
1657f22ef01cSRoman Divacky   cast<llvm::StructType>(getTypes().ConvertType(NSTy));
1658f22ef01cSRoman Divacky 
1659f22ef01cSRoman Divacky   std::vector<llvm::Constant*> Fields(3);
1660f22ef01cSRoman Divacky 
1661f22ef01cSRoman Divacky   // Class pointer.
1662f22ef01cSRoman Divacky   Fields[0] = NSConstantStringClassRef;
1663f22ef01cSRoman Divacky 
1664f22ef01cSRoman Divacky   // String pointer.
1665f22ef01cSRoman Divacky   llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1666f22ef01cSRoman Divacky 
1667f22ef01cSRoman Divacky   llvm::GlobalValue::LinkageTypes Linkage;
1668f22ef01cSRoman Divacky   bool isConstant;
1669f22ef01cSRoman Divacky   if (isUTF16) {
1670f22ef01cSRoman Divacky     // FIXME: why do utf strings get "_" labels instead of "L" labels?
1671f22ef01cSRoman Divacky     Linkage = llvm::GlobalValue::InternalLinkage;
1672f22ef01cSRoman Divacky     // Note: -fwritable-strings doesn't make unicode NSStrings writable, but
1673f22ef01cSRoman Divacky     // does make plain ascii ones writable.
1674f22ef01cSRoman Divacky     isConstant = true;
1675f22ef01cSRoman Divacky   } else {
1676f22ef01cSRoman Divacky     Linkage = llvm::GlobalValue::PrivateLinkage;
1677f22ef01cSRoman Divacky     isConstant = !Features.WritableStrings;
1678f22ef01cSRoman Divacky   }
1679f22ef01cSRoman Divacky 
1680f22ef01cSRoman Divacky   llvm::GlobalVariable *GV =
1681f22ef01cSRoman Divacky   new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1682f22ef01cSRoman Divacky                            ".str");
1683f22ef01cSRoman Divacky   if (isUTF16) {
1684f22ef01cSRoman Divacky     CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1685f22ef01cSRoman Divacky     GV->setAlignment(Align.getQuantity());
1686f22ef01cSRoman Divacky   }
1687f22ef01cSRoman Divacky   Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1688f22ef01cSRoman Divacky 
1689f22ef01cSRoman Divacky   // String length.
1690f22ef01cSRoman Divacky   const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1691f22ef01cSRoman Divacky   Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
1692f22ef01cSRoman Divacky 
1693f22ef01cSRoman Divacky   // The struct.
1694f22ef01cSRoman Divacky   C = llvm::ConstantStruct::get(STy, Fields);
1695f22ef01cSRoman Divacky   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1696f22ef01cSRoman Divacky                                 llvm::GlobalVariable::PrivateLinkage, C,
1697f22ef01cSRoman Divacky                                 "_unnamed_nsstring_");
1698f22ef01cSRoman Divacky   // FIXME. Fix section.
1699f22ef01cSRoman Divacky   if (const char *Sect =
1700f22ef01cSRoman Divacky         Features.ObjCNonFragileABI
1701f22ef01cSRoman Divacky           ? getContext().Target.getNSStringNonFragileABISection()
1702f22ef01cSRoman Divacky           : getContext().Target.getNSStringSection())
1703f22ef01cSRoman Divacky     GV->setSection(Sect);
1704f22ef01cSRoman Divacky   Entry.setValue(GV);
1705f22ef01cSRoman Divacky 
1706f22ef01cSRoman Divacky   return GV;
1707f22ef01cSRoman Divacky }
1708f22ef01cSRoman Divacky 
1709f22ef01cSRoman Divacky /// GetStringForStringLiteral - Return the appropriate bytes for a
1710f22ef01cSRoman Divacky /// string literal, properly padded to match the literal type.
1711f22ef01cSRoman Divacky std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
1712f22ef01cSRoman Divacky   const char *StrData = E->getStrData();
1713f22ef01cSRoman Divacky   unsigned Len = E->getByteLength();
1714f22ef01cSRoman Divacky 
1715f22ef01cSRoman Divacky   const ConstantArrayType *CAT =
1716f22ef01cSRoman Divacky     getContext().getAsConstantArrayType(E->getType());
1717f22ef01cSRoman Divacky   assert(CAT && "String isn't pointer or array!");
1718f22ef01cSRoman Divacky 
1719f22ef01cSRoman Divacky   // Resize the string to the right size.
1720f22ef01cSRoman Divacky   std::string Str(StrData, StrData+Len);
1721f22ef01cSRoman Divacky   uint64_t RealLen = CAT->getSize().getZExtValue();
1722f22ef01cSRoman Divacky 
1723f22ef01cSRoman Divacky   if (E->isWide())
1724f22ef01cSRoman Divacky     RealLen *= getContext().Target.getWCharWidth()/8;
1725f22ef01cSRoman Divacky 
1726f22ef01cSRoman Divacky   Str.resize(RealLen, '\0');
1727f22ef01cSRoman Divacky 
1728f22ef01cSRoman Divacky   return Str;
1729f22ef01cSRoman Divacky }
1730f22ef01cSRoman Divacky 
1731f22ef01cSRoman Divacky /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1732f22ef01cSRoman Divacky /// constant array for the given string literal.
1733f22ef01cSRoman Divacky llvm::Constant *
1734f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1735f22ef01cSRoman Divacky   // FIXME: This can be more efficient.
1736f22ef01cSRoman Divacky   // FIXME: We shouldn't need to bitcast the constant in the wide string case.
1737f22ef01cSRoman Divacky   llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S));
1738f22ef01cSRoman Divacky   if (S->isWide()) {
1739f22ef01cSRoman Divacky     llvm::Type *DestTy =
1740f22ef01cSRoman Divacky         llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType()));
1741f22ef01cSRoman Divacky     C = llvm::ConstantExpr::getBitCast(C, DestTy);
1742f22ef01cSRoman Divacky   }
1743f22ef01cSRoman Divacky   return C;
1744f22ef01cSRoman Divacky }
1745f22ef01cSRoman Divacky 
1746f22ef01cSRoman Divacky /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1747f22ef01cSRoman Divacky /// array for the given ObjCEncodeExpr node.
1748f22ef01cSRoman Divacky llvm::Constant *
1749f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1750f22ef01cSRoman Divacky   std::string Str;
1751f22ef01cSRoman Divacky   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
1752f22ef01cSRoman Divacky 
1753f22ef01cSRoman Divacky   return GetAddrOfConstantCString(Str);
1754f22ef01cSRoman Divacky }
1755f22ef01cSRoman Divacky 
1756f22ef01cSRoman Divacky 
1757f22ef01cSRoman Divacky /// GenerateWritableString -- Creates storage for a string literal.
1758f22ef01cSRoman Divacky static llvm::Constant *GenerateStringLiteral(const std::string &str,
1759f22ef01cSRoman Divacky                                              bool constant,
1760f22ef01cSRoman Divacky                                              CodeGenModule &CGM,
1761f22ef01cSRoman Divacky                                              const char *GlobalName) {
1762f22ef01cSRoman Divacky   // Create Constant for this string literal. Don't add a '\0'.
1763f22ef01cSRoman Divacky   llvm::Constant *C =
1764f22ef01cSRoman Divacky       llvm::ConstantArray::get(CGM.getLLVMContext(), str, false);
1765f22ef01cSRoman Divacky 
1766f22ef01cSRoman Divacky   // Create a global variable for this string
1767f22ef01cSRoman Divacky   return new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
1768f22ef01cSRoman Divacky                                   llvm::GlobalValue::PrivateLinkage,
1769f22ef01cSRoman Divacky                                   C, GlobalName);
1770f22ef01cSRoman Divacky }
1771f22ef01cSRoman Divacky 
1772f22ef01cSRoman Divacky /// GetAddrOfConstantString - Returns a pointer to a character array
1773f22ef01cSRoman Divacky /// containing the literal. This contents are exactly that of the
1774f22ef01cSRoman Divacky /// given string, i.e. it will not be null terminated automatically;
1775f22ef01cSRoman Divacky /// see GetAddrOfConstantCString. Note that whether the result is
1776f22ef01cSRoman Divacky /// actually a pointer to an LLVM constant depends on
1777f22ef01cSRoman Divacky /// Feature.WriteableStrings.
1778f22ef01cSRoman Divacky ///
1779f22ef01cSRoman Divacky /// The result has pointer to array type.
1780f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1781f22ef01cSRoman Divacky                                                        const char *GlobalName) {
1782f22ef01cSRoman Divacky   bool IsConstant = !Features.WritableStrings;
1783f22ef01cSRoman Divacky 
1784f22ef01cSRoman Divacky   // Get the default prefix if a name wasn't specified.
1785f22ef01cSRoman Divacky   if (!GlobalName)
1786f22ef01cSRoman Divacky     GlobalName = ".str";
1787f22ef01cSRoman Divacky 
1788f22ef01cSRoman Divacky   // Don't share any string literals if strings aren't constant.
1789f22ef01cSRoman Divacky   if (!IsConstant)
1790f22ef01cSRoman Divacky     return GenerateStringLiteral(str, false, *this, GlobalName);
1791f22ef01cSRoman Divacky 
1792f22ef01cSRoman Divacky   llvm::StringMapEntry<llvm::Constant *> &Entry =
1793f22ef01cSRoman Divacky     ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1794f22ef01cSRoman Divacky 
1795f22ef01cSRoman Divacky   if (Entry.getValue())
1796f22ef01cSRoman Divacky     return Entry.getValue();
1797f22ef01cSRoman Divacky 
1798f22ef01cSRoman Divacky   // Create a global variable for this.
1799f22ef01cSRoman Divacky   llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
1800f22ef01cSRoman Divacky   Entry.setValue(C);
1801f22ef01cSRoman Divacky   return C;
1802f22ef01cSRoman Divacky }
1803f22ef01cSRoman Divacky 
1804f22ef01cSRoman Divacky /// GetAddrOfConstantCString - Returns a pointer to a character
1805f22ef01cSRoman Divacky /// array containing the literal and a terminating '\-'
1806f22ef01cSRoman Divacky /// character. The result has pointer to array type.
1807f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1808f22ef01cSRoman Divacky                                                         const char *GlobalName){
1809f22ef01cSRoman Divacky   return GetAddrOfConstantString(str + '\0', GlobalName);
1810f22ef01cSRoman Divacky }
1811f22ef01cSRoman Divacky 
1812f22ef01cSRoman Divacky /// EmitObjCPropertyImplementations - Emit information for synthesized
1813f22ef01cSRoman Divacky /// properties for an implementation.
1814f22ef01cSRoman Divacky void CodeGenModule::EmitObjCPropertyImplementations(const
1815f22ef01cSRoman Divacky                                                     ObjCImplementationDecl *D) {
1816f22ef01cSRoman Divacky   for (ObjCImplementationDecl::propimpl_iterator
1817f22ef01cSRoman Divacky          i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
1818f22ef01cSRoman Divacky     ObjCPropertyImplDecl *PID = *i;
1819f22ef01cSRoman Divacky 
1820f22ef01cSRoman Divacky     // Dynamic is just for type-checking.
1821f22ef01cSRoman Divacky     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1822f22ef01cSRoman Divacky       ObjCPropertyDecl *PD = PID->getPropertyDecl();
1823f22ef01cSRoman Divacky 
1824f22ef01cSRoman Divacky       // Determine which methods need to be implemented, some may have
1825f22ef01cSRoman Divacky       // been overridden. Note that ::isSynthesized is not the method
1826f22ef01cSRoman Divacky       // we want, that just indicates if the decl came from a
1827f22ef01cSRoman Divacky       // property. What we want to know is if the method is defined in
1828f22ef01cSRoman Divacky       // this implementation.
1829f22ef01cSRoman Divacky       if (!D->getInstanceMethod(PD->getGetterName()))
1830f22ef01cSRoman Divacky         CodeGenFunction(*this).GenerateObjCGetter(
1831f22ef01cSRoman Divacky                                  const_cast<ObjCImplementationDecl *>(D), PID);
1832f22ef01cSRoman Divacky       if (!PD->isReadOnly() &&
1833f22ef01cSRoman Divacky           !D->getInstanceMethod(PD->getSetterName()))
1834f22ef01cSRoman Divacky         CodeGenFunction(*this).GenerateObjCSetter(
1835f22ef01cSRoman Divacky                                  const_cast<ObjCImplementationDecl *>(D), PID);
1836f22ef01cSRoman Divacky     }
1837f22ef01cSRoman Divacky   }
1838f22ef01cSRoman Divacky }
1839f22ef01cSRoman Divacky 
1840f22ef01cSRoman Divacky /// EmitObjCIvarInitializations - Emit information for ivar initialization
1841f22ef01cSRoman Divacky /// for an implementation.
1842f22ef01cSRoman Divacky void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
1843f22ef01cSRoman Divacky   if (!Features.NeXTRuntime || D->getNumIvarInitializers() == 0)
1844f22ef01cSRoman Divacky     return;
1845f22ef01cSRoman Divacky   DeclContext* DC = const_cast<DeclContext*>(dyn_cast<DeclContext>(D));
1846f22ef01cSRoman Divacky   assert(DC && "EmitObjCIvarInitializations - null DeclContext");
1847f22ef01cSRoman Divacky   IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
1848f22ef01cSRoman Divacky   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
1849f22ef01cSRoman Divacky   ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(getContext(),
1850f22ef01cSRoman Divacky                                                   D->getLocation(),
1851f22ef01cSRoman Divacky                                                   D->getLocation(), cxxSelector,
1852f22ef01cSRoman Divacky                                                   getContext().VoidTy, 0,
1853f22ef01cSRoman Divacky                                                   DC, true, false, true,
1854f22ef01cSRoman Divacky                                                   ObjCMethodDecl::Required);
1855f22ef01cSRoman Divacky   D->addInstanceMethod(DTORMethod);
1856f22ef01cSRoman Divacky   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
1857f22ef01cSRoman Divacky 
1858f22ef01cSRoman Divacky   II = &getContext().Idents.get(".cxx_construct");
1859f22ef01cSRoman Divacky   cxxSelector = getContext().Selectors.getSelector(0, &II);
1860f22ef01cSRoman Divacky   // The constructor returns 'self'.
1861f22ef01cSRoman Divacky   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
1862f22ef01cSRoman Divacky                                                 D->getLocation(),
1863f22ef01cSRoman Divacky                                                 D->getLocation(), cxxSelector,
1864f22ef01cSRoman Divacky                                                 getContext().getObjCIdType(), 0,
1865f22ef01cSRoman Divacky                                                 DC, true, false, true,
1866f22ef01cSRoman Divacky                                                 ObjCMethodDecl::Required);
1867f22ef01cSRoman Divacky   D->addInstanceMethod(CTORMethod);
1868f22ef01cSRoman Divacky   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
1869f22ef01cSRoman Divacky 
1870f22ef01cSRoman Divacky 
1871f22ef01cSRoman Divacky }
1872f22ef01cSRoman Divacky 
1873f22ef01cSRoman Divacky /// EmitNamespace - Emit all declarations in a namespace.
1874f22ef01cSRoman Divacky void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
1875f22ef01cSRoman Divacky   for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
1876f22ef01cSRoman Divacky        I != E; ++I)
1877f22ef01cSRoman Divacky     EmitTopLevelDecl(*I);
1878f22ef01cSRoman Divacky }
1879f22ef01cSRoman Divacky 
1880f22ef01cSRoman Divacky // EmitLinkageSpec - Emit all declarations in a linkage spec.
1881f22ef01cSRoman Divacky void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
1882f22ef01cSRoman Divacky   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
1883f22ef01cSRoman Divacky       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
1884f22ef01cSRoman Divacky     ErrorUnsupported(LSD, "linkage spec");
1885f22ef01cSRoman Divacky     return;
1886f22ef01cSRoman Divacky   }
1887f22ef01cSRoman Divacky 
1888f22ef01cSRoman Divacky   for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
1889f22ef01cSRoman Divacky        I != E; ++I)
1890f22ef01cSRoman Divacky     EmitTopLevelDecl(*I);
1891f22ef01cSRoman Divacky }
1892f22ef01cSRoman Divacky 
1893f22ef01cSRoman Divacky /// EmitTopLevelDecl - Emit code for a single top level declaration.
1894f22ef01cSRoman Divacky void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1895f22ef01cSRoman Divacky   // If an error has occurred, stop code generation, but continue
1896f22ef01cSRoman Divacky   // parsing and semantic analysis (to ensure all warnings and errors
1897f22ef01cSRoman Divacky   // are emitted).
1898f22ef01cSRoman Divacky   if (Diags.hasErrorOccurred())
1899f22ef01cSRoman Divacky     return;
1900f22ef01cSRoman Divacky 
1901f22ef01cSRoman Divacky   // Ignore dependent declarations.
1902f22ef01cSRoman Divacky   if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
1903f22ef01cSRoman Divacky     return;
1904f22ef01cSRoman Divacky 
1905f22ef01cSRoman Divacky   switch (D->getKind()) {
1906f22ef01cSRoman Divacky   case Decl::CXXConversion:
1907f22ef01cSRoman Divacky   case Decl::CXXMethod:
1908f22ef01cSRoman Divacky   case Decl::Function:
1909f22ef01cSRoman Divacky     // Skip function templates
1910f22ef01cSRoman Divacky     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
1911f22ef01cSRoman Divacky       return;
1912f22ef01cSRoman Divacky 
1913f22ef01cSRoman Divacky     EmitGlobal(cast<FunctionDecl>(D));
1914f22ef01cSRoman Divacky     break;
1915f22ef01cSRoman Divacky 
1916f22ef01cSRoman Divacky   case Decl::Var:
1917f22ef01cSRoman Divacky     EmitGlobal(cast<VarDecl>(D));
1918f22ef01cSRoman Divacky     break;
1919f22ef01cSRoman Divacky 
1920f22ef01cSRoman Divacky   // C++ Decls
1921f22ef01cSRoman Divacky   case Decl::Namespace:
1922f22ef01cSRoman Divacky     EmitNamespace(cast<NamespaceDecl>(D));
1923f22ef01cSRoman Divacky     break;
1924f22ef01cSRoman Divacky     // No code generation needed.
1925f22ef01cSRoman Divacky   case Decl::UsingShadow:
1926f22ef01cSRoman Divacky   case Decl::Using:
1927f22ef01cSRoman Divacky   case Decl::UsingDirective:
1928f22ef01cSRoman Divacky   case Decl::ClassTemplate:
1929f22ef01cSRoman Divacky   case Decl::FunctionTemplate:
1930f22ef01cSRoman Divacky   case Decl::NamespaceAlias:
1931f22ef01cSRoman Divacky     break;
1932f22ef01cSRoman Divacky   case Decl::CXXConstructor:
1933f22ef01cSRoman Divacky     // Skip function templates
1934f22ef01cSRoman Divacky     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
1935f22ef01cSRoman Divacky       return;
1936f22ef01cSRoman Divacky 
1937f22ef01cSRoman Divacky     EmitCXXConstructors(cast<CXXConstructorDecl>(D));
1938f22ef01cSRoman Divacky     break;
1939f22ef01cSRoman Divacky   case Decl::CXXDestructor:
1940f22ef01cSRoman Divacky     EmitCXXDestructors(cast<CXXDestructorDecl>(D));
1941f22ef01cSRoman Divacky     break;
1942f22ef01cSRoman Divacky 
1943f22ef01cSRoman Divacky   case Decl::StaticAssert:
1944f22ef01cSRoman Divacky     // Nothing to do.
1945f22ef01cSRoman Divacky     break;
1946f22ef01cSRoman Divacky 
1947f22ef01cSRoman Divacky   // Objective-C Decls
1948f22ef01cSRoman Divacky 
1949f22ef01cSRoman Divacky   // Forward declarations, no (immediate) code generation.
1950f22ef01cSRoman Divacky   case Decl::ObjCClass:
1951f22ef01cSRoman Divacky   case Decl::ObjCForwardProtocol:
1952f22ef01cSRoman Divacky   case Decl::ObjCCategory:
1953f22ef01cSRoman Divacky   case Decl::ObjCInterface:
1954f22ef01cSRoman Divacky     break;
1955f22ef01cSRoman Divacky 
1956f22ef01cSRoman Divacky   case Decl::ObjCProtocol:
1957f22ef01cSRoman Divacky     Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
1958f22ef01cSRoman Divacky     break;
1959f22ef01cSRoman Divacky 
1960f22ef01cSRoman Divacky   case Decl::ObjCCategoryImpl:
1961f22ef01cSRoman Divacky     // Categories have properties but don't support synthesize so we
1962f22ef01cSRoman Divacky     // can ignore them here.
1963f22ef01cSRoman Divacky     Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1964f22ef01cSRoman Divacky     break;
1965f22ef01cSRoman Divacky 
1966f22ef01cSRoman Divacky   case Decl::ObjCImplementation: {
1967f22ef01cSRoman Divacky     ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1968f22ef01cSRoman Divacky     EmitObjCPropertyImplementations(OMD);
1969f22ef01cSRoman Divacky     EmitObjCIvarInitializations(OMD);
1970f22ef01cSRoman Divacky     Runtime->GenerateClass(OMD);
1971f22ef01cSRoman Divacky     break;
1972f22ef01cSRoman Divacky   }
1973f22ef01cSRoman Divacky   case Decl::ObjCMethod: {
1974f22ef01cSRoman Divacky     ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1975f22ef01cSRoman Divacky     // If this is not a prototype, emit the body.
1976f22ef01cSRoman Divacky     if (OMD->getBody())
1977f22ef01cSRoman Divacky       CodeGenFunction(*this).GenerateObjCMethod(OMD);
1978f22ef01cSRoman Divacky     break;
1979f22ef01cSRoman Divacky   }
1980f22ef01cSRoman Divacky   case Decl::ObjCCompatibleAlias:
1981f22ef01cSRoman Divacky     // compatibility-alias is a directive and has no code gen.
1982f22ef01cSRoman Divacky     break;
1983f22ef01cSRoman Divacky 
1984f22ef01cSRoman Divacky   case Decl::LinkageSpec:
1985f22ef01cSRoman Divacky     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
1986f22ef01cSRoman Divacky     break;
1987f22ef01cSRoman Divacky 
1988f22ef01cSRoman Divacky   case Decl::FileScopeAsm: {
1989f22ef01cSRoman Divacky     FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1990f22ef01cSRoman Divacky     llvm::StringRef AsmString = AD->getAsmString()->getString();
1991f22ef01cSRoman Divacky 
1992f22ef01cSRoman Divacky     const std::string &S = getModule().getModuleInlineAsm();
1993f22ef01cSRoman Divacky     if (S.empty())
1994f22ef01cSRoman Divacky       getModule().setModuleInlineAsm(AsmString);
1995f22ef01cSRoman Divacky     else
1996f22ef01cSRoman Divacky       getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
1997f22ef01cSRoman Divacky     break;
1998f22ef01cSRoman Divacky   }
1999f22ef01cSRoman Divacky 
2000f22ef01cSRoman Divacky   default:
2001f22ef01cSRoman Divacky     // Make sure we handled everything we should, every other kind is a
2002f22ef01cSRoman Divacky     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
2003f22ef01cSRoman Divacky     // function. Need to recode Decl::Kind to do that easily.
2004f22ef01cSRoman Divacky     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
2005f22ef01cSRoman Divacky   }
2006f22ef01cSRoman Divacky }
2007