CodeGenModule.cpp revision 29254f4dd114fe2dd5c4e7a261ebea941973ad3d
15f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
25f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//
35f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//                     The LLVM Compiler Infrastructure
45f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//
50bc735ffcfb223c0186419547abaa5c84482663eChris Lattner// This file is distributed under the University of Illinois Open Source
60bc735ffcfb223c0186419547abaa5c84482663eChris Lattner// License. See LICENSE.TXT for details.
75f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//
85f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//===----------------------------------------------------------------------===//
95f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//
105f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer// This coordinates the per-module state used while generating code.
115f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//
125f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//===----------------------------------------------------------------------===//
135f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
145f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer#include "CodeGenModule.h"
15bd3606426d389370616126af969904ec493cb105Chris Lattner#include "CGDebugInfo.h"
165f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer#include "CodeGenFunction.h"
173d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman#include "CodeGenTBAA.h"
180dbe227feccf6a8dbadfff8ca3f80416b7bf2f28Daniel Dunbar#include "CGCall.h"
196c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne#include "CGCUDARuntime.h"
204c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall#include "CGCXXABI.h"
21af2f62ce32e462f256855cd24b06dec4755d2827Daniel Dunbar#include "CGObjCRuntime.h"
228c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne#include "CGOpenCLRuntime.h"
2382d0a418c8699fc6f4a9417457ffe93d43bba1c1Anton Korobeynikov#include "TargetInfo.h"
2406057cef0bcd7804e80f3ce2bbe352178396c715Chandler Carruth#include "clang/Frontend/CodeGenOptions.h"
255f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer#include "clang/AST/ASTContext.h"
26687cc4a850b59116efee061018f0d8df50728b82Ken Dyck#include "clang/AST/CharUnits.h"
27c4a1dea2dc56bd1357ec91b829a0b9e68229a13eDaniel Dunbar#include "clang/AST/DeclObjC.h"
2821ef7ae45c8b91f23cf5eab2263421bb398a644bChris Lattner#include "clang/AST/DeclCXX.h"
29af896897f7485176f43d40c4adced7efb0fb2b06Douglas Gregor#include "clang/AST/DeclTemplate.h"
3014110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne#include "clang/AST/Mangle.h"
311a5e0d7f18485e4fb958f96dcddff3e4486a4069Anders Carlsson#include "clang/AST/RecordLayout.h"
32a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola#include "clang/AST/RecursiveASTVisitor.h"
33bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola#include "clang/Basic/Builtins.h"
342c8569d5f43f7de1fb993e84c95ea571dd9ac55eChris Lattner#include "clang/Basic/Diagnostic.h"
358bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman#include "clang/Basic/SourceManager.h"
365f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer#include "clang/Basic/TargetInfo.h"
37e9b7d8ace8674585818990cff585daae7745bd88Steve Naroff#include "clang/Basic/ConvertUTF.h"
38ec9426ca6039279bcc99bc2c625bb2abe4f0353dNate Begeman#include "llvm/CallingConv.h"
39bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner#include "llvm/Module.h"
405f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer#include "llvm/Intrinsics.h"
41d5b8902c0329d80a216803b58dc3b689349a0c11Chris Lattner#include "llvm/LLVMContext.h"
426374c3307e2d73348f7b8cc73eeeb0998ad0ac94John McCall#include "llvm/ADT/Triple.h"
43c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola#include "llvm/Target/Mangler.h"
4420ff3108fcd2c3bd734dc79efc22ebaa090abd41Anton Korobeynikov#include "llvm/Target/TargetData.h"
456ba728d9687b2617793f5afd410650a8d6c71080Gabor Greif#include "llvm/Support/CallSite.h"
4678f7ece00e2ddfb64d4ed72a7be770b5b9b805e3Chris Lattner#include "llvm/Support/ErrorHandling.h"
475f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencerusing namespace clang;
485f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencerusing namespace CodeGen;
495f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
5077f68bb90af93b95045fb994e7cd68137adcc132Julien Lerougestatic const char AnnotationSection[] = "llvm.metadata";
5177f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
52f16aa103d3afd42fbca2ab346f191bf745cec092John McCallstatic CGCXXABI &createCXXABI(CodeGenModule &CGM) {
53bcfd1f55bfbb3e5944cd5e03d07b343e280838c4Douglas Gregor  switch (CGM.getContext().getTargetInfo().getCXXABI()) {
54f16aa103d3afd42fbca2ab346f191bf745cec092John McCall  case CXXABI_ARM: return *CreateARMCXXABI(CGM);
55f16aa103d3afd42fbca2ab346f191bf745cec092John McCall  case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM);
56f16aa103d3afd42fbca2ab346f191bf745cec092John McCall  case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM);
57f16aa103d3afd42fbca2ab346f191bf745cec092John McCall  }
58f16aa103d3afd42fbca2ab346f191bf745cec092John McCall
59f16aa103d3afd42fbca2ab346f191bf745cec092John McCall  llvm_unreachable("invalid C++ ABI kind");
60f16aa103d3afd42fbca2ab346f191bf745cec092John McCall}
61f16aa103d3afd42fbca2ab346f191bf745cec092John McCall
625f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
632811ccf48d6d898c42cc4cfad37abedb36236d20Chandler CarruthCodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
64468ec6c0266e48fccb26ce50d5b915c645bb3c7bJohn McCall                             llvm::Module &M, const llvm::TargetData &TD,
65d6471f7c1921c7802804ce3ff6fe9768310f72b9David Blaikie                             DiagnosticsEngine &diags)
66d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall  : Context(C), Features(C.getLangOptions()), CodeGenOpts(CGO), TheModule(M),
67468ec6c0266e48fccb26ce50d5b915c645bb3c7bJohn McCall    TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags),
68f16aa103d3afd42fbca2ab346f191bf745cec092John McCall    ABI(createCXXABI(*this)),
6908d4792bb5d9e0e7f122c6273636807029c06aaaDaniel Dunbar    Types(C, M, TD, getTargetCodeGenInfo().getABIInfo(), ABI, CGO),
703d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman    TBAA(0),
716c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne    VTables(*this), ObjCRuntime(0), OpenCLRuntime(0), CUDARuntime(0),
726c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne    DebugInfo(0), ARCData(0), RRData(0), CFConstantStringClassRef(0),
736c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne    ConstantStringClassRef(0), NSConstantStringType(0),
74673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar    VMContext(M.getContext()),
75673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar    NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
76d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall    BlockObjectAssign(0), BlockObjectDispose(0),
77d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall    BlockDescriptorType(0), GenericBlockLiteralType(0) {
7860be607e5d71627bf3dab8f51c3fdca74267c692David Chisnall  if (Features.ObjC1)
798c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne    createObjCRuntime();
808c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne  if (Features.OpenCL)
818c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne    createOpenCLRuntime();
826c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne  if (Features.CUDA)
836c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne    createCUDARuntime();
84e8b9f5b8ea60983c4a74cb8b63879616b914b65aSanjiv Gupta
853d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman  // Enable TBAA unless it's suppressed.
863d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman  if (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)
870b5c4fc2ae3b503c2b1f354bf52b718aa50a6aeeDan Gohman    TBAA = new CodeGenTBAA(Context, VMContext, getLangOptions(),
880b5c4fc2ae3b503c2b1f354bf52b718aa50a6aeeDan Gohman                           ABI.getMangleContext());
893d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman
90e8ba8d78a258ec992d3521eebdae8324db777b14Nick Lewycky  // If debug info or coverage generation is enabled, create the CGDebugInfo
91e8ba8d78a258ec992d3521eebdae8324db777b14Nick Lewycky  // object.
92e8ba8d78a258ec992d3521eebdae8324db777b14Nick Lewycky  if (CodeGenOpts.DebugInfo || CodeGenOpts.EmitGcovArcs ||
93e8ba8d78a258ec992d3521eebdae8324db777b14Nick Lewycky      CodeGenOpts.EmitGcovNotes)
94e8ba8d78a258ec992d3521eebdae8324db777b14Nick Lewycky    DebugInfo = new CGDebugInfo(*this);
95d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall
96d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall  Block.GlobalUniqueCount = 0;
975936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall
98f85e193739c953358c865005855253af4f68a497John McCall  if (C.getLangOptions().ObjCAutoRefCount)
99f85e193739c953358c865005855253af4f68a497John McCall    ARCData = new ARCEntrypoints();
100f85e193739c953358c865005855253af4f68a497John McCall  RRData = new RREntrypoints();
101f85e193739c953358c865005855253af4f68a497John McCall
1025936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall  // Initialize the type cache.
1035936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall  llvm::LLVMContext &LLVMContext = M.getContext();
1040774cb84719f2aea3016493a2bbd9a02aa3e0541John McCall  VoidTy = llvm::Type::getVoidTy(LLVMContext);
1050774cb84719f2aea3016493a2bbd9a02aa3e0541John McCall  Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
1060774cb84719f2aea3016493a2bbd9a02aa3e0541John McCall  Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
1070774cb84719f2aea3016493a2bbd9a02aa3e0541John McCall  Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
108bcfd1f55bfbb3e5944cd5e03d07b343e280838c4Douglas Gregor  PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
10934695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall  PointerAlignInBytes =
110bcfd1f55bfbb3e5944cd5e03d07b343e280838c4Douglas Gregor    C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
111bcfd1f55bfbb3e5944cd5e03d07b343e280838c4Douglas Gregor  IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
1125936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall  IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
1135936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall  Int8PtrTy = Int8Ty->getPointerTo(0);
1145936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall  Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
1152b94fe35edf951a14ecd32b21f7ebcc2e3754c67Chris Lattner}
1162b94fe35edf951a14ecd32b21f7ebcc2e3754c67Chris Lattner
1172b94fe35edf951a14ecd32b21f7ebcc2e3754c67Chris LattnerCodeGenModule::~CodeGenModule() {
118e926523105dd2604ccd5c101605dea43c5269965Peter Collingbourne  delete ObjCRuntime;
1198c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne  delete OpenCLRuntime;
1206c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne  delete CUDARuntime;
1210628b724ff68105dc88af00a39f859447f22981eTed Kremenek  delete TheTargetCodeGenInfo;
122f16aa103d3afd42fbca2ab346f191bf745cec092John McCall  delete &ABI;
1234376c85fb0ac9e7fd779d246efc77e1169179138Dan Gohman  delete TBAA;
124815c78fd9ab8bd5dfe8e8a91b8c6a413e2b8c889Ted Kremenek  delete DebugInfo;
125f85e193739c953358c865005855253af4f68a497John McCall  delete ARCData;
126f85e193739c953358c865005855253af4f68a497John McCall  delete RRData;
127815c78fd9ab8bd5dfe8e8a91b8c6a413e2b8c889Ted Kremenek}
128815c78fd9ab8bd5dfe8e8a91b8c6a413e2b8c889Ted Kremenek
1290d13f6fdbdd6f06e2449b8834dda53334abd399aDavid Chisnallvoid CodeGenModule::createObjCRuntime() {
1300d13f6fdbdd6f06e2449b8834dda53334abd399aDavid Chisnall  if (!Features.NeXTRuntime)
131e926523105dd2604ccd5c101605dea43c5269965Peter Collingbourne    ObjCRuntime = CreateGNUObjCRuntime(*this);
1320d13f6fdbdd6f06e2449b8834dda53334abd399aDavid Chisnall  else
133e926523105dd2604ccd5c101605dea43c5269965Peter Collingbourne    ObjCRuntime = CreateMacObjCRuntime(*this);
1340d13f6fdbdd6f06e2449b8834dda53334abd399aDavid Chisnall}
1350d13f6fdbdd6f06e2449b8834dda53334abd399aDavid Chisnall
1368c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbournevoid CodeGenModule::createOpenCLRuntime() {
1378c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne  OpenCLRuntime = new CGOpenCLRuntime(*this);
1388c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne}
1398c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne
1406c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbournevoid CodeGenModule::createCUDARuntime() {
1416c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne  CUDARuntime = CreateNVCUDARuntime(*this);
1426c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne}
1436c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne
144815c78fd9ab8bd5dfe8e8a91b8c6a413e2b8c889Ted Kremenekvoid CodeGenModule::Release() {
14582227ff4eb665bbf41720ebdc0dc9215a86ba838Chris Lattner  EmitDeferred();
1466c6bda3b0b1d8adaac2ba3f4da7056e9f1eef52eEli Friedman  EmitCXXGlobalInitFunc();
147efb0fa9e11f75af51744a6159530ef7cc8efa24aDaniel Dunbar  EmitCXXGlobalDtorFunc();
148e926523105dd2604ccd5c101605dea43c5269965Peter Collingbourne  if (ObjCRuntime)
149e926523105dd2604ccd5c101605dea43c5269965Peter Collingbourne    if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
150208ff5e8a073de2a5d15cbe03cab8a4c0d935e28Daniel Dunbar      AddGlobalCtor(ObjCInitFunction);
1516bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  EmitCtorList(GlobalCtors, "llvm.global_ctors");
1526bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  EmitCtorList(GlobalDtors, "llvm.global_dtors");
15377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  EmitGlobalAnnotations();
1540269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  EmitLLVMUsed();
155744016dde06fcffd50931e94a98c850f8b12cd87John McCall
156b25938303de0976b9f189363d43033e5788e3d36John McCall  SimplifyPersonality();
157b25938303de0976b9f189363d43033e5788e3d36John McCall
158744016dde06fcffd50931e94a98c850f8b12cd87John McCall  if (getCodeGenOpts().EmitDeclMetadata)
159744016dde06fcffd50931e94a98c850f8b12cd87John McCall    EmitDeclMetadata();
1605ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky
1615ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky  if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
1623dc05418538c719fea48b906bfa4febe5296e126Nick Lewycky    EmitCoverageFile();
163f391dbe39dca85f2a2c6ea558811dacc571c223eDevang Patel
164f391dbe39dca85f2a2c6ea558811dacc571c223eDevang Patel  if (DebugInfo)
165f391dbe39dca85f2a2c6ea558811dacc571c223eDevang Patel    DebugInfo->finalize();
166f1968f28869f4e0675450ae39c478a37c5b9abd6Daniel Dunbar}
167f1968f28869f4e0675450ae39c478a37c5b9abd6Daniel Dunbar
168e80d56771736c85fd8365c394a6731923b17e91dDevang Patelvoid CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
169e80d56771736c85fd8365c394a6731923b17e91dDevang Patel  // Make sure that this type is translated.
170e80d56771736c85fd8365c394a6731923b17e91dDevang Patel  Types.UpdateCompletedType(TD);
171e80d56771736c85fd8365c394a6731923b17e91dDevang Patel  if (DebugInfo)
172e80d56771736c85fd8365c394a6731923b17e91dDevang Patel    DebugInfo->UpdateCompletedType(TD);
173e80d56771736c85fd8365c394a6731923b17e91dDevang Patel}
174e80d56771736c85fd8365c394a6731923b17e91dDevang Patel
1753d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohmanllvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
1763d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman  if (!TBAA)
1773d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman    return 0;
1783d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman  return TBAA->getTBAAInfo(QTy);
1793d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman}
1803d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman
1813d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohmanvoid CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
1823d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman                                        llvm::MDNode *TBAAInfo) {
1833d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman  Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
1843d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman}
1853d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman
1866374c3307e2d73348f7b8cc73eeeb0998ad0ac94John McCallbool CodeGenModule::isTargetDarwin() const {
187bcfd1f55bfbb3e5944cd5e03d07b343e280838c4Douglas Gregor  return getContext().getTargetInfo().getTriple().isOSDarwin();
1886374c3307e2d73348f7b8cc73eeeb0998ad0ac94John McCall}
1896374c3307e2d73348f7b8cc73eeeb0998ad0ac94John McCall
1905f9e272e632e951b1efe824cd16acb4d96077930Chris Lattnervoid CodeGenModule::Error(SourceLocation loc, StringRef error) {
191d6471f7c1921c7802804ce3ff6fe9768310f72b9David Blaikie  unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, error);
19232096695c76033a6b0b1747c439f7378a11e8312John McCall  getDiags().Report(Context.getFullLoc(loc), diagID);
19332096695c76033a6b0b1747c439f7378a11e8312John McCall}
19432096695c76033a6b0b1747c439f7378a11e8312John McCall
195488e993a135ce700b982bf099c3d6b856301d642Daniel Dunbar/// ErrorUnsupported - Print out an error that codegen doesn't support the
1962c8569d5f43f7de1fb993e84c95ea571dd9ac55eChris Lattner/// specified stmt yet.
19790df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbarvoid CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
19890df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar                                     bool OmitOnError) {
19990df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar  if (OmitOnError && getDiags().hasErrorOccurred())
20090df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar    return;
201d6471f7c1921c7802804ce3ff6fe9768310f72b9David Blaikie  unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
20256b8001b42bd603ef593e3cb278d8b9b9ba26ca9Daniel Dunbar                                               "cannot compile this %0 yet");
2032c8569d5f43f7de1fb993e84c95ea571dd9ac55eChris Lattner  std::string Msg = Type;
2040a14eee528a901c16f0e288fbc10a3abc1660d87Chris Lattner  getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
2050a14eee528a901c16f0e288fbc10a3abc1660d87Chris Lattner    << Msg << S->getSourceRange();
2062c8569d5f43f7de1fb993e84c95ea571dd9ac55eChris Lattner}
20758c3f9ec11cbe852a518bf2f83af46f938b7b852Chris Lattner
208488e993a135ce700b982bf099c3d6b856301d642Daniel Dunbar/// ErrorUnsupported - Print out an error that codegen doesn't support the
209c6fdc34ac0183bfa03d65f317c78b7bdac52897eChris Lattner/// specified decl yet.
21090df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbarvoid CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
21190df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar                                     bool OmitOnError) {
21290df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar  if (OmitOnError && getDiags().hasErrorOccurred())
21390df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar    return;
214d6471f7c1921c7802804ce3ff6fe9768310f72b9David Blaikie  unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
21556b8001b42bd603ef593e3cb278d8b9b9ba26ca9Daniel Dunbar                                               "cannot compile this %0 yet");
216c6fdc34ac0183bfa03d65f317c78b7bdac52897eChris Lattner  std::string Msg = Type;
2170a14eee528a901c16f0e288fbc10a3abc1660d87Chris Lattner  getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
218c6fdc34ac0183bfa03d65f317c78b7bdac52897eChris Lattner}
219c6fdc34ac0183bfa03d65f317c78b7bdac52897eChris Lattner
220bc8d40d85f3fa1e34569834916f18fecaa635152John McCallllvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
221bc8d40d85f3fa1e34569834916f18fecaa635152John McCall  return llvm::ConstantInt::get(SizeTy, size.getQuantity());
222bc8d40d85f3fa1e34569834916f18fecaa635152John McCall}
223bc8d40d85f3fa1e34569834916f18fecaa635152John McCall
2241eb4433ac451dc16f4133a88af2d002ac26c58efMike Stumpvoid CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
2250ffeaad72cb335b926b064379be4c9886bbff004Anders Carlsson                                        const NamedDecl *D) const {
22604d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar  // Internal definitions always have default visibility.
227df102fcb978588d5edbc661fb5da0b6922f9ab1cChris Lattner  if (GV->hasLocalLinkage()) {
2287e714cd931fa3a90bfd728318a92485aa3e95748Daniel Dunbar    GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
2296ab187a49a42de6d351248d8a6e0206e39743a0cDaniel Dunbar    return;
2307e714cd931fa3a90bfd728318a92485aa3e95748Daniel Dunbar  }
2316ab187a49a42de6d351248d8a6e0206e39743a0cDaniel Dunbar
232af14603ca61757cf4361b583b45639a04c57e651John McCall  // Set visibility for definitions.
233af14603ca61757cf4361b583b45639a04c57e651John McCall  NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
234c7c9058f4977ef4584d68718e23f34504b150ef4Fariborz Jahanian  if (LV.visibilityExplicit() || !GV->hasAvailableExternallyLinkage())
235c7c9058f4977ef4584d68718e23f34504b150ef4Fariborz Jahanian    GV->setVisibility(GetLLVMVisibility(LV.visibility()));
2367cd2e93125e2f3b6ca01b24ed0c3fd7e94683fd9Fariborz Jahanian}
2377cd2e93125e2f3b6ca01b24ed0c3fd7e94683fd9Fariborz Jahanian
238cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall/// Set the symbol visibility of type information (vtable and RTTI)
239cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall/// associated with the given type.
240cbfe50224b19119e759802bd0c1463269dffd09eJohn McCallvoid CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
241cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall                                      const CXXRecordDecl *RD,
242fa2e99f72f9bfe2270ea8caf76d0eef11c45259fAnders Carlsson                                      TypeVisibilityKind TVK) const {
2430ffeaad72cb335b926b064379be4c9886bbff004Anders Carlsson  setGlobalVisibility(GV, RD);
244cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
245279b5eb6910d64a293e9c0e2887a05c65d8737d7John McCall  if (!CodeGenOpts.HiddenWeakVTables)
246279b5eb6910d64a293e9c0e2887a05c65d8737d7John McCall    return;
247279b5eb6910d64a293e9c0e2887a05c65d8737d7John McCall
2489a86a137b0872bad25161fb3408a71d919638757Anders Carlsson  // We never want to drop the visibility for RTTI names.
2499a86a137b0872bad25161fb3408a71d919638757Anders Carlsson  if (TVK == TVK_ForRTTIName)
2509a86a137b0872bad25161fb3408a71d919638757Anders Carlsson    return;
2519a86a137b0872bad25161fb3408a71d919638757Anders Carlsson
252cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // We want to drop the visibility to hidden for weak type symbols.
253cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // This isn't possible if there might be unresolved references
254cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // elsewhere that rely on this symbol being visible.
255cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
2567a536907da776bdc47a704e7cafd641e8150e653John McCall  // This should be kept roughly in sync with setThunkVisibility
2577a536907da776bdc47a704e7cafd641e8150e653John McCall  // in CGVTables.cpp.
2587a536907da776bdc47a704e7cafd641e8150e653John McCall
259cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // Preconditions.
260f502d93b0ea970bfbd897e657f8d940a20984de2Anders Carlsson  if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
261cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall      GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
262cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall    return;
263cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
264cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // Don't override an explicit visibility attribute.
2654421d2b341d041df44013769f23c306308bbab83Douglas Gregor  if (RD->getExplicitVisibility())
266cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall    return;
267cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
268cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  switch (RD->getTemplateSpecializationKind()) {
269cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // We have to disable the optimization if this is an EI definition
270cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // because there might be EI declarations in other shared objects.
271cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  case TSK_ExplicitInstantiationDefinition:
272cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  case TSK_ExplicitInstantiationDeclaration:
273cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall    return;
274cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
2757a536907da776bdc47a704e7cafd641e8150e653John McCall  // Every use of a non-template class's type information has to emit it.
276cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  case TSK_Undeclared:
277cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall    break;
278cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
2797a536907da776bdc47a704e7cafd641e8150e653John McCall  // In theory, implicit instantiations can ignore the possibility of
2807a536907da776bdc47a704e7cafd641e8150e653John McCall  // an explicit instantiation declaration because there necessarily
2817a536907da776bdc47a704e7cafd641e8150e653John McCall  // must be an EI definition somewhere with default visibility.  In
2827a536907da776bdc47a704e7cafd641e8150e653John McCall  // practice, it's possible to have an explicit instantiation for
2837a536907da776bdc47a704e7cafd641e8150e653John McCall  // an arbitrary template class, and linkers aren't necessarily able
2847a536907da776bdc47a704e7cafd641e8150e653John McCall  // to deal with mixed-visibility symbols.
2857a536907da776bdc47a704e7cafd641e8150e653John McCall  case TSK_ExplicitSpecialization:
286cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  case TSK_ImplicitInstantiation:
287279b5eb6910d64a293e9c0e2887a05c65d8737d7John McCall    if (!CodeGenOpts.HiddenWeakTemplateVTables)
2887a536907da776bdc47a704e7cafd641e8150e653John McCall      return;
289cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall    break;
290cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  }
291cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
292cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // If there's a key function, there may be translation units
293cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // that don't have the key function's definition.  But ignore
294cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // this if we're emitting RTTI under -fno-rtti.
295fa2e99f72f9bfe2270ea8caf76d0eef11c45259fAnders Carlsson  if (!(TVK != TVK_ForRTTI) || Features.RTTI) {
296cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall    if (Context.getKeyFunction(RD))
297cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall      return;
298fa2e99f72f9bfe2270ea8caf76d0eef11c45259fAnders Carlsson  }
299cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
300cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // Otherwise, drop the visibility to hidden.
301cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
302b1c65ff108de47a89585ad37874bd6cb232664cdRafael Espindola  GV->setUnnamedAddr(true);
303cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall}
304cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
3055f9e272e632e951b1efe824cd16acb4d96077930Chris LattnerStringRef CodeGenModule::getMangledName(GlobalDecl GD) {
306793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
307793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
3085f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
309793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  if (!Str.empty())
310793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson    return Str;
311793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
3124c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall  if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
313793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson    IdentifierInfo *II = ND->getIdentifier();
314793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson    assert(II && "Attempt to mangle unnamed decl.");
315793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
316793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson    Str = II->getName();
317793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson    return Str;
318793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  }
319793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
320793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  llvm::SmallString<256> Buffer;
321c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola  llvm::raw_svector_ostream Out(Buffer);
322793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
323c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola    getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
324793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
325c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola    getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
326793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
327c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola    getCXXABI().getMangleContext().mangleBlock(BD, Out);
328793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  else
329c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola    getCXXABI().getMangleContext().mangleName(ND, Out);
330793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
331793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  // Allocate space for the mangled name.
332c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola  Out.flush();
333793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  size_t Length = Buffer.size();
334793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  char *Name = MangledNamesAllocator.Allocate<char>(Length);
335793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  std::copy(Buffer.begin(), Buffer.end(), Name);
336793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
3375f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  Str = StringRef(Name, Length);
338793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
339793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  return Str;
340793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson}
341793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
34214110477887e3dc168ffc6c191e72d705051f99ePeter Collingbournevoid CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
34314110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne                                        const BlockDecl *BD) {
34414110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne  MangleContext &MangleCtx = getCXXABI().getMangleContext();
34514110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne  const Decl *D = GD.getDecl();
346c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola  llvm::raw_svector_ostream Out(Buffer.getBuffer());
34714110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne  if (D == 0)
348c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola    MangleCtx.mangleGlobalBlock(BD, Out);
34914110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne  else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
350c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola    MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
35114110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne  else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
352c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola    MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
35314110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne  else
354c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola    MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
3559a8822bb154b792cdb18fe4cfb34480ca0ec7661Anders Carlsson}
3569a8822bb154b792cdb18fe4cfb34480ca0ec7661Anders Carlsson
3575f9e272e632e951b1efe824cd16acb4d96077930Chris Lattnerllvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
358f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  return getModule().getNamedValue(Name);
3595f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor}
3605f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor
3616d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner/// AddGlobalCtor - Add a function to the list that will be called before
3626d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner/// main() runs.
3636bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbarvoid CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
36449988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar  // FIXME: Type coercion of void()* types.
3656bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  GlobalCtors.push_back(std::make_pair(Ctor, Priority));
3666d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner}
3676d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner
3686bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar/// AddGlobalDtor - Add a function to the list that will be called
3696bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar/// when the module is unloaded.
3706bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbarvoid CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
37149988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar  // FIXME: Type coercion of void()* types.
3726bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  GlobalDtors.push_back(std::make_pair(Dtor, Priority));
3736bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar}
3746bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar
3756bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbarvoid CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
3766bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  // Ctor function type is void()*.
3770774cb84719f2aea3016493a2bbd9a02aa3e0541John McCall  llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
37896e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson  llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
3796bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar
3806bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  // Get the type of a ctor entry, { i32, void ()* }.
381c5cbb909e8a27deb8f1a2b6b7bf56a96051af81aChris Lattner  llvm::StructType *CtorStructTy =
3827650d95a1a616ea300f37126a8dfc93dc19a662aChris Lattner    llvm::StructType::get(llvm::Type::getInt32Ty(VMContext),
38396e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson                          llvm::PointerType::getUnqual(CtorFTy), NULL);
3846bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar
3856bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  // Construct the constructor and destructor arrays.
3866bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  std::vector<llvm::Constant*> Ctors;
3876bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
3886bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar    std::vector<llvm::Constant*> S;
3891eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
3900032b2781b4deb131f8c9b7968f2030bf2489cddOwen Anderson                I->second, false));
3913c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson    S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
39208e252425ca2cbdc44ba65d9a657ed5398014e36Owen Anderson    Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
3936bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  }
3946bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar
3956bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  if (!Ctors.empty()) {
39696e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson    llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
3971c431b323d776362490bbf7cc796b74fedaf19f2Owen Anderson    new llvm::GlobalVariable(TheModule, AT, false,
398572cf09ae8a78af1c56d40b016ec4cf1837163acChris Lattner                             llvm::GlobalValue::AppendingLinkage,
3997db6d838aad4083fe86d7bf703a75fe6e8a17856Owen Anderson                             llvm::ConstantArray::get(AT, Ctors),
4001c431b323d776362490bbf7cc796b74fedaf19f2Owen Anderson                             GlobalName);
4016d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner  }
4026d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner}
4036d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner
404d46f98573ba104eda102dd3224b2dca69f1c6336John McCallllvm::GlobalValue::LinkageTypes
405d46f98573ba104eda102dd3224b2dca69f1c6336John McCallCodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
40690e99a84ddd020e8fda79643748243725a2ed071Argyrios Kyrtzidis  GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
4077c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
408f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  if (Linkage == GVA_Internal)
409d46f98573ba104eda102dd3224b2dca69f1c6336John McCall    return llvm::Function::InternalLinkage;
410f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner
411f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  if (D->hasAttr<DLLExportAttr>())
412d46f98573ba104eda102dd3224b2dca69f1c6336John McCall    return llvm::Function::DLLExportLinkage;
413f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner
414f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  if (D->hasAttr<WeakAttr>())
415d46f98573ba104eda102dd3224b2dca69f1c6336John McCall    return llvm::Function::WeakAnyLinkage;
416f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner
417f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // In C99 mode, 'inline' functions are guaranteed to have a strong
418f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // definition somewhere else, so we can use available_externally linkage.
419f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  if (Linkage == GVA_C99Inline)
420fd0f89d3d7e4220327abdec1cb115474d70219dcFariborz Jahanian    return llvm::Function::AvailableExternallyLinkage;
4215584d91c938384b57563edbca5c2d4f1c66ff02aJohn McCall
4225584d91c938384b57563edbca5c2d4f1c66ff02aJohn McCall  // Note that Apple's kernel linker doesn't support symbol
4235584d91c938384b57563edbca5c2d4f1c66ff02aJohn McCall  // coalescing, so we need to avoid linkonce and weak linkages there.
4245584d91c938384b57563edbca5c2d4f1c66ff02aJohn McCall  // Normally, this means we just map to internal, but for explicit
4255584d91c938384b57563edbca5c2d4f1c66ff02aJohn McCall  // instantiations we'll map to external.
4265584d91c938384b57563edbca5c2d4f1c66ff02aJohn McCall
427f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // In C++, the compiler has to emit a definition in every translation unit
428f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // that references the function.  We should use linkonce_odr because
429f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // a) if all references in this translation unit are optimized away, we
430f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // don't need to codegen it.  b) if the function persists, it needs to be
431f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // merged with other definitions. c) C++ has the ODR, so we know the
432f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // definition is dependable.
433f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
434142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian    return !Context.getLangOptions().AppleKext
435142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian             ? llvm::Function::LinkOnceODRLinkage
436142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian             : llvm::Function::InternalLinkage;
437f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner
438f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // An explicit instantiation of a template has weak linkage, since
439f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // explicit instantiations can occur in multiple translation units
440f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // and must all be equivalent. However, we are not allowed to
441f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // throw away these explicit instantiations.
442f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  if (Linkage == GVA_ExplicitTemplateInstantiation)
443142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian    return !Context.getLangOptions().AppleKext
444142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian             ? llvm::Function::WeakODRLinkage
4455584d91c938384b57563edbca5c2d4f1c66ff02aJohn McCall             : llvm::Function::ExternalLinkage;
446f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner
447f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // Otherwise, we have strong external linkage.
448f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  assert(Linkage == GVA_StrongExternal);
449f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  return llvm::Function::ExternalLinkage;
450d46f98573ba104eda102dd3224b2dca69f1c6336John McCall}
451d4cbda6292b321c2e7dce7f039d92918fee99b3aNuno Lopes
452d46f98573ba104eda102dd3224b2dca69f1c6336John McCall
453d46f98573ba104eda102dd3224b2dca69f1c6336John McCall/// SetFunctionDefinitionAttributes - Set attributes for a global.
454d46f98573ba104eda102dd3224b2dca69f1c6336John McCall///
455d46f98573ba104eda102dd3224b2dca69f1c6336John McCall/// FIXME: This is currently only done for aliases and functions, but not for
456d46f98573ba104eda102dd3224b2dca69f1c6336John McCall/// variables (these details are set in EmitGlobalVarDefinition for variables).
457d46f98573ba104eda102dd3224b2dca69f1c6336John McCallvoid CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
458d46f98573ba104eda102dd3224b2dca69f1c6336John McCall                                                    llvm::GlobalValue *GV) {
4597c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  SetCommonAttributes(D, GV);
460d4cbda6292b321c2e7dce7f039d92918fee99b3aNuno Lopes}
461d4cbda6292b321c2e7dce7f039d92918fee99b3aNuno Lopes
4627dbd8197040313d796282d4af06eccdf8a17319cDaniel Dunbarvoid CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
4631eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                              const CGFunctionInfo &Info,
4647dbd8197040313d796282d4af06eccdf8a17319cDaniel Dunbar                                              llvm::Function *F) {
465ca6408c3176783f0b29da4679a08512aa05f0c73Daniel Dunbar  unsigned CallingConv;
466761d7f78e2dac7ea5f35828c2271e60d91e106ceDevang Patel  AttributeListType AttributeList;
467ca6408c3176783f0b29da4679a08512aa05f0c73Daniel Dunbar  ConstructAttributeList(Info, D, AttributeList, CallingConv);
468761d7f78e2dac7ea5f35828c2271e60d91e106ceDevang Patel  F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
469ca6408c3176783f0b29da4679a08512aa05f0c73Daniel Dunbar                                          AttributeList.size()));
470ca6408c3176783f0b29da4679a08512aa05f0c73Daniel Dunbar  F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
471f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar}
472f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar
473d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall/// Determines whether the language options require us to model
474d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall/// unwind exceptions.  We treat -fexceptions as mandating this
475d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall/// except under the fragile ObjC ABI with only ObjC exceptions
476d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall/// enabled.  This means, for example, that C with -fexceptions
477d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall/// enables this.
478d1e40d5389a4382cbebc97d54792f41ee0414af4John McCallstatic bool hasUnwindExceptions(const LangOptions &Features) {
479d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall  // If exceptions are completely disabled, obviously this is false.
480d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall  if (!Features.Exceptions) return false;
481d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall
482d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall  // If C++ exceptions are enabled, this is true.
483d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall  if (Features.CXXExceptions) return true;
484d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall
485d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall  // If ObjC exceptions are enabled, this depends on the ABI.
486d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall  if (Features.ObjCExceptions) {
487d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall    if (!Features.ObjCNonFragileABI) return false;
488d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall  }
489d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall
490d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall  return true;
491d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall}
492d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall
4937c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbarvoid CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
4947c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar                                                           llvm::Function *F) {
495abca5a1b3e74e644e297c7590b46ab73a6bb476aRafael Espindola  if (CodeGenOpts.UnwindTables)
496abca5a1b3e74e644e297c7590b46ab73a6bb476aRafael Espindola    F->setHasUWTable();
497abca5a1b3e74e644e297c7590b46ab73a6bb476aRafael Espindola
498d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall  if (!hasUnwindExceptions(Features))
4991eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    F->addFnAttr(llvm::Attribute::NoUnwind);
500af668b0e7d3581dea3b4f29a9262686e83887e5bDaniel Dunbar
5012873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman  if (D->hasAttr<NakedAttr>()) {
5022873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman    // Naked implies noinline: we should not be inlining such functions.
503dd0cb22bd62e1e835327f478a2dbf0b8fa439713Daniel Dunbar    F->addFnAttr(llvm::Attribute::Naked);
5042873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman    F->addFnAttr(llvm::Attribute::NoInline);
5052873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman  }
506dd0cb22bd62e1e835327f478a2dbf0b8fa439713Daniel Dunbar
5071feade8e520be483293dbf55eb57a51720899589Mike Stump  if (D->hasAttr<NoInlineAttr>())
50881ebbde0fb30a40df0f5e913d8a1f71c383d271aAnders Carlsson    F->addFnAttr(llvm::Attribute::NoInline);
509f55314dce992fd60816ba337ad151a2fb7c42239Mike Stump
5102873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman  // (noinline wins over always_inline, and we can't specify both in IR)
5112873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman  if (D->hasAttr<AlwaysInlineAttr>() &&
5122873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman      !F->hasFnAttr(llvm::Attribute::NoInline))
5132873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman    F->addFnAttr(llvm::Attribute::AlwaysInline);
5142873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman
515c5f657fe308f22243f674fc1dfbe24915944d8bfRafael Espindola  if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
516c5f657fe308f22243f674fc1dfbe24915944d8bfRafael Espindola    F->setUnnamedAddr(true);
517c5f657fe308f22243f674fc1dfbe24915944d8bfRafael Espindola
518e289d81369914678db386f6aa86faf8f178e245dDouglas Gregor  if (Features.getStackProtector() == LangOptions::SSPOn)
519fd015353a3c4f528216276f25df5b4d464d7a0cdAnders Carlsson    F->addFnAttr(llvm::Attribute::StackProtect);
520e289d81369914678db386f6aa86faf8f178e245dDouglas Gregor  else if (Features.getStackProtector() == LangOptions::SSPReq)
521fd015353a3c4f528216276f25df5b4d464d7a0cdAnders Carlsson    F->addFnAttr(llvm::Attribute::StackProtectReq);
522fd015353a3c4f528216276f25df5b4d464d7a0cdAnders Carlsson
523cf807c4dfdb23e8fa3f400e0b24ef5b79db7a530Sean Hunt  unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
524cf807c4dfdb23e8fa3f400e0b24ef5b79db7a530Sean Hunt  if (alignment)
525cf807c4dfdb23e8fa3f400e0b24ef5b79db7a530Sean Hunt    F->setAlignment(alignment);
526cf807c4dfdb23e8fa3f400e0b24ef5b79db7a530Sean Hunt
527fb51ddfafcd5f8536d0312b3daa3c0b74b90ab5bMike Stump  // C++ ABI requires 2-byte alignment for member functions.
528bd6dbd19781cefd5b5ff9750c8bf86e6c341a68cMike Stump  if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
529bd6dbd19781cefd5b5ff9750c8bf86e6c341a68cMike Stump    F->setAlignment(2);
530f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar}
531f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar
5321eb4433ac451dc16f4133a88af2d002ac26c58efMike Stumpvoid CodeGenModule::SetCommonAttributes(const Decl *D,
5337c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar                                        llvm::GlobalValue *GV) {
534934176f27552141b5ad113cb3603ffb14906c570Anders Carlsson  if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
535934176f27552141b5ad113cb3603ffb14906c570Anders Carlsson    setGlobalVisibility(GV, ND);
5361fb0caaa7bef765b85972274e3b434af2572c141John McCall  else
5371fb0caaa7bef765b85972274e3b434af2572c141John McCall    GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
5387c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
53940b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (D->hasAttr<UsedAttr>())
5407c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    AddUsedGlobal(GV);
5417c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
54240b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (const SectionAttr *SA = D->getAttr<SectionAttr>())
5437c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    GV->setSection(SA->getName());
54482d0a418c8699fc6f4a9417457ffe93d43bba1c1Anton Korobeynikov
54582d0a418c8699fc6f4a9417457ffe93d43bba1c1Anton Korobeynikov  getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
5467c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar}
5477c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
5480e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbarvoid CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
5490e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar                                                  llvm::Function *F,
5500e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar                                                  const CGFunctionInfo &FI) {
5510e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar  SetLLVMFunctionAttributes(D, FI, F);
5520e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar  SetLLVMFunctionAttributesForDefinition(D, F);
5537c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
5547c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  F->setLinkage(llvm::Function::InternalLinkage);
5557c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
5560e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar  SetCommonAttributes(D, F);
557f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar}
558f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar
559b2bcf1c176b200b36f371e189ce22f93c86cdf45Anders Carlssonvoid CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
560c6c14d1cd68afcd90d097715296377f15be45210Eli Friedman                                          llvm::Function *F,
561c6c14d1cd68afcd90d097715296377f15be45210Eli Friedman                                          bool IsIncompleteFunction) {
5620ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne  if (unsigned IID = F->getIntrinsicID()) {
5630ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne    // If this is an intrinsic function, set the function's attributes
5640ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne    // to the intrinsic's attributes.
5650ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne    F->setAttributes(llvm::Intrinsic::getAttributes((llvm::Intrinsic::ID)IID));
5660ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne    return;
5670ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne  }
5680ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne
569b2bcf1c176b200b36f371e189ce22f93c86cdf45Anders Carlsson  const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
570b2bcf1c176b200b36f371e189ce22f93c86cdf45Anders Carlsson
571c6c14d1cd68afcd90d097715296377f15be45210Eli Friedman  if (!IsIncompleteFunction)
572b2bcf1c176b200b36f371e189ce22f93c86cdf45Anders Carlsson    SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(GD), F);
5731eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
5747c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // Only a few attributes are set on declarations; these may later be
5757c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // overridden by a definition.
5761eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
57740b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (FD->hasAttr<DLLImportAttr>()) {
5787c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    F->setLinkage(llvm::Function::DLLImportLinkage);
5791eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  } else if (FD->hasAttr<WeakAttr>() ||
5800a0d2b179085a52c10402feebeb6db8b4d96a140Douglas Gregor             FD->isWeakImported()) {
5817c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    // "extern_weak" is overloaded in LLVM; we probably should have
5821eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    // separate linkage types for this.
5837c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    F->setLinkage(llvm::Function::ExternalWeakLinkage);
5847c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  } else {
5851eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    F->setLinkage(llvm::Function::ExternalLinkage);
586af14603ca61757cf4361b583b45639a04c57e651John McCall
587af14603ca61757cf4361b583b45639a04c57e651John McCall    NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility();
588af14603ca61757cf4361b583b45639a04c57e651John McCall    if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) {
589af14603ca61757cf4361b583b45639a04c57e651John McCall      F->setVisibility(GetLLVMVisibility(LV.visibility()));
590af14603ca61757cf4361b583b45639a04c57e651John McCall    }
5917c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  }
5927c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
59340b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
5947c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    F->setSection(SA->getName());
595219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar}
596219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar
5970269871c9cba493f76237175ab60313406f3bafaDaniel Dunbarvoid CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
5981eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  assert(!GV->isDeclaration() &&
5990269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar         "Only globals with definition can force usage.");
60035f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  LLVMUsed.push_back(GV);
6010269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar}
6020269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar
6030269871c9cba493f76237175ab60313406f3bafaDaniel Dunbarvoid CodeGenModule::EmitLLVMUsed() {
6040269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  // Don't create llvm.used if there is no need.
605ad64e024bd18cf25dcfa44e049004371838decd8Chris Lattner  if (LLVMUsed.empty())
6060269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar    return;
6070269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar
6082acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext);
6091eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
61035f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  // Convert LLVMUsed to what ConstantArray needs.
61135f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  std::vector<llvm::Constant*> UsedArray;
61235f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  UsedArray.resize(LLVMUsed.size());
61335f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
6141eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    UsedArray[i] =
6151eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump     llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
616a1cf15f4680e5cf39e72e28c5ea854fcba792e84Owen Anderson                                      i8PTy);
61735f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  }
6181eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
619c38e9affd4519ea199af22419c8c794973cc4b23Fariborz Jahanian  if (UsedArray.empty())
620c38e9affd4519ea199af22419c8c794973cc4b23Fariborz Jahanian    return;
62196e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson  llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size());
6221eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
6231eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  llvm::GlobalVariable *GV =
6241eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    new llvm::GlobalVariable(getModule(), ATy, false,
6250269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar                             llvm::GlobalValue::AppendingLinkage,
6267db6d838aad4083fe86d7bf703a75fe6e8a17856Owen Anderson                             llvm::ConstantArray::get(ATy, UsedArray),
6271c431b323d776362490bbf7cc796b74fedaf19f2Owen Anderson                             "llvm.used");
6280269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar
6290269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  GV->setSection("llvm.metadata");
6300269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar}
6310269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar
6320269871c9cba493f76237175ab60313406f3bafaDaniel Dunbarvoid CodeGenModule::EmitDeferred() {
63367b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // Emit code for any potentially referenced deferred decls.  Since a
63467b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // previously unused static decl may become used during the generation of code
635dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky  // for a static function, iterate until no changes are made.
636bbf58bb1b8dd8c5e0f07547a6c20ffd55385fcf6Rafael Espindola
637046c294a43024874ff35656c6e785b64e72f1f36Anders Carlsson  while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) {
638046c294a43024874ff35656c6e785b64e72f1f36Anders Carlsson    if (!DeferredVTables.empty()) {
639046c294a43024874ff35656c6e785b64e72f1f36Anders Carlsson      const CXXRecordDecl *RD = DeferredVTables.back();
640046c294a43024874ff35656c6e785b64e72f1f36Anders Carlsson      DeferredVTables.pop_back();
641046c294a43024874ff35656c6e785b64e72f1f36Anders Carlsson      getVTables().GenerateClassData(getVTableLinkage(RD), RD);
642bbf58bb1b8dd8c5e0f07547a6c20ffd55385fcf6Rafael Espindola      continue;
643bbf58bb1b8dd8c5e0f07547a6c20ffd55385fcf6Rafael Espindola    }
644bbf58bb1b8dd8c5e0f07547a6c20ffd55385fcf6Rafael Espindola
6452a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson    GlobalDecl D = DeferredDeclsToEmit.back();
64667b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    DeferredDeclsToEmit.pop_back();
64767b00520c8f5b48fad722b790d87fea6be764efeChris Lattner
648c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // Check to see if we've already emitted this.  This is necessary
649c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // for a couple of reasons: first, decls can end up in the
650c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // deferred-decls queue multiple times, and second, decls can end
651c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // up with definitions in unusual ways (e.g. by an extern inline
652c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // function acquiring a strong function redefinition).  Just
653c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // ignore these cases.
654c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    //
655c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // TODO: That said, looking this up multiple times is very wasteful.
6565f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner    StringRef Name = getMangledName(D);
657f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    llvm::GlobalValue *CGRef = GetGlobalValue(Name);
65867b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    assert(CGRef && "Deferred decl wasn't referenced?");
6591eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
66067b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    if (!CGRef->isDeclaration())
66167b00520c8f5b48fad722b790d87fea6be764efeChris Lattner      continue;
6621eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
663c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // GlobalAlias::isDeclaration() defers to the aliasee, but for our
664c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // purposes an alias counts as a definition.
665c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    if (isa<llvm::GlobalAlias>(CGRef))
666c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall      continue;
667c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall
66867b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    // Otherwise, emit the definition and move on to the next one.
66967b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    EmitGlobalDefinition(D);
67067b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  }
6715f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
6725f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
67377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerougevoid CodeGenModule::EmitGlobalAnnotations() {
67477f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  if (Annotations.empty())
67577f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    return;
67677f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
67777f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  // Create a new global variable for the ConstantStruct in the Module.
67877f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
67977f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    Annotations[0]->getType(), Annotations.size()), Annotations);
68077f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(),
68177f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array,
68277f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    "llvm.global.annotations");
68377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  gv->setSection(AnnotationSection);
68477f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge}
68577f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
68677f68bb90af93b95045fb994e7cd68137adcc132Julien Lerougellvm::Constant *CodeGenModule::EmitAnnotationString(llvm::StringRef Str) {
68777f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  llvm::StringMap<llvm::Constant*>::iterator i = AnnotationStrings.find(Str);
68877f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  if (i != AnnotationStrings.end())
68977f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    return i->second;
69077f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
69177f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  // Not found yet, create a new global.
692ff8f9ec8336c62b5e3504e2a394f4b25c0cb1963Chris Lattner  llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
69377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(),
69477f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    true, llvm::GlobalValue::PrivateLinkage, s, ".str");
69577f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  gv->setSection(AnnotationSection);
69677f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  gv->setUnnamedAddr(true);
69777f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  AnnotationStrings[Str] = gv;
69877f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  return gv;
69977f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge}
70077f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
70177f68bb90af93b95045fb994e7cd68137adcc132Julien Lerougellvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
70277f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  SourceManager &SM = getContext().getSourceManager();
70377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  PresumedLoc PLoc = SM.getPresumedLoc(Loc);
70477f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  if (PLoc.isValid())
70577f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    return EmitAnnotationString(PLoc.getFilename());
70677f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  return EmitAnnotationString(SM.getBufferName(Loc));
70777f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge}
70877f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
70977f68bb90af93b95045fb994e7cd68137adcc132Julien Lerougellvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
71077f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  SourceManager &SM = getContext().getSourceManager();
71177f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  PresumedLoc PLoc = SM.getPresumedLoc(L);
71277f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
71377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    SM.getExpansionLineNumber(L);
71477f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  return llvm::ConstantInt::get(Int32Ty, LineNo);
71577f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge}
71677f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
7171eb4433ac451dc16f4133a88af2d002ac26c58efMike Stumpllvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
7188bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman                                                const AnnotateAttr *AA,
71977f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge                                                SourceLocation L) {
72077f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  // Get the globals for file name, annotation, and the line number.
72177f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
72277f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge                 *UnitGV = EmitAnnotationUnit(L),
72377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge                 *LineNoCst = EmitAnnotationLineNo(L);
7248bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman
72557d5cee133495bc21d1abdbce45ab05a79274a23Daniel Dunbar  // Create the ConstantStruct for the global annotation.
7268bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  llvm::Constant *Fields[4] = {
72777f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
72877f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
72977f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
73077f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    LineNoCst
7318bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  };
732c5cbb909e8a27deb8f1a2b6b7bf56a96051af81aChris Lattner  return llvm::ConstantStruct::getAnon(Fields);
7338bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman}
7348bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman
73577f68bb90af93b95045fb994e7cd68137adcc132Julien Lerougevoid CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
73677f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge                                         llvm::GlobalValue *GV) {
73777f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
73877f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  // Get the struct elements for these annotations.
73977f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  for (specific_attr_iterator<AnnotateAttr>
74077f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge       ai = D->specific_attr_begin<AnnotateAttr>(),
74177f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge       ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai)
74277f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    Annotations.push_back(EmitAnnotateAttr(GV, *ai, D->getLocation()));
74377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge}
74477f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
745a6d6af308bfc9b72467b432a045a9fc6673e3821Argyrios Kyrtzidisbool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
74690e99a84ddd020e8fda79643748243725a2ed071Argyrios Kyrtzidis  // Never defer when EmitAllDecls is specified.
74790e99a84ddd020e8fda79643748243725a2ed071Argyrios Kyrtzidis  if (Features.EmitAllDecls)
748a6d6af308bfc9b72467b432a045a9fc6673e3821Argyrios Kyrtzidis    return false;
7490b6bc8bd7a1d2a7d7478d13d78cff94cacad61fcDouglas Gregor
7504ac7c0bb39696e92fd220118fedc484c09a69870Argyrios Kyrtzidis  return !getContext().DeclMustBeEmitted(Global);
75173241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar}
75273241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar
7536a836706c40a31c716952b74785102c90fd6afa7Rafael Espindolallvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
7546a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  const AliasAttr *AA = VD->getAttr<AliasAttr>();
7556a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  assert(AA && "No alias?");
7566a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
7572acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
7586a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
7596a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  // See if there is already something with the target's name in the module.
760f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
7616a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
7626a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  llvm::Constant *Aliasee;
7636a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  if (isa<llvm::FunctionType>(DeclTy))
7641faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson    Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
7651faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson                                      /*ForVTable=*/false);
7666a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  else
767f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
7686a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola                                    llvm::PointerType::getUnqual(DeclTy), 0);
7696a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  if (!Entry) {
7706a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola    llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
7716a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola    F->setLinkage(llvm::Function::ExternalWeakLinkage);
7726a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola    WeakRefReferences.insert(F);
7736a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  }
7746a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
7756a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  return Aliasee;
7766a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola}
7776a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
778b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattnervoid CodeGenModule::EmitGlobal(GlobalDecl GD) {
7794a6835e650ff24e19ce08a3bd347c0ad186777fdAnders Carlsson  const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
7801eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
7816a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  // Weak references don't produce any output by themselves.
7826a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  if (Global->hasAttr<WeakRefAttr>())
7836a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola    return;
7846a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
785bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  // If this is an alias definition (which otherwise looks like a declaration)
786bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  // emit it now.
78740b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (Global->hasAttr<AliasAttr>())
788f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    return EmitAliasDefinition(GD);
789219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar
790d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne  // If this is CUDA, be selective about which declarations we emit.
791d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne  if (Features.CUDA) {
792d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne    if (CodeGenOpts.CUDAIsDevice) {
793d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne      if (!Global->hasAttr<CUDADeviceAttr>() &&
794d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne          !Global->hasAttr<CUDAGlobalAttr>() &&
795d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne          !Global->hasAttr<CUDAConstantAttr>() &&
796d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne          !Global->hasAttr<CUDASharedAttr>())
797d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne        return;
798d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne    } else {
799d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne      if (!Global->hasAttr<CUDAHostAttr>() && (
800d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne            Global->hasAttr<CUDADeviceAttr>() ||
801d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne            Global->hasAttr<CUDAConstantAttr>() ||
802d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne            Global->hasAttr<CUDASharedAttr>()))
803d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne        return;
804d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne    }
805d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne  }
806d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne
80767b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // Ignore declarations, they will be emitted on their first use.
8085e1e1f95c98b1add70c238093bbd5dc8d4f9c4e9Daniel Dunbar  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
80973241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar    // Forward declarations are emitted lazily on first use.
810dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky    if (!FD->doesThisDeclarationHaveABody()) {
811dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky      if (!FD->doesDeclarationForceExternallyVisibleDefinition())
812dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky        return;
813dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky
814dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky      const FunctionDecl *InlineDefinition = 0;
815dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky      FD->getBody(InlineDefinition);
816dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky
8175f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner      StringRef MangledName = getMangledName(GD);
818dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky      llvm::StringMap<GlobalDecl>::iterator DDI =
819dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky          DeferredDecls.find(MangledName);
820dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky      if (DDI != DeferredDecls.end())
821dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky        DeferredDecls.erase(DDI);
822dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky      EmitGlobalDefinition(InlineDefinition);
82373241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar      return;
824dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky    }
8250269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  } else {
8260269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar    const VarDecl *VD = cast<VarDecl>(Global);
827bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar    assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
828bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
829a9a55c063e9e59c6ab0a6d7a21302660f7bde9f9Douglas Gregor    if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
83073241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar      return;
8314c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman  }
8324c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman
83367b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // Defer code generation when possible if this is a static definition, inline
83467b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // function etc.  These we only want to emit if they are used.
8354357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner  if (!MayDeferGeneration(Global)) {
8364357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner    // Emit the definition if it can't be deferred.
8374357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner    EmitGlobalDefinition(GD);
838bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar    return;
839bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar  }
840bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall
841bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall  // If we're deferring emission of a C++ variable with an
842bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall  // initializer, remember the order in which it appeared in the file.
843bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall  if (getLangOptions().CPlusPlus && isa<VarDecl>(Global) &&
844bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall      cast<VarDecl>(Global)->hasInit()) {
845bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall    DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
846bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall    CXXGlobalInits.push_back(0);
847bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall  }
8484357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner
8494357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner  // If the value has already been used, add it directly to the
8504357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner  // DeferredDeclsToEmit list.
8515f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  StringRef MangledName = getMangledName(GD);
8524357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner  if (GetGlobalValue(MangledName))
8534357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner    DeferredDeclsToEmit.push_back(GD);
8544357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner  else {
8554357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner    // Otherwise, remember that we saw a deferred decl with this name.  The
8564357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner    // first use of the mangled name will cause it to move into
8574357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner    // DeferredDeclsToEmit.
8584357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner    DeferredDecls[MangledName] = GD;
8594357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner  }
8604c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman}
8614c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman
862a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindolanamespace {
863a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  struct FunctionIsDirectlyRecursive :
864a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
865a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    const StringRef Name;
866bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola    const Builtin::Context &BI;
867a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    bool Result;
868bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola    FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
869bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola      Name(N), BI(C), Result(false) {
870a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    }
871a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
872a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola
873a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    bool TraverseCallExpr(CallExpr *E) {
874bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola      const FunctionDecl *FD = E->getDirectCallee();
875bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola      if (!FD)
876a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola        return true;
877bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola      AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
878bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola      if (Attr && Name == Attr->getLabel()) {
879bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola        Result = true;
880bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola        return false;
881bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola      }
882bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola      unsigned BuiltinID = FD->getBuiltinID();
883bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola      if (!BuiltinID)
884a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola        return true;
885f6b56374e4e5b9f0078efac5ed4918c3a04296f7Nick Lewycky      StringRef BuiltinName = BI.GetName(BuiltinID);
886f6b56374e4e5b9f0078efac5ed4918c3a04296f7Nick Lewycky      if (BuiltinName.startswith("__builtin_") &&
887f6b56374e4e5b9f0078efac5ed4918c3a04296f7Nick Lewycky          Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
888a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola        Result = true;
889a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola        return false;
890a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola      }
891a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola      return true;
892a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    }
893a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  };
894a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola}
895a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola
896bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola// isTriviallyRecursive - Check if this function calls another
897bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola// decl that, because of the asm attribute or the other decl being a builtin,
898bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola// ends up pointing to itself.
899a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindolabool
900bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael EspindolaCodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
901bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola  StringRef Name;
902bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola  if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
90322afaccd9ab77d46106e94c47907d955a014ae3fNick Lewycky    // asm labels are a special kind of mangling we have to support.
904bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola    AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
905bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola    if (!Attr)
906bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola      return false;
907bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola    Name = Attr->getLabel();
908bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola  } else {
909bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola    Name = FD->getName();
910bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola  }
911a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola
912bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola  FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
913bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola  Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
914a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  return Walker.Result;
915a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola}
916a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola
917a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindolabool
918a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael EspindolaCodeGenModule::shouldEmitFunction(const FunctionDecl *F) {
919a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  if (getFunctionLinkage(F) != llvm::Function::AvailableExternallyLinkage)
920a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    return true;
921cc4889f72ec68319969ba51e214d9940eb9327e5Rafael Espindola  if (CodeGenOpts.OptimizationLevel == 0 &&
922cc4889f72ec68319969ba51e214d9940eb9327e5Rafael Espindola      !F->hasAttr<AlwaysInlineAttr>())
923a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    return false;
924a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  // PR9614. Avoid cases where the source code is lying to us. An available
925a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  // externally function should have an equivalent function somewhere else,
926a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  // but a function that calls itself is clearly not equivalent to the real
927a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  // implementation.
928a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  // This happens in glibc's btowc and in some configure checks.
929bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola  return !isTriviallyRecursive(F);
930a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola}
931a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola
932b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattnervoid CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
9334a6835e650ff24e19ce08a3bd347c0ad186777fdAnders Carlsson  const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
9341eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
935cb421fa690da545b58a720abe5f1c49b166dbde7Dan Gohman  PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
9368e2efcc267ed12dc435782288b7f9a4a1bc56c72Anders Carlsson                                 Context.getSourceManager(),
9378e2efcc267ed12dc435782288b7f9a4a1bc56c72Anders Carlsson                                 "Generating code for declaration");
9388e2efcc267ed12dc435782288b7f9a4a1bc56c72Anders Carlsson
93944eac33ae12df384f3f002102f919f603bee330fDouglas Gregor  if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
94044eac33ae12df384f3f002102f919f603bee330fDouglas Gregor    // At -O0, don't generate IR for functions with available_externally
94144eac33ae12df384f3f002102f919f603bee330fDouglas Gregor    // linkage.
942a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    if (!shouldEmitFunction(Function))
94344eac33ae12df384f3f002102f919f603bee330fDouglas Gregor      return;
94444eac33ae12df384f3f002102f919f603bee330fDouglas Gregor
94544eac33ae12df384f3f002102f919f603bee330fDouglas Gregor    if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
9467dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman      // Make sure to emit the definition(s) before we emit the thunks.
9477dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman      // This is necessary for the generation of certain thunks.
9487dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman      if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
9497dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman        EmitCXXConstructor(CD, GD.getCtorType());
9507dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman      else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method))
9517dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman        EmitCXXDestructor(DD, GD.getDtorType());
9527dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman      else
9537dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman        EmitGlobalFunctionDefinition(GD);
9547dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman
95544eac33ae12df384f3f002102f919f603bee330fDouglas Gregor      if (Method->isVirtual())
95644eac33ae12df384f3f002102f919f603bee330fDouglas Gregor        getVTables().EmitThunks(GD);
9577270ee4cd4794281c09dfb6931a98bbb2581ef02Anders Carlsson
9587dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman      return;
95944eac33ae12df384f3f002102f919f603bee330fDouglas Gregor    }
960b5e8156ebd6accd27daeaae6971597c45d5e5139Chris Lattner
961b5e8156ebd6accd27daeaae6971597c45d5e5139Chris Lattner    return EmitGlobalFunctionDefinition(GD);
96244eac33ae12df384f3f002102f919f603bee330fDouglas Gregor  }
963b5e8156ebd6accd27daeaae6971597c45d5e5139Chris Lattner
964b5e8156ebd6accd27daeaae6971597c45d5e5139Chris Lattner  if (const VarDecl *VD = dyn_cast<VarDecl>(D))
965b5e8156ebd6accd27daeaae6971597c45d5e5139Chris Lattner    return EmitGlobalVarDefinition(VD);
9664357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner
967b219cfc4d75f0a03630b7c4509ef791b7e97b2c8David Blaikie  llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
968bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar}
969bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
97074391b48b4791cded373683a3baf67314f358d50Chris Lattner/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
97174391b48b4791cded373683a3baf67314f358d50Chris Lattner/// module, create and return an llvm Function with the specified type. If there
97274391b48b4791cded373683a3baf67314f358d50Chris Lattner/// is something in the module with the specified name, return it potentially
97374391b48b4791cded373683a3baf67314f358d50Chris Lattner/// bitcasted to the right type.
97474391b48b4791cded373683a3baf67314f358d50Chris Lattner///
97574391b48b4791cded373683a3baf67314f358d50Chris Lattner/// If D is non-null, it specifies a decl that correspond to this.  This is used
97674391b48b4791cded373683a3baf67314f358d50Chris Lattner/// to set the attributes on the function when it is first created.
977f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCallllvm::Constant *
9785f9e272e632e951b1efe824cd16acb4d96077930Chris LattnerCodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
9792acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner                                       llvm::Type *Ty,
980f85e193739c953358c865005855253af4f68a497John McCall                                       GlobalDecl D, bool ForVTable,
981f85e193739c953358c865005855253af4f68a497John McCall                                       llvm::Attributes ExtraAttrs) {
9820558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  // Lookup the entry, lazily creating it if necessary.
983f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
9840558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  if (Entry) {
9856a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola    if (WeakRefReferences.count(Entry)) {
9866a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola      const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
9876a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola      if (FD && !FD->hasAttr<WeakAttr>())
9887270ee4cd4794281c09dfb6931a98bbb2581ef02Anders Carlsson        Entry->setLinkage(llvm::Function::ExternalLinkage);
9896a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
9906a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola      WeakRefReferences.erase(Entry);
9916a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola    }
9926a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
9930558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    if (Entry->getType()->getElementType() == Ty)
9940558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner      return Entry;
9951eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
9960558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    // Make sure the result is of the correct type.
9979cbe4f0ba01ec304e1e3d071c071f7bca33631c0Chris Lattner    return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
9980558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  }
9991eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1000654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman  // This function doesn't have a complete type (for example, the return
1001654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman  // type is an incomplete struct). Use a fake type instead, and make
1002654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman  // sure not to try to set attributes.
1003654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman  bool IsIncompleteFunction = false;
1004784f21121a6c9418ebd86baa6814e36e1176c410John McCall
10052acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::FunctionType *FTy;
1006784f21121a6c9418ebd86baa6814e36e1176c410John McCall  if (isa<llvm::FunctionType>(Ty)) {
1007784f21121a6c9418ebd86baa6814e36e1176c410John McCall    FTy = cast<llvm::FunctionType>(Ty);
1008784f21121a6c9418ebd86baa6814e36e1176c410John McCall  } else {
10090774cb84719f2aea3016493a2bbd9a02aa3e0541John McCall    FTy = llvm::FunctionType::get(VoidTy, false);
1010654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman    IsIncompleteFunction = true;
1011654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman  }
1012bcaedaed309ce453a992fdeef4a4c908cc7d9dfbChris Lattner
1013784f21121a6c9418ebd86baa6814e36e1176c410John McCall  llvm::Function *F = llvm::Function::Create(FTy,
1014654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman                                             llvm::Function::ExternalLinkage,
1015f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall                                             MangledName, &getModule());
1016f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  assert(F->getName() == MangledName && "name was uniqued!");
1017654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman  if (D.getDecl())
1018b2bcf1c176b200b36f371e189ce22f93c86cdf45Anders Carlsson    SetFunctionAttributes(D, F, IsIncompleteFunction);
1019f85e193739c953358c865005855253af4f68a497John McCall  if (ExtraAttrs != llvm::Attribute::None)
1020f85e193739c953358c865005855253af4f68a497John McCall    F->addFnAttr(ExtraAttrs);
1021654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman
102271efba0bbafaefab14419fbd284efff5f7acade7Kostya Serebryany  if (Features.AddressSanitizer) {
102371efba0bbafaefab14419fbd284efff5f7acade7Kostya Serebryany    // When AddressSanitizer is enabled, set AddressSafety attribute
102471efba0bbafaefab14419fbd284efff5f7acade7Kostya Serebryany    // unless __attribute__((no_address_safety_analysis)) is used.
102571efba0bbafaefab14419fbd284efff5f7acade7Kostya Serebryany    const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
102671efba0bbafaefab14419fbd284efff5f7acade7Kostya Serebryany    if (!FD || !FD->hasAttr<NoAddressSafetyAnalysisAttr>())
102771efba0bbafaefab14419fbd284efff5f7acade7Kostya Serebryany      F->addFnAttr(llvm::Attribute::AddressSafety);
102871efba0bbafaefab14419fbd284efff5f7acade7Kostya Serebryany  }
102971efba0bbafaefab14419fbd284efff5f7acade7Kostya Serebryany
103067b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // This is the first use or definition of a mangled name.  If there is a
103167b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // deferred decl with this name, remember that we need to emit it at the end
103267b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // of the file.
1033f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
103467b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  if (DDI != DeferredDecls.end()) {
103567b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
103667b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    // list, and remove it from DeferredDecls (since we don't need it anymore).
103767b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    DeferredDeclsToEmit.push_back(DDI->second);
103867b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    DeferredDecls.erase(DDI);
1039bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall
1040bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  // Otherwise, there are cases we have to worry about where we're
1041bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  // using a declaration for which we must emit a definition but where
1042bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  // we might not find a top-level definition:
1043bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  //   - member functions defined inline in their classes
1044bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  //   - friend functions defined inline in some class
1045bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  //   - special member functions with implicit definitions
1046bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  // If we ever change our AST traversal to walk into class methods,
1047bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  // this will be unnecessary.
10481faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson  //
10491faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson  // We also don't emit a definition for a function if it's going to be an entry
10501faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson  // in a vtable, unless it's already marked as used.
105101de7a44cea9f77cbcda65faad8edc8b48a3b617Rafael Espindola  } else if (getLangOptions().CPlusPlus && D.getDecl()) {
1052bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall    // Look for a declaration that's lexically in a record.
1053bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall    const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl());
1054bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall    do {
1055bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall      if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
10561faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson        if (FD->isImplicit() && !ForVTable) {
1057bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall          assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
1058a29bf41b8f49578207ce36f6b21ff9bb7ee77babDouglas Gregor          DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
1059bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall          break;
106010620eb5164e31208fcbf0437cd79ae535ed0559Sean Hunt        } else if (FD->doesThisDeclarationHaveABody()) {
1061a29bf41b8f49578207ce36f6b21ff9bb7ee77babDouglas Gregor          DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
1062bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall          break;
1063bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall        }
10647b9a5aa7c0d76f577699d25ce6afe21ecccb60b7Rafael Espindola      }
1065ef96ee0be5f100789f451641542a69cd719144d2Douglas Gregor      FD = FD->getPreviousDecl();
1066bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall    } while (FD);
106767b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  }
10681eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1069784f21121a6c9418ebd86baa6814e36e1176c410John McCall  // Make sure the result is of the requested type.
1070784f21121a6c9418ebd86baa6814e36e1176c410John McCall  if (!IsIncompleteFunction) {
1071784f21121a6c9418ebd86baa6814e36e1176c410John McCall    assert(F->getType()->getElementType() == Ty);
1072784f21121a6c9418ebd86baa6814e36e1176c410John McCall    return F;
1073784f21121a6c9418ebd86baa6814e36e1176c410John McCall  }
1074784f21121a6c9418ebd86baa6814e36e1176c410John McCall
10759cbe4f0ba01ec304e1e3d071c071f7bca33631c0Chris Lattner  llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
1076784f21121a6c9418ebd86baa6814e36e1176c410John McCall  return llvm::ConstantExpr::getBitCast(F, PTy);
10770558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner}
10780558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner
107974391b48b4791cded373683a3baf67314f358d50Chris Lattner/// GetAddrOfFunction - Return the address of the given function.  If Ty is
108074391b48b4791cded373683a3baf67314f358d50Chris Lattner/// non-null, then this function will use the specified type if it has to
108174391b48b4791cded373683a3baf67314f358d50Chris Lattner/// create it (this occurs when we see a definition of the function).
1082b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattnerllvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
10832acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner                                                 llvm::Type *Ty,
10841faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson                                                 bool ForVTable) {
108574391b48b4791cded373683a3baf67314f358d50Chris Lattner  // If there was no specific requested type, just convert it now.
108674391b48b4791cded373683a3baf67314f358d50Chris Lattner  if (!Ty)
10874a6835e650ff24e19ce08a3bd347c0ad186777fdAnders Carlsson    Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
1088bcaedaed309ce453a992fdeef4a4c908cc7d9dfbChris Lattner
10895f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  StringRef MangledName = getMangledName(GD);
10901faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson  return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable);
109174391b48b4791cded373683a3baf67314f358d50Chris Lattner}
109277ba708819285931932ecd33691a672bb59d221aEli Friedman
109374391b48b4791cded373683a3baf67314f358d50Chris Lattner/// CreateRuntimeFunction - Create a new runtime function with the specified
109474391b48b4791cded373683a3baf67314f358d50Chris Lattner/// type and name.
109574391b48b4791cded373683a3baf67314f358d50Chris Lattnerllvm::Constant *
10962acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris LattnerCodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
10975f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner                                     StringRef Name,
1098f85e193739c953358c865005855253af4f68a497John McCall                                     llvm::Attributes ExtraAttrs) {
1099f85e193739c953358c865005855253af4f68a497John McCall  return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
1100f85e193739c953358c865005855253af4f68a497John McCall                                 ExtraAttrs);
110174391b48b4791cded373683a3baf67314f358d50Chris Lattner}
1102bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
1103da55074866ca2fe7f718c5d3334648d6e340fb15Douglas Gregorstatic bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D,
1104da55074866ca2fe7f718c5d3334648d6e340fb15Douglas Gregor                                 bool ConstantInit) {
110588786862424cb2d478516d911709dc19c962af9cJohn McCall  if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType())
110620e098b7e7fda6bed1d67441b56cce77cd3aa918Eli Friedman    return false;
1107da55074866ca2fe7f718c5d3334648d6e340fb15Douglas Gregor
1108da55074866ca2fe7f718c5d3334648d6e340fb15Douglas Gregor  if (Context.getLangOptions().CPlusPlus) {
1109da55074866ca2fe7f718c5d3334648d6e340fb15Douglas Gregor    if (const RecordType *Record
1110da55074866ca2fe7f718c5d3334648d6e340fb15Douglas Gregor          = Context.getBaseElementType(D->getType())->getAs<RecordType>())
11112bb110125e0e5adb7c1c65d12adfa34151ca1c47Douglas Gregor      return ConstantInit &&
11122bb110125e0e5adb7c1c65d12adfa34151ca1c47Douglas Gregor             cast<CXXRecordDecl>(Record->getDecl())->isPOD() &&
11132bb110125e0e5adb7c1c65d12adfa34151ca1c47Douglas Gregor             !cast<CXXRecordDecl>(Record->getDecl())->hasMutableFields();
111420e098b7e7fda6bed1d67441b56cce77cd3aa918Eli Friedman  }
1115da55074866ca2fe7f718c5d3334648d6e340fb15Douglas Gregor
111620e098b7e7fda6bed1d67441b56cce77cd3aa918Eli Friedman  return true;
111720e098b7e7fda6bed1d67441b56cce77cd3aa918Eli Friedman}
111820e098b7e7fda6bed1d67441b56cce77cd3aa918Eli Friedman
111974391b48b4791cded373683a3baf67314f358d50Chris Lattner/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
112074391b48b4791cded373683a3baf67314f358d50Chris Lattner/// create and return an llvm GlobalVariable with the specified type.  If there
112174391b48b4791cded373683a3baf67314f358d50Chris Lattner/// is something in the module with the specified name, return it potentially
112274391b48b4791cded373683a3baf67314f358d50Chris Lattner/// bitcasted to the right type.
112374391b48b4791cded373683a3baf67314f358d50Chris Lattner///
112474391b48b4791cded373683a3baf67314f358d50Chris Lattner/// If D is non-null, it specifies a decl that correspond to this.  This is used
112574391b48b4791cded373683a3baf67314f358d50Chris Lattner/// to set the attributes on the global when it is first created.
1126f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCallllvm::Constant *
11275f9e272e632e951b1efe824cd16acb4d96077930Chris LattnerCodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
11282acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner                                     llvm::PointerType *Ty,
1129c532b502858032f377056dc8cba2fe43cba8702bRafael Espindola                                     const VarDecl *D,
1130c532b502858032f377056dc8cba2fe43cba8702bRafael Espindola                                     bool UnnamedAddr) {
11313c827a79cb7d04c255db8080e682ee2c6912373dDaniel Dunbar  // Lookup the entry, lazily creating it if necessary.
1132f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
113399b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner  if (Entry) {
11346a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola    if (WeakRefReferences.count(Entry)) {
11356a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola      if (D && !D->hasAttr<WeakAttr>())
11367270ee4cd4794281c09dfb6931a98bbb2581ef02Anders Carlsson        Entry->setLinkage(llvm::Function::ExternalLinkage);
11376a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
11386a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola      WeakRefReferences.erase(Entry);
11396a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola    }
11406a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
1141c532b502858032f377056dc8cba2fe43cba8702bRafael Espindola    if (UnnamedAddr)
1142c532b502858032f377056dc8cba2fe43cba8702bRafael Espindola      Entry->setUnnamedAddr(true);
1143c532b502858032f377056dc8cba2fe43cba8702bRafael Espindola
114474391b48b4791cded373683a3baf67314f358d50Chris Lattner    if (Entry->getType() == Ty)
1145570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner      return Entry;
11461eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
114799b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner    // Make sure the result is of the correct type.
11483c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson    return llvm::ConstantExpr::getBitCast(Entry, Ty);
114999b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner  }
11501eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
115167b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // This is the first use or definition of a mangled name.  If there is a
115267b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // deferred decl with this name, remember that we need to emit it at the end
115367b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // of the file.
1154f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
115567b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  if (DDI != DeferredDecls.end()) {
115667b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
115767b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    // list, and remove it from DeferredDecls (since we don't need it anymore).
115867b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    DeferredDeclsToEmit.push_back(DDI->second);
115967b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    DeferredDecls.erase(DDI);
116067b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  }
11611eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
11621eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  llvm::GlobalVariable *GV =
11631eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
116499b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner                             llvm::GlobalValue::ExternalLinkage,
1165f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall                             0, MangledName, 0,
116656ebe5082da7411fb37479e230b52735f77cff35Eli Friedman                             false, Ty->getAddressSpace());
116749988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar
116899b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner  // Handle things which are present even on external declarations.
116974391b48b4791cded373683a3baf67314f358d50Chris Lattner  if (D) {
1170f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump    // FIXME: This code is overly simple and should be merged with other global
1171f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump    // handling.
1172da55074866ca2fe7f718c5d3334648d6e340fb15Douglas Gregor    GV->setConstant(DeclIsConstantGlobal(Context, D, false));
117349988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar
1174110e8e56af30363072c140285961592b0107f789John McCall    // Set linkage and visibility in case we never see a definition.
1175af14603ca61757cf4361b583b45639a04c57e651John McCall    NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
1176af14603ca61757cf4361b583b45639a04c57e651John McCall    if (LV.linkage() != ExternalLinkage) {
117715e310a3b970b64a84cb30f0005bc396b4d978cbJohn McCall      // Don't set internal linkage on declarations.
1178110e8e56af30363072c140285961592b0107f789John McCall    } else {
1179110e8e56af30363072c140285961592b0107f789John McCall      if (D->hasAttr<DLLImportAttr>())
1180110e8e56af30363072c140285961592b0107f789John McCall        GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
11810a0d2b179085a52c10402feebeb6db8b4d96a140Douglas Gregor      else if (D->hasAttr<WeakAttr>() || D->isWeakImported())
1182110e8e56af30363072c140285961592b0107f789John McCall        GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1183110e8e56af30363072c140285961592b0107f789John McCall
1184af14603ca61757cf4361b583b45639a04c57e651John McCall      // Set visibility on a declaration only if it's explicit.
1185af14603ca61757cf4361b583b45639a04c57e651John McCall      if (LV.visibilityExplicit())
1186af14603ca61757cf4361b583b45639a04c57e651John McCall        GV->setVisibility(GetLLVMVisibility(LV.visibility()));
1187110e8e56af30363072c140285961592b0107f789John McCall    }
118856ebe5082da7411fb37479e230b52735f77cff35Eli Friedman
118956ebe5082da7411fb37479e230b52735f77cff35Eli Friedman    GV->setThreadLocal(D->isThreadSpecified());
119074391b48b4791cded373683a3baf67314f358d50Chris Lattner  }
11911eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1192f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  return GV;
119374391b48b4791cded373683a3baf67314f358d50Chris Lattner}
1194eda9a5ec380f172f4e0063744eb796144a125480Daniel Dunbar
1195eda9a5ec380f172f4e0063744eb796144a125480Daniel Dunbar
11963bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlssonllvm::GlobalVariable *
11975f9e272e632e951b1efe824cd16acb4d96077930Chris LattnerCodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
11982acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner                                      llvm::Type *Ty,
11993bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson                                      llvm::GlobalValue::LinkageTypes Linkage) {
12003bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
12013bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  llvm::GlobalVariable *OldGV = 0;
12023bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
12033bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
12043bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  if (GV) {
12053bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    // Check if the variable has the right type.
12063bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    if (GV->getType()->getElementType() == Ty)
12073bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson      return GV;
12083bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
12093bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    // Because C++ name mangling, the only way we can end up with an already
12103bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    // existing global with the same name is if it has been declared extern "C".
121196eaf2992b5955d1470fc9cce7a96e7e1e3b4ea7Anders Carlsson      assert(GV->isDeclaration() && "Declaration has wrong type!");
12123bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    OldGV = GV;
12133bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  }
12143bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
12153bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  // Create a new variable.
12163bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
12173bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson                                Linkage, 0, Name);
12183bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
12193bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  if (OldGV) {
12203bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    // Replace occurrences of the old variable if needed.
12213bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    GV->takeName(OldGV);
12223bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
12233bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    if (!OldGV->use_empty()) {
12243bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson      llvm::Constant *NewPtrForOldDecl =
12253bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson      llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
12263bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson      OldGV->replaceAllUsesWith(NewPtrForOldDecl);
12273bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    }
12283bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
12293bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    OldGV->eraseFromParent();
12303bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  }
12313bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
12323bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  return GV;
12333bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson}
12343bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
123574391b48b4791cded373683a3baf67314f358d50Chris Lattner/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
123674391b48b4791cded373683a3baf67314f358d50Chris Lattner/// given global variable.  If Ty is non-null and if the global doesn't exist,
123774391b48b4791cded373683a3baf67314f358d50Chris Lattner/// then it will be greated with the specified type instead of whatever the
123874391b48b4791cded373683a3baf67314f358d50Chris Lattner/// normal requested type would be.
123974391b48b4791cded373683a3baf67314f358d50Chris Lattnerllvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
12402acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner                                                  llvm::Type *Ty) {
124174391b48b4791cded373683a3baf67314f358d50Chris Lattner  assert(D->hasGlobalStorage() && "Not a global variable");
124274391b48b4791cded373683a3baf67314f358d50Chris Lattner  QualType ASTTy = D->getType();
124374391b48b4791cded373683a3baf67314f358d50Chris Lattner  if (Ty == 0)
124474391b48b4791cded373683a3baf67314f358d50Chris Lattner    Ty = getTypes().ConvertTypeForMem(ASTTy);
12451eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
12462acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::PointerType *PTy =
1247207f4d8543529221932af82836016a2ef066c917Peter Collingbourne    llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
1248f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall
12495f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  StringRef MangledName = getMangledName(D);
1250f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  return GetOrCreateLLVMGlobal(MangledName, PTy, D);
125174391b48b4791cded373683a3baf67314f358d50Chris Lattner}
12523f75c43bd77e063342bc888ac276daf64ba0ce07Daniel Dunbar
125374391b48b4791cded373683a3baf67314f358d50Chris Lattner/// CreateRuntimeVariable - Create a new runtime global variable with the
125474391b48b4791cded373683a3baf67314f358d50Chris Lattner/// specified type and name.
125574391b48b4791cded373683a3baf67314f358d50Chris Lattnerllvm::Constant *
12562acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris LattnerCodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
12575f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner                                     StringRef Name) {
12581de4d4e8cb2e9c88809fea8092bc6e835a5473d2John McCall  return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
1259c532b502858032f377056dc8cba2fe43cba8702bRafael Espindola                               true);
1260bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar}
1261bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
126203f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbarvoid CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
126303f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar  assert(!D->getInit() && "Cannot emit definite definitions here!");
126403f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar
12657520bd1de12af10ea08c662440565adbdf589317Douglas Gregor  if (MayDeferGeneration(D)) {
12667520bd1de12af10ea08c662440565adbdf589317Douglas Gregor    // If we have not seen a reference to this variable yet, place it
12677520bd1de12af10ea08c662440565adbdf589317Douglas Gregor    // into the deferred declarations table to be emitted if needed
12687520bd1de12af10ea08c662440565adbdf589317Douglas Gregor    // later.
12695f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner    StringRef MangledName = getMangledName(D);
1270f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    if (!GetGlobalValue(MangledName)) {
1271555b4bb2749aea2ec8e2adc351a71ec1cb9bdc33Anders Carlsson      DeferredDecls[MangledName] = D;
127203f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar      return;
12737520bd1de12af10ea08c662440565adbdf589317Douglas Gregor    }
12747520bd1de12af10ea08c662440565adbdf589317Douglas Gregor  }
12757520bd1de12af10ea08c662440565adbdf589317Douglas Gregor
12767520bd1de12af10ea08c662440565adbdf589317Douglas Gregor  // The tentative definition is the only definition.
127703f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar  EmitGlobalVarDefinition(D);
127803f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar}
127903f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar
12806fb745bdf1ff1e32caf07e42093a7920726892c1Douglas Gregorvoid CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) {
12816fb745bdf1ff1e32caf07e42093a7920726892c1Douglas Gregor  if (DefinitionRequired)
12826fb745bdf1ff1e32caf07e42093a7920726892c1Douglas Gregor    getVTables().GenerateClassData(getVTableLinkage(Class), Class);
12836fb745bdf1ff1e32caf07e42093a7920726892c1Douglas Gregor}
12846fb745bdf1ff1e32caf07e42093a7920726892c1Douglas Gregor
12854b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregorllvm::GlobalVariable::LinkageTypes
1286046c294a43024874ff35656c6e785b64e72f1f36Anders CarlssonCodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
1287cb5d2d0647fdab2e36c85b417e03bf18916ce10cEli Friedman  if (RD->getLinkage() != ExternalLinkage)
1288dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor    return llvm::GlobalVariable::InternalLinkage;
1289dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor
1290dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor  if (const CXXMethodDecl *KeyFunction
1291dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor                                    = RD->getASTContext().getKeyFunction(RD)) {
1292dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor    // If this class has a key function, use that to determine the linkage of
1293dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor    // the vtable.
12944b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor    const FunctionDecl *Def = 0;
129506a54a38be5054c910ffc92db60edab23f9ea105Argyrios Kyrtzidis    if (KeyFunction->hasBody(Def))
12964b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor      KeyFunction = cast<CXXMethodDecl>(Def);
1297dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor
12984b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor    switch (KeyFunction->getTemplateSpecializationKind()) {
12994b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor      case TSK_Undeclared:
13004b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor      case TSK_ExplicitSpecialization:
13016d7f8473cd6e967b3676948894ce72472102f9cbAnders Carlsson        // When compiling with optimizations turned on, we emit all vtables,
13026d7f8473cd6e967b3676948894ce72472102f9cbAnders Carlsson        // even if the key function is not defined in the current translation
13036d7f8473cd6e967b3676948894ce72472102f9cbAnders Carlsson        // unit. If this is the case, use available_externally linkage.
13046d7f8473cd6e967b3676948894ce72472102f9cbAnders Carlsson        if (!Def && CodeGenOpts.OptimizationLevel)
13056d7f8473cd6e967b3676948894ce72472102f9cbAnders Carlsson          return llvm::GlobalVariable::AvailableExternallyLinkage;
13066d7f8473cd6e967b3676948894ce72472102f9cbAnders Carlsson
13074b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor        if (KeyFunction->isInlined())
1308142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian          return !Context.getLangOptions().AppleKext ?
1309142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian                   llvm::GlobalVariable::LinkOnceODRLinkage :
1310142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian                   llvm::Function::InternalLinkage;
13114b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor
13124b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor        return llvm::GlobalVariable::ExternalLinkage;
13134b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor
13144b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor      case TSK_ImplicitInstantiation:
1315142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian        return !Context.getLangOptions().AppleKext ?
1316142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian                 llvm::GlobalVariable::LinkOnceODRLinkage :
1317142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian                 llvm::Function::InternalLinkage;
1318f502d93b0ea970bfbd897e657f8d940a20984de2Anders Carlsson
13194b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor      case TSK_ExplicitInstantiationDefinition:
1320142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian        return !Context.getLangOptions().AppleKext ?
1321142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian                 llvm::GlobalVariable::WeakODRLinkage :
1322142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian                 llvm::Function::InternalLinkage;
1323f502d93b0ea970bfbd897e657f8d940a20984de2Anders Carlsson
13244b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor      case TSK_ExplicitInstantiationDeclaration:
13254b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor        // FIXME: Use available_externally linkage. However, this currently
13264b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor        // breaks LLVM's build due to undefined symbols.
13274b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor        //      return llvm::GlobalVariable::AvailableExternallyLinkage;
1328142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian        return !Context.getLangOptions().AppleKext ?
1329142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian                 llvm::GlobalVariable::LinkOnceODRLinkage :
1330142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian                 llvm::Function::InternalLinkage;
13314b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor    }
1332dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor  }
1333dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor
133453bad4e98ed5e765df4231099bf1c737582908bfFariborz Jahanian  if (Context.getLangOptions().AppleKext)
133553bad4e98ed5e765df4231099bf1c737582908bfFariborz Jahanian    return llvm::Function::InternalLinkage;
133653bad4e98ed5e765df4231099bf1c737582908bfFariborz Jahanian
1337dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor  switch (RD->getTemplateSpecializationKind()) {
1338dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor  case TSK_Undeclared:
1339dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor  case TSK_ExplicitSpecialization:
1340dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor  case TSK_ImplicitInstantiation:
1341dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor    // FIXME: Use available_externally linkage. However, this currently
1342dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor    // breaks LLVM's build due to undefined symbols.
1343dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor    //   return llvm::GlobalVariable::AvailableExternallyLinkage;
1344142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian  case TSK_ExplicitInstantiationDeclaration:
134553bad4e98ed5e765df4231099bf1c737582908bfFariborz Jahanian    return llvm::GlobalVariable::LinkOnceODRLinkage;
1346142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian
1347142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian  case TSK_ExplicitInstantiationDefinition:
134853bad4e98ed5e765df4231099bf1c737582908bfFariborz Jahanian      return llvm::GlobalVariable::WeakODRLinkage;
13494b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor  }
13503026348bd4c13a0f83b59839f64065e0fcbea253David Blaikie
13513026348bd4c13a0f83b59839f64065e0fcbea253David Blaikie  llvm_unreachable("Invalid TemplateSpecializationKind!");
13524b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor}
13534b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor
13542acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris LattnerCharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
135506f486ecd05bd6788da97c39164c1903a084c26dKen Dyck    return Context.toCharUnitsFromBits(
135606f486ecd05bd6788da97c39164c1903a084c26dKen Dyck      TheTargetData.getTypeStoreSizeInBits(Ty));
1357687cc4a850b59116efee061018f0d8df50728b82Ken Dyck}
1358687cc4a850b59116efee061018f0d8df50728b82Ken Dyck
1359bd012ff1fa088181646a784f385b28867372d434Daniel Dunbarvoid CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
13608f32f7189b12f67aa4a19bc7c3855b599980eca0Chris Lattner  llvm::Constant *Init = 0;
136177ba708819285931932ecd33691a672bb59d221aEli Friedman  QualType ASTTy = D->getType();
13626c6bda3b0b1d8adaac2ba3f4da7056e9f1eef52eEli Friedman  bool NonConstInit = false;
13631eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
13642d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith  const VarDecl *InitDecl;
13652d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith  const Expr *InitExpr = D->getAnyInitializer(InitDecl);
13663bb92693c3332c1e99870a4e45afff3892e1c6aeAnders Carlsson
13673bb92693c3332c1e99870a4e45afff3892e1c6aeAnders Carlsson  if (!InitExpr) {
1368cd5f4aaf0c219189878126d556f35e38fdb8afa1Eli Friedman    // This is a tentative definition; tentative definitions are
136903f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // implicitly initialized with { 0 }.
137003f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    //
137103f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // Note that tentative definitions are only emitted at the end of
137203f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // a translation unit, so they should never have incomplete
137303f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // type. In addition, EmitTentativeDefinition makes sure that we
137403f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // never attempt to emit a tentative definition if a real one
137503f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // exists. A use may still exists, however, so we still may need
137603f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // to do a RAUW.
137703f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
1378b0d0ea042116c1f451d3db8ceff9f1dd92bc36d2Anders Carlsson    Init = EmitNullConstant(D->getType());
137977ba708819285931932ecd33691a672bb59d221aEli Friedman  } else {
13802d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith    Init = EmitConstantInit(*InitDecl);
13816e656f45ae04b415ba7a4c0c25e55633e2d0ecd0Eli Friedman    if (!Init) {
13823bb92693c3332c1e99870a4e45afff3892e1c6aeAnders Carlsson      QualType T = InitExpr->getType();
1383c446d1816f46a4b6d2337102dfc001f55fc18211Douglas Gregor      if (D->getType()->isReferenceType())
1384c446d1816f46a4b6d2337102dfc001f55fc18211Douglas Gregor        T = D->getType();
13852d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith
138689ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson      if (getLangOptions().CPlusPlus) {
138789ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson        Init = EmitNullConstant(T);
13886c6bda3b0b1d8adaac2ba3f4da7056e9f1eef52eEli Friedman        NonConstInit = true;
138989ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson      } else {
139089ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson        ErrorUnsupported(D, "static initializer");
139189ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson        Init = llvm::UndefValue::get(getTypes().ConvertType(T));
139289ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson      }
1393bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall    } else {
1394bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall      // We don't need an initializer, so remove the entry for the delayed
1395bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall      // initializer position (just in case this entry was delayed).
1396bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall      if (getLangOptions().CPlusPlus)
1397bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall        DelayedCXXInitPosition.erase(D);
13986e656f45ae04b415ba7a4c0c25e55633e2d0ecd0Eli Friedman    }
13998f32f7189b12f67aa4a19bc7c3855b599980eca0Chris Lattner  }
14008e53e720b3d7c962e91138a130dbd5d6c2def0e5Devang Patel
14012acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type* InitType = Init->getType();
1402570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
14031eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1404570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // Strip off a bitcast if we got one back.
1405570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
14069d4a15fd3b85434c43ea27562793de63a793321aChris Lattner    assert(CE->getOpcode() == llvm::Instruction::BitCast ||
14079d4a15fd3b85434c43ea27562793de63a793321aChris Lattner           // all zero index gep.
14089d4a15fd3b85434c43ea27562793de63a793321aChris Lattner           CE->getOpcode() == llvm::Instruction::GetElementPtr);
1409570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    Entry = CE->getOperand(0);
1410570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  }
14111eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1412570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // Entry is now either a Function or GlobalVariable.
1413570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
14141eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1415570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // We have a definition after a declaration with the wrong type.
1416570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // We must make a new GlobalVariable* and update everything that used OldGV
1417570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // (a declaration or tentative definition) with the new GlobalVariable*
1418570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // (which will be a definition).
1419570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  //
1420570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // This happens if there is a prototype for a global (e.g.
1421570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // "extern int x[];") and then a definition of a different type (e.g.
1422570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // "int x[10];"). This also happens when an initializer has a different type
1423570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // from the type of the global (this happens with unions).
1424570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  if (GV == 0 ||
1425570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner      GV->getType()->getElementType() != InitType ||
1426207f4d8543529221932af82836016a2ef066c917Peter Collingbourne      GV->getType()->getAddressSpace() !=
1427207f4d8543529221932af82836016a2ef066c917Peter Collingbourne        getContext().getTargetAddressSpace(ASTTy)) {
14281eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1429f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    // Move the old entry aside so that we'll create a new one.
14305f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner    Entry->setName(StringRef());
1431232350d4faf46ec38d5ff60e11505f9c4fa9535bDaniel Dunbar
1432570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    // Make a new global with the correct type, this is now guaranteed to work.
1433570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
14340558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner
143577ba708819285931932ecd33691a672bb59d221aEli Friedman    // Replace all uses of the old global with the new global
14361eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    llvm::Constant *NewPtrForOldDecl =
14373c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson        llvm::ConstantExpr::getBitCast(GV, Entry->getType());
1438570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    Entry->replaceAllUsesWith(NewPtrForOldDecl);
143977ba708819285931932ecd33691a672bb59d221aEli Friedman
144077ba708819285931932ecd33691a672bb59d221aEli Friedman    // Erase the old global, since it is no longer used.
1441570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    cast<llvm::GlobalValue>(Entry)->eraseFromParent();
144277ba708819285931932ecd33691a672bb59d221aEli Friedman  }
144377ba708819285931932ecd33691a672bb59d221aEli Friedman
144477f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  if (D->hasAttr<AnnotateAttr>())
144577f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    AddGlobalAnnotations(D, GV);
14468bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman
144788a69ad80e1550e9932666e6efa050a5b1223889Chris Lattner  GV->setInitializer(Init);
1448e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner
1449e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner  // If it is safe to mark the global 'constant', do so now.
1450e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner  GV->setConstant(false);
1451da55074866ca2fe7f718c5d3334648d6e340fb15Douglas Gregor  if (!NonConstInit && DeclIsConstantGlobal(Context, D, true))
1452e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner    GV->setConstant(true);
14531eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
14548b752f10c394b140f9ef89e049cbad1a7676fc25Ken Dyck  GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
1455354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian
145688a69ad80e1550e9932666e6efa050a5b1223889Chris Lattner  // Set the llvm linkage type as appropriate.
1457354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  llvm::GlobalValue::LinkageTypes Linkage =
1458354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    GetLLVMLinkageVarDefinition(D, GV);
1459354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  GV->setLinkage(Linkage);
1460354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  if (Linkage == llvm::GlobalVariable::CommonLinkage)
1461354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    // common vars aren't constant even if declared const.
1462354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    GV->setConstant(false);
1463354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian
1464354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  SetCommonAttributes(D, GV);
1465354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian
14663030eb82593097502469a8b3fc26112c79c75605John McCall  // Emit the initializer function if necessary.
14673030eb82593097502469a8b3fc26112c79c75605John McCall  if (NonConstInit)
14683030eb82593097502469a8b3fc26112c79c75605John McCall    EmitCXXGlobalVarDeclInitFunc(D, GV);
14693030eb82593097502469a8b3fc26112c79c75605John McCall
1470354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  // Emit global variable debug information.
147173fb35003aad027492e661a3749e921b5d1ecaf9Eric Christopher  if (CGDebugInfo *DI = getModuleDebugInfo())
1472354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    DI->EmitGlobalVariable(GV, D);
1473354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian}
1474354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian
1475354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanianllvm::GlobalValue::LinkageTypes
1476354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz JahanianCodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
1477354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian                                           llvm::GlobalVariable *GV) {
147890e99a84ddd020e8fda79643748243725a2ed071Argyrios Kyrtzidis  GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1479a0f00a71fcb0f98298709d5e5318339acf7958acDouglas Gregor  if (Linkage == GVA_Internal)
1480354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    return llvm::Function::InternalLinkage;
148140b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  else if (D->hasAttr<DLLImportAttr>())
1482354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    return llvm::Function::DLLImportLinkage;
148340b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  else if (D->hasAttr<DLLExportAttr>())
1484354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    return llvm::Function::DLLExportLinkage;
1485e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner  else if (D->hasAttr<WeakAttr>()) {
1486e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner    if (GV->isConstant())
1487354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian      return llvm::GlobalVariable::WeakODRLinkage;
1488e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner    else
1489354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian      return llvm::GlobalVariable::WeakAnyLinkage;
14908f51a4f2d00b0abda3cde7f3828fb2e2b9beafb5Douglas Gregor  } else if (Linkage == GVA_TemplateInstantiation ||
14918f51a4f2d00b0abda3cde7f3828fb2e2b9beafb5Douglas Gregor             Linkage == GVA_ExplicitTemplateInstantiation)
149299ace16bc6962f1fc3dc45bbbdf2eb74e555a8adJohn McCall    return llvm::GlobalVariable::WeakODRLinkage;
1493a6cf1e709b96865210b81bd611d41e9a2d41500aEric Christopher  else if (!getLangOptions().CPlusPlus &&
1494a6cf1e709b96865210b81bd611d41e9a2d41500aEric Christopher           ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
1495a6cf1e709b96865210b81bd611d41e9a2d41500aEric Christopher             D->getAttr<CommonAttr>()) &&
1496309457d0f1b416c1b379c9f3e172848adffedb23Chris Lattner           !D->hasExternalStorage() && !D->getInit() &&
1497ab27d6ea7b4ce2762a16905281de796db32bb6f2Fariborz Jahanian           !D->getAttr<SectionAttr>() && !D->isThreadSpecified() &&
1498ab27d6ea7b4ce2762a16905281de796db32bb6f2Fariborz Jahanian           !D->getAttr<WeakImportAttr>()) {
149991f31dc234bbc98f3dd20e6741a7b0b98c7916bfEric Christopher    // Thread local vars aren't considered common linkage.
1500354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    return llvm::GlobalVariable::CommonLinkage;
1501686226b538e72c5059ab7c9a8f87eb883193b645Sanjiv Gupta  }
1502354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  return llvm::GlobalVariable::ExternalLinkage;
150388a69ad80e1550e9932666e6efa050a5b1223889Chris Lattner}
15045f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
1505bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
1506bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// implement a function with no prototype, e.g. "int foo() {}".  If there are
1507bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// existing call uses of the old function in the module, this adjusts them to
1508bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// call the new function directly.
1509bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner///
1510bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// This is not just a cleanup: the always_inline pass requires direct calls to
1511bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// functions to be able to inline them.  If there is a bitcast in the way, it
1512bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// won't inline them.  Instcombine normally deletes these calls, but it isn't
1513bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// run at -O0.
1514bdb0132722082886558f31eccdba06ae1852c0eeChris Lattnerstatic void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1515bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner                                                      llvm::Function *NewFn) {
1516bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  // If we're redefining a global as a function, don't transform it.
1517bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
1518bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  if (OldFn == 0) return;
15191eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
15202acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type *NewRetTy = NewFn->getReturnType();
15215f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  SmallVector<llvm::Value*, 4> ArgList;
1522bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
1523bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
1524dbf02bccc9fc1115cb7dd45c84df77252d68f220Benjamin Kramer       UI != E; ) {
1525bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // TODO: Do invokes ever occur in C code?  If so, we should handle them too.
1526dbf02bccc9fc1115cb7dd45c84df77252d68f220Benjamin Kramer    llvm::Value::use_iterator I = UI++; // Increment before the CI is erased.
1527dbf02bccc9fc1115cb7dd45c84df77252d68f220Benjamin Kramer    llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I);
15288670cd3ea4dfbf86caacd270ec2441e9949bbb6aGabor Greif    if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I)
152935db3b9aad1829a1279b9e213ddee36395314a0bGabor Greif    llvm::CallSite CS(CI);
1530dbf02bccc9fc1115cb7dd45c84df77252d68f220Benjamin Kramer    if (!CI || !CS.isCallee(I)) continue;
15311eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1532bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // If the return types don't match exactly, and if the call isn't dead, then
1533bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // we can't transform this call.
1534bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    if (CI->getType() != NewRetTy && !CI->use_empty())
1535bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      continue;
1536bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
153740f9c302f23a35611cd354f40b22b37f2c554a40John McCall    // Get the attribute list.
153840f9c302f23a35611cd354f40b22b37f2c554a40John McCall    llvm::SmallVector<llvm::AttributeWithIndex, 8> AttrVec;
153940f9c302f23a35611cd354f40b22b37f2c554a40John McCall    llvm::AttrListPtr AttrList = CI->getAttributes();
154040f9c302f23a35611cd354f40b22b37f2c554a40John McCall
154140f9c302f23a35611cd354f40b22b37f2c554a40John McCall    // Get any return attributes.
154240f9c302f23a35611cd354f40b22b37f2c554a40John McCall    llvm::Attributes RAttrs = AttrList.getRetAttributes();
154340f9c302f23a35611cd354f40b22b37f2c554a40John McCall
154440f9c302f23a35611cd354f40b22b37f2c554a40John McCall    // Add the return attributes.
154540f9c302f23a35611cd354f40b22b37f2c554a40John McCall    if (RAttrs)
154640f9c302f23a35611cd354f40b22b37f2c554a40John McCall      AttrVec.push_back(llvm::AttributeWithIndex::get(0, RAttrs));
154740f9c302f23a35611cd354f40b22b37f2c554a40John McCall
1548bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // If the function was passed too few arguments, don't transform.  If extra
1549bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // arguments were passed, we silently drop them.  If any of the types
1550bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // mismatch, we don't transform.
1551bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    unsigned ArgNo = 0;
1552bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    bool DontTransform = false;
1553bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
1554bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner         E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
155535db3b9aad1829a1279b9e213ddee36395314a0bGabor Greif      if (CS.arg_size() == ArgNo ||
155635db3b9aad1829a1279b9e213ddee36395314a0bGabor Greif          CS.getArgument(ArgNo)->getType() != AI->getType()) {
1557bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner        DontTransform = true;
1558bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner        break;
1559bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      }
156040f9c302f23a35611cd354f40b22b37f2c554a40John McCall
156140f9c302f23a35611cd354f40b22b37f2c554a40John McCall      // Add any parameter attributes.
156240f9c302f23a35611cd354f40b22b37f2c554a40John McCall      if (llvm::Attributes PAttrs = AttrList.getParamAttributes(ArgNo + 1))
156340f9c302f23a35611cd354f40b22b37f2c554a40John McCall        AttrVec.push_back(llvm::AttributeWithIndex::get(ArgNo + 1, PAttrs));
1564bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    }
1565bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    if (DontTransform)
1566bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      continue;
15671eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
156840f9c302f23a35611cd354f40b22b37f2c554a40John McCall    if (llvm::Attributes FnAttrs =  AttrList.getFnAttributes())
156940f9c302f23a35611cd354f40b22b37f2c554a40John McCall      AttrVec.push_back(llvm::AttributeWithIndex::get(~0, FnAttrs));
157040f9c302f23a35611cd354f40b22b37f2c554a40John McCall
1571bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // Okay, we can transform this.  Create the new call instruction and copy
1572bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // over the required information.
15736ba728d9687b2617793f5afd410650a8d6c71080Gabor Greif    ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo);
15744c7d9f1507d0f102bd4133bba63348636facd469Jay Foad    llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList, "", CI);
1575bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    ArgList.clear();
1576ffbb15e54a6dc120087003d1e42448b8705bd58aBenjamin Kramer    if (!NewCall->getType()->isVoidTy())
1577bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      NewCall->takeName(CI);
157840f9c302f23a35611cd354f40b22b37f2c554a40John McCall    NewCall->setAttributes(llvm::AttrListPtr::get(AttrVec.begin(),
157940f9c302f23a35611cd354f40b22b37f2c554a40John McCall                                                  AttrVec.end()));
1580ca6408c3176783f0b29da4679a08512aa05f0c73Daniel Dunbar    NewCall->setCallingConv(CI->getCallingConv());
1581bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
1582bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // Finally, remove the old call, replacing any uses with the new one.
158300549fcec0490b2daf27543e532f94adbb186063Chris Lattner    if (!CI->use_empty())
158400549fcec0490b2daf27543e532f94adbb186063Chris Lattner      CI->replaceAllUsesWith(NewCall);
15853b122bc5f1203615e2128e0c1a63da438865b1ccDevang Patel
1586c60346388d60b1756f3675dabb60dc58da0728ecChris Lattner    // Copy debug location attached to CI.
1587c60346388d60b1756f3675dabb60dc58da0728ecChris Lattner    if (!CI->getDebugLoc().isUnknown())
1588c60346388d60b1756f3675dabb60dc58da0728ecChris Lattner      NewCall->setDebugLoc(CI->getDebugLoc());
1589bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    CI->eraseFromParent();
1590bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  }
1591bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner}
1592bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
1593bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
1594b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattnervoid CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
1595b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner  const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
1596d26bc76c98006609002d9930f8840490e88ac5b5John McCall
15971f6f961293da9c2b1c23da2411c1b439a9502ed0John McCall  // Compute the function info and LLVM type.
1598d26bc76c98006609002d9930f8840490e88ac5b5John McCall  const CGFunctionInfo &FI = getTypes().getFunctionInfo(GD);
15991f6f961293da9c2b1c23da2411c1b439a9502ed0John McCall  bool variadic = false;
16001f6f961293da9c2b1c23da2411c1b439a9502ed0John McCall  if (const FunctionProtoType *fpt = D->getType()->getAs<FunctionProtoType>())
16011f6f961293da9c2b1c23da2411c1b439a9502ed0John McCall    variadic = fpt->isVariadic();
16022acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::FunctionType *Ty = getTypes().GetFunctionType(FI, variadic);
1603d26bc76c98006609002d9930f8840490e88ac5b5John McCall
16049fa959d5bfbbb17d7c6ba71252219201fc8dc971Chris Lattner  // Get or create the prototype for the function.
1605b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner  llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
16061eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
16070558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  // Strip off a bitcast if we got one back.
16080558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
16090558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    assert(CE->getOpcode() == llvm::Instruction::BitCast);
16100558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    Entry = CE->getOperand(0);
16110558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  }
16121eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
16131eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
16140558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
1615bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
16161eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
161742745815fa4e90bfb07e581d2e5152b2c2db08ffDaniel Dunbar    // If the types mismatch then we have to rewrite the definition.
1618bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    assert(OldFn->isDeclaration() &&
16190558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner           "Shouldn't replace non-declaration");
162034809507232bc4c3c4840c7d092c7440219fddafChris Lattner
162162b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // F is the Function* for the one with the wrong type, we must make a new
162262b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // Function* and update everything that used F (a declaration) with the new
162362b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // Function* (which will be a definition).
162462b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    //
162562b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // This happens if there is a prototype for a function
162662b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // (e.g. "int f()") and then a definition of a different type
1627f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    // (e.g. "int f(int x)").  Move the old function aside so that it
1628f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    // doesn't interfere with GetAddrOfFunction.
16295f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner    OldFn->setName(StringRef());
1630b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner    llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
16311eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1632bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // If this is an implementation of a function without a prototype, try to
1633bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // replace any existing uses of the function (which may be calls) with uses
1634bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // of the new function
16359fa959d5bfbbb17d7c6ba71252219201fc8dc971Chris Lattner    if (D->getType()->isFunctionNoProtoType()) {
1636bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
16379fa959d5bfbbb17d7c6ba71252219201fc8dc971Chris Lattner      OldFn->removeDeadConstantUsers();
16389fa959d5bfbbb17d7c6ba71252219201fc8dc971Chris Lattner    }
16391eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
164062b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // Replace uses of F with the Function we will endow with a body.
1641bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    if (!Entry->use_empty()) {
16421eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      llvm::Constant *NewPtrForOldDecl =
16433c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson        llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
1644bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      Entry->replaceAllUsesWith(NewPtrForOldDecl);
1645bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    }
16461eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
164762b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // Ok, delete the old function now, which is dead.
1648bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    OldFn->eraseFromParent();
16491eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
16500558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    Entry = NewFn;
1651bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar  }
16521eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1653112c967bd5c862a0f5d7913aa06700c048807db8John McCall  // We need to set linkage and visibility on the function before
1654112c967bd5c862a0f5d7913aa06700c048807db8John McCall  // generating code for it because various parts of IR generation
1655112c967bd5c862a0f5d7913aa06700c048807db8John McCall  // want to propagate this information down (e.g. to local static
1656112c967bd5c862a0f5d7913aa06700c048807db8John McCall  // declarations).
16570558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  llvm::Function *Fn = cast<llvm::Function>(Entry);
16588b2423361648c39a7d8a3c5e8129e12006deac32John McCall  setFunctionLinkage(D, Fn);
1659bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
1660112c967bd5c862a0f5d7913aa06700c048807db8John McCall  // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
16610ffeaad72cb335b926b064379be4c9886bbff004Anders Carlsson  setGlobalVisibility(Fn, D);
1662112c967bd5c862a0f5d7913aa06700c048807db8John McCall
1663d26bc76c98006609002d9930f8840490e88ac5b5John McCall  CodeGenFunction(*this).GenerateCode(D, Fn, FI);
16646379a7a15335e0af543a942efe9cfd514a83dab8Daniel Dunbar
16657c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  SetFunctionDefinitionAttributes(D, Fn);
16667c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  SetLLVMFunctionAttributesForDefinition(D, Fn);
16671eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
166840b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
1669219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar    AddGlobalCtor(Fn, CA->getPriority());
167040b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
1671219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar    AddGlobalDtor(Fn, DA->getPriority());
167277f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  if (D->hasAttr<AnnotateAttr>())
167377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    AddGlobalAnnotations(D, Fn);
1674bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar}
1675bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
1676f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCallvoid CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
1677f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
167840b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  const AliasAttr *AA = D->getAttr<AliasAttr>();
1679bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  assert(AA && "Not an alias?");
1680bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner
16815f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  StringRef MangledName = getMangledName(GD);
1682f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall
1683f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  // If there is a definition in the module, then it wins over the alias.
1684f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  // This is dubious, but allow it to be safe.  Just ignore the alias.
1685f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1686f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  if (Entry && !Entry->isDeclaration())
1687f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    return;
16881eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
16892acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
1690bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner
1691bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  // Create a reference to the named value.  This ensures that it is emitted
1692bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  // if a deferred decl.
1693bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  llvm::Constant *Aliasee;
1694bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  if (isa<llvm::FunctionType>(DeclTy))
16951faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson    Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
16961faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson                                      /*ForVTable=*/false);
1697bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  else
1698f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
169996e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson                                    llvm::PointerType::getUnqual(DeclTy), 0);
1700bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner
1701bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  // Create the new alias itself, but don't set a name yet.
17021eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  llvm::GlobalValue *GA =
1703bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    new llvm::GlobalAlias(Aliasee->getType(),
1704bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner                          llvm::Function::ExternalLinkage,
1705bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner                          "", Aliasee, &getModule());
17061eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1707bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  if (Entry) {
1708f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    assert(Entry->isDeclaration());
1709f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall
1710bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    // If there is a declaration in the module, then we had an extern followed
1711bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    // by the alias, as in:
1712bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    //   extern int test6();
1713bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    //   ...
1714bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    //   int test6() __attribute__((alias("test7")));
1715bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    //
1716bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    // Remove it and replace uses of it with the alias.
1717f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    GA->takeName(Entry);
17181eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
17193c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson    Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
1720bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner                                                          Entry->getType()));
1721bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    Entry->eraseFromParent();
1722f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  } else {
17239a20d55807cc2f6534a9c51a46cc8143ed16786dAnders Carlsson    GA->setName(MangledName);
1724bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  }
17251eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
17267c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // Set attributes which are particular to an alias; this is a
17277c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // specialization of the attributes which may be set on a global
17287c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // variable/function.
172940b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (D->hasAttr<DLLExportAttr>()) {
17307c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
17317c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar      // The dllexport attribute is ignored for undefined symbols.
173206a54a38be5054c910ffc92db60edab23f9ea105Argyrios Kyrtzidis      if (FD->hasBody())
17337c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar        GA->setLinkage(llvm::Function::DLLExportLinkage);
17347c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    } else {
17357c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar      GA->setLinkage(llvm::Function::DLLExportLinkage);
17367c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    }
17371eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  } else if (D->hasAttr<WeakAttr>() ||
173811e8ce7380856abee188b237c2600272df2ed09dRafael Espindola             D->hasAttr<WeakRefAttr>() ||
17390a0d2b179085a52c10402feebeb6db8b4d96a140Douglas Gregor             D->isWeakImported()) {
17407c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    GA->setLinkage(llvm::Function::WeakAnyLinkage);
17417c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  }
17427c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
17437c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  SetCommonAttributes(D, GA);
1744bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner}
1745bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner
17468dd55a3c3b28d195717c87bbc60e765951d408feBenjamin Kramerllvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
17472d3ba4f5a923a90c3fc290ddfba5e36c2d0a9b46Chris Lattner                                            ArrayRef<llvm::Type*> Tys) {
1748df983a8bcbbcea911b8dce283f044787df119d50Jay Foad  return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
17498dd55a3c3b28d195717c87bbc60e765951d408feBenjamin Kramer                                         Tys);
17507acda7c4a0e4aec6c003b3169ca45a5f3bc7e033Chris Lattner}
1751bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner
17521d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbarstatic llvm::StringMapEntry<llvm::Constant*> &
17531d5529132e4620562cab931c1f84c24e42f02741Daniel DunbarGetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
17541d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar                         const StringLiteral *Literal,
175570ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar                         bool TargetIsLSB,
17561d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar                         bool &IsUTF16,
17571d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar                         unsigned &StringLength) {
17585f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  StringRef String = Literal->getString();
17592f4eaef37476ae6891ede8ba215d0f6fd093629bBenjamin Kramer  unsigned NumBytes = String.size();
17601d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar
1761f015b034159d40e7033309e50036804eb1971787Daniel Dunbar  // Check for simple case.
1762f015b034159d40e7033309e50036804eb1971787Daniel Dunbar  if (!Literal->containsNonAsciiOrNull()) {
1763f015b034159d40e7033309e50036804eb1971787Daniel Dunbar    StringLength = NumBytes;
17642f4eaef37476ae6891ede8ba215d0f6fd093629bBenjamin Kramer    return Map.GetOrCreateValue(String);
1765f015b034159d40e7033309e50036804eb1971787Daniel Dunbar  }
1766f015b034159d40e7033309e50036804eb1971787Daniel Dunbar
17671d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  // Otherwise, convert the UTF8 literals into a byte string.
17685f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  SmallVector<UTF16, 128> ToBuf(NumBytes);
17692f4eaef37476ae6891ede8ba215d0f6fd093629bBenjamin Kramer  const UTF8 *FromPtr = (UTF8 *)String.data();
17701d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  UTF16 *ToPtr = &ToBuf[0];
17711eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1772e7ddfb974884ec75ffd66953b79511ea457493baFariborz Jahanian  (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1773e7ddfb974884ec75ffd66953b79511ea457493baFariborz Jahanian                           &ToPtr, ToPtr + NumBytes,
1774e7ddfb974884ec75ffd66953b79511ea457493baFariborz Jahanian                           strictConversion);
17751eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
177670ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  // ConvertUTF8toUTF16 returns the length in ToPtr.
17771d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  StringLength = ToPtr - &ToBuf[0];
177870ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar
177970ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  // Render the UTF-16 string into a byte array and convert to the target byte
178070ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  // order.
178170ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  //
178270ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  // FIXME: This isn't something we should need to do here.
178370ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  llvm::SmallString<128> AsBytes;
178470ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  AsBytes.reserve(StringLength * 2);
178570ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  for (unsigned i = 0; i != StringLength; ++i) {
178670ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar    unsigned short Val = ToBuf[i];
178770ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar    if (TargetIsLSB) {
178870ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar      AsBytes.push_back(Val & 0xFF);
178970ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar      AsBytes.push_back(Val >> 8);
179070ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar    } else {
179170ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar      AsBytes.push_back(Val >> 8);
179270ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar      AsBytes.push_back(Val & 0xFF);
179370ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar    }
179470ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  }
1795434da48d0e35764f18b3fc96c75504746050b046Daniel Dunbar  // Append one extra null character, the second is automatically added by our
1796434da48d0e35764f18b3fc96c75504746050b046Daniel Dunbar  // caller.
1797434da48d0e35764f18b3fc96c75504746050b046Daniel Dunbar  AsBytes.push_back(0);
179870ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar
17991d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  IsUTF16 = true;
18005f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  return Map.GetOrCreateValue(StringRef(AsBytes.data(), AsBytes.size()));
18011d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar}
18021d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar
1803cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanianstatic llvm::StringMapEntry<llvm::Constant*> &
1804cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz JahanianGetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1805cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian		       const StringLiteral *Literal,
1806cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian		       unsigned &StringLength)
1807cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian{
18085f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner	StringRef String = Literal->getString();
1809cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian	StringLength = String.size();
1810cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian	return Map.GetOrCreateValue(String);
1811cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian}
1812cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian
18131d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbarllvm::Constant *
18141d5529132e4620562cab931c1f84c24e42f02741Daniel DunbarCodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
18151d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  unsigned StringLength = 0;
18161d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  bool isUTF16 = false;
18171d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  llvm::StringMapEntry<llvm::Constant*> &Entry =
18181eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    GetConstantCFStringEntry(CFConstantStringMap, Literal,
181970ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar                             getTargetData().isLittleEndian(),
182070ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar                             isUTF16, StringLength);
18211eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
18221d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  if (llvm::Constant *C = Entry.getValue())
18231d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar    return C;
18241eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
18250032b2781b4deb131f8c9b7968f2030bf2489cddOwen Anderson  llvm::Constant *Zero =
18260032b2781b4deb131f8c9b7968f2030bf2489cddOwen Anderson      llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
18273e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar  llvm::Constant *Zeros[] = { Zero, Zero };
18281eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
18299d4a15fd3b85434c43ea27562793de63a793321aChris Lattner  // If we don't already have it, get __CFConstantStringClassReference.
1830c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  if (!CFConstantStringClassRef) {
18312acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner    llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
183296e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson    Ty = llvm::ArrayType::get(Ty, 0);
18331eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    llvm::Constant *GV = CreateRuntimeVariable(Ty,
18349d4a15fd3b85434c43ea27562793de63a793321aChris Lattner                                           "__CFConstantStringClassReference");
18353e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar    // Decay array -> ptr
18363e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar    CFConstantStringClassRef =
1837a5c04344fa70d6eec34344760c1fe511e16f2d76Jay Foad      llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
1838c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  }
18391eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1840e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson  QualType CFTy = getContext().getCFConstantStringType();
18413e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar
18422acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::StructType *STy =
1843e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson    cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1844e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson
18451d236ab930816f5da27bade92904914c44b73b4cBenjamin Kramer  llvm::Constant *Fields[4];
184644b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor
1847c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  // Class pointer.
18485add6835b0c6b0f67e19fd5366825d3e41eb0dcfAnders Carlsson  Fields[0] = CFConstantStringClassRef;
18491eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1850c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  // Flags.
18512acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
18521eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
18535add6835b0c6b0f67e19fd5366825d3e41eb0dcfAnders Carlsson    llvm::ConstantInt::get(Ty, 0x07C8);
18545add6835b0c6b0f67e19fd5366825d3e41eb0dcfAnders Carlsson
1855c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  // String pointer.
1856ff8f9ec8336c62b5e3504e2a394f4b25c0cb1963Chris Lattner  llvm::Constant *C = llvm::ConstantDataArray::getString(VMContext,
1857ff8f9ec8336c62b5e3504e2a394f4b25c0cb1963Chris Lattner                                                         Entry.getKey());
1858a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar
185995b851e55c328af4b69da7bfc1124bf258c0ffe5Chris Lattner  llvm::GlobalValue::LinkageTypes Linkage;
18601bf7a3fcc4e2ad30688f7b0db464ad1ccabe77e2Bill Wendling  if (isUTF16)
1861278b9f06933c385ffbccc15f8491787470cb4a1bChris Lattner    // FIXME: why do utf strings get "_" labels instead of "L" labels?
186295b851e55c328af4b69da7bfc1124bf258c0ffe5Chris Lattner    Linkage = llvm::GlobalValue::InternalLinkage;
18631bf7a3fcc4e2ad30688f7b0db464ad1ccabe77e2Bill Wendling  else
1864584acf2ded2c18a18d6da0e1c01f5859a384d99fRafael Espindola    // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error
1865584acf2ded2c18a18d6da0e1c01f5859a384d99fRafael Espindola    // when using private linkage. It is not clear if this is a bug in ld
1866584acf2ded2c18a18d6da0e1c01f5859a384d99fRafael Espindola    // or a reasonable new restriction.
1867dc0f137295bc7ec5b231ff1842388f149f43c0c8Rafael Espindola    Linkage = llvm::GlobalValue::LinkerPrivateLinkage;
1868278b9f06933c385ffbccc15f8491787470cb4a1bChris Lattner
18691bf7a3fcc4e2ad30688f7b0db464ad1ccabe77e2Bill Wendling  // Note: -fwritable-strings doesn't make the backing store strings of
18701bf7a3fcc4e2ad30688f7b0db464ad1ccabe77e2Bill Wendling  // CFStrings writable. (See <rdar://problem/10657500>)
18711eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  llvm::GlobalVariable *GV =
18721bf7a3fcc4e2ad30688f7b0db464ad1ccabe77e2Bill Wendling    new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
18731bf7a3fcc4e2ad30688f7b0db464ad1ccabe77e2Bill Wendling                             Linkage, C, ".str");
1874b266a1fce09ab4ee7033268199509aacfbef056aRafael Espindola  GV->setUnnamedAddr(true);
1875a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar  if (isUTF16) {
18764da244c23d6093adbbbc41654aa5c5111b38f431Ken Dyck    CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
18774da244c23d6093adbbbc41654aa5c5111b38f431Ken Dyck    GV->setAlignment(Align.getQuantity());
1878f7e903d7a30891083420c07ebeed281726a101d6Daniel Dunbar  } else {
1879f7e903d7a30891083420c07ebeed281726a101d6Daniel Dunbar    CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
1880f7e903d7a30891083420c07ebeed281726a101d6Daniel Dunbar    GV->setAlignment(Align.getQuantity());
1881a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar  }
1882a5c04344fa70d6eec34344760c1fe511e16f2d76Jay Foad  Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
18835add6835b0c6b0f67e19fd5366825d3e41eb0dcfAnders Carlsson
1884c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  // String length.
1885c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  Ty = getTypes().ConvertType(getContext().LongTy);
18865add6835b0c6b0f67e19fd5366825d3e41eb0dcfAnders Carlsson  Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
18871eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1888c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  // The struct.
188908e252425ca2cbdc44ba65d9a657ed5398014e36Owen Anderson  C = llvm::ConstantStruct::get(STy, Fields);
18901eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
18911eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                llvm::GlobalVariable::PrivateLinkage, C,
189295b851e55c328af4b69da7bfc1124bf258c0ffe5Chris Lattner                                "_unnamed_cfstring_");
1893bcfd1f55bfbb3e5944cd5e03d07b343e280838c4Douglas Gregor  if (const char *Sect = getContext().getTargetInfo().getCFStringSection())
18948e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar    GV->setSection(Sect);
18951d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  Entry.setValue(GV);
18961eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
18970c67829763b98bc670062b553897a851fab17401Anders Carlsson  return GV;
1898c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson}
189945e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner
190045c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregorstatic RecordDecl *
190145c4ea75b235de94f44bf96843624e6a559e4c00Douglas GregorCreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
190245c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                 DeclContext *DC, IdentifierInfo *Id) {
190345c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor  SourceLocation Loc;
190445c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor  if (Ctx.getLangOptions().CPlusPlus)
190545c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
190645c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor  else
190745c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
190845c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor}
190945c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor
191033e982bf782d851bfe5767acb1336fcf3419ac6bFariborz Jahanianllvm::Constant *
19114c73307c74764ba99e1379677fe92af72f676531Fariborz JahanianCodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
19122bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  unsigned StringLength = 0;
19132bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  llvm::StringMapEntry<llvm::Constant*> &Entry =
1914cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian    GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
19152bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
19162bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  if (llvm::Constant *C = Entry.getValue())
19172bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian    return C;
19182bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
19192bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  llvm::Constant *Zero =
19202bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
19212bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  llvm::Constant *Zeros[] = { Zero, Zero };
19222bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
1923ec951e0c2fc0db00c36bc60c900331dde32c1b43Fariborz Jahanian  // If we don't already have it, get _NSConstantStringClassReference.
19244c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian  if (!ConstantStringClassRef) {
19254c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian    std::string StringClass(getLangOptions().ObjCConstantStringClass);
19262acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner    llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
19274c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian    llvm::Constant *GV;
19286f40e2244b0590f144c5ceee07981a962fbbc72eFariborz Jahanian    if (Features.ObjCNonFragileABI) {
192925dba5d294364fa8339091e4d9e6a8f5db008377Fariborz Jahanian      std::string str =
193025dba5d294364fa8339091e4d9e6a8f5db008377Fariborz Jahanian        StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
193125dba5d294364fa8339091e4d9e6a8f5db008377Fariborz Jahanian                            : "OBJC_CLASS_$_" + StringClass;
19326f40e2244b0590f144c5ceee07981a962fbbc72eFariborz Jahanian      GV = getObjCRuntime().GetClassGlobal(str);
19336f40e2244b0590f144c5ceee07981a962fbbc72eFariborz Jahanian      // Make sure the result is of the correct type.
19342acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner      llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
19356f40e2244b0590f144c5ceee07981a962fbbc72eFariborz Jahanian      ConstantStringClassRef =
19366f40e2244b0590f144c5ceee07981a962fbbc72eFariborz Jahanian        llvm::ConstantExpr::getBitCast(GV, PTy);
19376f40e2244b0590f144c5ceee07981a962fbbc72eFariborz Jahanian    } else {
193825dba5d294364fa8339091e4d9e6a8f5db008377Fariborz Jahanian      std::string str =
193925dba5d294364fa8339091e4d9e6a8f5db008377Fariborz Jahanian        StringClass.empty() ? "_NSConstantStringClassReference"
194025dba5d294364fa8339091e4d9e6a8f5db008377Fariborz Jahanian                            : "_" + StringClass + "ClassReference";
19412acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner      llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
194225dba5d294364fa8339091e4d9e6a8f5db008377Fariborz Jahanian      GV = CreateRuntimeVariable(PTy, str);
19436f40e2244b0590f144c5ceee07981a962fbbc72eFariborz Jahanian      // Decay array -> ptr
19446f40e2244b0590f144c5ceee07981a962fbbc72eFariborz Jahanian      ConstantStringClassRef =
1945a5c04344fa70d6eec34344760c1fe511e16f2d76Jay Foad        llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
19464c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian    }
19472bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  }
194845c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor
194945c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor  if (!NSConstantStringType) {
195045c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    // Construct the type for a constant NSString.
195145c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
195245c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                                     Context.getTranslationUnitDecl(),
195345c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                                   &Context.Idents.get("__builtin_NSString"));
195445c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    D->startDefinition();
195545c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor
195645c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    QualType FieldTypes[3];
195745c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor
195845c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    // const int *isa;
195945c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
196045c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    // const char *str;
196145c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
196245c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    // unsigned int length;
196345c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    FieldTypes[2] = Context.UnsignedIntTy;
196445c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor
196545c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    // Create fields
196645c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    for (unsigned i = 0; i < 3; ++i) {
196745c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor      FieldDecl *Field = FieldDecl::Create(Context, D,
196845c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                                           SourceLocation(),
196945c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                                           SourceLocation(), 0,
197045c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                                           FieldTypes[i], /*TInfo=*/0,
197145c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                                           /*BitWidth=*/0,
197245c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                                           /*Mutable=*/false,
197345c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                                           /*HasInit=*/false);
197445c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor      Field->setAccess(AS_public);
197545c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor      D->addDecl(Field);
197645c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    }
197745c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor
197845c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    D->completeDefinition();
197945c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    QualType NSTy = Context.getTagDeclType(D);
198045c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
198145c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor  }
19822bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
19831d236ab930816f5da27bade92904914c44b73b4cBenjamin Kramer  llvm::Constant *Fields[3];
19842bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
19852bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  // Class pointer.
19864c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian  Fields[0] = ConstantStringClassRef;
19872bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
19882bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  // String pointer.
1989ff8f9ec8336c62b5e3504e2a394f4b25c0cb1963Chris Lattner  llvm::Constant *C =
1990ff8f9ec8336c62b5e3504e2a394f4b25c0cb1963Chris Lattner    llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
19912bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
19922bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  llvm::GlobalValue::LinkageTypes Linkage;
19932bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  bool isConstant;
1994cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian  Linkage = llvm::GlobalValue::PrivateLinkage;
1995cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian  isConstant = !Features.WritableStrings;
19962bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
19972bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  llvm::GlobalVariable *GV =
19982bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
19992bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian                           ".str");
2000803d307a5385059b1a84dfe9706ab158c80a20dcRafael Espindola  GV->setUnnamedAddr(true);
2001cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian  CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2002cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian  GV->setAlignment(Align.getQuantity());
2003a5c04344fa70d6eec34344760c1fe511e16f2d76Jay Foad  Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
20042bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
20052bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  // String length.
20062acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
20072bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
20082bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
20092bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  // The struct.
201045c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor  C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
20112bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
20122bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian                                llvm::GlobalVariable::PrivateLinkage, C,
20132bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian                                "_unnamed_nsstring_");
20142bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  // FIXME. Fix section.
2015ec951e0c2fc0db00c36bc60c900331dde32c1b43Fariborz Jahanian  if (const char *Sect =
2016ec951e0c2fc0db00c36bc60c900331dde32c1b43Fariborz Jahanian        Features.ObjCNonFragileABI
2017bcfd1f55bfbb3e5944cd5e03d07b343e280838c4Douglas Gregor          ? getContext().getTargetInfo().getNSStringNonFragileABISection()
2018bcfd1f55bfbb3e5944cd5e03d07b343e280838c4Douglas Gregor          : getContext().getTargetInfo().getNSStringSection())
20192bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian    GV->setSection(Sect);
20202bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  Entry.setValue(GV);
20212bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
20222bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  return GV;
202333e982bf782d851bfe5767acb1336fcf3419ac6bFariborz Jahanian}
202433e982bf782d851bfe5767acb1336fcf3419ac6bFariborz Jahanian
20250815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas GregorQualType CodeGenModule::getObjCFastEnumerationStateType() {
20260815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor  if (ObjCFastEnumerationStateType.isNull()) {
20270815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
20280815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                                     Context.getTranslationUnitDecl(),
20290815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                      &Context.Idents.get("__objcFastEnumerationState"));
20300815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    D->startDefinition();
20310815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor
20320815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    QualType FieldTypes[] = {
20330815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor      Context.UnsignedLongTy,
20340815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor      Context.getPointerType(Context.getObjCIdType()),
20350815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor      Context.getPointerType(Context.UnsignedLongTy),
20360815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor      Context.getConstantArrayType(Context.UnsignedLongTy,
20370815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                           llvm::APInt(32, 5), ArrayType::Normal, 0)
20380815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    };
20390815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor
20400815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    for (size_t i = 0; i < 4; ++i) {
20410815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor      FieldDecl *Field = FieldDecl::Create(Context,
20420815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                                           D,
20430815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                                           SourceLocation(),
20440815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                                           SourceLocation(), 0,
20450815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                                           FieldTypes[i], /*TInfo=*/0,
20460815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                                           /*BitWidth=*/0,
20470815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                                           /*Mutable=*/false,
20480815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                                           /*HasInit=*/false);
20490815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor      Field->setAccess(AS_public);
20500815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor      D->addDecl(Field);
20510815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    }
20520815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor
20530815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    D->completeDefinition();
20540815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    ObjCFastEnumerationStateType = Context.getTagDeclType(D);
20550815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor  }
20560815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor
20570815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor  return ObjCFastEnumerationStateType;
20580815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor}
20590815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor
20606143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// GetStringForStringLiteral - Return the appropriate bytes for a
20611e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar/// string literal, properly padded to match the literal type.
20626143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbarstd::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
206364f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  assert((E->isAscii() || E->isUTF8())
206464f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman         && "Use GetConstantArrayFromStringLiteral for wide strings");
20653b8037a8c6f462e51f75c82b3d7fe1b8dbcf06c0Ken Dyck  const ASTContext &Context = getContext();
20661e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar  const ConstantArrayType *CAT =
20673b8037a8c6f462e51f75c82b3d7fe1b8dbcf06c0Ken Dyck    Context.getAsConstantArrayType(E->getType());
20681e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar  assert(CAT && "String isn't pointer or array!");
20691eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2070dbb1ecc32ca122b07b7c98fd0a8f6f53985adaccChris Lattner  // Resize the string to the right size.
20711e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar  uint64_t RealLen = CAT->getSize().getZExtValue();
20721eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
20732f4eaef37476ae6891ede8ba215d0f6fd093629bBenjamin Kramer  std::string Str = E->getString().str();
20741e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar  Str.resize(RealLen, '\0');
20751eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
20761e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar  return Str;
20771e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar}
20781e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar
207964f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedmanllvm::Constant *
208064f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli FriedmanCodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
208164f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  assert(!E->getType()->isPointerType() && "Strings are always arrays");
208264f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman
208364f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  // Don't emit it as the address of the string, emit the string data itself
208464f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  // as an inline array.
208564f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  if (E->getCharByteWidth()==1) {
2086ff8f9ec8336c62b5e3504e2a394f4b25c0cb1963Chris Lattner    return llvm::ConstantDataArray::getString(VMContext,
208764f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman                                    GetStringForStringLiteral(E), false);
208864f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  }
2089ff8f9ec8336c62b5e3504e2a394f4b25c0cb1963Chris Lattner
2090ff8f9ec8336c62b5e3504e2a394f4b25c0cb1963Chris Lattner  llvm::ArrayType *AType =
2091ff8f9ec8336c62b5e3504e2a394f4b25c0cb1963Chris Lattner    cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
2092ff8f9ec8336c62b5e3504e2a394f4b25c0cb1963Chris Lattner  llvm::Type *ElemTy = AType->getElementType();
2093ff8f9ec8336c62b5e3504e2a394f4b25c0cb1963Chris Lattner  unsigned NumElements = AType->getNumElements();
2094ff8f9ec8336c62b5e3504e2a394f4b25c0cb1963Chris Lattner  std::vector<llvm::Constant*> Elts;
2095ff8f9ec8336c62b5e3504e2a394f4b25c0cb1963Chris Lattner  Elts.reserve(NumElements);
2096ff8f9ec8336c62b5e3504e2a394f4b25c0cb1963Chris Lattner
2097ff8f9ec8336c62b5e3504e2a394f4b25c0cb1963Chris Lattner  for(unsigned i=0;i<E->getLength();++i) {
2098ff8f9ec8336c62b5e3504e2a394f4b25c0cb1963Chris Lattner    unsigned value = E->getCodeUnit(i);
2099ff8f9ec8336c62b5e3504e2a394f4b25c0cb1963Chris Lattner    llvm::Constant *C = llvm::ConstantInt::get(ElemTy,value,false);
2100ff8f9ec8336c62b5e3504e2a394f4b25c0cb1963Chris Lattner    Elts.push_back(C);
2101ff8f9ec8336c62b5e3504e2a394f4b25c0cb1963Chris Lattner  }
2102ff8f9ec8336c62b5e3504e2a394f4b25c0cb1963Chris Lattner  for(unsigned i=E->getLength();i<NumElements;++i) {
2103ff8f9ec8336c62b5e3504e2a394f4b25c0cb1963Chris Lattner    llvm::Constant *C = llvm::ConstantInt::get(ElemTy,0,false);
2104ff8f9ec8336c62b5e3504e2a394f4b25c0cb1963Chris Lattner    Elts.push_back(C);
2105ff8f9ec8336c62b5e3504e2a394f4b25c0cb1963Chris Lattner  }
2106ff8f9ec8336c62b5e3504e2a394f4b25c0cb1963Chris Lattner
2107ff8f9ec8336c62b5e3504e2a394f4b25c0cb1963Chris Lattner  return llvm::ConstantArray::get(AType, Elts);
210864f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman}
210964f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman
21106143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
21116143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// constant array for the given string literal.
21126143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbarllvm::Constant *
21136143293fa4366ee95d7e47e61bd030a34bf68b55Daniel DunbarCodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
21146143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar  // FIXME: This can be more efficient.
21157eb79c1010c8d30b852768bec96e81cd3e6def2eEli Friedman  // FIXME: We shouldn't need to bitcast the constant in the wide string case.
2116a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall  CharUnits Align = getContext().getTypeAlignInChars(S->getType());
211764f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  if (S->isAscii() || S->isUTF8()) {
211864f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman    return GetAddrOfConstantString(GetStringForStringLiteral(S),
211964f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman                                   /* GlobalName */ 0,
212064f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman                                   Align.getQuantity());
21217eb79c1010c8d30b852768bec96e81cd3e6def2eEli Friedman  }
212264f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman
212364f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  // FIXME: the following does not memoize wide strings
212464f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
212564f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  llvm::GlobalVariable *GV =
212664f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman    new llvm::GlobalVariable(getModule(),C->getType(),
212764f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman                             !Features.WritableStrings,
212864f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman                             llvm::GlobalValue::PrivateLinkage,
212964f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman                             C,".str");
21307d6a7c004361c45a463874a58da28d9f3c35f2e6Seth Cantrell
213164f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  GV->setAlignment(Align.getQuantity());
213264f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  GV->setUnnamedAddr(true);
213364f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman
213464f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  return GV;
21356143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar}
21366143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar
2137eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
2138eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner/// array for the given ObjCEncodeExpr node.
2139eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattnerllvm::Constant *
2140eaf2bb89eb2aad3b80673de30febe52df43c10ecChris LattnerCodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
2141eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner  std::string Str;
2142eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner  getContext().getObjCEncodingForType(E->getEncodedType(), Str);
2143a210f350fa78c263caa26e0f999cce85bb235309Eli Friedman
2144a210f350fa78c263caa26e0f999cce85bb235309Eli Friedman  return GetAddrOfConstantCString(Str);
2145eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner}
2146eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner
2147eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner
2148a7ad98ff0919d6a24ea7c46634ea29bea551c1a0Chris Lattner/// GenerateWritableString -- Creates storage for a string literal.
2149a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCallstatic llvm::GlobalVariable *GenerateStringLiteral(StringRef str,
215045e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner                                             bool constant,
21515fabf9dbee29464bcd06cd09f8e569d1b850f948Daniel Dunbar                                             CodeGenModule &CGM,
2152a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall                                             const char *GlobalName,
2153a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall                                             unsigned Alignment) {
21546143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar  // Create Constant for this string literal. Don't add a '\0'.
21550032b2781b4deb131f8c9b7968f2030bf2489cddOwen Anderson  llvm::Constant *C =
2156ff8f9ec8336c62b5e3504e2a394f4b25c0cb1963Chris Lattner      llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false);
21571eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
215845e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner  // Create a global variable for this string
21591257bc6ee76b931e3f8e51a88298b95379963d24Rafael Espindola  llvm::GlobalVariable *GV =
21601257bc6ee76b931e3f8e51a88298b95379963d24Rafael Espindola    new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
21611257bc6ee76b931e3f8e51a88298b95379963d24Rafael Espindola                             llvm::GlobalValue::PrivateLinkage,
21621257bc6ee76b931e3f8e51a88298b95379963d24Rafael Espindola                             C, GlobalName);
2163a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall  GV->setAlignment(Alignment);
21641257bc6ee76b931e3f8e51a88298b95379963d24Rafael Espindola  GV->setUnnamedAddr(true);
21651257bc6ee76b931e3f8e51a88298b95379963d24Rafael Espindola  return GV;
216645e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner}
216745e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner
21686143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// GetAddrOfConstantString - Returns a pointer to a character array
21696143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// containing the literal. This contents are exactly that of the
21706143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// given string, i.e. it will not be null terminated automatically;
21716143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// see GetAddrOfConstantCString. Note that whether the result is
21726143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// actually a pointer to an LLVM constant depends on
21736143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// Feature.WriteableStrings.
21746143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar///
21756143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// The result has pointer to array type.
21765f9e272e632e951b1efe824cd16acb4d96077930Chris Lattnerllvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str,
2177a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall                                                       const char *GlobalName,
2178a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall                                                       unsigned Alignment) {
21798e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar  bool IsConstant = !Features.WritableStrings;
21808e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar
21818e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar  // Get the default prefix if a name wasn't specified.
21828e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar  if (!GlobalName)
218395b851e55c328af4b69da7bfc1124bf258c0ffe5Chris Lattner    GlobalName = ".str";
21848e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar
21858e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar  // Don't share any string literals if strings aren't constant.
21868e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar  if (!IsConstant)
2187a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall    return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment);
21881eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2189a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall  llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
21909de4342ef79a18c706e46bc23f8f579f5add2375Benjamin Kramer    ConstantStringMap.GetOrCreateValue(Str);
219145e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner
2192a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall  if (llvm::GlobalVariable *GV = Entry.getValue()) {
2193a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall    if (Alignment > GV->getAlignment()) {
2194a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall      GV->setAlignment(Alignment);
2195a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall    }
2196a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall    return GV;
2197a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall  }
219845e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner
219945e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner  // Create a global variable for this.
2200a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall  llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName, Alignment);
2201a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall  Entry.setValue(GV);
2202a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall  return GV;
220345e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner}
22046143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar
22056143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// GetAddrOfConstantCString - Returns a pointer to a character
22069de4342ef79a18c706e46bc23f8f579f5add2375Benjamin Kramer/// array containing the literal and a terminating '\0'
22076143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// character. The result has pointer to array type.
22089de4342ef79a18c706e46bc23f8f579f5add2375Benjamin Kramerllvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
2209a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall                                                        const char *GlobalName,
2210a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall                                                        unsigned Alignment) {
22115f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  StringRef StrWithNull(Str.c_str(), Str.size() + 1);
2212a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall  return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment);
22136143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar}
221441071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
2215af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar/// EmitObjCPropertyImplementations - Emit information for synthesized
2216af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar/// properties for an implementation.
22171eb4433ac451dc16f4133a88af2d002ac26c58efMike Stumpvoid CodeGenModule::EmitObjCPropertyImplementations(const
2218af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar                                                    ObjCImplementationDecl *D) {
22191eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  for (ObjCImplementationDecl::propimpl_iterator
222017945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis         i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
2221af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    ObjCPropertyImplDecl *PID = *i;
22221eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2223af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    // Dynamic is just for type-checking.
2224af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
2225af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      ObjCPropertyDecl *PD = PID->getPropertyDecl();
2226af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar
2227af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      // Determine which methods need to be implemented, some may have
2228af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      // been overridden. Note that ::isSynthesized is not the method
2229af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      // we want, that just indicates if the decl came from a
2230af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      // property. What we want to know is if the method is defined in
2231af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      // this implementation.
223217945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis      if (!D->getInstanceMethod(PD->getGetterName()))
2233fef30b55230064d334a669a065a1c9acdb87cdfeFariborz Jahanian        CodeGenFunction(*this).GenerateObjCGetter(
2234fef30b55230064d334a669a065a1c9acdb87cdfeFariborz Jahanian                                 const_cast<ObjCImplementationDecl *>(D), PID);
2235af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      if (!PD->isReadOnly() &&
223617945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis          !D->getInstanceMethod(PD->getSetterName()))
2237fef30b55230064d334a669a065a1c9acdb87cdfeFariborz Jahanian        CodeGenFunction(*this).GenerateObjCSetter(
2238fef30b55230064d334a669a065a1c9acdb87cdfeFariborz Jahanian                                 const_cast<ObjCImplementationDecl *>(D), PID);
2239af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    }
2240af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar  }
2241af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar}
2242af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar
2243e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCallstatic bool needsDestructMethod(ObjCImplementationDecl *impl) {
2244db8264e4c5ffd7af6fbad4ca4306bd382bb02691Jordy Rose  const ObjCInterfaceDecl *iface = impl->getClassInterface();
2245db8264e4c5ffd7af6fbad4ca4306bd382bb02691Jordy Rose  for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
2246e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall       ivar; ivar = ivar->getNextIvar())
2247e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall    if (ivar->getType().isDestructedType())
2248e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall      return true;
2249e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall
2250e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  return false;
2251e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall}
2252e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall
2253109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian/// EmitObjCIvarInitializations - Emit information for ivar initialization
2254109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian/// for an implementation.
2255109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanianvoid CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
2256e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  // We might need a .cxx_destruct even if we don't have any ivar initializers.
2257e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  if (needsDestructMethod(D)) {
2258e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall    IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
2259e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall    Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2260e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall    ObjCMethodDecl *DTORMethod =
2261e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall      ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
226275cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis                             cxxSelector, getContext().VoidTy, 0, D,
226375cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis                             /*isInstance=*/true, /*isVariadic=*/false,
226475cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis                          /*isSynthesized=*/true, /*isImplicitlyDeclared=*/true,
226575cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis                             /*isDefined=*/false, ObjCMethodDecl::Required);
2266e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall    D->addInstanceMethod(DTORMethod);
2267e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall    CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
2268f85e193739c953358c865005855253af4f68a497John McCall    D->setHasCXXStructors(true);
2269e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  }
2270e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall
2271e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  // If the implementation doesn't have any ivar initializers, we don't need
2272e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  // a .cxx_construct.
2273827bbcc8a9115782693b21030a45378abe5c1862David Chisnall  if (D->getNumIvarInitializers() == 0)
2274109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian    return;
2275109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian
2276e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
2277e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2278109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian  // The constructor returns 'self'.
2279109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian  ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
2280109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian                                                D->getLocation(),
228111d77169555480ee0a04c6e5bc390d8fde41175dArgyrios Kyrtzidis                                                D->getLocation(),
228211d77169555480ee0a04c6e5bc390d8fde41175dArgyrios Kyrtzidis                                                cxxSelector,
2283109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian                                                getContext().getObjCIdType(), 0,
228475cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis                                                D, /*isInstance=*/true,
228575cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis                                                /*isVariadic=*/false,
228675cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis                                                /*isSynthesized=*/true,
228775cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis                                                /*isImplicitlyDeclared=*/true,
228875cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis                                                /*isDefined=*/false,
2289109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian                                                ObjCMethodDecl::Required);
2290109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian  D->addInstanceMethod(CTORMethod);
2291109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian  CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
2292f85e193739c953358c865005855253af4f68a497John McCall  D->setHasCXXStructors(true);
2293109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian}
2294109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian
229591e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson/// EmitNamespace - Emit all declarations in a namespace.
2296984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlssonvoid CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
229717945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis  for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
2298984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlsson       I != E; ++I)
2299984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlsson    EmitTopLevelDecl(*I);
2300984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlsson}
2301984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlsson
230291e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson// EmitLinkageSpec - Emit all declarations in a linkage spec.
230391e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlssonvoid CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
2304f976be8a63f9e0d3bd50e33dadef02c3c9921747Eli Friedman  if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
2305f976be8a63f9e0d3bd50e33dadef02c3c9921747Eli Friedman      LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
230691e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson    ErrorUnsupported(LSD, "linkage spec");
230791e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson    return;
230891e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson  }
230991e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson
231017945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis  for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
231191e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson       I != E; ++I)
231291e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson    EmitTopLevelDecl(*I);
231391e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson}
231491e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson
231541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar/// EmitTopLevelDecl - Emit code for a single top level declaration.
231641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbarvoid CodeGenModule::EmitTopLevelDecl(Decl *D) {
231741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  // If an error has occurred, stop code generation, but continue
231841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  // parsing and semantic analysis (to ensure all warnings and errors
231941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  // are emitted).
232041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  if (Diags.hasErrorOccurred())
232141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    return;
232241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
232316e8be2ac532358d4e413fdfa2643b1876edda78Douglas Gregor  // Ignore dependent declarations.
232416e8be2ac532358d4e413fdfa2643b1876edda78Douglas Gregor  if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
232516e8be2ac532358d4e413fdfa2643b1876edda78Douglas Gregor    return;
23261eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
232741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  switch (D->getKind()) {
2328293361afd4199c92aabff9267fddea890943c586Anders Carlsson  case Decl::CXXConversion:
23292b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson  case Decl::CXXMethod:
233041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::Function:
233116e8be2ac532358d4e413fdfa2643b1876edda78Douglas Gregor    // Skip function templates
23328387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichet    if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
23338387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichet        cast<FunctionDecl>(D)->isLateTemplateParsed())
233416e8be2ac532358d4e413fdfa2643b1876edda78Douglas Gregor      return;
23351eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2336555b4bb2749aea2ec8e2adc351a71ec1cb9bdc33Anders Carlsson    EmitGlobal(cast<FunctionDecl>(D));
2337555b4bb2749aea2ec8e2adc351a71ec1cb9bdc33Anders Carlsson    break;
2338555b4bb2749aea2ec8e2adc351a71ec1cb9bdc33Anders Carlsson
233941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::Var:
2340555b4bb2749aea2ec8e2adc351a71ec1cb9bdc33Anders Carlsson    EmitGlobal(cast<VarDecl>(D));
234141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
234241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
234326fbc72b33bdbd20b0145bf117c64d373f8051e3John McCall  // Indirect fields from global anonymous structs and unions can be
234426fbc72b33bdbd20b0145bf117c64d373f8051e3John McCall  // ignored; only the actual variable requires IR gen support.
234526fbc72b33bdbd20b0145bf117c64d373f8051e3John McCall  case Decl::IndirectField:
234626fbc72b33bdbd20b0145bf117c64d373f8051e3John McCall    break;
234726fbc72b33bdbd20b0145bf117c64d373f8051e3John McCall
234895d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson  // C++ Decls
234941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::Namespace:
2350984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlsson    EmitNamespace(cast<NamespaceDecl>(D));
235141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
23529cfbe48a7a20a217fdb2920b29b67ae7941cb116Douglas Gregor    // No code generation needed.
23539d0c6613ec040ad8d952556be909232a7f25dedeJohn McCall  case Decl::UsingShadow:
23549cfbe48a7a20a217fdb2920b29b67ae7941cb116Douglas Gregor  case Decl::Using:
2355dd9967a6374c9a44be4af02aaeee340ffb82848fDouglas Gregor  case Decl::UsingDirective:
2356127102b5196ffe04bdb70fd553fe62c265ab10a9Douglas Gregor  case Decl::ClassTemplate:
2357127102b5196ffe04bdb70fd553fe62c265ab10a9Douglas Gregor  case Decl::FunctionTemplate:
23583e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard Smith  case Decl::TypeAliasTemplate:
2359018837b081bd1a725bae1c020eb1649975b04d67Anders Carlsson  case Decl::NamespaceAlias:
23606a576ab708d3aa7d40e5d867ab1de5d3cb507553Douglas Gregor  case Decl::Block:
236115de72cf580840c61e5704c2f8a2b56f9d0638e1Douglas Gregor  case Decl::Import:
23629cfbe48a7a20a217fdb2920b29b67ae7941cb116Douglas Gregor    break;
236395d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson  case Decl::CXXConstructor:
23641fe598c026dc03fddbd65efb8119eb1afd9b1520Anders Carlsson    // Skip function templates
23658387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichet    if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
23668387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichet        cast<FunctionDecl>(D)->isLateTemplateParsed())
23671fe598c026dc03fddbd65efb8119eb1afd9b1520Anders Carlsson      return;
23681fe598c026dc03fddbd65efb8119eb1afd9b1520Anders Carlsson
236995d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson    EmitCXXConstructors(cast<CXXConstructorDecl>(D));
237095d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson    break;
237127ae53665f8b00fe4ba21da0fa79a4ce6e0b6cd5Anders Carlsson  case Decl::CXXDestructor:
23728387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichet    if (cast<FunctionDecl>(D)->isLateTemplateParsed())
23738387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichet      return;
237427ae53665f8b00fe4ba21da0fa79a4ce6e0b6cd5Anders Carlsson    EmitCXXDestructors(cast<CXXDestructorDecl>(D));
237527ae53665f8b00fe4ba21da0fa79a4ce6e0b6cd5Anders Carlsson    break;
237636674d2978eb53962218ac67bb4d352cc287ea05Anders Carlsson
237736674d2978eb53962218ac67bb4d352cc287ea05Anders Carlsson  case Decl::StaticAssert:
237836674d2978eb53962218ac67bb4d352cc287ea05Anders Carlsson    // Nothing to do.
237936674d2978eb53962218ac67bb4d352cc287ea05Anders Carlsson    break;
238036674d2978eb53962218ac67bb4d352cc287ea05Anders Carlsson
238195d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson  // Objective-C Decls
23821eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
238338e24c782c17b6058bf61d635747bbde19fb1bc7Fariborz Jahanian  // Forward declarations, no (immediate) code generation.
2384b31cb7f1752ea011fd06ac9574ce24667d11cbdbFariborz Jahanian  case Decl::ObjCInterface:
238541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
2386000835d0b04345c0014c603fe6339b3bc154050eFariborz Jahanian
2387baf101d1f96b4e41c9f2797875329840514f54f1Chris Lattner  case Decl::ObjCCategory: {
2388baf101d1f96b4e41c9f2797875329840514f54f1Chris Lattner    ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D);
2389baf101d1f96b4e41c9f2797875329840514f54f1Chris Lattner    if (CD->IsClassExtension() && CD->hasSynthBitfield())
2390baf101d1f96b4e41c9f2797875329840514f54f1Chris Lattner      Context.ResetObjCLayout(CD->getClassInterface());
2391baf101d1f96b4e41c9f2797875329840514f54f1Chris Lattner    break;
2392baf101d1f96b4e41c9f2797875329840514f54f1Chris Lattner  }
2393285d0dba947b7c9960eaa88e8c4fced0398d4319Chris Lattner
2394bd9482d859a74bf2c45ef8b8aedec61c0e1c8374Douglas Gregor  case Decl::ObjCProtocol: {
2395bd9482d859a74bf2c45ef8b8aedec61c0e1c8374Douglas Gregor    ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(D);
2396bd9482d859a74bf2c45ef8b8aedec61c0e1c8374Douglas Gregor    if (Proto->isThisDeclarationADefinition())
2397bd9482d859a74bf2c45ef8b8aedec61c0e1c8374Douglas Gregor      ObjCRuntime->GenerateProtocol(Proto);
239841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
2399bd9482d859a74bf2c45ef8b8aedec61c0e1c8374Douglas Gregor  }
2400bd9482d859a74bf2c45ef8b8aedec61c0e1c8374Douglas Gregor
240141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::ObjCCategoryImpl:
2402af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    // Categories have properties but don't support synthesize so we
2403af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    // can ignore them here.
2404e926523105dd2604ccd5c101605dea43c5269965Peter Collingbourne    ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
240541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
240641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
2407af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar  case Decl::ObjCImplementation: {
2408af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
2409000835d0b04345c0014c603fe6339b3bc154050eFariborz Jahanian    if (Features.ObjCNonFragileABI2 && OMD->hasSynthBitfield())
2410000835d0b04345c0014c603fe6339b3bc154050eFariborz Jahanian      Context.ResetObjCLayout(OMD->getClassInterface());
2411af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    EmitObjCPropertyImplementations(OMD);
2412109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian    EmitObjCIvarInitializations(OMD);
2413e926523105dd2604ccd5c101605dea43c5269965Peter Collingbourne    ObjCRuntime->GenerateClass(OMD);
241441071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
24151eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  }
241641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::ObjCMethod: {
241741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
241841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    // If this is not a prototype, emit the body.
24196fb0aee4f9dc261bbec72e1283ad8dc0557a6d96Argyrios Kyrtzidis    if (OMD->getBody())
242041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar      CodeGenFunction(*this).GenerateObjCMethod(OMD);
242141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
242241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  }
24231eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  case Decl::ObjCCompatibleAlias:
242429254f4dd114fe2dd5c4e7a261ebea941973ad3dDavid Chisnall    ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
242541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
242641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
242791e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson  case Decl::LinkageSpec:
242891e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson    EmitLinkageSpec(cast<LinkageSpecDecl>(D));
242941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
243041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
243141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::FileScopeAsm: {
243241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
24335f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner    StringRef AsmString = AD->getAsmString()->getString();
24341eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
243541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    const std::string &S = getModule().getModuleInlineAsm();
243641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    if (S.empty())
243741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar      getModule().setModuleInlineAsm(AsmString);
24389f5bff086cad25c15b4deb8a7763786097aadccdChris Lattner    else if (*--S.end() == '\n')
24399f5bff086cad25c15b4deb8a7763786097aadccdChris Lattner      getModule().setModuleInlineAsm(S + AsmString.str());
244041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    else
24418d04258483be6583f0865464234d014807a3e1ccBenjamin Kramer      getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
244241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
244341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  }
24441eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
24451eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  default:
2446f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump    // Make sure we handled everything we should, every other kind is a
2447f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump    // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
2448f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump    // function. Need to recode Decl::Kind to do that easily.
244941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    assert(isa<TypeDecl>(D) && "Unsupported decl kind");
245041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  }
245141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar}
2452744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2453744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// Turns the given pointer into a constant.
2454744016dde06fcffd50931e94a98c850f8b12cd87John McCallstatic llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
2455744016dde06fcffd50931e94a98c850f8b12cd87John McCall                                          const void *Ptr) {
2456744016dde06fcffd50931e94a98c850f8b12cd87John McCall  uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
24572acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
2458744016dde06fcffd50931e94a98c850f8b12cd87John McCall  return llvm::ConstantInt::get(i64, PtrInt);
2459744016dde06fcffd50931e94a98c850f8b12cd87John McCall}
2460744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2461744016dde06fcffd50931e94a98c850f8b12cd87John McCallstatic void EmitGlobalDeclMetadata(CodeGenModule &CGM,
2462744016dde06fcffd50931e94a98c850f8b12cd87John McCall                                   llvm::NamedMDNode *&GlobalMetadata,
2463744016dde06fcffd50931e94a98c850f8b12cd87John McCall                                   GlobalDecl D,
2464744016dde06fcffd50931e94a98c850f8b12cd87John McCall                                   llvm::GlobalValue *Addr) {
2465744016dde06fcffd50931e94a98c850f8b12cd87John McCall  if (!GlobalMetadata)
2466744016dde06fcffd50931e94a98c850f8b12cd87John McCall    GlobalMetadata =
2467744016dde06fcffd50931e94a98c850f8b12cd87John McCall      CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
2468744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2469744016dde06fcffd50931e94a98c850f8b12cd87John McCall  // TODO: should we report variant information for ctors/dtors?
2470744016dde06fcffd50931e94a98c850f8b12cd87John McCall  llvm::Value *Ops[] = {
2471744016dde06fcffd50931e94a98c850f8b12cd87John McCall    Addr,
2472744016dde06fcffd50931e94a98c850f8b12cd87John McCall    GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
2473744016dde06fcffd50931e94a98c850f8b12cd87John McCall  };
24746f141659cab11109d9931d92d0988f8850778de3Jay Foad  GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2475744016dde06fcffd50931e94a98c850f8b12cd87John McCall}
2476744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2477744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// Emits metadata nodes associating all the global values in the
2478744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// current module with the Decls they came from.  This is useful for
2479744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// projects using IR gen as a subroutine.
2480744016dde06fcffd50931e94a98c850f8b12cd87John McCall///
2481744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// Since there's currently no way to associate an MDNode directly
2482744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// with an llvm::GlobalValue, we create a global named metadata
2483744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// with the name 'clang.global.decl.ptrs'.
2484744016dde06fcffd50931e94a98c850f8b12cd87John McCallvoid CodeGenModule::EmitDeclMetadata() {
2485744016dde06fcffd50931e94a98c850f8b12cd87John McCall  llvm::NamedMDNode *GlobalMetadata = 0;
2486744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2487744016dde06fcffd50931e94a98c850f8b12cd87John McCall  // StaticLocalDeclMap
24885f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  for (llvm::DenseMap<GlobalDecl,StringRef>::iterator
2489744016dde06fcffd50931e94a98c850f8b12cd87John McCall         I = MangledDeclNames.begin(), E = MangledDeclNames.end();
2490744016dde06fcffd50931e94a98c850f8b12cd87John McCall       I != E; ++I) {
2491744016dde06fcffd50931e94a98c850f8b12cd87John McCall    llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
2492744016dde06fcffd50931e94a98c850f8b12cd87John McCall    EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
2493744016dde06fcffd50931e94a98c850f8b12cd87John McCall  }
2494744016dde06fcffd50931e94a98c850f8b12cd87John McCall}
2495744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2496744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// Emits metadata nodes for all the local variables in the current
2497744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// function.
2498744016dde06fcffd50931e94a98c850f8b12cd87John McCallvoid CodeGenFunction::EmitDeclMetadata() {
2499744016dde06fcffd50931e94a98c850f8b12cd87John McCall  if (LocalDeclMap.empty()) return;
2500744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2501744016dde06fcffd50931e94a98c850f8b12cd87John McCall  llvm::LLVMContext &Context = getLLVMContext();
2502744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2503744016dde06fcffd50931e94a98c850f8b12cd87John McCall  // Find the unique metadata ID for this name.
2504744016dde06fcffd50931e94a98c850f8b12cd87John McCall  unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
2505744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2506744016dde06fcffd50931e94a98c850f8b12cd87John McCall  llvm::NamedMDNode *GlobalMetadata = 0;
2507744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2508744016dde06fcffd50931e94a98c850f8b12cd87John McCall  for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
2509744016dde06fcffd50931e94a98c850f8b12cd87John McCall         I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
2510744016dde06fcffd50931e94a98c850f8b12cd87John McCall    const Decl *D = I->first;
2511744016dde06fcffd50931e94a98c850f8b12cd87John McCall    llvm::Value *Addr = I->second;
2512744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2513744016dde06fcffd50931e94a98c850f8b12cd87John McCall    if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
2514744016dde06fcffd50931e94a98c850f8b12cd87John McCall      llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
25156f141659cab11109d9931d92d0988f8850778de3Jay Foad      Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
2516744016dde06fcffd50931e94a98c850f8b12cd87John McCall    } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
2517744016dde06fcffd50931e94a98c850f8b12cd87John McCall      GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
2518744016dde06fcffd50931e94a98c850f8b12cd87John McCall      EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
2519744016dde06fcffd50931e94a98c850f8b12cd87John McCall    }
2520744016dde06fcffd50931e94a98c850f8b12cd87John McCall  }
2521744016dde06fcffd50931e94a98c850f8b12cd87John McCall}
2522673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar
25233dc05418538c719fea48b906bfa4febe5296e126Nick Lewyckyvoid CodeGenModule::EmitCoverageFile() {
25243dc05418538c719fea48b906bfa4febe5296e126Nick Lewycky  if (!getCodeGenOpts().CoverageFile.empty()) {
25255ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky    if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
25265ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky      llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
25275ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky      llvm::LLVMContext &Ctx = TheModule.getContext();
25283dc05418538c719fea48b906bfa4febe5296e126Nick Lewycky      llvm::MDString *CoverageFile =
25293dc05418538c719fea48b906bfa4febe5296e126Nick Lewycky          llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
25305ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky      for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
25315ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky        llvm::MDNode *CU = CUNode->getOperand(i);
25323dc05418538c719fea48b906bfa4febe5296e126Nick Lewycky        llvm::Value *node[] = { CoverageFile, CU };
25335ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky        llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
25345ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky        GCov->addOperand(N);
25355ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky      }
25365ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky    }
25375ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky  }
25385ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky}
2539