1 //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This coordinates the per-module state used while generating code.
12 //===----------------------------------------------------------------------===//
14 #include "CodeGenModule.h"
15 #include "CGDebugInfo.h"
16 #include "CodeGenFunction.h"
17 #include "CodeGenTBAA.h"
20 #include "CGObjCRuntime.h"
21 #include "TargetInfo.h"
22 #include "clang/Frontend/CodeGenOptions.h"
23 #include "clang/AST/ASTContext.h"
24 #include "clang/AST/CharUnits.h"
25 #include "clang/AST/DeclObjC.h"
26 #include "clang/AST/DeclCXX.h"
27 #include "clang/AST/DeclTemplate.h"
28 #include "clang/AST/Mangle.h"
29 #include "clang/AST/RecordLayout.h"
30 #include "clang/Basic/Builtins.h"
31 #include "clang/Basic/Diagnostic.h"
32 #include "clang/Basic/SourceManager.h"
33 #include "clang/Basic/TargetInfo.h"
34 #include "clang/Basic/ConvertUTF.h"
35 #include "llvm/CallingConv.h"
36 #include "llvm/Module.h"
37 #include "llvm/Intrinsics.h"
38 #include "llvm/LLVMContext.h"
39 #include "llvm/ADT/Triple.h"
40 #include "llvm/Target/Mangler.h"
41 #include "llvm/Target/TargetData.h"
42 #include "llvm/Support/CallSite.h"
43 #include "llvm/Support/ErrorHandling.h"
44 using namespace clang;
45 using namespace CodeGen;
47 static CGCXXABI &createCXXABI(CodeGenModule &CGM) {
48 switch (CGM.getContext().Target.getCXXABI()) {
49 case CXXABI_ARM: return *CreateARMCXXABI(CGM);
50 case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM);
51 case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM);
54 llvm_unreachable("invalid C++ ABI kind");
55 return *CreateItaniumCXXABI(CGM);
59 CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
60 llvm::Module &M, const llvm::TargetData &TD,
62 : Context(C), Features(C.getLangOptions()), CodeGenOpts(CGO), TheModule(M),
63 TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags),
64 ABI(createCXXABI(*this)),
65 Types(C, M, TD, getTargetCodeGenInfo().getABIInfo(), ABI, CGO),
67 VTables(*this), Runtime(0), DebugInfo(0), ARCData(0), RRData(0),
68 CFConstantStringClassRef(0), ConstantStringClassRef(0),
69 VMContext(M.getContext()),
70 NSConcreteGlobalBlockDecl(0), NSConcreteStackBlockDecl(0),
71 NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
72 BlockObjectAssignDecl(0), BlockObjectDisposeDecl(0),
73 BlockObjectAssign(0), BlockObjectDispose(0),
74 BlockDescriptorType(0), GenericBlockLiteralType(0) {
78 // Enable TBAA unless it's suppressed.
79 if (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)
80 TBAA = new CodeGenTBAA(Context, VMContext, getLangOptions(),
81 ABI.getMangleContext());
83 // If debug info or coverage generation is enabled, create the CGDebugInfo
85 if (CodeGenOpts.DebugInfo || CodeGenOpts.EmitGcovArcs ||
86 CodeGenOpts.EmitGcovNotes)
87 DebugInfo = new CGDebugInfo(*this);
89 Block.GlobalUniqueCount = 0;
91 if (C.getLangOptions().ObjCAutoRefCount)
92 ARCData = new ARCEntrypoints();
93 RRData = new RREntrypoints();
95 // Initialize the type cache.
96 llvm::LLVMContext &LLVMContext = M.getContext();
97 VoidTy = llvm::Type::getVoidTy(LLVMContext);
98 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
99 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
100 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
101 PointerWidthInBits = C.Target.getPointerWidth(0);
102 PointerAlignInBytes =
103 C.toCharUnitsFromBits(C.Target.getPointerAlign(0)).getQuantity();
104 IntTy = llvm::IntegerType::get(LLVMContext, C.Target.getIntWidth());
105 IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
106 Int8PtrTy = Int8Ty->getPointerTo(0);
107 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
110 CodeGenModule::~CodeGenModule() {
119 void CodeGenModule::createObjCRuntime() {
120 if (!Features.NeXTRuntime)
121 Runtime = CreateGNUObjCRuntime(*this);
123 Runtime = CreateMacObjCRuntime(*this);
126 void CodeGenModule::Release() {
128 EmitCXXGlobalInitFunc();
129 EmitCXXGlobalDtorFunc();
131 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
132 AddGlobalCtor(ObjCInitFunction);
133 EmitCtorList(GlobalCtors, "llvm.global_ctors");
134 EmitCtorList(GlobalDtors, "llvm.global_dtors");
138 SimplifyPersonality();
140 if (getCodeGenOpts().EmitDeclMetadata)
143 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
147 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
148 // Make sure that this type is translated.
149 Types.UpdateCompletedType(TD);
151 DebugInfo->UpdateCompletedType(TD);
154 llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
157 return TBAA->getTBAAInfo(QTy);
160 void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
161 llvm::MDNode *TBAAInfo) {
162 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
165 bool CodeGenModule::isTargetDarwin() const {
166 return getContext().Target.getTriple().isOSDarwin();
169 void CodeGenModule::Error(SourceLocation loc, llvm::StringRef error) {
170 unsigned diagID = getDiags().getCustomDiagID(Diagnostic::Error, error);
171 getDiags().Report(Context.getFullLoc(loc), diagID);
174 /// ErrorUnsupported - Print out an error that codegen doesn't support the
175 /// specified stmt yet.
176 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
178 if (OmitOnError && getDiags().hasErrorOccurred())
180 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
181 "cannot compile this %0 yet");
182 std::string Msg = Type;
183 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
184 << Msg << S->getSourceRange();
187 /// ErrorUnsupported - Print out an error that codegen doesn't support the
188 /// specified decl yet.
189 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
191 if (OmitOnError && getDiags().hasErrorOccurred())
193 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
194 "cannot compile this %0 yet");
195 std::string Msg = Type;
196 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
199 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
200 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
203 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
204 const NamedDecl *D) const {
205 // Internal definitions always have default visibility.
206 if (GV->hasLocalLinkage()) {
207 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
211 // Set visibility for definitions.
212 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
213 if (LV.visibilityExplicit() || !GV->hasAvailableExternallyLinkage())
214 GV->setVisibility(GetLLVMVisibility(LV.visibility()));
217 /// Set the symbol visibility of type information (vtable and RTTI)
218 /// associated with the given type.
219 void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
220 const CXXRecordDecl *RD,
221 TypeVisibilityKind TVK) const {
222 setGlobalVisibility(GV, RD);
224 if (!CodeGenOpts.HiddenWeakVTables)
227 // We never want to drop the visibility for RTTI names.
228 if (TVK == TVK_ForRTTIName)
231 // We want to drop the visibility to hidden for weak type symbols.
232 // This isn't possible if there might be unresolved references
233 // elsewhere that rely on this symbol being visible.
235 // This should be kept roughly in sync with setThunkVisibility
239 if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
240 GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
243 // Don't override an explicit visibility attribute.
244 if (RD->getExplicitVisibility())
247 switch (RD->getTemplateSpecializationKind()) {
248 // We have to disable the optimization if this is an EI definition
249 // because there might be EI declarations in other shared objects.
250 case TSK_ExplicitInstantiationDefinition:
251 case TSK_ExplicitInstantiationDeclaration:
254 // Every use of a non-template class's type information has to emit it.
258 // In theory, implicit instantiations can ignore the possibility of
259 // an explicit instantiation declaration because there necessarily
260 // must be an EI definition somewhere with default visibility. In
261 // practice, it's possible to have an explicit instantiation for
262 // an arbitrary template class, and linkers aren't necessarily able
263 // to deal with mixed-visibility symbols.
264 case TSK_ExplicitSpecialization:
265 case TSK_ImplicitInstantiation:
266 if (!CodeGenOpts.HiddenWeakTemplateVTables)
271 // If there's a key function, there may be translation units
272 // that don't have the key function's definition. But ignore
273 // this if we're emitting RTTI under -fno-rtti.
274 if (!(TVK != TVK_ForRTTI) || Features.RTTI) {
275 if (Context.getKeyFunction(RD))
279 // Otherwise, drop the visibility to hidden.
280 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
281 GV->setUnnamedAddr(true);
284 llvm::StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
285 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
287 llvm::StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
291 if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
292 IdentifierInfo *II = ND->getIdentifier();
293 assert(II && "Attempt to mangle unnamed decl.");
299 llvm::SmallString<256> Buffer;
300 llvm::raw_svector_ostream Out(Buffer);
301 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
302 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
303 else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
304 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
305 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
306 getCXXABI().getMangleContext().mangleBlock(BD, Out);
308 getCXXABI().getMangleContext().mangleName(ND, Out);
310 // Allocate space for the mangled name.
312 size_t Length = Buffer.size();
313 char *Name = MangledNamesAllocator.Allocate<char>(Length);
314 std::copy(Buffer.begin(), Buffer.end(), Name);
316 Str = llvm::StringRef(Name, Length);
321 void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
322 const BlockDecl *BD) {
323 MangleContext &MangleCtx = getCXXABI().getMangleContext();
324 const Decl *D = GD.getDecl();
325 llvm::raw_svector_ostream Out(Buffer.getBuffer());
327 MangleCtx.mangleGlobalBlock(BD, Out);
328 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
329 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
330 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
331 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
333 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
336 llvm::GlobalValue *CodeGenModule::GetGlobalValue(llvm::StringRef Name) {
337 return getModule().getNamedValue(Name);
340 /// AddGlobalCtor - Add a function to the list that will be called before
342 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
343 // FIXME: Type coercion of void()* types.
344 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
347 /// AddGlobalDtor - Add a function to the list that will be called
348 /// when the module is unloaded.
349 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
350 // FIXME: Type coercion of void()* types.
351 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
354 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
355 // Ctor function type is void()*.
356 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
357 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
359 // Get the type of a ctor entry, { i32, void ()* }.
360 llvm::StructType *CtorStructTy =
361 llvm::StructType::get(llvm::Type::getInt32Ty(VMContext),
362 llvm::PointerType::getUnqual(CtorFTy), NULL);
364 // Construct the constructor and destructor arrays.
365 std::vector<llvm::Constant*> Ctors;
366 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
367 std::vector<llvm::Constant*> S;
368 S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
370 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
371 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
374 if (!Ctors.empty()) {
375 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
376 new llvm::GlobalVariable(TheModule, AT, false,
377 llvm::GlobalValue::AppendingLinkage,
378 llvm::ConstantArray::get(AT, Ctors),
383 void CodeGenModule::EmitAnnotations() {
384 if (Annotations.empty())
387 // Create a new global variable for the ConstantStruct in the Module.
388 llvm::Constant *Array =
389 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
392 llvm::GlobalValue *gv =
393 new llvm::GlobalVariable(TheModule, Array->getType(), false,
394 llvm::GlobalValue::AppendingLinkage, Array,
395 "llvm.global.annotations");
396 gv->setSection("llvm.metadata");
399 llvm::GlobalValue::LinkageTypes
400 CodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
401 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
403 if (Linkage == GVA_Internal)
404 return llvm::Function::InternalLinkage;
406 if (D->hasAttr<DLLExportAttr>())
407 return llvm::Function::DLLExportLinkage;
409 if (D->hasAttr<WeakAttr>())
410 return llvm::Function::WeakAnyLinkage;
412 // In C99 mode, 'inline' functions are guaranteed to have a strong
413 // definition somewhere else, so we can use available_externally linkage.
414 if (Linkage == GVA_C99Inline)
415 return llvm::Function::AvailableExternallyLinkage;
417 // In C++, the compiler has to emit a definition in every translation unit
418 // that references the function. We should use linkonce_odr because
419 // a) if all references in this translation unit are optimized away, we
420 // don't need to codegen it. b) if the function persists, it needs to be
421 // merged with other definitions. c) C++ has the ODR, so we know the
422 // definition is dependable.
423 if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
424 return !Context.getLangOptions().AppleKext
425 ? llvm::Function::LinkOnceODRLinkage
426 : llvm::Function::InternalLinkage;
428 // An explicit instantiation of a template has weak linkage, since
429 // explicit instantiations can occur in multiple translation units
430 // and must all be equivalent. However, we are not allowed to
431 // throw away these explicit instantiations.
432 if (Linkage == GVA_ExplicitTemplateInstantiation)
433 return !Context.getLangOptions().AppleKext
434 ? llvm::Function::WeakODRLinkage
435 : llvm::Function::InternalLinkage;
437 // Otherwise, we have strong external linkage.
438 assert(Linkage == GVA_StrongExternal);
439 return llvm::Function::ExternalLinkage;
443 /// SetFunctionDefinitionAttributes - Set attributes for a global.
445 /// FIXME: This is currently only done for aliases and functions, but not for
446 /// variables (these details are set in EmitGlobalVarDefinition for variables).
447 void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
448 llvm::GlobalValue *GV) {
449 SetCommonAttributes(D, GV);
452 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
453 const CGFunctionInfo &Info,
455 unsigned CallingConv;
456 AttributeListType AttributeList;
457 ConstructAttributeList(Info, D, AttributeList, CallingConv);
458 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
459 AttributeList.size()));
460 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
463 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
465 if (CodeGenOpts.UnwindTables)
468 if (!Features.Exceptions && !Features.ObjCNonFragileABI)
469 F->addFnAttr(llvm::Attribute::NoUnwind);
471 if (D->hasAttr<AlwaysInlineAttr>())
472 F->addFnAttr(llvm::Attribute::AlwaysInline);
474 if (D->hasAttr<NakedAttr>())
475 F->addFnAttr(llvm::Attribute::Naked);
477 if (D->hasAttr<NoInlineAttr>())
478 F->addFnAttr(llvm::Attribute::NoInline);
480 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
481 F->setUnnamedAddr(true);
483 if (Features.getStackProtectorMode() == LangOptions::SSPOn)
484 F->addFnAttr(llvm::Attribute::StackProtect);
485 else if (Features.getStackProtectorMode() == LangOptions::SSPReq)
486 F->addFnAttr(llvm::Attribute::StackProtectReq);
488 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
490 F->setAlignment(alignment);
492 // C++ ABI requires 2-byte alignment for member functions.
493 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
497 void CodeGenModule::SetCommonAttributes(const Decl *D,
498 llvm::GlobalValue *GV) {
499 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
500 setGlobalVisibility(GV, ND);
502 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
504 if (D->hasAttr<UsedAttr>())
507 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
508 GV->setSection(SA->getName());
510 getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
513 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
515 const CGFunctionInfo &FI) {
516 SetLLVMFunctionAttributes(D, FI, F);
517 SetLLVMFunctionAttributesForDefinition(D, F);
519 F->setLinkage(llvm::Function::InternalLinkage);
521 SetCommonAttributes(D, F);
524 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
526 bool IsIncompleteFunction) {
527 if (unsigned IID = F->getIntrinsicID()) {
528 // If this is an intrinsic function, set the function's attributes
529 // to the intrinsic's attributes.
530 F->setAttributes(llvm::Intrinsic::getAttributes((llvm::Intrinsic::ID)IID));
534 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
536 if (!IsIncompleteFunction)
537 SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(GD), F);
539 // Only a few attributes are set on declarations; these may later be
540 // overridden by a definition.
542 if (FD->hasAttr<DLLImportAttr>()) {
543 F->setLinkage(llvm::Function::DLLImportLinkage);
544 } else if (FD->hasAttr<WeakAttr>() ||
545 FD->isWeakImported()) {
546 // "extern_weak" is overloaded in LLVM; we probably should have
547 // separate linkage types for this.
548 F->setLinkage(llvm::Function::ExternalWeakLinkage);
550 F->setLinkage(llvm::Function::ExternalLinkage);
552 NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility();
553 if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) {
554 F->setVisibility(GetLLVMVisibility(LV.visibility()));
558 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
559 F->setSection(SA->getName());
562 void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
563 assert(!GV->isDeclaration() &&
564 "Only globals with definition can force usage.");
565 LLVMUsed.push_back(GV);
568 void CodeGenModule::EmitLLVMUsed() {
569 // Don't create llvm.used if there is no need.
570 if (LLVMUsed.empty())
573 const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext);
575 // Convert LLVMUsed to what ConstantArray needs.
576 std::vector<llvm::Constant*> UsedArray;
577 UsedArray.resize(LLVMUsed.size());
578 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
580 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
584 if (UsedArray.empty())
586 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size());
588 llvm::GlobalVariable *GV =
589 new llvm::GlobalVariable(getModule(), ATy, false,
590 llvm::GlobalValue::AppendingLinkage,
591 llvm::ConstantArray::get(ATy, UsedArray),
594 GV->setSection("llvm.metadata");
597 void CodeGenModule::EmitDeferred() {
598 // Emit code for any potentially referenced deferred decls. Since a
599 // previously unused static decl may become used during the generation of code
600 // for a static function, iterate until no changes are made.
602 while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) {
603 if (!DeferredVTables.empty()) {
604 const CXXRecordDecl *RD = DeferredVTables.back();
605 DeferredVTables.pop_back();
606 getVTables().GenerateClassData(getVTableLinkage(RD), RD);
610 GlobalDecl D = DeferredDeclsToEmit.back();
611 DeferredDeclsToEmit.pop_back();
613 // Check to see if we've already emitted this. This is necessary
614 // for a couple of reasons: first, decls can end up in the
615 // deferred-decls queue multiple times, and second, decls can end
616 // up with definitions in unusual ways (e.g. by an extern inline
617 // function acquiring a strong function redefinition). Just
618 // ignore these cases.
620 // TODO: That said, looking this up multiple times is very wasteful.
621 llvm::StringRef Name = getMangledName(D);
622 llvm::GlobalValue *CGRef = GetGlobalValue(Name);
623 assert(CGRef && "Deferred decl wasn't referenced?");
625 if (!CGRef->isDeclaration())
628 // GlobalAlias::isDeclaration() defers to the aliasee, but for our
629 // purposes an alias counts as a definition.
630 if (isa<llvm::GlobalAlias>(CGRef))
633 // Otherwise, emit the definition and move on to the next one.
634 EmitGlobalDefinition(D);
638 /// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
639 /// annotation information for a given GlobalValue. The annotation struct is
640 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
641 /// GlobalValue being annotated. The second field is the constant string
642 /// created from the AnnotateAttr's annotation. The third field is a constant
643 /// string containing the name of the translation unit. The fourth field is
644 /// the line number in the file of the annotated value declaration.
646 /// FIXME: this does not unique the annotation string constants, as llvm-gcc
649 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
650 const AnnotateAttr *AA,
652 llvm::Module *M = &getModule();
654 // get [N x i8] constants for the annotation string, and the filename string
655 // which are the 2nd and 3rd elements of the global annotation structure.
656 const llvm::Type *SBP = llvm::Type::getInt8PtrTy(VMContext);
657 llvm::Constant *anno = llvm::ConstantArray::get(VMContext,
658 AA->getAnnotation(), true);
659 llvm::Constant *unit = llvm::ConstantArray::get(VMContext,
660 M->getModuleIdentifier(),
663 // Get the two global values corresponding to the ConstantArrays we just
664 // created to hold the bytes of the strings.
665 llvm::GlobalValue *annoGV =
666 new llvm::GlobalVariable(*M, anno->getType(), false,
667 llvm::GlobalValue::PrivateLinkage, anno,
669 // translation unit name string, emitted into the llvm.metadata section.
670 llvm::GlobalValue *unitGV =
671 new llvm::GlobalVariable(*M, unit->getType(), false,
672 llvm::GlobalValue::PrivateLinkage, unit,
674 unitGV->setUnnamedAddr(true);
676 // Create the ConstantStruct for the global annotation.
677 llvm::Constant *Fields[4] = {
678 llvm::ConstantExpr::getBitCast(GV, SBP),
679 llvm::ConstantExpr::getBitCast(annoGV, SBP),
680 llvm::ConstantExpr::getBitCast(unitGV, SBP),
681 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo)
683 return llvm::ConstantStruct::getAnon(Fields);
686 bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
687 // Never defer when EmitAllDecls is specified.
688 if (Features.EmitAllDecls)
691 return !getContext().DeclMustBeEmitted(Global);
694 llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
695 const AliasAttr *AA = VD->getAttr<AliasAttr>();
696 assert(AA && "No alias?");
698 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
700 // See if there is already something with the target's name in the module.
701 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
703 llvm::Constant *Aliasee;
704 if (isa<llvm::FunctionType>(DeclTy))
705 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
706 /*ForVTable=*/false);
708 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
709 llvm::PointerType::getUnqual(DeclTy), 0);
711 llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
712 F->setLinkage(llvm::Function::ExternalWeakLinkage);
713 WeakRefReferences.insert(F);
719 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
720 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
722 // Weak references don't produce any output by themselves.
723 if (Global->hasAttr<WeakRefAttr>())
726 // If this is an alias definition (which otherwise looks like a declaration)
728 if (Global->hasAttr<AliasAttr>())
729 return EmitAliasDefinition(GD);
731 // Ignore declarations, they will be emitted on their first use.
732 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
733 if (FD->getIdentifier()) {
734 llvm::StringRef Name = FD->getName();
735 if (Name == "_Block_object_assign") {
736 BlockObjectAssignDecl = FD;
737 } else if (Name == "_Block_object_dispose") {
738 BlockObjectDisposeDecl = FD;
742 // Forward declarations are emitted lazily on first use.
743 if (!FD->doesThisDeclarationHaveABody())
746 const VarDecl *VD = cast<VarDecl>(Global);
747 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
749 if (VD->getIdentifier()) {
750 llvm::StringRef Name = VD->getName();
751 if (Name == "_NSConcreteGlobalBlock") {
752 NSConcreteGlobalBlockDecl = VD;
753 } else if (Name == "_NSConcreteStackBlock") {
754 NSConcreteStackBlockDecl = VD;
759 if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
763 // Defer code generation when possible if this is a static definition, inline
764 // function etc. These we only want to emit if they are used.
765 if (!MayDeferGeneration(Global)) {
766 // Emit the definition if it can't be deferred.
767 EmitGlobalDefinition(GD);
771 // If we're deferring emission of a C++ variable with an
772 // initializer, remember the order in which it appeared in the file.
773 if (getLangOptions().CPlusPlus && isa<VarDecl>(Global) &&
774 cast<VarDecl>(Global)->hasInit()) {
775 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
776 CXXGlobalInits.push_back(0);
779 // If the value has already been used, add it directly to the
780 // DeferredDeclsToEmit list.
781 llvm::StringRef MangledName = getMangledName(GD);
782 if (GetGlobalValue(MangledName))
783 DeferredDeclsToEmit.push_back(GD);
785 // Otherwise, remember that we saw a deferred decl with this name. The
786 // first use of the mangled name will cause it to move into
787 // DeferredDeclsToEmit.
788 DeferredDecls[MangledName] = GD;
792 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
793 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
795 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
796 Context.getSourceManager(),
797 "Generating code for declaration");
799 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
800 // At -O0, don't generate IR for functions with available_externally
802 if (CodeGenOpts.OptimizationLevel == 0 &&
803 !Function->hasAttr<AlwaysInlineAttr>() &&
804 getFunctionLinkage(Function)
805 == llvm::Function::AvailableExternallyLinkage)
808 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
809 // Make sure to emit the definition(s) before we emit the thunks.
810 // This is necessary for the generation of certain thunks.
811 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
812 EmitCXXConstructor(CD, GD.getCtorType());
813 else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method))
814 EmitCXXDestructor(DD, GD.getDtorType());
816 EmitGlobalFunctionDefinition(GD);
818 if (Method->isVirtual())
819 getVTables().EmitThunks(GD);
824 return EmitGlobalFunctionDefinition(GD);
827 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
828 return EmitGlobalVarDefinition(VD);
830 assert(0 && "Invalid argument to EmitGlobalDefinition()");
833 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
834 /// module, create and return an llvm Function with the specified type. If there
835 /// is something in the module with the specified name, return it potentially
836 /// bitcasted to the right type.
838 /// If D is non-null, it specifies a decl that correspond to this. This is used
839 /// to set the attributes on the function when it is first created.
841 CodeGenModule::GetOrCreateLLVMFunction(llvm::StringRef MangledName,
842 const llvm::Type *Ty,
843 GlobalDecl D, bool ForVTable,
844 llvm::Attributes ExtraAttrs) {
845 // Lookup the entry, lazily creating it if necessary.
846 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
848 if (WeakRefReferences.count(Entry)) {
849 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
850 if (FD && !FD->hasAttr<WeakAttr>())
851 Entry->setLinkage(llvm::Function::ExternalLinkage);
853 WeakRefReferences.erase(Entry);
856 if (Entry->getType()->getElementType() == Ty)
859 // Make sure the result is of the correct type.
860 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
863 // This function doesn't have a complete type (for example, the return
864 // type is an incomplete struct). Use a fake type instead, and make
865 // sure not to try to set attributes.
866 bool IsIncompleteFunction = false;
868 const llvm::FunctionType *FTy;
869 if (isa<llvm::FunctionType>(Ty)) {
870 FTy = cast<llvm::FunctionType>(Ty);
872 FTy = llvm::FunctionType::get(VoidTy, false);
873 IsIncompleteFunction = true;
876 llvm::Function *F = llvm::Function::Create(FTy,
877 llvm::Function::ExternalLinkage,
878 MangledName, &getModule());
879 assert(F->getName() == MangledName && "name was uniqued!");
881 SetFunctionAttributes(D, F, IsIncompleteFunction);
882 if (ExtraAttrs != llvm::Attribute::None)
883 F->addFnAttr(ExtraAttrs);
885 // This is the first use or definition of a mangled name. If there is a
886 // deferred decl with this name, remember that we need to emit it at the end
888 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
889 if (DDI != DeferredDecls.end()) {
890 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
891 // list, and remove it from DeferredDecls (since we don't need it anymore).
892 DeferredDeclsToEmit.push_back(DDI->second);
893 DeferredDecls.erase(DDI);
895 // Otherwise, there are cases we have to worry about where we're
896 // using a declaration for which we must emit a definition but where
897 // we might not find a top-level definition:
898 // - member functions defined inline in their classes
899 // - friend functions defined inline in some class
900 // - special member functions with implicit definitions
901 // If we ever change our AST traversal to walk into class methods,
902 // this will be unnecessary.
904 // We also don't emit a definition for a function if it's going to be an entry
905 // in a vtable, unless it's already marked as used.
906 } else if (getLangOptions().CPlusPlus && D.getDecl()) {
907 // Look for a declaration that's lexically in a record.
908 const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl());
910 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
911 if (FD->isImplicit() && !ForVTable) {
912 assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
913 DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
915 } else if (FD->doesThisDeclarationHaveABody()) {
916 DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
920 FD = FD->getPreviousDeclaration();
924 // Make sure the result is of the requested type.
925 if (!IsIncompleteFunction) {
926 assert(F->getType()->getElementType() == Ty);
930 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
931 return llvm::ConstantExpr::getBitCast(F, PTy);
934 /// GetAddrOfFunction - Return the address of the given function. If Ty is
935 /// non-null, then this function will use the specified type if it has to
936 /// create it (this occurs when we see a definition of the function).
937 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
938 const llvm::Type *Ty,
940 // If there was no specific requested type, just convert it now.
942 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
944 llvm::StringRef MangledName = getMangledName(GD);
945 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable);
948 /// CreateRuntimeFunction - Create a new runtime function with the specified
951 CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
952 llvm::StringRef Name,
953 llvm::Attributes ExtraAttrs) {
954 return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
958 static bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D,
960 if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType())
963 if (Context.getLangOptions().CPlusPlus) {
964 if (const RecordType *Record
965 = Context.getBaseElementType(D->getType())->getAs<RecordType>())
966 return ConstantInit &&
967 cast<CXXRecordDecl>(Record->getDecl())->isPOD() &&
968 !cast<CXXRecordDecl>(Record->getDecl())->hasMutableFields();
974 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
975 /// create and return an llvm GlobalVariable with the specified type. If there
976 /// is something in the module with the specified name, return it potentially
977 /// bitcasted to the right type.
979 /// If D is non-null, it specifies a decl that correspond to this. This is used
980 /// to set the attributes on the global when it is first created.
982 CodeGenModule::GetOrCreateLLVMGlobal(llvm::StringRef MangledName,
983 const llvm::PointerType *Ty,
986 // Lookup the entry, lazily creating it if necessary.
987 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
989 if (WeakRefReferences.count(Entry)) {
990 if (D && !D->hasAttr<WeakAttr>())
991 Entry->setLinkage(llvm::Function::ExternalLinkage);
993 WeakRefReferences.erase(Entry);
997 Entry->setUnnamedAddr(true);
999 if (Entry->getType() == Ty)
1002 // Make sure the result is of the correct type.
1003 return llvm::ConstantExpr::getBitCast(Entry, Ty);
1006 // This is the first use or definition of a mangled name. If there is a
1007 // deferred decl with this name, remember that we need to emit it at the end
1009 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
1010 if (DDI != DeferredDecls.end()) {
1011 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1012 // list, and remove it from DeferredDecls (since we don't need it anymore).
1013 DeferredDeclsToEmit.push_back(DDI->second);
1014 DeferredDecls.erase(DDI);
1017 llvm::GlobalVariable *GV =
1018 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
1019 llvm::GlobalValue::ExternalLinkage,
1021 false, Ty->getAddressSpace());
1023 // Handle things which are present even on external declarations.
1025 // FIXME: This code is overly simple and should be merged with other global
1027 GV->setConstant(DeclIsConstantGlobal(Context, D, false));
1029 // Set linkage and visibility in case we never see a definition.
1030 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
1031 if (LV.linkage() != ExternalLinkage) {
1032 // Don't set internal linkage on declarations.
1034 if (D->hasAttr<DLLImportAttr>())
1035 GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
1036 else if (D->hasAttr<WeakAttr>() || D->isWeakImported())
1037 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1039 // Set visibility on a declaration only if it's explicit.
1040 if (LV.visibilityExplicit())
1041 GV->setVisibility(GetLLVMVisibility(LV.visibility()));
1044 GV->setThreadLocal(D->isThreadSpecified());
1051 llvm::GlobalVariable *
1052 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(llvm::StringRef Name,
1053 const llvm::Type *Ty,
1054 llvm::GlobalValue::LinkageTypes Linkage) {
1055 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
1056 llvm::GlobalVariable *OldGV = 0;
1060 // Check if the variable has the right type.
1061 if (GV->getType()->getElementType() == Ty)
1064 // Because C++ name mangling, the only way we can end up with an already
1065 // existing global with the same name is if it has been declared extern "C".
1066 assert(GV->isDeclaration() && "Declaration has wrong type!");
1070 // Create a new variable.
1071 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
1075 // Replace occurrences of the old variable if needed.
1076 GV->takeName(OldGV);
1078 if (!OldGV->use_empty()) {
1079 llvm::Constant *NewPtrForOldDecl =
1080 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1081 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1084 OldGV->eraseFromParent();
1090 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1091 /// given global variable. If Ty is non-null and if the global doesn't exist,
1092 /// then it will be greated with the specified type instead of whatever the
1093 /// normal requested type would be.
1094 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
1095 const llvm::Type *Ty) {
1096 assert(D->hasGlobalStorage() && "Not a global variable");
1097 QualType ASTTy = D->getType();
1099 Ty = getTypes().ConvertTypeForMem(ASTTy);
1101 const llvm::PointerType *PTy =
1102 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
1104 llvm::StringRef MangledName = getMangledName(D);
1105 return GetOrCreateLLVMGlobal(MangledName, PTy, D);
1108 /// CreateRuntimeVariable - Create a new runtime global variable with the
1109 /// specified type and name.
1111 CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
1112 llvm::StringRef Name) {
1113 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
1117 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1118 assert(!D->getInit() && "Cannot emit definite definitions here!");
1120 if (MayDeferGeneration(D)) {
1121 // If we have not seen a reference to this variable yet, place it
1122 // into the deferred declarations table to be emitted if needed
1124 llvm::StringRef MangledName = getMangledName(D);
1125 if (!GetGlobalValue(MangledName)) {
1126 DeferredDecls[MangledName] = D;
1131 // The tentative definition is the only definition.
1132 EmitGlobalVarDefinition(D);
1135 void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) {
1136 if (DefinitionRequired)
1137 getVTables().GenerateClassData(getVTableLinkage(Class), Class);
1140 llvm::GlobalVariable::LinkageTypes
1141 CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
1142 if (RD->getLinkage() != ExternalLinkage)
1143 return llvm::GlobalVariable::InternalLinkage;
1145 if (const CXXMethodDecl *KeyFunction
1146 = RD->getASTContext().getKeyFunction(RD)) {
1147 // If this class has a key function, use that to determine the linkage of
1149 const FunctionDecl *Def = 0;
1150 if (KeyFunction->hasBody(Def))
1151 KeyFunction = cast<CXXMethodDecl>(Def);
1153 switch (KeyFunction->getTemplateSpecializationKind()) {
1154 case TSK_Undeclared:
1155 case TSK_ExplicitSpecialization:
1156 // When compiling with optimizations turned on, we emit all vtables,
1157 // even if the key function is not defined in the current translation
1158 // unit. If this is the case, use available_externally linkage.
1159 if (!Def && CodeGenOpts.OptimizationLevel)
1160 return llvm::GlobalVariable::AvailableExternallyLinkage;
1162 if (KeyFunction->isInlined())
1163 return !Context.getLangOptions().AppleKext ?
1164 llvm::GlobalVariable::LinkOnceODRLinkage :
1165 llvm::Function::InternalLinkage;
1167 return llvm::GlobalVariable::ExternalLinkage;
1169 case TSK_ImplicitInstantiation:
1170 return !Context.getLangOptions().AppleKext ?
1171 llvm::GlobalVariable::LinkOnceODRLinkage :
1172 llvm::Function::InternalLinkage;
1174 case TSK_ExplicitInstantiationDefinition:
1175 return !Context.getLangOptions().AppleKext ?
1176 llvm::GlobalVariable::WeakODRLinkage :
1177 llvm::Function::InternalLinkage;
1179 case TSK_ExplicitInstantiationDeclaration:
1180 // FIXME: Use available_externally linkage. However, this currently
1181 // breaks LLVM's build due to undefined symbols.
1182 // return llvm::GlobalVariable::AvailableExternallyLinkage;
1183 return !Context.getLangOptions().AppleKext ?
1184 llvm::GlobalVariable::LinkOnceODRLinkage :
1185 llvm::Function::InternalLinkage;
1189 if (Context.getLangOptions().AppleKext)
1190 return llvm::Function::InternalLinkage;
1192 switch (RD->getTemplateSpecializationKind()) {
1193 case TSK_Undeclared:
1194 case TSK_ExplicitSpecialization:
1195 case TSK_ImplicitInstantiation:
1196 // FIXME: Use available_externally linkage. However, this currently
1197 // breaks LLVM's build due to undefined symbols.
1198 // return llvm::GlobalVariable::AvailableExternallyLinkage;
1199 case TSK_ExplicitInstantiationDeclaration:
1200 return llvm::GlobalVariable::LinkOnceODRLinkage;
1202 case TSK_ExplicitInstantiationDefinition:
1203 return llvm::GlobalVariable::WeakODRLinkage;
1206 // Silence GCC warning.
1207 return llvm::GlobalVariable::LinkOnceODRLinkage;
1210 CharUnits CodeGenModule::GetTargetTypeStoreSize(const llvm::Type *Ty) const {
1211 return Context.toCharUnitsFromBits(
1212 TheTargetData.getTypeStoreSizeInBits(Ty));
1215 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
1216 llvm::Constant *Init = 0;
1217 QualType ASTTy = D->getType();
1218 bool NonConstInit = false;
1220 const Expr *InitExpr = D->getAnyInitializer();
1223 // This is a tentative definition; tentative definitions are
1224 // implicitly initialized with { 0 }.
1226 // Note that tentative definitions are only emitted at the end of
1227 // a translation unit, so they should never have incomplete
1228 // type. In addition, EmitTentativeDefinition makes sure that we
1229 // never attempt to emit a tentative definition if a real one
1230 // exists. A use may still exists, however, so we still may need
1232 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
1233 Init = EmitNullConstant(D->getType());
1235 Init = EmitConstantExpr(InitExpr, D->getType());
1237 QualType T = InitExpr->getType();
1238 if (D->getType()->isReferenceType())
1241 if (getLangOptions().CPlusPlus) {
1242 Init = EmitNullConstant(T);
1243 NonConstInit = true;
1245 ErrorUnsupported(D, "static initializer");
1246 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1249 // We don't need an initializer, so remove the entry for the delayed
1250 // initializer position (just in case this entry was delayed).
1251 if (getLangOptions().CPlusPlus)
1252 DelayedCXXInitPosition.erase(D);
1256 const llvm::Type* InitType = Init->getType();
1257 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
1259 // Strip off a bitcast if we got one back.
1260 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1261 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1262 // all zero index gep.
1263 CE->getOpcode() == llvm::Instruction::GetElementPtr);
1264 Entry = CE->getOperand(0);
1267 // Entry is now either a Function or GlobalVariable.
1268 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
1270 // We have a definition after a declaration with the wrong type.
1271 // We must make a new GlobalVariable* and update everything that used OldGV
1272 // (a declaration or tentative definition) with the new GlobalVariable*
1273 // (which will be a definition).
1275 // This happens if there is a prototype for a global (e.g.
1276 // "extern int x[];") and then a definition of a different type (e.g.
1277 // "int x[10];"). This also happens when an initializer has a different type
1278 // from the type of the global (this happens with unions).
1280 GV->getType()->getElementType() != InitType ||
1281 GV->getType()->getAddressSpace() !=
1282 getContext().getTargetAddressSpace(ASTTy)) {
1284 // Move the old entry aside so that we'll create a new one.
1285 Entry->setName(llvm::StringRef());
1287 // Make a new global with the correct type, this is now guaranteed to work.
1288 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
1290 // Replace all uses of the old global with the new global
1291 llvm::Constant *NewPtrForOldDecl =
1292 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
1293 Entry->replaceAllUsesWith(NewPtrForOldDecl);
1295 // Erase the old global, since it is no longer used.
1296 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
1299 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
1300 SourceManager &SM = Context.getSourceManager();
1301 AddAnnotation(EmitAnnotateAttr(GV, AA,
1302 SM.getInstantiationLineNumber(D->getLocation())));
1305 GV->setInitializer(Init);
1307 // If it is safe to mark the global 'constant', do so now.
1308 GV->setConstant(false);
1309 if (!NonConstInit && DeclIsConstantGlobal(Context, D, true))
1310 GV->setConstant(true);
1312 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
1314 // Set the llvm linkage type as appropriate.
1315 llvm::GlobalValue::LinkageTypes Linkage =
1316 GetLLVMLinkageVarDefinition(D, GV);
1317 GV->setLinkage(Linkage);
1318 if (Linkage == llvm::GlobalVariable::CommonLinkage)
1319 // common vars aren't constant even if declared const.
1320 GV->setConstant(false);
1322 SetCommonAttributes(D, GV);
1324 // Emit the initializer function if necessary.
1326 EmitCXXGlobalVarDeclInitFunc(D, GV);
1328 // Emit global variable debug information.
1329 if (CGDebugInfo *DI = getModuleDebugInfo()) {
1330 DI->setLocation(D->getLocation());
1331 DI->EmitGlobalVariable(GV, D);
1335 llvm::GlobalValue::LinkageTypes
1336 CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
1337 llvm::GlobalVariable *GV) {
1338 GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1339 if (Linkage == GVA_Internal)
1340 return llvm::Function::InternalLinkage;
1341 else if (D->hasAttr<DLLImportAttr>())
1342 return llvm::Function::DLLImportLinkage;
1343 else if (D->hasAttr<DLLExportAttr>())
1344 return llvm::Function::DLLExportLinkage;
1345 else if (D->hasAttr<WeakAttr>()) {
1346 if (GV->isConstant())
1347 return llvm::GlobalVariable::WeakODRLinkage;
1349 return llvm::GlobalVariable::WeakAnyLinkage;
1350 } else if (Linkage == GVA_TemplateInstantiation ||
1351 Linkage == GVA_ExplicitTemplateInstantiation)
1352 return llvm::GlobalVariable::WeakODRLinkage;
1353 else if (!getLangOptions().CPlusPlus &&
1354 ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
1355 D->getAttr<CommonAttr>()) &&
1356 !D->hasExternalStorage() && !D->getInit() &&
1357 !D->getAttr<SectionAttr>() && !D->isThreadSpecified() &&
1358 !D->getAttr<WeakImportAttr>()) {
1359 // Thread local vars aren't considered common linkage.
1360 return llvm::GlobalVariable::CommonLinkage;
1362 return llvm::GlobalVariable::ExternalLinkage;
1365 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
1366 /// implement a function with no prototype, e.g. "int foo() {}". If there are
1367 /// existing call uses of the old function in the module, this adjusts them to
1368 /// call the new function directly.
1370 /// This is not just a cleanup: the always_inline pass requires direct calls to
1371 /// functions to be able to inline them. If there is a bitcast in the way, it
1372 /// won't inline them. Instcombine normally deletes these calls, but it isn't
1374 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1375 llvm::Function *NewFn) {
1376 // If we're redefining a global as a function, don't transform it.
1377 llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
1378 if (OldFn == 0) return;
1380 const llvm::Type *NewRetTy = NewFn->getReturnType();
1381 llvm::SmallVector<llvm::Value*, 4> ArgList;
1383 for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
1385 // TODO: Do invokes ever occur in C code? If so, we should handle them too.
1386 llvm::Value::use_iterator I = UI++; // Increment before the CI is erased.
1387 llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I);
1388 if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I)
1389 llvm::CallSite CS(CI);
1390 if (!CI || !CS.isCallee(I)) continue;
1392 // If the return types don't match exactly, and if the call isn't dead, then
1393 // we can't transform this call.
1394 if (CI->getType() != NewRetTy && !CI->use_empty())
1397 // If the function was passed too few arguments, don't transform. If extra
1398 // arguments were passed, we silently drop them. If any of the types
1399 // mismatch, we don't transform.
1401 bool DontTransform = false;
1402 for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
1403 E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
1404 if (CS.arg_size() == ArgNo ||
1405 CS.getArgument(ArgNo)->getType() != AI->getType()) {
1406 DontTransform = true;
1413 // Okay, we can transform this. Create the new call instruction and copy
1414 // over the required information.
1415 ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo);
1416 llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList, "", CI);
1418 if (!NewCall->getType()->isVoidTy())
1419 NewCall->takeName(CI);
1420 NewCall->setAttributes(CI->getAttributes());
1421 NewCall->setCallingConv(CI->getCallingConv());
1423 // Finally, remove the old call, replacing any uses with the new one.
1424 if (!CI->use_empty())
1425 CI->replaceAllUsesWith(NewCall);
1427 // Copy debug location attached to CI.
1428 if (!CI->getDebugLoc().isUnknown())
1429 NewCall->setDebugLoc(CI->getDebugLoc());
1430 CI->eraseFromParent();
1435 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
1436 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
1438 // Compute the function info and LLVM type.
1439 const CGFunctionInfo &FI = getTypes().getFunctionInfo(GD);
1440 bool variadic = false;
1441 if (const FunctionProtoType *fpt = D->getType()->getAs<FunctionProtoType>())
1442 variadic = fpt->isVariadic();
1443 const llvm::FunctionType *Ty = getTypes().GetFunctionType(FI, variadic);
1445 // Get or create the prototype for the function.
1446 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
1448 // Strip off a bitcast if we got one back.
1449 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1450 assert(CE->getOpcode() == llvm::Instruction::BitCast);
1451 Entry = CE->getOperand(0);
1455 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
1456 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
1458 // If the types mismatch then we have to rewrite the definition.
1459 assert(OldFn->isDeclaration() &&
1460 "Shouldn't replace non-declaration");
1462 // F is the Function* for the one with the wrong type, we must make a new
1463 // Function* and update everything that used F (a declaration) with the new
1464 // Function* (which will be a definition).
1466 // This happens if there is a prototype for a function
1467 // (e.g. "int f()") and then a definition of a different type
1468 // (e.g. "int f(int x)"). Move the old function aside so that it
1469 // doesn't interfere with GetAddrOfFunction.
1470 OldFn->setName(llvm::StringRef());
1471 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
1473 // If this is an implementation of a function without a prototype, try to
1474 // replace any existing uses of the function (which may be calls) with uses
1475 // of the new function
1476 if (D->getType()->isFunctionNoProtoType()) {
1477 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
1478 OldFn->removeDeadConstantUsers();
1481 // Replace uses of F with the Function we will endow with a body.
1482 if (!Entry->use_empty()) {
1483 llvm::Constant *NewPtrForOldDecl =
1484 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
1485 Entry->replaceAllUsesWith(NewPtrForOldDecl);
1488 // Ok, delete the old function now, which is dead.
1489 OldFn->eraseFromParent();
1494 // We need to set linkage and visibility on the function before
1495 // generating code for it because various parts of IR generation
1496 // want to propagate this information down (e.g. to local static
1498 llvm::Function *Fn = cast<llvm::Function>(Entry);
1499 setFunctionLinkage(D, Fn);
1501 // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
1502 setGlobalVisibility(Fn, D);
1504 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
1506 SetFunctionDefinitionAttributes(D, Fn);
1507 SetLLVMFunctionAttributesForDefinition(D, Fn);
1509 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
1510 AddGlobalCtor(Fn, CA->getPriority());
1511 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
1512 AddGlobalDtor(Fn, DA->getPriority());
1515 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
1516 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
1517 const AliasAttr *AA = D->getAttr<AliasAttr>();
1518 assert(AA && "Not an alias?");
1520 llvm::StringRef MangledName = getMangledName(GD);
1522 // If there is a definition in the module, then it wins over the alias.
1523 // This is dubious, but allow it to be safe. Just ignore the alias.
1524 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1525 if (Entry && !Entry->isDeclaration())
1528 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
1530 // Create a reference to the named value. This ensures that it is emitted
1531 // if a deferred decl.
1532 llvm::Constant *Aliasee;
1533 if (isa<llvm::FunctionType>(DeclTy))
1534 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
1535 /*ForVTable=*/false);
1537 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1538 llvm::PointerType::getUnqual(DeclTy), 0);
1540 // Create the new alias itself, but don't set a name yet.
1541 llvm::GlobalValue *GA =
1542 new llvm::GlobalAlias(Aliasee->getType(),
1543 llvm::Function::ExternalLinkage,
1544 "", Aliasee, &getModule());
1547 assert(Entry->isDeclaration());
1549 // If there is a declaration in the module, then we had an extern followed
1550 // by the alias, as in:
1551 // extern int test6();
1553 // int test6() __attribute__((alias("test7")));
1555 // Remove it and replace uses of it with the alias.
1556 GA->takeName(Entry);
1558 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
1560 Entry->eraseFromParent();
1562 GA->setName(MangledName);
1565 // Set attributes which are particular to an alias; this is a
1566 // specialization of the attributes which may be set on a global
1567 // variable/function.
1568 if (D->hasAttr<DLLExportAttr>()) {
1569 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1570 // The dllexport attribute is ignored for undefined symbols.
1572 GA->setLinkage(llvm::Function::DLLExportLinkage);
1574 GA->setLinkage(llvm::Function::DLLExportLinkage);
1576 } else if (D->hasAttr<WeakAttr>() ||
1577 D->hasAttr<WeakRefAttr>() ||
1578 D->isWeakImported()) {
1579 GA->setLinkage(llvm::Function::WeakAnyLinkage);
1582 SetCommonAttributes(D, GA);
1585 /// getBuiltinLibFunction - Given a builtin id for a function like
1586 /// "__builtin_fabsf", return a Function* for "fabsf".
1587 llvm::Value *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD,
1588 unsigned BuiltinID) {
1589 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
1590 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
1593 // Get the name, skip over the __builtin_ prefix (if necessary).
1594 llvm::StringRef Name;
1597 // If the builtin has been declared explicitly with an assembler label,
1598 // use the mangled name. This differs from the plain label on platforms
1599 // that prefix labels.
1600 if (FD->hasAttr<AsmLabelAttr>())
1601 Name = getMangledName(D);
1602 else if (Context.BuiltinInfo.isLibFunction(BuiltinID))
1603 Name = Context.BuiltinInfo.GetName(BuiltinID) + 10;
1605 Name = Context.BuiltinInfo.GetName(BuiltinID);
1608 const llvm::FunctionType *Ty =
1609 cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType()));
1611 return GetOrCreateLLVMFunction(Name, Ty, D, /*ForVTable=*/false);
1614 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
1615 llvm::ArrayRef<llvm::Type*> Tys) {
1616 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
1620 static llvm::StringMapEntry<llvm::Constant*> &
1621 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1622 const StringLiteral *Literal,
1625 unsigned &StringLength) {
1626 llvm::StringRef String = Literal->getString();
1627 unsigned NumBytes = String.size();
1629 // Check for simple case.
1630 if (!Literal->containsNonAsciiOrNull()) {
1631 StringLength = NumBytes;
1632 return Map.GetOrCreateValue(String);
1635 // Otherwise, convert the UTF8 literals into a byte string.
1636 llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
1637 const UTF8 *FromPtr = (UTF8 *)String.data();
1638 UTF16 *ToPtr = &ToBuf[0];
1640 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1641 &ToPtr, ToPtr + NumBytes,
1644 // ConvertUTF8toUTF16 returns the length in ToPtr.
1645 StringLength = ToPtr - &ToBuf[0];
1647 // Render the UTF-16 string into a byte array and convert to the target byte
1650 // FIXME: This isn't something we should need to do here.
1651 llvm::SmallString<128> AsBytes;
1652 AsBytes.reserve(StringLength * 2);
1653 for (unsigned i = 0; i != StringLength; ++i) {
1654 unsigned short Val = ToBuf[i];
1656 AsBytes.push_back(Val & 0xFF);
1657 AsBytes.push_back(Val >> 8);
1659 AsBytes.push_back(Val >> 8);
1660 AsBytes.push_back(Val & 0xFF);
1663 // Append one extra null character, the second is automatically added by our
1665 AsBytes.push_back(0);
1668 return Map.GetOrCreateValue(llvm::StringRef(AsBytes.data(), AsBytes.size()));
1671 static llvm::StringMapEntry<llvm::Constant*> &
1672 GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1673 const StringLiteral *Literal,
1674 unsigned &StringLength)
1676 llvm::StringRef String = Literal->getString();
1677 StringLength = String.size();
1678 return Map.GetOrCreateValue(String);
1682 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
1683 unsigned StringLength = 0;
1684 bool isUTF16 = false;
1685 llvm::StringMapEntry<llvm::Constant*> &Entry =
1686 GetConstantCFStringEntry(CFConstantStringMap, Literal,
1687 getTargetData().isLittleEndian(),
1688 isUTF16, StringLength);
1690 if (llvm::Constant *C = Entry.getValue())
1693 llvm::Constant *Zero =
1694 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
1695 llvm::Constant *Zeros[] = { Zero, Zero };
1697 // If we don't already have it, get __CFConstantStringClassReference.
1698 if (!CFConstantStringClassRef) {
1699 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1700 Ty = llvm::ArrayType::get(Ty, 0);
1701 llvm::Constant *GV = CreateRuntimeVariable(Ty,
1702 "__CFConstantStringClassReference");
1703 // Decay array -> ptr
1704 CFConstantStringClassRef =
1705 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1708 QualType CFTy = getContext().getCFConstantStringType();
1710 const llvm::StructType *STy =
1711 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1713 std::vector<llvm::Constant*> Fields(4);
1716 Fields[0] = CFConstantStringClassRef;
1719 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1720 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
1721 llvm::ConstantInt::get(Ty, 0x07C8);
1724 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1726 llvm::GlobalValue::LinkageTypes Linkage;
1729 // FIXME: why do utf strings get "_" labels instead of "L" labels?
1730 Linkage = llvm::GlobalValue::InternalLinkage;
1731 // Note: -fwritable-strings doesn't make unicode CFStrings writable, but
1732 // does make plain ascii ones writable.
1735 // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error
1736 // when using private linkage. It is not clear if this is a bug in ld
1737 // or a reasonable new restriction.
1738 Linkage = llvm::GlobalValue::LinkerPrivateLinkage;
1739 isConstant = !Features.WritableStrings;
1742 llvm::GlobalVariable *GV =
1743 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1745 GV->setUnnamedAddr(true);
1747 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1748 GV->setAlignment(Align.getQuantity());
1750 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
1751 GV->setAlignment(Align.getQuantity());
1753 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1756 Ty = getTypes().ConvertType(getContext().LongTy);
1757 Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
1760 C = llvm::ConstantStruct::get(STy, Fields);
1761 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1762 llvm::GlobalVariable::PrivateLinkage, C,
1763 "_unnamed_cfstring_");
1764 if (const char *Sect = getContext().Target.getCFStringSection())
1765 GV->setSection(Sect);
1772 CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
1773 unsigned StringLength = 0;
1774 llvm::StringMapEntry<llvm::Constant*> &Entry =
1775 GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
1777 if (llvm::Constant *C = Entry.getValue())
1780 llvm::Constant *Zero =
1781 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
1782 llvm::Constant *Zeros[] = { Zero, Zero };
1784 // If we don't already have it, get _NSConstantStringClassReference.
1785 if (!ConstantStringClassRef) {
1786 std::string StringClass(getLangOptions().ObjCConstantStringClass);
1787 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1789 if (Features.ObjCNonFragileABI) {
1791 StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
1792 : "OBJC_CLASS_$_" + StringClass;
1793 GV = getObjCRuntime().GetClassGlobal(str);
1794 // Make sure the result is of the correct type.
1795 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
1796 ConstantStringClassRef =
1797 llvm::ConstantExpr::getBitCast(GV, PTy);
1800 StringClass.empty() ? "_NSConstantStringClassReference"
1801 : "_" + StringClass + "ClassReference";
1802 const llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
1803 GV = CreateRuntimeVariable(PTy, str);
1804 // Decay array -> ptr
1805 ConstantStringClassRef =
1806 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1810 QualType NSTy = getContext().getNSConstantStringType();
1812 const llvm::StructType *STy =
1813 cast<llvm::StructType>(getTypes().ConvertType(NSTy));
1815 std::vector<llvm::Constant*> Fields(3);
1818 Fields[0] = ConstantStringClassRef;
1821 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1823 llvm::GlobalValue::LinkageTypes Linkage;
1825 Linkage = llvm::GlobalValue::PrivateLinkage;
1826 isConstant = !Features.WritableStrings;
1828 llvm::GlobalVariable *GV =
1829 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1831 GV->setUnnamedAddr(true);
1832 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
1833 GV->setAlignment(Align.getQuantity());
1834 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1837 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1838 Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
1841 C = llvm::ConstantStruct::get(STy, Fields);
1842 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1843 llvm::GlobalVariable::PrivateLinkage, C,
1844 "_unnamed_nsstring_");
1845 // FIXME. Fix section.
1846 if (const char *Sect =
1847 Features.ObjCNonFragileABI
1848 ? getContext().Target.getNSStringNonFragileABISection()
1849 : getContext().Target.getNSStringSection())
1850 GV->setSection(Sect);
1856 /// GetStringForStringLiteral - Return the appropriate bytes for a
1857 /// string literal, properly padded to match the literal type.
1858 std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
1859 const ASTContext &Context = getContext();
1860 const ConstantArrayType *CAT =
1861 Context.getAsConstantArrayType(E->getType());
1862 assert(CAT && "String isn't pointer or array!");
1864 // Resize the string to the right size.
1865 uint64_t RealLen = CAT->getSize().getZExtValue();
1868 RealLen *= Context.Target.getWCharWidth() / Context.getCharWidth();
1870 std::string Str = E->getString().str();
1871 Str.resize(RealLen, '\0');
1876 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1877 /// constant array for the given string literal.
1879 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1880 // FIXME: This can be more efficient.
1881 // FIXME: We shouldn't need to bitcast the constant in the wide string case.
1882 llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S));
1884 llvm::Type *DestTy =
1885 llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType()));
1886 C = llvm::ConstantExpr::getBitCast(C, DestTy);
1891 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1892 /// array for the given ObjCEncodeExpr node.
1894 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1896 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
1898 return GetAddrOfConstantCString(Str);
1902 /// GenerateWritableString -- Creates storage for a string literal.
1903 static llvm::Constant *GenerateStringLiteral(llvm::StringRef str,
1906 const char *GlobalName) {
1907 // Create Constant for this string literal. Don't add a '\0'.
1909 llvm::ConstantArray::get(CGM.getLLVMContext(), str, false);
1911 // Create a global variable for this string
1912 llvm::GlobalVariable *GV =
1913 new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
1914 llvm::GlobalValue::PrivateLinkage,
1916 GV->setAlignment(1);
1917 GV->setUnnamedAddr(true);
1921 /// GetAddrOfConstantString - Returns a pointer to a character array
1922 /// containing the literal. This contents are exactly that of the
1923 /// given string, i.e. it will not be null terminated automatically;
1924 /// see GetAddrOfConstantCString. Note that whether the result is
1925 /// actually a pointer to an LLVM constant depends on
1926 /// Feature.WriteableStrings.
1928 /// The result has pointer to array type.
1929 llvm::Constant *CodeGenModule::GetAddrOfConstantString(llvm::StringRef Str,
1930 const char *GlobalName) {
1931 bool IsConstant = !Features.WritableStrings;
1933 // Get the default prefix if a name wasn't specified.
1935 GlobalName = ".str";
1937 // Don't share any string literals if strings aren't constant.
1939 return GenerateStringLiteral(Str, false, *this, GlobalName);
1941 llvm::StringMapEntry<llvm::Constant *> &Entry =
1942 ConstantStringMap.GetOrCreateValue(Str);
1944 if (Entry.getValue())
1945 return Entry.getValue();
1947 // Create a global variable for this.
1948 llvm::Constant *C = GenerateStringLiteral(Str, true, *this, GlobalName);
1953 /// GetAddrOfConstantCString - Returns a pointer to a character
1954 /// array containing the literal and a terminating '\0'
1955 /// character. The result has pointer to array type.
1956 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
1957 const char *GlobalName){
1958 llvm::StringRef StrWithNull(Str.c_str(), Str.size() + 1);
1959 return GetAddrOfConstantString(StrWithNull, GlobalName);
1962 /// EmitObjCPropertyImplementations - Emit information for synthesized
1963 /// properties for an implementation.
1964 void CodeGenModule::EmitObjCPropertyImplementations(const
1965 ObjCImplementationDecl *D) {
1966 for (ObjCImplementationDecl::propimpl_iterator
1967 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
1968 ObjCPropertyImplDecl *PID = *i;
1970 // Dynamic is just for type-checking.
1971 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1972 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1974 // Determine which methods need to be implemented, some may have
1975 // been overridden. Note that ::isSynthesized is not the method
1976 // we want, that just indicates if the decl came from a
1977 // property. What we want to know is if the method is defined in
1978 // this implementation.
1979 if (!D->getInstanceMethod(PD->getGetterName()))
1980 CodeGenFunction(*this).GenerateObjCGetter(
1981 const_cast<ObjCImplementationDecl *>(D), PID);
1982 if (!PD->isReadOnly() &&
1983 !D->getInstanceMethod(PD->getSetterName()))
1984 CodeGenFunction(*this).GenerateObjCSetter(
1985 const_cast<ObjCImplementationDecl *>(D), PID);
1990 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
1991 ObjCInterfaceDecl *iface
1992 = const_cast<ObjCInterfaceDecl*>(impl->getClassInterface());
1993 for (ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
1994 ivar; ivar = ivar->getNextIvar())
1995 if (ivar->getType().isDestructedType())
2001 /// EmitObjCIvarInitializations - Emit information for ivar initialization
2002 /// for an implementation.
2003 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
2004 // We might need a .cxx_destruct even if we don't have any ivar initializers.
2005 if (needsDestructMethod(D)) {
2006 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
2007 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2008 ObjCMethodDecl *DTORMethod =
2009 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
2010 cxxSelector, getContext().VoidTy, 0, D, true,
2011 false, true, false, ObjCMethodDecl::Required);
2012 D->addInstanceMethod(DTORMethod);
2013 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
2014 D->setHasCXXStructors(true);
2017 // If the implementation doesn't have any ivar initializers, we don't need
2018 // a .cxx_construct.
2019 if (D->getNumIvarInitializers() == 0)
2022 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
2023 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2024 // The constructor returns 'self'.
2025 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
2027 D->getLocation(), cxxSelector,
2028 getContext().getObjCIdType(), 0,
2029 D, true, false, true, false,
2030 ObjCMethodDecl::Required);
2031 D->addInstanceMethod(CTORMethod);
2032 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
2033 D->setHasCXXStructors(true);
2036 /// EmitNamespace - Emit all declarations in a namespace.
2037 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
2038 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
2040 EmitTopLevelDecl(*I);
2043 // EmitLinkageSpec - Emit all declarations in a linkage spec.
2044 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
2045 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
2046 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
2047 ErrorUnsupported(LSD, "linkage spec");
2051 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
2053 EmitTopLevelDecl(*I);
2056 /// EmitTopLevelDecl - Emit code for a single top level declaration.
2057 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
2058 // If an error has occurred, stop code generation, but continue
2059 // parsing and semantic analysis (to ensure all warnings and errors
2061 if (Diags.hasErrorOccurred())
2064 // Ignore dependent declarations.
2065 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
2068 switch (D->getKind()) {
2069 case Decl::CXXConversion:
2070 case Decl::CXXMethod:
2071 case Decl::Function:
2072 // Skip function templates
2073 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2074 cast<FunctionDecl>(D)->isLateTemplateParsed())
2077 EmitGlobal(cast<FunctionDecl>(D));
2081 EmitGlobal(cast<VarDecl>(D));
2084 // Indirect fields from global anonymous structs and unions can be
2085 // ignored; only the actual variable requires IR gen support.
2086 case Decl::IndirectField:
2090 case Decl::Namespace:
2091 EmitNamespace(cast<NamespaceDecl>(D));
2093 // No code generation needed.
2094 case Decl::UsingShadow:
2096 case Decl::UsingDirective:
2097 case Decl::ClassTemplate:
2098 case Decl::FunctionTemplate:
2099 case Decl::TypeAliasTemplate:
2100 case Decl::NamespaceAlias:
2103 case Decl::CXXConstructor:
2104 // Skip function templates
2105 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2106 cast<FunctionDecl>(D)->isLateTemplateParsed())
2109 EmitCXXConstructors(cast<CXXConstructorDecl>(D));
2111 case Decl::CXXDestructor:
2112 if (cast<FunctionDecl>(D)->isLateTemplateParsed())
2114 EmitCXXDestructors(cast<CXXDestructorDecl>(D));
2117 case Decl::StaticAssert:
2121 // Objective-C Decls
2123 // Forward declarations, no (immediate) code generation.
2124 case Decl::ObjCClass:
2125 case Decl::ObjCForwardProtocol:
2126 case Decl::ObjCInterface:
2129 case Decl::ObjCCategory: {
2130 ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D);
2131 if (CD->IsClassExtension() && CD->hasSynthBitfield())
2132 Context.ResetObjCLayout(CD->getClassInterface());
2136 case Decl::ObjCProtocol:
2137 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
2140 case Decl::ObjCCategoryImpl:
2141 // Categories have properties but don't support synthesize so we
2142 // can ignore them here.
2143 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
2146 case Decl::ObjCImplementation: {
2147 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
2148 if (Features.ObjCNonFragileABI2 && OMD->hasSynthBitfield())
2149 Context.ResetObjCLayout(OMD->getClassInterface());
2150 EmitObjCPropertyImplementations(OMD);
2151 EmitObjCIvarInitializations(OMD);
2152 Runtime->GenerateClass(OMD);
2155 case Decl::ObjCMethod: {
2156 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
2157 // If this is not a prototype, emit the body.
2159 CodeGenFunction(*this).GenerateObjCMethod(OMD);
2162 case Decl::ObjCCompatibleAlias:
2163 // compatibility-alias is a directive and has no code gen.
2166 case Decl::LinkageSpec:
2167 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
2170 case Decl::FileScopeAsm: {
2171 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
2172 llvm::StringRef AsmString = AD->getAsmString()->getString();
2174 const std::string &S = getModule().getModuleInlineAsm();
2176 getModule().setModuleInlineAsm(AsmString);
2178 getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
2183 // Make sure we handled everything we should, every other kind is a
2184 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
2185 // function. Need to recode Decl::Kind to do that easily.
2186 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
2190 /// Turns the given pointer into a constant.
2191 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
2193 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
2194 const llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
2195 return llvm::ConstantInt::get(i64, PtrInt);
2198 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
2199 llvm::NamedMDNode *&GlobalMetadata,
2201 llvm::GlobalValue *Addr) {
2202 if (!GlobalMetadata)
2204 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
2206 // TODO: should we report variant information for ctors/dtors?
2207 llvm::Value *Ops[] = {
2209 GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
2211 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2214 /// Emits metadata nodes associating all the global values in the
2215 /// current module with the Decls they came from. This is useful for
2216 /// projects using IR gen as a subroutine.
2218 /// Since there's currently no way to associate an MDNode directly
2219 /// with an llvm::GlobalValue, we create a global named metadata
2220 /// with the name 'clang.global.decl.ptrs'.
2221 void CodeGenModule::EmitDeclMetadata() {
2222 llvm::NamedMDNode *GlobalMetadata = 0;
2224 // StaticLocalDeclMap
2225 for (llvm::DenseMap<GlobalDecl,llvm::StringRef>::iterator
2226 I = MangledDeclNames.begin(), E = MangledDeclNames.end();
2228 llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
2229 EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
2233 /// Emits metadata nodes for all the local variables in the current
2235 void CodeGenFunction::EmitDeclMetadata() {
2236 if (LocalDeclMap.empty()) return;
2238 llvm::LLVMContext &Context = getLLVMContext();
2240 // Find the unique metadata ID for this name.
2241 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
2243 llvm::NamedMDNode *GlobalMetadata = 0;
2245 for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
2246 I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
2247 const Decl *D = I->first;
2248 llvm::Value *Addr = I->second;
2250 if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
2251 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
2252 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
2253 } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
2254 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
2255 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
2260 void CodeGenModule::EmitCoverageFile() {
2261 if (!getCodeGenOpts().CoverageFile.empty()) {
2262 if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
2263 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
2264 llvm::LLVMContext &Ctx = TheModule.getContext();
2265 llvm::MDString *CoverageFile =
2266 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
2267 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
2268 llvm::MDNode *CU = CUNode->getOperand(i);
2269 llvm::Value *node[] = { CoverageFile, CU };
2270 llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
2271 GCov->addOperand(N);
2277 ///@name Custom Runtime Function Interfaces
2280 // FIXME: These can be eliminated once we can have clients just get the required
2281 // AST nodes from the builtin tables.
2283 llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2284 if (BlockObjectDispose)
2285 return BlockObjectDispose;
2287 // If we saw an explicit decl, use that.
2288 if (BlockObjectDisposeDecl) {
2289 return BlockObjectDispose = GetAddrOfFunction(
2290 BlockObjectDisposeDecl,
2291 getTypes().GetFunctionType(BlockObjectDisposeDecl));
2294 // Otherwise construct the function by hand.
2295 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2296 const llvm::FunctionType *fty
2297 = llvm::FunctionType::get(VoidTy, args, false);
2298 return BlockObjectDispose =
2299 CreateRuntimeFunction(fty, "_Block_object_dispose");
2302 llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2303 if (BlockObjectAssign)
2304 return BlockObjectAssign;
2306 // If we saw an explicit decl, use that.
2307 if (BlockObjectAssignDecl) {
2308 return BlockObjectAssign = GetAddrOfFunction(
2309 BlockObjectAssignDecl,
2310 getTypes().GetFunctionType(BlockObjectAssignDecl));
2313 // Otherwise construct the function by hand.
2314 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2315 const llvm::FunctionType *fty
2316 = llvm::FunctionType::get(VoidTy, args, false);
2317 return BlockObjectAssign =
2318 CreateRuntimeFunction(fty, "_Block_object_assign");
2321 llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2322 if (NSConcreteGlobalBlock)
2323 return NSConcreteGlobalBlock;
2325 // If we saw an explicit decl, use that.
2326 if (NSConcreteGlobalBlockDecl) {
2327 return NSConcreteGlobalBlock = GetAddrOfGlobalVar(
2328 NSConcreteGlobalBlockDecl,
2329 getTypes().ConvertType(NSConcreteGlobalBlockDecl->getType()));
2332 // Otherwise construct the variable by hand.
2333 return NSConcreteGlobalBlock =
2334 CreateRuntimeVariable(Int8PtrTy, "_NSConcreteGlobalBlock");
2337 llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2338 if (NSConcreteStackBlock)
2339 return NSConcreteStackBlock;
2341 // If we saw an explicit decl, use that.
2342 if (NSConcreteStackBlockDecl) {
2343 return NSConcreteStackBlock = GetAddrOfGlobalVar(
2344 NSConcreteStackBlockDecl,
2345 getTypes().ConvertType(NSConcreteStackBlockDecl->getType()));
2348 // Otherwise construct the variable by hand.
2349 return NSConcreteStackBlock =
2350 CreateRuntimeVariable(Int8PtrTy, "_NSConcreteStackBlock");