CodeGenModule.cpp revision c1868e533e63a1b7dad7a22714fc593c045382ae
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"
4219b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl#include "llvm/ADT/APSInt.h"
436374c3307e2d73348f7b8cc73eeeb0998ad0ac94John McCall#include "llvm/ADT/Triple.h"
44c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola#include "llvm/Target/Mangler.h"
4525a6a84cf5067b32c271e3ba078676dee838798dMicah Villmow#include "llvm/DataLayout.h"
466ba728d9687b2617793f5afd410650a8d6c71080Gabor Greif#include "llvm/Support/CallSite.h"
4778f7ece00e2ddfb64d4ed72a7be770b5b9b805e3Chris Lattner#include "llvm/Support/ErrorHandling.h"
485f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencerusing namespace clang;
495f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencerusing namespace CodeGen;
505f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
5177f68bb90af93b95045fb994e7cd68137adcc132Julien Lerougestatic const char AnnotationSection[] = "llvm.metadata";
5277f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
53f16aa103d3afd42fbca2ab346f191bf745cec092John McCallstatic CGCXXABI &createCXXABI(CodeGenModule &CGM) {
54bcfd1f55bfbb3e5944cd5e03d07b343e280838c4Douglas Gregor  switch (CGM.getContext().getTargetInfo().getCXXABI()) {
55f16aa103d3afd42fbca2ab346f191bf745cec092John McCall  case CXXABI_ARM: return *CreateARMCXXABI(CGM);
56f16aa103d3afd42fbca2ab346f191bf745cec092John McCall  case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM);
57f16aa103d3afd42fbca2ab346f191bf745cec092John McCall  case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM);
58f16aa103d3afd42fbca2ab346f191bf745cec092John McCall  }
59f16aa103d3afd42fbca2ab346f191bf745cec092John McCall
60f16aa103d3afd42fbca2ab346f191bf745cec092John McCall  llvm_unreachable("invalid C++ ABI kind");
61f16aa103d3afd42fbca2ab346f191bf745cec092John McCall}
62f16aa103d3afd42fbca2ab346f191bf745cec092John McCall
635f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
642811ccf48d6d898c42cc4cfad37abedb36236d20Chandler CarruthCodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
6525a6a84cf5067b32c271e3ba078676dee838798dMicah Villmow                             llvm::Module &M, const llvm::DataLayout &TD,
66d6471f7c1921c7802804ce3ff6fe9768310f72b9David Blaikie                             DiagnosticsEngine &diags)
674e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M),
6825a6a84cf5067b32c271e3ba078676dee838798dMicah Villmow    TheDataLayout(TD), TheTargetCodeGenInfo(0), Diags(diags),
69f16aa103d3afd42fbca2ab346f191bf745cec092John McCall    ABI(createCXXABI(*this)),
70de5d3c717684f3821b8db58037bc7140acf134aaJohn McCall    Types(*this),
713d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman    TBAA(0),
726c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne    VTables(*this), ObjCRuntime(0), OpenCLRuntime(0), CUDARuntime(0),
73b49bd27b334a6c4e3bf9d810a7d5b022578f1194Dan Gohman    DebugInfo(0), ARCData(0), NoObjCARCExceptionsMetadata(0),
74b49bd27b334a6c4e3bf9d810a7d5b022578f1194Dan Gohman    RRData(0), CFConstantStringClassRef(0),
756c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne    ConstantStringClassRef(0), NSConstantStringType(0),
76673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar    VMContext(M.getContext()),
77673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar    NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
78d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall    BlockObjectAssign(0), BlockObjectDispose(0),
79d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall    BlockDescriptorType(0), GenericBlockLiteralType(0) {
808b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner
818b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  // Initialize the type cache.
828b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  llvm::LLVMContext &LLVMContext = M.getContext();
838b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  VoidTy = llvm::Type::getVoidTy(LLVMContext);
848b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
858b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
868b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
878b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
888b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  FloatTy = llvm::Type::getFloatTy(LLVMContext);
898b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
908b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
918b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  PointerAlignInBytes =
928b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
938b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
948b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
958b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  Int8PtrTy = Int8Ty->getPointerTo(0);
968b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
978b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner
984e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (LangOpts.ObjC1)
998c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne    createObjCRuntime();
1004e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (LangOpts.OpenCL)
1018c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne    createOpenCLRuntime();
1024e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (LangOpts.CUDA)
1036c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne    createCUDARuntime();
104e8b9f5b8ea60983c4a74cb8b63879616b914b65aSanjiv Gupta
105c9fe6056e4ce8ffad1ef439fca3318a5faf1c075Kostya Serebryany  // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
106c9fe6056e4ce8ffad1ef439fca3318a5faf1c075Kostya Serebryany  if (LangOpts.ThreadSanitizer ||
107c9fe6056e4ce8ffad1ef439fca3318a5faf1c075Kostya Serebryany      (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
108c9fe6056e4ce8ffad1ef439fca3318a5faf1c075Kostya Serebryany    TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
1090b5c4fc2ae3b503c2b1f354bf52b718aa50a6aeeDan Gohman                           ABI.getMangleContext());
1103d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman
111e8ba8d78a258ec992d3521eebdae8324db777b14Nick Lewycky  // If debug info or coverage generation is enabled, create the CGDebugInfo
112e8ba8d78a258ec992d3521eebdae8324db777b14Nick Lewycky  // object.
1134cdad3151bfb2075c6bdbfe89fbb08f31a90a45bDouglas Gregor  if (CodeGenOpts.getDebugInfo() != CodeGenOptions::NoDebugInfo ||
1143a70cd6e1cc414856e41ce5509aa61c89bf472dcAlexey Samsonov      CodeGenOpts.EmitGcovArcs ||
115e8ba8d78a258ec992d3521eebdae8324db777b14Nick Lewycky      CodeGenOpts.EmitGcovNotes)
116e8ba8d78a258ec992d3521eebdae8324db777b14Nick Lewycky    DebugInfo = new CGDebugInfo(*this);
117d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall
118d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall  Block.GlobalUniqueCount = 0;
1195936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall
1204e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (C.getLangOpts().ObjCAutoRefCount)
121f85e193739c953358c865005855253af4f68a497John McCall    ARCData = new ARCEntrypoints();
122f85e193739c953358c865005855253af4f68a497John McCall  RRData = new RREntrypoints();
1232b94fe35edf951a14ecd32b21f7ebcc2e3754c67Chris Lattner}
1242b94fe35edf951a14ecd32b21f7ebcc2e3754c67Chris Lattner
1252b94fe35edf951a14ecd32b21f7ebcc2e3754c67Chris LattnerCodeGenModule::~CodeGenModule() {
126e926523105dd2604ccd5c101605dea43c5269965Peter Collingbourne  delete ObjCRuntime;
1278c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne  delete OpenCLRuntime;
1286c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne  delete CUDARuntime;
1290628b724ff68105dc88af00a39f859447f22981eTed Kremenek  delete TheTargetCodeGenInfo;
130f16aa103d3afd42fbca2ab346f191bf745cec092John McCall  delete &ABI;
1314376c85fb0ac9e7fd779d246efc77e1169179138Dan Gohman  delete TBAA;
132815c78fd9ab8bd5dfe8e8a91b8c6a413e2b8c889Ted Kremenek  delete DebugInfo;
133f85e193739c953358c865005855253af4f68a497John McCall  delete ARCData;
134f85e193739c953358c865005855253af4f68a497John McCall  delete RRData;
135815c78fd9ab8bd5dfe8e8a91b8c6a413e2b8c889Ted Kremenek}
136815c78fd9ab8bd5dfe8e8a91b8c6a413e2b8c889Ted Kremenek
1370d13f6fdbdd6f06e2449b8834dda53334abd399aDavid Chisnallvoid CodeGenModule::createObjCRuntime() {
138260611a32535c851237926bfcf78869b13c07d5bJohn McCall  // This is just isGNUFamily(), but we want to force implementors of
139260611a32535c851237926bfcf78869b13c07d5bJohn McCall  // new ABIs to decide how best to do this.
140260611a32535c851237926bfcf78869b13c07d5bJohn McCall  switch (LangOpts.ObjCRuntime.getKind()) {
14111d3f4cc27e6b923fc32481dc1bb5ec46c7d1f4bDavid Chisnall  case ObjCRuntime::GNUstep:
14211d3f4cc27e6b923fc32481dc1bb5ec46c7d1f4bDavid Chisnall  case ObjCRuntime::GCC:
143f7226fbe677a9c7578fa0613491ed15c6dc6a5e1John McCall  case ObjCRuntime::ObjFW:
144e926523105dd2604ccd5c101605dea43c5269965Peter Collingbourne    ObjCRuntime = CreateGNUObjCRuntime(*this);
145260611a32535c851237926bfcf78869b13c07d5bJohn McCall    return;
146260611a32535c851237926bfcf78869b13c07d5bJohn McCall
147260611a32535c851237926bfcf78869b13c07d5bJohn McCall  case ObjCRuntime::FragileMacOSX:
148260611a32535c851237926bfcf78869b13c07d5bJohn McCall  case ObjCRuntime::MacOSX:
149260611a32535c851237926bfcf78869b13c07d5bJohn McCall  case ObjCRuntime::iOS:
150e926523105dd2604ccd5c101605dea43c5269965Peter Collingbourne    ObjCRuntime = CreateMacObjCRuntime(*this);
151260611a32535c851237926bfcf78869b13c07d5bJohn McCall    return;
152260611a32535c851237926bfcf78869b13c07d5bJohn McCall  }
153260611a32535c851237926bfcf78869b13c07d5bJohn McCall  llvm_unreachable("bad runtime kind");
1540d13f6fdbdd6f06e2449b8834dda53334abd399aDavid Chisnall}
1550d13f6fdbdd6f06e2449b8834dda53334abd399aDavid Chisnall
1568c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbournevoid CodeGenModule::createOpenCLRuntime() {
1578c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne  OpenCLRuntime = new CGOpenCLRuntime(*this);
1588c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne}
1598c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne
1606c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbournevoid CodeGenModule::createCUDARuntime() {
1616c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne  CUDARuntime = CreateNVCUDARuntime(*this);
1626c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne}
1636c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne
164815c78fd9ab8bd5dfe8e8a91b8c6a413e2b8c889Ted Kremenekvoid CodeGenModule::Release() {
16582227ff4eb665bbf41720ebdc0dc9215a86ba838Chris Lattner  EmitDeferred();
1666c6bda3b0b1d8adaac2ba3f4da7056e9f1eef52eEli Friedman  EmitCXXGlobalInitFunc();
167efb0fa9e11f75af51744a6159530ef7cc8efa24aDaniel Dunbar  EmitCXXGlobalDtorFunc();
168e926523105dd2604ccd5c101605dea43c5269965Peter Collingbourne  if (ObjCRuntime)
169e926523105dd2604ccd5c101605dea43c5269965Peter Collingbourne    if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
170208ff5e8a073de2a5d15cbe03cab8a4c0d935e28Daniel Dunbar      AddGlobalCtor(ObjCInitFunction);
1716bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  EmitCtorList(GlobalCtors, "llvm.global_ctors");
1726bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  EmitCtorList(GlobalDtors, "llvm.global_dtors");
17377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  EmitGlobalAnnotations();
1740269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  EmitLLVMUsed();
175744016dde06fcffd50931e94a98c850f8b12cd87John McCall
176b25938303de0976b9f189363d43033e5788e3d36John McCall  SimplifyPersonality();
177b25938303de0976b9f189363d43033e5788e3d36John McCall
178744016dde06fcffd50931e94a98c850f8b12cd87John McCall  if (getCodeGenOpts().EmitDeclMetadata)
179744016dde06fcffd50931e94a98c850f8b12cd87John McCall    EmitDeclMetadata();
1805ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky
1815ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky  if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
1823dc05418538c719fea48b906bfa4febe5296e126Nick Lewycky    EmitCoverageFile();
183f391dbe39dca85f2a2c6ea558811dacc571c223eDevang Patel
184f391dbe39dca85f2a2c6ea558811dacc571c223eDevang Patel  if (DebugInfo)
185f391dbe39dca85f2a2c6ea558811dacc571c223eDevang Patel    DebugInfo->finalize();
186f1968f28869f4e0675450ae39c478a37c5b9abd6Daniel Dunbar}
187f1968f28869f4e0675450ae39c478a37c5b9abd6Daniel Dunbar
188e80d56771736c85fd8365c394a6731923b17e91dDevang Patelvoid CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
189e80d56771736c85fd8365c394a6731923b17e91dDevang Patel  // Make sure that this type is translated.
190e80d56771736c85fd8365c394a6731923b17e91dDevang Patel  Types.UpdateCompletedType(TD);
191e80d56771736c85fd8365c394a6731923b17e91dDevang Patel}
192e80d56771736c85fd8365c394a6731923b17e91dDevang Patel
1933d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohmanllvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
1943d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman  if (!TBAA)
1953d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman    return 0;
1963d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman  return TBAA->getTBAAInfo(QTy);
1973d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman}
1983d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman
1998cb4a070d491ddd671b049110cc8d0accb08b905Kostya Serebryanyllvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
2008cb4a070d491ddd671b049110cc8d0accb08b905Kostya Serebryany  if (!TBAA)
2018cb4a070d491ddd671b049110cc8d0accb08b905Kostya Serebryany    return 0;
2028cb4a070d491ddd671b049110cc8d0accb08b905Kostya Serebryany  return TBAA->getTBAAInfoForVTablePtr();
2038cb4a070d491ddd671b049110cc8d0accb08b905Kostya Serebryany}
2048cb4a070d491ddd671b049110cc8d0accb08b905Kostya Serebryany
205b22c7dc707cf3770ff3b5e5f11f11fd0aaa06d9bDan Gohmanllvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
206b22c7dc707cf3770ff3b5e5f11f11fd0aaa06d9bDan Gohman  if (!TBAA)
207b22c7dc707cf3770ff3b5e5f11f11fd0aaa06d9bDan Gohman    return 0;
208b22c7dc707cf3770ff3b5e5f11f11fd0aaa06d9bDan Gohman  return TBAA->getTBAAStructInfo(QTy);
209b22c7dc707cf3770ff3b5e5f11f11fd0aaa06d9bDan Gohman}
210b22c7dc707cf3770ff3b5e5f11f11fd0aaa06d9bDan Gohman
2113d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohmanvoid CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
2123d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman                                        llvm::MDNode *TBAAInfo) {
2133d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman  Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
2143d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman}
2153d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman
2166374c3307e2d73348f7b8cc73eeeb0998ad0ac94John McCallbool CodeGenModule::isTargetDarwin() const {
217bcfd1f55bfbb3e5944cd5e03d07b343e280838c4Douglas Gregor  return getContext().getTargetInfo().getTriple().isOSDarwin();
2186374c3307e2d73348f7b8cc73eeeb0998ad0ac94John McCall}
2196374c3307e2d73348f7b8cc73eeeb0998ad0ac94John McCall
2200f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruthvoid CodeGenModule::Error(SourceLocation loc, StringRef error) {
2210f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruth  unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, error);
22232096695c76033a6b0b1747c439f7378a11e8312John McCall  getDiags().Report(Context.getFullLoc(loc), diagID);
22332096695c76033a6b0b1747c439f7378a11e8312John McCall}
22432096695c76033a6b0b1747c439f7378a11e8312John McCall
225488e993a135ce700b982bf099c3d6b856301d642Daniel Dunbar/// ErrorUnsupported - Print out an error that codegen doesn't support the
2262c8569d5f43f7de1fb993e84c95ea571dd9ac55eChris Lattner/// specified stmt yet.
22790df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbarvoid CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
22890df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar                                     bool OmitOnError) {
22990df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar  if (OmitOnError && getDiags().hasErrorOccurred())
23090df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar    return;
231d6471f7c1921c7802804ce3ff6fe9768310f72b9David Blaikie  unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
23256b8001b42bd603ef593e3cb278d8b9b9ba26ca9Daniel Dunbar                                               "cannot compile this %0 yet");
2332c8569d5f43f7de1fb993e84c95ea571dd9ac55eChris Lattner  std::string Msg = Type;
2340a14eee528a901c16f0e288fbc10a3abc1660d87Chris Lattner  getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
2350a14eee528a901c16f0e288fbc10a3abc1660d87Chris Lattner    << Msg << S->getSourceRange();
2362c8569d5f43f7de1fb993e84c95ea571dd9ac55eChris Lattner}
23758c3f9ec11cbe852a518bf2f83af46f938b7b852Chris Lattner
238488e993a135ce700b982bf099c3d6b856301d642Daniel Dunbar/// ErrorUnsupported - Print out an error that codegen doesn't support the
239c6fdc34ac0183bfa03d65f317c78b7bdac52897eChris Lattner/// specified decl yet.
24090df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbarvoid CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
24190df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar                                     bool OmitOnError) {
24290df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar  if (OmitOnError && getDiags().hasErrorOccurred())
24390df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar    return;
244d6471f7c1921c7802804ce3ff6fe9768310f72b9David Blaikie  unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
24556b8001b42bd603ef593e3cb278d8b9b9ba26ca9Daniel Dunbar                                               "cannot compile this %0 yet");
246c6fdc34ac0183bfa03d65f317c78b7bdac52897eChris Lattner  std::string Msg = Type;
2470a14eee528a901c16f0e288fbc10a3abc1660d87Chris Lattner  getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
248c6fdc34ac0183bfa03d65f317c78b7bdac52897eChris Lattner}
249c6fdc34ac0183bfa03d65f317c78b7bdac52897eChris Lattner
250bc8d40d85f3fa1e34569834916f18fecaa635152John McCallllvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
251bc8d40d85f3fa1e34569834916f18fecaa635152John McCall  return llvm::ConstantInt::get(SizeTy, size.getQuantity());
252bc8d40d85f3fa1e34569834916f18fecaa635152John McCall}
253bc8d40d85f3fa1e34569834916f18fecaa635152John McCall
2541eb4433ac451dc16f4133a88af2d002ac26c58efMike Stumpvoid CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
2550ffeaad72cb335b926b064379be4c9886bbff004Anders Carlsson                                        const NamedDecl *D) const {
25604d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar  // Internal definitions always have default visibility.
257df102fcb978588d5edbc661fb5da0b6922f9ab1cChris Lattner  if (GV->hasLocalLinkage()) {
2587e714cd931fa3a90bfd728318a92485aa3e95748Daniel Dunbar    GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
2596ab187a49a42de6d351248d8a6e0206e39743a0cDaniel Dunbar    return;
2607e714cd931fa3a90bfd728318a92485aa3e95748Daniel Dunbar  }
2616ab187a49a42de6d351248d8a6e0206e39743a0cDaniel Dunbar
262af14603ca61757cf4361b583b45639a04c57e651John McCall  // Set visibility for definitions.
263af14603ca61757cf4361b583b45639a04c57e651John McCall  NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
264c7c9058f4977ef4584d68718e23f34504b150ef4Fariborz Jahanian  if (LV.visibilityExplicit() || !GV->hasAvailableExternallyLinkage())
265c7c9058f4977ef4584d68718e23f34504b150ef4Fariborz Jahanian    GV->setVisibility(GetLLVMVisibility(LV.visibility()));
2667cd2e93125e2f3b6ca01b24ed0c3fd7e94683fd9Fariborz Jahanian}
2677cd2e93125e2f3b6ca01b24ed0c3fd7e94683fd9Fariborz Jahanian
268de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborgstatic llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
269de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg  return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
270de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg      .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
271de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg      .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
272de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg      .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
273de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg      .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
274de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg}
275de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg
276de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborgstatic llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
277de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg    CodeGenOptions::TLSModel M) {
278de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg  switch (M) {
279de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg  case CodeGenOptions::GeneralDynamicTLSModel:
280de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg    return llvm::GlobalVariable::GeneralDynamicTLSModel;
281de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg  case CodeGenOptions::LocalDynamicTLSModel:
282de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg    return llvm::GlobalVariable::LocalDynamicTLSModel;
283de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg  case CodeGenOptions::InitialExecTLSModel:
284de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg    return llvm::GlobalVariable::InitialExecTLSModel;
285de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg  case CodeGenOptions::LocalExecTLSModel:
286de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg    return llvm::GlobalVariable::LocalExecTLSModel;
287de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg  }
288de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg  llvm_unreachable("Invalid TLS model!");
289de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg}
290de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg
291de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborgvoid CodeGenModule::setTLSMode(llvm::GlobalVariable *GV,
292de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg                               const VarDecl &D) const {
293de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg  assert(D.isThreadSpecified() && "setting TLS mode on non-TLS var!");
294de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg
295de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg  llvm::GlobalVariable::ThreadLocalMode TLM;
2964cdad3151bfb2075c6bdbfe89fbb08f31a90a45bDouglas Gregor  TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
297de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg
298de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg  // Override the TLS model if it is explicitly specified.
299de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg  if (D.hasAttr<TLSModelAttr>()) {
300de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg    const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>();
301de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg    TLM = GetLLVMTLSModel(Attr->getModel());
302de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg  }
303de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg
304de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg  GV->setThreadLocalMode(TLM);
305de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg}
306de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg
307cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall/// Set the symbol visibility of type information (vtable and RTTI)
308cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall/// associated with the given type.
309cbfe50224b19119e759802bd0c1463269dffd09eJohn McCallvoid CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
310cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall                                      const CXXRecordDecl *RD,
311fa2e99f72f9bfe2270ea8caf76d0eef11c45259fAnders Carlsson                                      TypeVisibilityKind TVK) const {
3120ffeaad72cb335b926b064379be4c9886bbff004Anders Carlsson  setGlobalVisibility(GV, RD);
313cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
314279b5eb6910d64a293e9c0e2887a05c65d8737d7John McCall  if (!CodeGenOpts.HiddenWeakVTables)
315279b5eb6910d64a293e9c0e2887a05c65d8737d7John McCall    return;
316279b5eb6910d64a293e9c0e2887a05c65d8737d7John McCall
3179a86a137b0872bad25161fb3408a71d919638757Anders Carlsson  // We never want to drop the visibility for RTTI names.
3189a86a137b0872bad25161fb3408a71d919638757Anders Carlsson  if (TVK == TVK_ForRTTIName)
3199a86a137b0872bad25161fb3408a71d919638757Anders Carlsson    return;
3209a86a137b0872bad25161fb3408a71d919638757Anders Carlsson
321cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // We want to drop the visibility to hidden for weak type symbols.
322cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // This isn't possible if there might be unresolved references
323cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // elsewhere that rely on this symbol being visible.
324cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
3257a536907da776bdc47a704e7cafd641e8150e653John McCall  // This should be kept roughly in sync with setThunkVisibility
3267a536907da776bdc47a704e7cafd641e8150e653John McCall  // in CGVTables.cpp.
3277a536907da776bdc47a704e7cafd641e8150e653John McCall
328cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // Preconditions.
329f502d93b0ea970bfbd897e657f8d940a20984de2Anders Carlsson  if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
330cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall      GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
331cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall    return;
332cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
333cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // Don't override an explicit visibility attribute.
3344421d2b341d041df44013769f23c306308bbab83Douglas Gregor  if (RD->getExplicitVisibility())
335cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall    return;
336cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
337cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  switch (RD->getTemplateSpecializationKind()) {
338cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // We have to disable the optimization if this is an EI definition
339cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // because there might be EI declarations in other shared objects.
340cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  case TSK_ExplicitInstantiationDefinition:
341cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  case TSK_ExplicitInstantiationDeclaration:
342cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall    return;
343cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
3447a536907da776bdc47a704e7cafd641e8150e653John McCall  // Every use of a non-template class's type information has to emit it.
345cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  case TSK_Undeclared:
346cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall    break;
347cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
3487a536907da776bdc47a704e7cafd641e8150e653John McCall  // In theory, implicit instantiations can ignore the possibility of
3497a536907da776bdc47a704e7cafd641e8150e653John McCall  // an explicit instantiation declaration because there necessarily
3507a536907da776bdc47a704e7cafd641e8150e653John McCall  // must be an EI definition somewhere with default visibility.  In
3517a536907da776bdc47a704e7cafd641e8150e653John McCall  // practice, it's possible to have an explicit instantiation for
3527a536907da776bdc47a704e7cafd641e8150e653John McCall  // an arbitrary template class, and linkers aren't necessarily able
3537a536907da776bdc47a704e7cafd641e8150e653John McCall  // to deal with mixed-visibility symbols.
3547a536907da776bdc47a704e7cafd641e8150e653John McCall  case TSK_ExplicitSpecialization:
355cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  case TSK_ImplicitInstantiation:
356aafd111afa6acd50fe4bec6c41add02ecf556535Douglas Gregor    return;
357cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  }
358cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
359cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // If there's a key function, there may be translation units
360cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // that don't have the key function's definition.  But ignore
361cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // this if we're emitting RTTI under -fno-rtti.
3624e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (!(TVK != TVK_ForRTTI) || LangOpts.RTTI) {
363cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall    if (Context.getKeyFunction(RD))
364cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall      return;
365fa2e99f72f9bfe2270ea8caf76d0eef11c45259fAnders Carlsson  }
366cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
367cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // Otherwise, drop the visibility to hidden.
368cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
369b1c65ff108de47a89585ad37874bd6cb232664cdRafael Espindola  GV->setUnnamedAddr(true);
370cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall}
371cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
3725f9e272e632e951b1efe824cd16acb4d96077930Chris LattnerStringRef CodeGenModule::getMangledName(GlobalDecl GD) {
373793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
374793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
3755f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
376793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  if (!Str.empty())
377793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson    return Str;
378793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
3794c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall  if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
380793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson    IdentifierInfo *II = ND->getIdentifier();
381793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson    assert(II && "Attempt to mangle unnamed decl.");
382793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
383793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson    Str = II->getName();
384793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson    return Str;
385793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  }
386793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
387f7ccbad5d9949e7ddd1cbef43d482553b811e026Dylan Noblesmith  SmallString<256> Buffer;
388c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola  llvm::raw_svector_ostream Out(Buffer);
389793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
390c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola    getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
391793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
392c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola    getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
393793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
3944904bf4e84cfb48080270ebaa9005327f18ab0e5Fariborz Jahanian    getCXXABI().getMangleContext().mangleBlock(BD, Out,
3954904bf4e84cfb48080270ebaa9005327f18ab0e5Fariborz Jahanian      dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()));
396793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  else
397c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola    getCXXABI().getMangleContext().mangleName(ND, Out);
398793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
399793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  // Allocate space for the mangled name.
400c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola  Out.flush();
401793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  size_t Length = Buffer.size();
402793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  char *Name = MangledNamesAllocator.Allocate<char>(Length);
403793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  std::copy(Buffer.begin(), Buffer.end(), Name);
404793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
4055f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  Str = StringRef(Name, Length);
406793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
407793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  return Str;
408793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson}
409793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
41014110477887e3dc168ffc6c191e72d705051f99ePeter Collingbournevoid CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
41114110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne                                        const BlockDecl *BD) {
41214110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne  MangleContext &MangleCtx = getCXXABI().getMangleContext();
41314110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne  const Decl *D = GD.getDecl();
414c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola  llvm::raw_svector_ostream Out(Buffer.getBuffer());
41514110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne  if (D == 0)
4164904bf4e84cfb48080270ebaa9005327f18ab0e5Fariborz Jahanian    MangleCtx.mangleGlobalBlock(BD,
4174904bf4e84cfb48080270ebaa9005327f18ab0e5Fariborz Jahanian      dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
41814110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne  else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
419c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola    MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
42014110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne  else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
421c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola    MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
42214110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne  else
423c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola    MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
4249a8822bb154b792cdb18fe4cfb34480ca0ec7661Anders Carlsson}
4259a8822bb154b792cdb18fe4cfb34480ca0ec7661Anders Carlsson
4265f9e272e632e951b1efe824cd16acb4d96077930Chris Lattnerllvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
427f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  return getModule().getNamedValue(Name);
4285f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor}
4295f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor
4306d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner/// AddGlobalCtor - Add a function to the list that will be called before
4316d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner/// main() runs.
4326bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbarvoid CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
43349988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar  // FIXME: Type coercion of void()* types.
4346bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  GlobalCtors.push_back(std::make_pair(Ctor, Priority));
4356d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner}
4366d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner
4376bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar/// AddGlobalDtor - Add a function to the list that will be called
4386bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar/// when the module is unloaded.
4396bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbarvoid CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
44049988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar  // FIXME: Type coercion of void()* types.
4416bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  GlobalDtors.push_back(std::make_pair(Dtor, Priority));
4426bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar}
4436bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar
4446bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbarvoid CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
4456bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  // Ctor function type is void()*.
4460774cb84719f2aea3016493a2bbd9a02aa3e0541John McCall  llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
44796e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson  llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
4486bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar
4496bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  // Get the type of a ctor entry, { i32, void ()* }.
450c5cbb909e8a27deb8f1a2b6b7bf56a96051af81aChris Lattner  llvm::StructType *CtorStructTy =
4518b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner    llvm::StructType::get(Int32Ty, llvm::PointerType::getUnqual(CtorFTy), NULL);
4526bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar
4536bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  // Construct the constructor and destructor arrays.
4540b2397132efe74ee11c1b371dd9033820c54240fChris Lattner  SmallVector<llvm::Constant*, 8> Ctors;
4556bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
4560b2397132efe74ee11c1b371dd9033820c54240fChris Lattner    llvm::Constant *S[] = {
4570b2397132efe74ee11c1b371dd9033820c54240fChris Lattner      llvm::ConstantInt::get(Int32Ty, I->second, false),
4580b2397132efe74ee11c1b371dd9033820c54240fChris Lattner      llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)
4590b2397132efe74ee11c1b371dd9033820c54240fChris Lattner    };
46008e252425ca2cbdc44ba65d9a657ed5398014e36Owen Anderson    Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
4616bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  }
4626bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar
4636bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  if (!Ctors.empty()) {
46496e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson    llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
4651c431b323d776362490bbf7cc796b74fedaf19f2Owen Anderson    new llvm::GlobalVariable(TheModule, AT, false,
466572cf09ae8a78af1c56d40b016ec4cf1837163acChris Lattner                             llvm::GlobalValue::AppendingLinkage,
4677db6d838aad4083fe86d7bf703a75fe6e8a17856Owen Anderson                             llvm::ConstantArray::get(AT, Ctors),
4681c431b323d776362490bbf7cc796b74fedaf19f2Owen Anderson                             GlobalName);
4696d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner  }
4706d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner}
4716d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner
472d46f98573ba104eda102dd3224b2dca69f1c6336John McCallllvm::GlobalValue::LinkageTypes
473d46f98573ba104eda102dd3224b2dca69f1c6336John McCallCodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
47490e99a84ddd020e8fda79643748243725a2ed071Argyrios Kyrtzidis  GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
4757c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
476f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  if (Linkage == GVA_Internal)
477d46f98573ba104eda102dd3224b2dca69f1c6336John McCall    return llvm::Function::InternalLinkage;
478f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner
479f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  if (D->hasAttr<DLLExportAttr>())
480d46f98573ba104eda102dd3224b2dca69f1c6336John McCall    return llvm::Function::DLLExportLinkage;
481f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner
482f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  if (D->hasAttr<WeakAttr>())
483d46f98573ba104eda102dd3224b2dca69f1c6336John McCall    return llvm::Function::WeakAnyLinkage;
484f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner
485f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // In C99 mode, 'inline' functions are guaranteed to have a strong
486f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // definition somewhere else, so we can use available_externally linkage.
487f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  if (Linkage == GVA_C99Inline)
488fd0f89d3d7e4220327abdec1cb115474d70219dcFariborz Jahanian    return llvm::Function::AvailableExternallyLinkage;
4895584d91c938384b57563edbca5c2d4f1c66ff02aJohn McCall
4905584d91c938384b57563edbca5c2d4f1c66ff02aJohn McCall  // Note that Apple's kernel linker doesn't support symbol
4915584d91c938384b57563edbca5c2d4f1c66ff02aJohn McCall  // coalescing, so we need to avoid linkonce and weak linkages there.
4925584d91c938384b57563edbca5c2d4f1c66ff02aJohn McCall  // Normally, this means we just map to internal, but for explicit
4935584d91c938384b57563edbca5c2d4f1c66ff02aJohn McCall  // instantiations we'll map to external.
4945584d91c938384b57563edbca5c2d4f1c66ff02aJohn McCall
495f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // In C++, the compiler has to emit a definition in every translation unit
496f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // that references the function.  We should use linkonce_odr because
497f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // a) if all references in this translation unit are optimized away, we
498f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // don't need to codegen it.  b) if the function persists, it needs to be
499f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // merged with other definitions. c) C++ has the ODR, so we know the
500f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // definition is dependable.
501f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
5024e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie    return !Context.getLangOpts().AppleKext
503142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian             ? llvm::Function::LinkOnceODRLinkage
504142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian             : llvm::Function::InternalLinkage;
505f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner
506f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // An explicit instantiation of a template has weak linkage, since
507f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // explicit instantiations can occur in multiple translation units
508f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // and must all be equivalent. However, we are not allowed to
509f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // throw away these explicit instantiations.
510f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  if (Linkage == GVA_ExplicitTemplateInstantiation)
5114e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie    return !Context.getLangOpts().AppleKext
512142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian             ? llvm::Function::WeakODRLinkage
5135584d91c938384b57563edbca5c2d4f1c66ff02aJohn McCall             : llvm::Function::ExternalLinkage;
514f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner
515f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // Otherwise, we have strong external linkage.
516f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  assert(Linkage == GVA_StrongExternal);
517f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  return llvm::Function::ExternalLinkage;
518d46f98573ba104eda102dd3224b2dca69f1c6336John McCall}
519d4cbda6292b321c2e7dce7f039d92918fee99b3aNuno Lopes
520d46f98573ba104eda102dd3224b2dca69f1c6336John McCall
521d46f98573ba104eda102dd3224b2dca69f1c6336John McCall/// SetFunctionDefinitionAttributes - Set attributes for a global.
522d46f98573ba104eda102dd3224b2dca69f1c6336John McCall///
523d46f98573ba104eda102dd3224b2dca69f1c6336John McCall/// FIXME: This is currently only done for aliases and functions, but not for
524d46f98573ba104eda102dd3224b2dca69f1c6336John McCall/// variables (these details are set in EmitGlobalVarDefinition for variables).
525d46f98573ba104eda102dd3224b2dca69f1c6336John McCallvoid CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
526d46f98573ba104eda102dd3224b2dca69f1c6336John McCall                                                    llvm::GlobalValue *GV) {
5277c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  SetCommonAttributes(D, GV);
528d4cbda6292b321c2e7dce7f039d92918fee99b3aNuno Lopes}
529d4cbda6292b321c2e7dce7f039d92918fee99b3aNuno Lopes
5307dbd8197040313d796282d4af06eccdf8a17319cDaniel Dunbarvoid CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
5311eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                              const CGFunctionInfo &Info,
5327dbd8197040313d796282d4af06eccdf8a17319cDaniel Dunbar                                              llvm::Function *F) {
533ca6408c3176783f0b29da4679a08512aa05f0c73Daniel Dunbar  unsigned CallingConv;
534761d7f78e2dac7ea5f35828c2271e60d91e106ceDevang Patel  AttributeListType AttributeList;
535ca6408c3176783f0b29da4679a08512aa05f0c73Daniel Dunbar  ConstructAttributeList(Info, D, AttributeList, CallingConv);
536a61ab0521576e9e9e90cd2d482f8684e6070a93cChris Lattner  F->setAttributes(llvm::AttrListPtr::get(AttributeList));
537ca6408c3176783f0b29da4679a08512aa05f0c73Daniel Dunbar  F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
538f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar}
539f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar
540d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall/// Determines whether the language options require us to model
541d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall/// unwind exceptions.  We treat -fexceptions as mandating this
542d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall/// except under the fragile ObjC ABI with only ObjC exceptions
543d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall/// enabled.  This means, for example, that C with -fexceptions
544d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall/// enables this.
5454e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikiestatic bool hasUnwindExceptions(const LangOptions &LangOpts) {
546d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall  // If exceptions are completely disabled, obviously this is false.
5474e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (!LangOpts.Exceptions) return false;
548d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall
549d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall  // If C++ exceptions are enabled, this is true.
5504e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (LangOpts.CXXExceptions) return true;
551d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall
552d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall  // If ObjC exceptions are enabled, this depends on the ABI.
5534e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (LangOpts.ObjCExceptions) {
55411d3f4cc27e6b923fc32481dc1bb5ec46c7d1f4bDavid Chisnall    return LangOpts.ObjCRuntime.hasUnwindExceptions();
555d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall  }
556d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall
557d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall  return true;
558d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall}
559d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall
5607c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbarvoid CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
5617c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar                                                           llvm::Function *F) {
562abca5a1b3e74e644e297c7590b46ab73a6bb476aRafael Espindola  if (CodeGenOpts.UnwindTables)
563abca5a1b3e74e644e297c7590b46ab73a6bb476aRafael Espindola    F->setHasUWTable();
564abca5a1b3e74e644e297c7590b46ab73a6bb476aRafael Espindola
5654e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (!hasUnwindExceptions(LangOpts))
566fac631052809b59c1b66f687c08a743de7fb50e9Bill Wendling    F->addFnAttr(llvm::Attributes::NoUnwind);
567af668b0e7d3581dea3b4f29a9262686e83887e5bDaniel Dunbar
5682873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman  if (D->hasAttr<NakedAttr>()) {
5692873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman    // Naked implies noinline: we should not be inlining such functions.
570fac631052809b59c1b66f687c08a743de7fb50e9Bill Wendling    F->addFnAttr(llvm::Attributes::Naked);
571fac631052809b59c1b66f687c08a743de7fb50e9Bill Wendling    F->addFnAttr(llvm::Attributes::NoInline);
5722873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman  }
573dd0cb22bd62e1e835327f478a2dbf0b8fa439713Daniel Dunbar
5741feade8e520be483293dbf55eb57a51720899589Mike Stump  if (D->hasAttr<NoInlineAttr>())
575fac631052809b59c1b66f687c08a743de7fb50e9Bill Wendling    F->addFnAttr(llvm::Attributes::NoInline);
576f55314dce992fd60816ba337ad151a2fb7c42239Mike Stump
5772873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman  // (noinline wins over always_inline, and we can't specify both in IR)
578adc6cbf5b502f1b58078455ab4fca66c7daac239Michael J. Spencer  if ((D->hasAttr<AlwaysInlineAttr>() || D->hasAttr<ForceInlineAttr>()) &&
5795c3e4ca581faa27c74443d17e5f740a686b62884Bill Wendling      !F->getFnAttributes().hasAttribute(llvm::Attributes::NoInline))
580fac631052809b59c1b66f687c08a743de7fb50e9Bill Wendling    F->addFnAttr(llvm::Attributes::AlwaysInline);
5812873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman
582ee409a916e9b97ed6bc2f48d8d6aac6b8b773d7bBenjamin Kramer  // FIXME: Communicate hot and cold attributes to LLVM more directly.
583ee409a916e9b97ed6bc2f48d8d6aac6b8b773d7bBenjamin Kramer  if (D->hasAttr<ColdAttr>())
584fac631052809b59c1b66f687c08a743de7fb50e9Bill Wendling    F->addFnAttr(llvm::Attributes::OptimizeForSize);
585ee409a916e9b97ed6bc2f48d8d6aac6b8b773d7bBenjamin Kramer
586c5f657fe308f22243f674fc1dfbe24915944d8bfRafael Espindola  if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
587c5f657fe308f22243f674fc1dfbe24915944d8bfRafael Espindola    F->setUnnamedAddr(true);
588c5f657fe308f22243f674fc1dfbe24915944d8bfRafael Espindola
589ef4d5ced04bf0b3d987e6b0e931f43125492f50cRichard Smith  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D))
590ef4d5ced04bf0b3d987e6b0e931f43125492f50cRichard Smith    if (MD->isVirtual())
591ef4d5ced04bf0b3d987e6b0e931f43125492f50cRichard Smith      F->setUnnamedAddr(true);
592ef4d5ced04bf0b3d987e6b0e931f43125492f50cRichard Smith
5934e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (LangOpts.getStackProtector() == LangOptions::SSPOn)
594fac631052809b59c1b66f687c08a743de7fb50e9Bill Wendling    F->addFnAttr(llvm::Attributes::StackProtect);
5954e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
596fac631052809b59c1b66f687c08a743de7fb50e9Bill Wendling    F->addFnAttr(llvm::Attributes::StackProtectReq);
597fd015353a3c4f528216276f25df5b4d464d7a0cdAnders Carlsson
5984e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (LangOpts.AddressSanitizer) {
59989651eaf4170168cac2f34f2738e3d58fc38bbf1Alexander Potapenko    // When AddressSanitizer is enabled, set AddressSafety attribute
60089651eaf4170168cac2f34f2738e3d58fc38bbf1Alexander Potapenko    // unless __attribute__((no_address_safety_analysis)) is used.
60189651eaf4170168cac2f34f2738e3d58fc38bbf1Alexander Potapenko    if (!D->hasAttr<NoAddressSafetyAnalysisAttr>())
602fac631052809b59c1b66f687c08a743de7fb50e9Bill Wendling      F->addFnAttr(llvm::Attributes::AddressSafety);
60389651eaf4170168cac2f34f2738e3d58fc38bbf1Alexander Potapenko  }
60489651eaf4170168cac2f34f2738e3d58fc38bbf1Alexander Potapenko
605cf807c4dfdb23e8fa3f400e0b24ef5b79db7a530Sean Hunt  unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
606cf807c4dfdb23e8fa3f400e0b24ef5b79db7a530Sean Hunt  if (alignment)
607cf807c4dfdb23e8fa3f400e0b24ef5b79db7a530Sean Hunt    F->setAlignment(alignment);
608cf807c4dfdb23e8fa3f400e0b24ef5b79db7a530Sean Hunt
609fb51ddfafcd5f8536d0312b3daa3c0b74b90ab5bMike Stump  // C++ ABI requires 2-byte alignment for member functions.
610bd6dbd19781cefd5b5ff9750c8bf86e6c341a68cMike Stump  if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
611bd6dbd19781cefd5b5ff9750c8bf86e6c341a68cMike Stump    F->setAlignment(2);
612f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar}
613f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar
6141eb4433ac451dc16f4133a88af2d002ac26c58efMike Stumpvoid CodeGenModule::SetCommonAttributes(const Decl *D,
6157c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar                                        llvm::GlobalValue *GV) {
616934176f27552141b5ad113cb3603ffb14906c570Anders Carlsson  if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
617934176f27552141b5ad113cb3603ffb14906c570Anders Carlsson    setGlobalVisibility(GV, ND);
6181fb0caaa7bef765b85972274e3b434af2572c141John McCall  else
6191fb0caaa7bef765b85972274e3b434af2572c141John McCall    GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
6207c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
62140b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (D->hasAttr<UsedAttr>())
6227c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    AddUsedGlobal(GV);
6237c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
62440b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (const SectionAttr *SA = D->getAttr<SectionAttr>())
6257c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    GV->setSection(SA->getName());
62682d0a418c8699fc6f4a9417457ffe93d43bba1c1Anton Korobeynikov
62782d0a418c8699fc6f4a9417457ffe93d43bba1c1Anton Korobeynikov  getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
6287c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar}
6297c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
6300e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbarvoid CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
6310e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar                                                  llvm::Function *F,
6320e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar                                                  const CGFunctionInfo &FI) {
6330e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar  SetLLVMFunctionAttributes(D, FI, F);
6340e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar  SetLLVMFunctionAttributesForDefinition(D, F);
6357c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
6367c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  F->setLinkage(llvm::Function::InternalLinkage);
6377c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
6380e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar  SetCommonAttributes(D, F);
639f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar}
640f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar
641b2bcf1c176b200b36f371e189ce22f93c86cdf45Anders Carlssonvoid CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
642c6c14d1cd68afcd90d097715296377f15be45210Eli Friedman                                          llvm::Function *F,
643c6c14d1cd68afcd90d097715296377f15be45210Eli Friedman                                          bool IsIncompleteFunction) {
6440ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne  if (unsigned IID = F->getIntrinsicID()) {
6450ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne    // If this is an intrinsic function, set the function's attributes
6460ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne    // to the intrinsic's attributes.
64750e6b18f99c45b31e6216ab221f6b3911b24fa1fBill Wendling    F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(),
64850e6b18f99c45b31e6216ab221f6b3911b24fa1fBill Wendling                                                    (llvm::Intrinsic::ID)IID));
6490ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne    return;
6500ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne  }
6510ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne
652b2bcf1c176b200b36f371e189ce22f93c86cdf45Anders Carlsson  const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
653b2bcf1c176b200b36f371e189ce22f93c86cdf45Anders Carlsson
654c6c14d1cd68afcd90d097715296377f15be45210Eli Friedman  if (!IsIncompleteFunction)
655de5d3c717684f3821b8db58037bc7140acf134aaJohn McCall    SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
6561eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
6577c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // Only a few attributes are set on declarations; these may later be
6587c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // overridden by a definition.
6591eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
66040b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (FD->hasAttr<DLLImportAttr>()) {
6617c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    F->setLinkage(llvm::Function::DLLImportLinkage);
6621eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  } else if (FD->hasAttr<WeakAttr>() ||
6630a0d2b179085a52c10402feebeb6db8b4d96a140Douglas Gregor             FD->isWeakImported()) {
6647c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    // "extern_weak" is overloaded in LLVM; we probably should have
6651eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    // separate linkage types for this.
6667c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    F->setLinkage(llvm::Function::ExternalWeakLinkage);
6677c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  } else {
6681eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    F->setLinkage(llvm::Function::ExternalLinkage);
669af14603ca61757cf4361b583b45639a04c57e651John McCall
670af14603ca61757cf4361b583b45639a04c57e651John McCall    NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility();
671af14603ca61757cf4361b583b45639a04c57e651John McCall    if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) {
672af14603ca61757cf4361b583b45639a04c57e651John McCall      F->setVisibility(GetLLVMVisibility(LV.visibility()));
673af14603ca61757cf4361b583b45639a04c57e651John McCall    }
6747c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  }
6757c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
67640b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
6777c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    F->setSection(SA->getName());
678219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar}
679219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar
6800269871c9cba493f76237175ab60313406f3bafaDaniel Dunbarvoid CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
6811eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  assert(!GV->isDeclaration() &&
6820269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar         "Only globals with definition can force usage.");
68335f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  LLVMUsed.push_back(GV);
6840269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar}
6850269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar
6860269871c9cba493f76237175ab60313406f3bafaDaniel Dunbarvoid CodeGenModule::EmitLLVMUsed() {
6870269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  // Don't create llvm.used if there is no need.
688ad64e024bd18cf25dcfa44e049004371838decd8Chris Lattner  if (LLVMUsed.empty())
6890269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar    return;
6900269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar
69135f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  // Convert LLVMUsed to what ConstantArray needs.
6920b2397132efe74ee11c1b371dd9033820c54240fChris Lattner  SmallVector<llvm::Constant*, 8> UsedArray;
69335f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  UsedArray.resize(LLVMUsed.size());
69435f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
6951eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    UsedArray[i] =
6961eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump     llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
6970b2397132efe74ee11c1b371dd9033820c54240fChris Lattner                                    Int8PtrTy);
69835f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  }
6991eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
700c38e9affd4519ea199af22419c8c794973cc4b23Fariborz Jahanian  if (UsedArray.empty())
701c38e9affd4519ea199af22419c8c794973cc4b23Fariborz Jahanian    return;
7020b2397132efe74ee11c1b371dd9033820c54240fChris Lattner  llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size());
7031eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
7041eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  llvm::GlobalVariable *GV =
7051eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    new llvm::GlobalVariable(getModule(), ATy, false,
7060269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar                             llvm::GlobalValue::AppendingLinkage,
7077db6d838aad4083fe86d7bf703a75fe6e8a17856Owen Anderson                             llvm::ConstantArray::get(ATy, UsedArray),
7081c431b323d776362490bbf7cc796b74fedaf19f2Owen Anderson                             "llvm.used");
7090269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar
7100269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  GV->setSection("llvm.metadata");
7110269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar}
7120269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar
7130269871c9cba493f76237175ab60313406f3bafaDaniel Dunbarvoid CodeGenModule::EmitDeferred() {
71467b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // Emit code for any potentially referenced deferred decls.  Since a
71567b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // previously unused static decl may become used during the generation of code
716dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky  // for a static function, iterate until no changes are made.
717bbf58bb1b8dd8c5e0f07547a6c20ffd55385fcf6Rafael Espindola
718046c294a43024874ff35656c6e785b64e72f1f36Anders Carlsson  while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) {
719046c294a43024874ff35656c6e785b64e72f1f36Anders Carlsson    if (!DeferredVTables.empty()) {
720046c294a43024874ff35656c6e785b64e72f1f36Anders Carlsson      const CXXRecordDecl *RD = DeferredVTables.back();
721046c294a43024874ff35656c6e785b64e72f1f36Anders Carlsson      DeferredVTables.pop_back();
7229ee494f98610dcd79441dce469d7bf609fcd7b92Charles Davis      getCXXABI().EmitVTables(RD);
723bbf58bb1b8dd8c5e0f07547a6c20ffd55385fcf6Rafael Espindola      continue;
724bbf58bb1b8dd8c5e0f07547a6c20ffd55385fcf6Rafael Espindola    }
725bbf58bb1b8dd8c5e0f07547a6c20ffd55385fcf6Rafael Espindola
7262a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson    GlobalDecl D = DeferredDeclsToEmit.back();
72767b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    DeferredDeclsToEmit.pop_back();
72867b00520c8f5b48fad722b790d87fea6be764efeChris Lattner
729c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // Check to see if we've already emitted this.  This is necessary
730c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // for a couple of reasons: first, decls can end up in the
731c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // deferred-decls queue multiple times, and second, decls can end
732c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // up with definitions in unusual ways (e.g. by an extern inline
733c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // function acquiring a strong function redefinition).  Just
734c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // ignore these cases.
735c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    //
736c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // TODO: That said, looking this up multiple times is very wasteful.
7375f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner    StringRef Name = getMangledName(D);
738f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    llvm::GlobalValue *CGRef = GetGlobalValue(Name);
73967b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    assert(CGRef && "Deferred decl wasn't referenced?");
7401eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
74167b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    if (!CGRef->isDeclaration())
74267b00520c8f5b48fad722b790d87fea6be764efeChris Lattner      continue;
7431eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
744c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // GlobalAlias::isDeclaration() defers to the aliasee, but for our
745c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // purposes an alias counts as a definition.
746c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    if (isa<llvm::GlobalAlias>(CGRef))
747c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall      continue;
748c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall
74967b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    // Otherwise, emit the definition and move on to the next one.
75067b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    EmitGlobalDefinition(D);
75167b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  }
7525f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
7535f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
75477f68bb90af93b95045fb994e7cd68137adcc132Julien Lerougevoid CodeGenModule::EmitGlobalAnnotations() {
75577f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  if (Annotations.empty())
75677f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    return;
75777f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
75877f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  // Create a new global variable for the ConstantStruct in the Module.
75977f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
76077f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    Annotations[0]->getType(), Annotations.size()), Annotations);
76177f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(),
76277f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array,
76377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    "llvm.global.annotations");
76477f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  gv->setSection(AnnotationSection);
76577f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge}
76677f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
76777f68bb90af93b95045fb994e7cd68137adcc132Julien Lerougellvm::Constant *CodeGenModule::EmitAnnotationString(llvm::StringRef Str) {
76877f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  llvm::StringMap<llvm::Constant*>::iterator i = AnnotationStrings.find(Str);
76977f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  if (i != AnnotationStrings.end())
77077f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    return i->second;
77177f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
77277f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  // Not found yet, create a new global.
77394010695f7fce626e41ef045b60def9c912e9ce8Chris Lattner  llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
77477f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(),
77577f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    true, llvm::GlobalValue::PrivateLinkage, s, ".str");
77677f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  gv->setSection(AnnotationSection);
77777f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  gv->setUnnamedAddr(true);
77877f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  AnnotationStrings[Str] = gv;
77977f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  return gv;
78077f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge}
78177f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
78277f68bb90af93b95045fb994e7cd68137adcc132Julien Lerougellvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
78377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  SourceManager &SM = getContext().getSourceManager();
78477f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  PresumedLoc PLoc = SM.getPresumedLoc(Loc);
78577f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  if (PLoc.isValid())
78677f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    return EmitAnnotationString(PLoc.getFilename());
78777f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  return EmitAnnotationString(SM.getBufferName(Loc));
78877f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge}
78977f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
79077f68bb90af93b95045fb994e7cd68137adcc132Julien Lerougellvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
79177f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  SourceManager &SM = getContext().getSourceManager();
79277f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  PresumedLoc PLoc = SM.getPresumedLoc(L);
79377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
79477f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    SM.getExpansionLineNumber(L);
79577f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  return llvm::ConstantInt::get(Int32Ty, LineNo);
79677f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge}
79777f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
7981eb4433ac451dc16f4133a88af2d002ac26c58efMike Stumpllvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
7998bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman                                                const AnnotateAttr *AA,
80077f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge                                                SourceLocation L) {
80177f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  // Get the globals for file name, annotation, and the line number.
80277f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
80377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge                 *UnitGV = EmitAnnotationUnit(L),
80477f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge                 *LineNoCst = EmitAnnotationLineNo(L);
8058bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman
80657d5cee133495bc21d1abdbce45ab05a79274a23Daniel Dunbar  // Create the ConstantStruct for the global annotation.
8078bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  llvm::Constant *Fields[4] = {
80877f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
80977f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
81077f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
81177f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    LineNoCst
8128bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  };
813c5cbb909e8a27deb8f1a2b6b7bf56a96051af81aChris Lattner  return llvm::ConstantStruct::getAnon(Fields);
8148bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman}
8158bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman
81677f68bb90af93b95045fb994e7cd68137adcc132Julien Lerougevoid CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
81777f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge                                         llvm::GlobalValue *GV) {
81877f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
81977f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  // Get the struct elements for these annotations.
82077f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  for (specific_attr_iterator<AnnotateAttr>
82177f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge       ai = D->specific_attr_begin<AnnotateAttr>(),
82277f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge       ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai)
82377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    Annotations.push_back(EmitAnnotateAttr(GV, *ai, D->getLocation()));
82477f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge}
82577f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
826a6d6af308bfc9b72467b432a045a9fc6673e3821Argyrios Kyrtzidisbool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
82790e99a84ddd020e8fda79643748243725a2ed071Argyrios Kyrtzidis  // Never defer when EmitAllDecls is specified.
8284e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (LangOpts.EmitAllDecls)
829a6d6af308bfc9b72467b432a045a9fc6673e3821Argyrios Kyrtzidis    return false;
8300b6bc8bd7a1d2a7d7478d13d78cff94cacad61fcDouglas Gregor
8314ac7c0bb39696e92fd220118fedc484c09a69870Argyrios Kyrtzidis  return !getContext().DeclMustBeEmitted(Global);
83273241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar}
83373241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar
834c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weberllvm::Constant *CodeGenModule::GetAddrOfUuidDescriptor(
835c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber    const CXXUuidofExpr* E) {
836c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  // Sema has verified that IIDSource has a __declspec(uuid()), and that its
837c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  // well-formed.
838c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  StringRef Uuid;
839c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  if (E->isTypeOperand())
840c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber    Uuid = CXXUuidofExpr::GetUuidAttrOfType(E->getTypeOperand())->getGuid();
841c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  else {
842c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber    // Special case: __uuidof(0) means an all-zero GUID.
843c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber    Expr *Op = E->getExprOperand();
844c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber    if (!Op->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
845c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber      Uuid = CXXUuidofExpr::GetUuidAttrOfType(Op->getType())->getGuid();
846c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber    else
847c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber      Uuid = "00000000-0000-0000-0000-000000000000";
848c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  }
849c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  std::string Name = "__uuid_" + Uuid.str();
850c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber
851c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  // Look for an existing global.
852c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
853c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber    return GV;
854c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber
855c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  llvm::Constant *Init = EmitUuidofInitializer(Uuid, E->getType());
856c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  assert(Init && "failed to initialize as constant");
857c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber
858c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  // GUIDs are assumed to be 16 bytes, spread over 4-2-2-8 bytes. However, the
859c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  // first field is declared as "long", which for many targets is 8 bytes.
860c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  // Those architectures are not supported. (With the MS abi, long is always 4
861c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  // bytes.)
862c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  llvm::Type *GuidType = getTypes().ConvertType(E->getType());
863c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  if (Init->getType() != GuidType) {
864c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber    DiagnosticsEngine &Diags = getDiags();
865c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber    unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
866c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber        "__uuidof codegen is not supported on this architecture");
867c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber    Diags.Report(E->getExprLoc(), DiagID) << E->getSourceRange();
868c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber    Init = llvm::UndefValue::get(GuidType);
869c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  }
870c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber
871c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  llvm::GlobalVariable *GV = new llvm::GlobalVariable(getModule(), GuidType,
872c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber      /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, Init, Name);
873c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  GV->setUnnamedAddr(true);
874c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  return GV;
875c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber}
876c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber
8776a836706c40a31c716952b74785102c90fd6afa7Rafael Espindolallvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
8786a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  const AliasAttr *AA = VD->getAttr<AliasAttr>();
8796a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  assert(AA && "No alias?");
8806a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
8812acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
8826a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
8836a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  // See if there is already something with the target's name in the module.
884f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
8854695f91f4302a90ae462cd64dda59b34c3dad821Joerg Sonnenberger  if (Entry) {
8864695f91f4302a90ae462cd64dda59b34c3dad821Joerg Sonnenberger    unsigned AS = getContext().getTargetAddressSpace(VD->getType());
8874695f91f4302a90ae462cd64dda59b34c3dad821Joerg Sonnenberger    return llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
8884695f91f4302a90ae462cd64dda59b34c3dad821Joerg Sonnenberger  }
8896a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
8906a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  llvm::Constant *Aliasee;
8916a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  if (isa<llvm::FunctionType>(DeclTy))
892c857ce8b08397ed778928b8a000732ca90da2a8cAlex Rosenberg    Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
893c857ce8b08397ed778928b8a000732ca90da2a8cAlex Rosenberg                                      GlobalDecl(cast<FunctionDecl>(VD)),
8941faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson                                      /*ForVTable=*/false);
8956a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  else
896f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
8976a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola                                    llvm::PointerType::getUnqual(DeclTy), 0);
8984695f91f4302a90ae462cd64dda59b34c3dad821Joerg Sonnenberger
8994695f91f4302a90ae462cd64dda59b34c3dad821Joerg Sonnenberger  llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
9004695f91f4302a90ae462cd64dda59b34c3dad821Joerg Sonnenberger  F->setLinkage(llvm::Function::ExternalWeakLinkage);
9014695f91f4302a90ae462cd64dda59b34c3dad821Joerg Sonnenberger  WeakRefReferences.insert(F);
9026a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
9036a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  return Aliasee;
9046a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola}
9056a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
906b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattnervoid CodeGenModule::EmitGlobal(GlobalDecl GD) {
9074a6835e650ff24e19ce08a3bd347c0ad186777fdAnders Carlsson  const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
9081eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
9096a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  // Weak references don't produce any output by themselves.
9106a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  if (Global->hasAttr<WeakRefAttr>())
9116a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola    return;
9126a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
913bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  // If this is an alias definition (which otherwise looks like a declaration)
914bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  // emit it now.
91540b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (Global->hasAttr<AliasAttr>())
916f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    return EmitAliasDefinition(GD);
917219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar
918d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne  // If this is CUDA, be selective about which declarations we emit.
9194e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (LangOpts.CUDA) {
920d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne    if (CodeGenOpts.CUDAIsDevice) {
921d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne      if (!Global->hasAttr<CUDADeviceAttr>() &&
922d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne          !Global->hasAttr<CUDAGlobalAttr>() &&
923d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne          !Global->hasAttr<CUDAConstantAttr>() &&
924d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne          !Global->hasAttr<CUDASharedAttr>())
925d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne        return;
926d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne    } else {
927d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne      if (!Global->hasAttr<CUDAHostAttr>() && (
928d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne            Global->hasAttr<CUDADeviceAttr>() ||
929d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne            Global->hasAttr<CUDAConstantAttr>() ||
930d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne            Global->hasAttr<CUDASharedAttr>()))
931d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne        return;
932d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne    }
933d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne  }
934d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne
93567b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // Ignore declarations, they will be emitted on their first use.
9365e1e1f95c98b1add70c238093bbd5dc8d4f9c4e9Daniel Dunbar  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
93773241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar    // Forward declarations are emitted lazily on first use.
938dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky    if (!FD->doesThisDeclarationHaveABody()) {
939dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky      if (!FD->doesDeclarationForceExternallyVisibleDefinition())
940dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky        return;
941dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky
942dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky      const FunctionDecl *InlineDefinition = 0;
943dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky      FD->getBody(InlineDefinition);
944dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky
9455f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner      StringRef MangledName = getMangledName(GD);
9467e42392eb2ea29ddeb6d125417fb4c17d847b5e0Benjamin Kramer      DeferredDecls.erase(MangledName);
947dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky      EmitGlobalDefinition(InlineDefinition);
94873241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar      return;
949dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky    }
9500269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  } else {
9510269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar    const VarDecl *VD = cast<VarDecl>(Global);
952bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar    assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
953bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
954a9a55c063e9e59c6ab0a6d7a21302660f7bde9f9Douglas Gregor    if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
95573241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar      return;
9564c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman  }
9574c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman
95867b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // Defer code generation when possible if this is a static definition, inline
95967b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // function etc.  These we only want to emit if they are used.
9604357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner  if (!MayDeferGeneration(Global)) {
9614357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner    // Emit the definition if it can't be deferred.
9624357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner    EmitGlobalDefinition(GD);
963bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar    return;
964bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar  }
965bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall
966bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall  // If we're deferring emission of a C++ variable with an
967bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall  // initializer, remember the order in which it appeared in the file.
9684e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
969bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall      cast<VarDecl>(Global)->hasInit()) {
970bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall    DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
971bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall    CXXGlobalInits.push_back(0);
972bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall  }
9734357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner
9744357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner  // If the value has already been used, add it directly to the
9754357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner  // DeferredDeclsToEmit list.
9765f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  StringRef MangledName = getMangledName(GD);
9774357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner  if (GetGlobalValue(MangledName))
9784357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner    DeferredDeclsToEmit.push_back(GD);
9794357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner  else {
9804357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner    // Otherwise, remember that we saw a deferred decl with this name.  The
9814357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner    // first use of the mangled name will cause it to move into
9824357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner    // DeferredDeclsToEmit.
9834357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner    DeferredDecls[MangledName] = GD;
9844357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner  }
9854c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman}
9864c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman
987a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindolanamespace {
988a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  struct FunctionIsDirectlyRecursive :
989a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
990a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    const StringRef Name;
991bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola    const Builtin::Context &BI;
992a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    bool Result;
993bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola    FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
994bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola      Name(N), BI(C), Result(false) {
995a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    }
996a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
997a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola
998a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    bool TraverseCallExpr(CallExpr *E) {
999bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola      const FunctionDecl *FD = E->getDirectCallee();
1000bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola      if (!FD)
1001a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola        return true;
1002bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola      AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1003bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola      if (Attr && Name == Attr->getLabel()) {
1004bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola        Result = true;
1005bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola        return false;
1006bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola      }
1007bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola      unsigned BuiltinID = FD->getBuiltinID();
1008bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola      if (!BuiltinID)
1009a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola        return true;
1010f6b56374e4e5b9f0078efac5ed4918c3a04296f7Nick Lewycky      StringRef BuiltinName = BI.GetName(BuiltinID);
1011f6b56374e4e5b9f0078efac5ed4918c3a04296f7Nick Lewycky      if (BuiltinName.startswith("__builtin_") &&
1012f6b56374e4e5b9f0078efac5ed4918c3a04296f7Nick Lewycky          Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
1013a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola        Result = true;
1014a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola        return false;
1015a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola      }
1016a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola      return true;
1017a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    }
1018a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  };
1019a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola}
1020a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola
1021bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola// isTriviallyRecursive - Check if this function calls another
1022bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola// decl that, because of the asm attribute or the other decl being a builtin,
1023bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola// ends up pointing to itself.
1024a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindolabool
1025bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael EspindolaCodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1026bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola  StringRef Name;
1027bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola  if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
102822afaccd9ab77d46106e94c47907d955a014ae3fNick Lewycky    // asm labels are a special kind of mangling we have to support.
1029bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola    AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1030bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola    if (!Attr)
1031bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola      return false;
1032bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola    Name = Attr->getLabel();
1033bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola  } else {
1034bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola    Name = FD->getName();
1035bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola  }
1036a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola
1037bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola  FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1038bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola  Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
1039a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  return Walker.Result;
1040a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola}
1041a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola
1042a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindolabool
1043a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael EspindolaCodeGenModule::shouldEmitFunction(const FunctionDecl *F) {
1044a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  if (getFunctionLinkage(F) != llvm::Function::AvailableExternallyLinkage)
1045a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    return true;
1046cc4889f72ec68319969ba51e214d9940eb9327e5Rafael Espindola  if (CodeGenOpts.OptimizationLevel == 0 &&
1047adc6cbf5b502f1b58078455ab4fca66c7daac239Michael J. Spencer      !F->hasAttr<AlwaysInlineAttr>() && !F->hasAttr<ForceInlineAttr>())
1048a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    return false;
1049a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  // PR9614. Avoid cases where the source code is lying to us. An available
1050a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  // externally function should have an equivalent function somewhere else,
1051a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  // but a function that calls itself is clearly not equivalent to the real
1052a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  // implementation.
1053a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  // This happens in glibc's btowc and in some configure checks.
1054bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola  return !isTriviallyRecursive(F);
1055a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola}
1056a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola
1057b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattnervoid CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
10584a6835e650ff24e19ce08a3bd347c0ad186777fdAnders Carlsson  const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
10591eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1060cb421fa690da545b58a720abe5f1c49b166dbde7Dan Gohman  PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
10618e2efcc267ed12dc435782288b7f9a4a1bc56c72Anders Carlsson                                 Context.getSourceManager(),
10628e2efcc267ed12dc435782288b7f9a4a1bc56c72Anders Carlsson                                 "Generating code for declaration");
10638e2efcc267ed12dc435782288b7f9a4a1bc56c72Anders Carlsson
106444eac33ae12df384f3f002102f919f603bee330fDouglas Gregor  if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
106544eac33ae12df384f3f002102f919f603bee330fDouglas Gregor    // At -O0, don't generate IR for functions with available_externally
106644eac33ae12df384f3f002102f919f603bee330fDouglas Gregor    // linkage.
1067a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    if (!shouldEmitFunction(Function))
106844eac33ae12df384f3f002102f919f603bee330fDouglas Gregor      return;
106944eac33ae12df384f3f002102f919f603bee330fDouglas Gregor
107044eac33ae12df384f3f002102f919f603bee330fDouglas Gregor    if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
10717dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman      // Make sure to emit the definition(s) before we emit the thunks.
10727dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman      // This is necessary for the generation of certain thunks.
10737dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman      if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
10747dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman        EmitCXXConstructor(CD, GD.getCtorType());
10757dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman      else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method))
10767dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman        EmitCXXDestructor(DD, GD.getDtorType());
10777dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman      else
10787dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman        EmitGlobalFunctionDefinition(GD);
10797dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman
108044eac33ae12df384f3f002102f919f603bee330fDouglas Gregor      if (Method->isVirtual())
108144eac33ae12df384f3f002102f919f603bee330fDouglas Gregor        getVTables().EmitThunks(GD);
10827270ee4cd4794281c09dfb6931a98bbb2581ef02Anders Carlsson
10837dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman      return;
108444eac33ae12df384f3f002102f919f603bee330fDouglas Gregor    }
1085b5e8156ebd6accd27daeaae6971597c45d5e5139Chris Lattner
1086b5e8156ebd6accd27daeaae6971597c45d5e5139Chris Lattner    return EmitGlobalFunctionDefinition(GD);
108744eac33ae12df384f3f002102f919f603bee330fDouglas Gregor  }
1088b5e8156ebd6accd27daeaae6971597c45d5e5139Chris Lattner
1089b5e8156ebd6accd27daeaae6971597c45d5e5139Chris Lattner  if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1090b5e8156ebd6accd27daeaae6971597c45d5e5139Chris Lattner    return EmitGlobalVarDefinition(VD);
10914357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner
1092b219cfc4d75f0a03630b7c4509ef791b7e97b2c8David Blaikie  llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
1093bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar}
1094bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
109574391b48b4791cded373683a3baf67314f358d50Chris Lattner/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
109674391b48b4791cded373683a3baf67314f358d50Chris Lattner/// module, create and return an llvm Function with the specified type. If there
109774391b48b4791cded373683a3baf67314f358d50Chris Lattner/// is something in the module with the specified name, return it potentially
109874391b48b4791cded373683a3baf67314f358d50Chris Lattner/// bitcasted to the right type.
109974391b48b4791cded373683a3baf67314f358d50Chris Lattner///
110074391b48b4791cded373683a3baf67314f358d50Chris Lattner/// If D is non-null, it specifies a decl that correspond to this.  This is used
110174391b48b4791cded373683a3baf67314f358d50Chris Lattner/// to set the attributes on the function when it is first created.
1102f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCallllvm::Constant *
11035f9e272e632e951b1efe824cd16acb4d96077930Chris LattnerCodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
11042acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner                                       llvm::Type *Ty,
1105f85e193739c953358c865005855253af4f68a497John McCall                                       GlobalDecl D, bool ForVTable,
1106f85e193739c953358c865005855253af4f68a497John McCall                                       llvm::Attributes ExtraAttrs) {
11070558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  // Lookup the entry, lazily creating it if necessary.
1108f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
11090558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  if (Entry) {
1110d48bcb2f4dedf8e7b654cb017968b3d7b6663a57Benjamin Kramer    if (WeakRefReferences.erase(Entry)) {
11116a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola      const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
11126a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola      if (FD && !FD->hasAttr<WeakAttr>())
11137270ee4cd4794281c09dfb6931a98bbb2581ef02Anders Carlsson        Entry->setLinkage(llvm::Function::ExternalLinkage);
11146a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola    }
11156a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
11160558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    if (Entry->getType()->getElementType() == Ty)
11170558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner      return Entry;
11181eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
11190558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    // Make sure the result is of the correct type.
11209cbe4f0ba01ec304e1e3d071c071f7bca33631c0Chris Lattner    return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
11210558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  }
11221eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1123654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman  // This function doesn't have a complete type (for example, the return
1124654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman  // type is an incomplete struct). Use a fake type instead, and make
1125654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman  // sure not to try to set attributes.
1126654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman  bool IsIncompleteFunction = false;
1127784f21121a6c9418ebd86baa6814e36e1176c410John McCall
11282acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::FunctionType *FTy;
1129784f21121a6c9418ebd86baa6814e36e1176c410John McCall  if (isa<llvm::FunctionType>(Ty)) {
1130784f21121a6c9418ebd86baa6814e36e1176c410John McCall    FTy = cast<llvm::FunctionType>(Ty);
1131784f21121a6c9418ebd86baa6814e36e1176c410John McCall  } else {
11320774cb84719f2aea3016493a2bbd9a02aa3e0541John McCall    FTy = llvm::FunctionType::get(VoidTy, false);
1133654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman    IsIncompleteFunction = true;
1134654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman  }
1135bcaedaed309ce453a992fdeef4a4c908cc7d9dfbChris Lattner
1136784f21121a6c9418ebd86baa6814e36e1176c410John McCall  llvm::Function *F = llvm::Function::Create(FTy,
1137654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman                                             llvm::Function::ExternalLinkage,
1138f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall                                             MangledName, &getModule());
1139f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  assert(F->getName() == MangledName && "name was uniqued!");
1140654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman  if (D.getDecl())
1141b2bcf1c176b200b36f371e189ce22f93c86cdf45Anders Carlsson    SetFunctionAttributes(D, F, IsIncompleteFunction);
1142fac631052809b59c1b66f687c08a743de7fb50e9Bill Wendling  if (ExtraAttrs.hasAttributes())
114375d37b493e2282f993a19a166bd573b03a7535afBill Wendling    F->addAttribute(llvm::AttrListPtr::FunctionIndex, ExtraAttrs);
1144654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman
114567b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // This is the first use or definition of a mangled name.  If there is a
114667b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // deferred decl with this name, remember that we need to emit it at the end
114767b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // of the file.
1148f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
114967b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  if (DDI != DeferredDecls.end()) {
115067b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
115167b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    // list, and remove it from DeferredDecls (since we don't need it anymore).
115267b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    DeferredDeclsToEmit.push_back(DDI->second);
115367b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    DeferredDecls.erase(DDI);
1154bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall
1155bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  // Otherwise, there are cases we have to worry about where we're
1156bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  // using a declaration for which we must emit a definition but where
1157bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  // we might not find a top-level definition:
1158bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  //   - member functions defined inline in their classes
1159bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  //   - friend functions defined inline in some class
1160bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  //   - special member functions with implicit definitions
1161bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  // If we ever change our AST traversal to walk into class methods,
1162bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  // this will be unnecessary.
11631faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson  //
11641faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson  // We also don't emit a definition for a function if it's going to be an entry
11651faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson  // in a vtable, unless it's already marked as used.
11664e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  } else if (getLangOpts().CPlusPlus && D.getDecl()) {
1167bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall    // Look for a declaration that's lexically in a record.
1168bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall    const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl());
1169b135f0f2d893121ed2cc46d4d6c5bd5ab87d872fEli Friedman    FD = FD->getMostRecentDecl();
1170bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall    do {
1171bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall      if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
11721faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson        if (FD->isImplicit() && !ForVTable) {
1173bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall          assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
1174a29bf41b8f49578207ce36f6b21ff9bb7ee77babDouglas Gregor          DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
1175bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall          break;
117610620eb5164e31208fcbf0437cd79ae535ed0559Sean Hunt        } else if (FD->doesThisDeclarationHaveABody()) {
1177a29bf41b8f49578207ce36f6b21ff9bb7ee77babDouglas Gregor          DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
1178bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall          break;
1179bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall        }
11807b9a5aa7c0d76f577699d25ce6afe21ecccb60b7Rafael Espindola      }
1181ef96ee0be5f100789f451641542a69cd719144d2Douglas Gregor      FD = FD->getPreviousDecl();
1182bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall    } while (FD);
118367b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  }
11841eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1185784f21121a6c9418ebd86baa6814e36e1176c410John McCall  // Make sure the result is of the requested type.
1186784f21121a6c9418ebd86baa6814e36e1176c410John McCall  if (!IsIncompleteFunction) {
1187784f21121a6c9418ebd86baa6814e36e1176c410John McCall    assert(F->getType()->getElementType() == Ty);
1188784f21121a6c9418ebd86baa6814e36e1176c410John McCall    return F;
1189784f21121a6c9418ebd86baa6814e36e1176c410John McCall  }
1190784f21121a6c9418ebd86baa6814e36e1176c410John McCall
11919cbe4f0ba01ec304e1e3d071c071f7bca33631c0Chris Lattner  llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
1192784f21121a6c9418ebd86baa6814e36e1176c410John McCall  return llvm::ConstantExpr::getBitCast(F, PTy);
11930558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner}
11940558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner
119574391b48b4791cded373683a3baf67314f358d50Chris Lattner/// GetAddrOfFunction - Return the address of the given function.  If Ty is
119674391b48b4791cded373683a3baf67314f358d50Chris Lattner/// non-null, then this function will use the specified type if it has to
119774391b48b4791cded373683a3baf67314f358d50Chris Lattner/// create it (this occurs when we see a definition of the function).
1198b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattnerllvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
11992acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner                                                 llvm::Type *Ty,
12001faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson                                                 bool ForVTable) {
120174391b48b4791cded373683a3baf67314f358d50Chris Lattner  // If there was no specific requested type, just convert it now.
120274391b48b4791cded373683a3baf67314f358d50Chris Lattner  if (!Ty)
12034a6835e650ff24e19ce08a3bd347c0ad186777fdAnders Carlsson    Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
1204bcaedaed309ce453a992fdeef4a4c908cc7d9dfbChris Lattner
12055f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  StringRef MangledName = getMangledName(GD);
12061faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson  return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable);
120774391b48b4791cded373683a3baf67314f358d50Chris Lattner}
120877ba708819285931932ecd33691a672bb59d221aEli Friedman
120974391b48b4791cded373683a3baf67314f358d50Chris Lattner/// CreateRuntimeFunction - Create a new runtime function with the specified
121074391b48b4791cded373683a3baf67314f358d50Chris Lattner/// type and name.
121174391b48b4791cded373683a3baf67314f358d50Chris Lattnerllvm::Constant *
12122acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris LattnerCodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
12135f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner                                     StringRef Name,
1214f85e193739c953358c865005855253af4f68a497John McCall                                     llvm::Attributes ExtraAttrs) {
1215f85e193739c953358c865005855253af4f68a497John McCall  return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
1216f85e193739c953358c865005855253af4f68a497John McCall                                 ExtraAttrs);
121774391b48b4791cded373683a3baf67314f358d50Chris Lattner}
1218bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
1219a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith/// isTypeConstant - Determine whether an object of this type can be emitted
1220a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith/// as a constant.
1221a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith///
1222a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith/// If ExcludeCtor is true, the duration when the object's constructor runs
1223a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith/// will not be considered. The caller will need to verify that the object is
1224a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith/// not written to during its construction.
1225a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smithbool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
1226a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith  if (!Ty.isConstant(Context) && !Ty->isReferenceType())
122720e098b7e7fda6bed1d67441b56cce77cd3aa918Eli Friedman    return false;
1228a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith
12294e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (Context.getLangOpts().CPlusPlus) {
1230a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith    if (const CXXRecordDecl *Record
1231a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith          = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
1232a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith      return ExcludeCtor && !Record->hasMutableFields() &&
1233a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith             Record->hasTrivialDestructor();
123420e098b7e7fda6bed1d67441b56cce77cd3aa918Eli Friedman  }
1235a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith
123620e098b7e7fda6bed1d67441b56cce77cd3aa918Eli Friedman  return true;
123720e098b7e7fda6bed1d67441b56cce77cd3aa918Eli Friedman}
123820e098b7e7fda6bed1d67441b56cce77cd3aa918Eli Friedman
123974391b48b4791cded373683a3baf67314f358d50Chris Lattner/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
124074391b48b4791cded373683a3baf67314f358d50Chris Lattner/// create and return an llvm GlobalVariable with the specified type.  If there
124174391b48b4791cded373683a3baf67314f358d50Chris Lattner/// is something in the module with the specified name, return it potentially
124274391b48b4791cded373683a3baf67314f358d50Chris Lattner/// bitcasted to the right type.
124374391b48b4791cded373683a3baf67314f358d50Chris Lattner///
124474391b48b4791cded373683a3baf67314f358d50Chris Lattner/// If D is non-null, it specifies a decl that correspond to this.  This is used
124574391b48b4791cded373683a3baf67314f358d50Chris Lattner/// to set the attributes on the global when it is first created.
1246f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCallllvm::Constant *
12475f9e272e632e951b1efe824cd16acb4d96077930Chris LattnerCodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
12482acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner                                     llvm::PointerType *Ty,
1249c532b502858032f377056dc8cba2fe43cba8702bRafael Espindola                                     const VarDecl *D,
1250c532b502858032f377056dc8cba2fe43cba8702bRafael Espindola                                     bool UnnamedAddr) {
12513c827a79cb7d04c255db8080e682ee2c6912373dDaniel Dunbar  // Lookup the entry, lazily creating it if necessary.
1252f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
125399b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner  if (Entry) {
1254d48bcb2f4dedf8e7b654cb017968b3d7b6663a57Benjamin Kramer    if (WeakRefReferences.erase(Entry)) {
12556a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola      if (D && !D->hasAttr<WeakAttr>())
12567270ee4cd4794281c09dfb6931a98bbb2581ef02Anders Carlsson        Entry->setLinkage(llvm::Function::ExternalLinkage);
12576a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola    }
12586a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
1259c532b502858032f377056dc8cba2fe43cba8702bRafael Espindola    if (UnnamedAddr)
1260c532b502858032f377056dc8cba2fe43cba8702bRafael Espindola      Entry->setUnnamedAddr(true);
1261c532b502858032f377056dc8cba2fe43cba8702bRafael Espindola
126274391b48b4791cded373683a3baf67314f358d50Chris Lattner    if (Entry->getType() == Ty)
1263570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner      return Entry;
12641eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
126599b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner    // Make sure the result is of the correct type.
12663c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson    return llvm::ConstantExpr::getBitCast(Entry, Ty);
126799b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner  }
12681eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
126967b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // This is the first use or definition of a mangled name.  If there is a
127067b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // deferred decl with this name, remember that we need to emit it at the end
127167b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // of the file.
1272f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
127367b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  if (DDI != DeferredDecls.end()) {
127467b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
127567b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    // list, and remove it from DeferredDecls (since we don't need it anymore).
127667b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    DeferredDeclsToEmit.push_back(DDI->second);
127767b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    DeferredDecls.erase(DDI);
127867b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  }
12791eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
12804dc34ebf2a0716bf77ba110dab6777a3fc4397ddPeter Collingbourne  unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
12811eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  llvm::GlobalVariable *GV =
12821eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
128399b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner                             llvm::GlobalValue::ExternalLinkage,
1284f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall                             0, MangledName, 0,
12855e2d5dec7736f6f9292d4212dec67295909f1328Hans Wennborg                             llvm::GlobalVariable::NotThreadLocal, AddrSpace);
128649988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar
128799b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner  // Handle things which are present even on external declarations.
128874391b48b4791cded373683a3baf67314f358d50Chris Lattner  if (D) {
1289f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump    // FIXME: This code is overly simple and should be merged with other global
1290f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump    // handling.
1291a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith    GV->setConstant(isTypeConstant(D->getType(), false));
129249988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar
1293110e8e56af30363072c140285961592b0107f789John McCall    // Set linkage and visibility in case we never see a definition.
1294af14603ca61757cf4361b583b45639a04c57e651John McCall    NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
1295af14603ca61757cf4361b583b45639a04c57e651John McCall    if (LV.linkage() != ExternalLinkage) {
129615e310a3b970b64a84cb30f0005bc396b4d978cbJohn McCall      // Don't set internal linkage on declarations.
1297110e8e56af30363072c140285961592b0107f789John McCall    } else {
1298110e8e56af30363072c140285961592b0107f789John McCall      if (D->hasAttr<DLLImportAttr>())
1299110e8e56af30363072c140285961592b0107f789John McCall        GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
13000a0d2b179085a52c10402feebeb6db8b4d96a140Douglas Gregor      else if (D->hasAttr<WeakAttr>() || D->isWeakImported())
1301110e8e56af30363072c140285961592b0107f789John McCall        GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1302110e8e56af30363072c140285961592b0107f789John McCall
1303af14603ca61757cf4361b583b45639a04c57e651John McCall      // Set visibility on a declaration only if it's explicit.
1304af14603ca61757cf4361b583b45639a04c57e651John McCall      if (LV.visibilityExplicit())
1305af14603ca61757cf4361b583b45639a04c57e651John McCall        GV->setVisibility(GetLLVMVisibility(LV.visibility()));
1306110e8e56af30363072c140285961592b0107f789John McCall    }
130756ebe5082da7411fb37479e230b52735f77cff35Eli Friedman
1308de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg    if (D->isThreadSpecified())
1309de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg      setTLSMode(GV, *D);
131074391b48b4791cded373683a3baf67314f358d50Chris Lattner  }
13111eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
13124dc34ebf2a0716bf77ba110dab6777a3fc4397ddPeter Collingbourne  if (AddrSpace != Ty->getAddressSpace())
13134dc34ebf2a0716bf77ba110dab6777a3fc4397ddPeter Collingbourne    return llvm::ConstantExpr::getBitCast(GV, Ty);
13144dc34ebf2a0716bf77ba110dab6777a3fc4397ddPeter Collingbourne  else
13154dc34ebf2a0716bf77ba110dab6777a3fc4397ddPeter Collingbourne    return GV;
131674391b48b4791cded373683a3baf67314f358d50Chris Lattner}
1317eda9a5ec380f172f4e0063744eb796144a125480Daniel Dunbar
1318eda9a5ec380f172f4e0063744eb796144a125480Daniel Dunbar
13193bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlssonllvm::GlobalVariable *
13205f9e272e632e951b1efe824cd16acb4d96077930Chris LattnerCodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
13212acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner                                      llvm::Type *Ty,
13223bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson                                      llvm::GlobalValue::LinkageTypes Linkage) {
13233bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
13243bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  llvm::GlobalVariable *OldGV = 0;
13253bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
13263bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
13273bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  if (GV) {
13283bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    // Check if the variable has the right type.
13293bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    if (GV->getType()->getElementType() == Ty)
13303bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson      return GV;
13313bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
13323bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    // Because C++ name mangling, the only way we can end up with an already
13333bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    // existing global with the same name is if it has been declared extern "C".
1334c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber    assert(GV->isDeclaration() && "Declaration has wrong type!");
13353bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    OldGV = GV;
13363bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  }
13373bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
13383bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  // Create a new variable.
13393bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
13403bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson                                Linkage, 0, Name);
13413bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
13423bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  if (OldGV) {
13433bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    // Replace occurrences of the old variable if needed.
13443bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    GV->takeName(OldGV);
13453bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
13463bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    if (!OldGV->use_empty()) {
13473bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson      llvm::Constant *NewPtrForOldDecl =
13483bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson      llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
13493bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson      OldGV->replaceAllUsesWith(NewPtrForOldDecl);
13503bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    }
13513bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
13523bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    OldGV->eraseFromParent();
13533bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  }
13543bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
13553bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  return GV;
13563bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson}
13573bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
135874391b48b4791cded373683a3baf67314f358d50Chris Lattner/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
135974391b48b4791cded373683a3baf67314f358d50Chris Lattner/// given global variable.  If Ty is non-null and if the global doesn't exist,
13600ff258b933fe385425bf2a85429bf46376d338f1Eric Christopher/// then it will be created with the specified type instead of whatever the
136174391b48b4791cded373683a3baf67314f358d50Chris Lattner/// normal requested type would be.
136274391b48b4791cded373683a3baf67314f358d50Chris Lattnerllvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
13632acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner                                                  llvm::Type *Ty) {
136474391b48b4791cded373683a3baf67314f358d50Chris Lattner  assert(D->hasGlobalStorage() && "Not a global variable");
136574391b48b4791cded373683a3baf67314f358d50Chris Lattner  QualType ASTTy = D->getType();
136674391b48b4791cded373683a3baf67314f358d50Chris Lattner  if (Ty == 0)
136774391b48b4791cded373683a3baf67314f358d50Chris Lattner    Ty = getTypes().ConvertTypeForMem(ASTTy);
13681eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
13692acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::PointerType *PTy =
1370207f4d8543529221932af82836016a2ef066c917Peter Collingbourne    llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
1371f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall
13725f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  StringRef MangledName = getMangledName(D);
1373f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  return GetOrCreateLLVMGlobal(MangledName, PTy, D);
137474391b48b4791cded373683a3baf67314f358d50Chris Lattner}
13753f75c43bd77e063342bc888ac276daf64ba0ce07Daniel Dunbar
137674391b48b4791cded373683a3baf67314f358d50Chris Lattner/// CreateRuntimeVariable - Create a new runtime global variable with the
137774391b48b4791cded373683a3baf67314f358d50Chris Lattner/// specified type and name.
137874391b48b4791cded373683a3baf67314f358d50Chris Lattnerllvm::Constant *
13792acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris LattnerCodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
13805f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner                                     StringRef Name) {
13811de4d4e8cb2e9c88809fea8092bc6e835a5473d2John McCall  return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
1382c532b502858032f377056dc8cba2fe43cba8702bRafael Espindola                               true);
1383bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar}
1384bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
138503f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbarvoid CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
138603f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar  assert(!D->getInit() && "Cannot emit definite definitions here!");
138703f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar
13887520bd1de12af10ea08c662440565adbdf589317Douglas Gregor  if (MayDeferGeneration(D)) {
13897520bd1de12af10ea08c662440565adbdf589317Douglas Gregor    // If we have not seen a reference to this variable yet, place it
13907520bd1de12af10ea08c662440565adbdf589317Douglas Gregor    // into the deferred declarations table to be emitted if needed
13917520bd1de12af10ea08c662440565adbdf589317Douglas Gregor    // later.
13925f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner    StringRef MangledName = getMangledName(D);
1393f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    if (!GetGlobalValue(MangledName)) {
1394555b4bb2749aea2ec8e2adc351a71ec1cb9bdc33Anders Carlsson      DeferredDecls[MangledName] = D;
139503f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar      return;
13967520bd1de12af10ea08c662440565adbdf589317Douglas Gregor    }
13977520bd1de12af10ea08c662440565adbdf589317Douglas Gregor  }
13987520bd1de12af10ea08c662440565adbdf589317Douglas Gregor
13997520bd1de12af10ea08c662440565adbdf589317Douglas Gregor  // The tentative definition is the only definition.
140003f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar  EmitGlobalVarDefinition(D);
140103f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar}
140203f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar
14036fb745bdf1ff1e32caf07e42093a7920726892c1Douglas Gregorvoid CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) {
14046fb745bdf1ff1e32caf07e42093a7920726892c1Douglas Gregor  if (DefinitionRequired)
14059ee494f98610dcd79441dce469d7bf609fcd7b92Charles Davis    getCXXABI().EmitVTables(Class);
14066fb745bdf1ff1e32caf07e42093a7920726892c1Douglas Gregor}
14076fb745bdf1ff1e32caf07e42093a7920726892c1Douglas Gregor
14084b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregorllvm::GlobalVariable::LinkageTypes
1409046c294a43024874ff35656c6e785b64e72f1f36Anders CarlssonCodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
1410cb5d2d0647fdab2e36c85b417e03bf18916ce10cEli Friedman  if (RD->getLinkage() != ExternalLinkage)
1411dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor    return llvm::GlobalVariable::InternalLinkage;
1412dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor
1413dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor  if (const CXXMethodDecl *KeyFunction
1414dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor                                    = RD->getASTContext().getKeyFunction(RD)) {
1415dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor    // If this class has a key function, use that to determine the linkage of
1416dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor    // the vtable.
14174b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor    const FunctionDecl *Def = 0;
141806a54a38be5054c910ffc92db60edab23f9ea105Argyrios Kyrtzidis    if (KeyFunction->hasBody(Def))
14194b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor      KeyFunction = cast<CXXMethodDecl>(Def);
1420dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor
14214b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor    switch (KeyFunction->getTemplateSpecializationKind()) {
14224b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor      case TSK_Undeclared:
14234b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor      case TSK_ExplicitSpecialization:
14246d7f8473cd6e967b3676948894ce72472102f9cbAnders Carlsson        // When compiling with optimizations turned on, we emit all vtables,
14256d7f8473cd6e967b3676948894ce72472102f9cbAnders Carlsson        // even if the key function is not defined in the current translation
14266d7f8473cd6e967b3676948894ce72472102f9cbAnders Carlsson        // unit. If this is the case, use available_externally linkage.
14276d7f8473cd6e967b3676948894ce72472102f9cbAnders Carlsson        if (!Def && CodeGenOpts.OptimizationLevel)
14286d7f8473cd6e967b3676948894ce72472102f9cbAnders Carlsson          return llvm::GlobalVariable::AvailableExternallyLinkage;
14296d7f8473cd6e967b3676948894ce72472102f9cbAnders Carlsson
14304b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor        if (KeyFunction->isInlined())
14314e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie          return !Context.getLangOpts().AppleKext ?
1432142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian                   llvm::GlobalVariable::LinkOnceODRLinkage :
1433142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian                   llvm::Function::InternalLinkage;
14344b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor
14354b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor        return llvm::GlobalVariable::ExternalLinkage;
14364b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor
14374b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor      case TSK_ImplicitInstantiation:
14384e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie        return !Context.getLangOpts().AppleKext ?
1439142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian                 llvm::GlobalVariable::LinkOnceODRLinkage :
1440142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian                 llvm::Function::InternalLinkage;
1441f502d93b0ea970bfbd897e657f8d940a20984de2Anders Carlsson
14424b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor      case TSK_ExplicitInstantiationDefinition:
14434e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie        return !Context.getLangOpts().AppleKext ?
1444142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian                 llvm::GlobalVariable::WeakODRLinkage :
1445142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian                 llvm::Function::InternalLinkage;
1446f502d93b0ea970bfbd897e657f8d940a20984de2Anders Carlsson
14474b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor      case TSK_ExplicitInstantiationDeclaration:
14484b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor        // FIXME: Use available_externally linkage. However, this currently
14494b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor        // breaks LLVM's build due to undefined symbols.
14504b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor        //      return llvm::GlobalVariable::AvailableExternallyLinkage;
14514e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie        return !Context.getLangOpts().AppleKext ?
1452142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian                 llvm::GlobalVariable::LinkOnceODRLinkage :
1453142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian                 llvm::Function::InternalLinkage;
14544b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor    }
1455dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor  }
1456dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor
14574e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (Context.getLangOpts().AppleKext)
145853bad4e98ed5e765df4231099bf1c737582908bfFariborz Jahanian    return llvm::Function::InternalLinkage;
145953bad4e98ed5e765df4231099bf1c737582908bfFariborz Jahanian
1460dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor  switch (RD->getTemplateSpecializationKind()) {
1461dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor  case TSK_Undeclared:
1462dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor  case TSK_ExplicitSpecialization:
1463dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor  case TSK_ImplicitInstantiation:
1464dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor    // FIXME: Use available_externally linkage. However, this currently
1465dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor    // breaks LLVM's build due to undefined symbols.
1466dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor    //   return llvm::GlobalVariable::AvailableExternallyLinkage;
1467142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian  case TSK_ExplicitInstantiationDeclaration:
146853bad4e98ed5e765df4231099bf1c737582908bfFariborz Jahanian    return llvm::GlobalVariable::LinkOnceODRLinkage;
1469142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian
1470142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian  case TSK_ExplicitInstantiationDefinition:
147153bad4e98ed5e765df4231099bf1c737582908bfFariborz Jahanian      return llvm::GlobalVariable::WeakODRLinkage;
14724b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor  }
14733026348bd4c13a0f83b59839f64065e0fcbea253David Blaikie
14743026348bd4c13a0f83b59839f64065e0fcbea253David Blaikie  llvm_unreachable("Invalid TemplateSpecializationKind!");
14754b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor}
14764b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor
14772acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris LattnerCharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
147806f486ecd05bd6788da97c39164c1903a084c26dKen Dyck    return Context.toCharUnitsFromBits(
147925a6a84cf5067b32c271e3ba078676dee838798dMicah Villmow      TheDataLayout.getTypeStoreSizeInBits(Ty));
1480687cc4a850b59116efee061018f0d8df50728b82Ken Dyck}
1481687cc4a850b59116efee061018f0d8df50728b82Ken Dyck
148219b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redlllvm::Constant *
148319b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian RedlCodeGenModule::MaybeEmitGlobalStdInitializerListInitializer(const VarDecl *D,
148419b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl                                                       const Expr *rawInit) {
148519b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  ArrayRef<ExprWithCleanups::CleanupObject> cleanups;
148619b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  if (const ExprWithCleanups *withCleanups =
148719b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl          dyn_cast<ExprWithCleanups>(rawInit)) {
148819b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    cleanups = withCleanups->getObjects();
148919b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    rawInit = withCleanups->getSubExpr();
149019b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  }
149119b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl
149219b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  const InitListExpr *init = dyn_cast<InitListExpr>(rawInit);
149319b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  if (!init || !init->initializesStdInitializerList() ||
149419b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl      init->getNumInits() == 0)
149519b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    return 0;
149619b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl
149719b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  ASTContext &ctx = getContext();
149819b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  unsigned numInits = init->getNumInits();
1499062a82cdfab01d95f7fa3d759342e6f2ee5c51b0Sebastian Redl  // FIXME: This check is here because we would otherwise silently miscompile
1500062a82cdfab01d95f7fa3d759342e6f2ee5c51b0Sebastian Redl  // nested global std::initializer_lists. Better would be to have a real
1501062a82cdfab01d95f7fa3d759342e6f2ee5c51b0Sebastian Redl  // implementation.
1502062a82cdfab01d95f7fa3d759342e6f2ee5c51b0Sebastian Redl  for (unsigned i = 0; i < numInits; ++i) {
1503062a82cdfab01d95f7fa3d759342e6f2ee5c51b0Sebastian Redl    const InitListExpr *inner = dyn_cast<InitListExpr>(init->getInit(i));
1504062a82cdfab01d95f7fa3d759342e6f2ee5c51b0Sebastian Redl    if (inner && inner->initializesStdInitializerList()) {
1505062a82cdfab01d95f7fa3d759342e6f2ee5c51b0Sebastian Redl      ErrorUnsupported(inner, "nested global std::initializer_list");
1506062a82cdfab01d95f7fa3d759342e6f2ee5c51b0Sebastian Redl      return 0;
1507062a82cdfab01d95f7fa3d759342e6f2ee5c51b0Sebastian Redl    }
1508062a82cdfab01d95f7fa3d759342e6f2ee5c51b0Sebastian Redl  }
1509062a82cdfab01d95f7fa3d759342e6f2ee5c51b0Sebastian Redl
1510062a82cdfab01d95f7fa3d759342e6f2ee5c51b0Sebastian Redl  // Synthesize a fake VarDecl for the array and initialize that.
151119b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  QualType elementType = init->getInit(0)->getType();
151219b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  llvm::APInt numElements(ctx.getTypeSize(ctx.getSizeType()), numInits);
151319b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  QualType arrayType = ctx.getConstantArrayType(elementType, numElements,
151419b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl                                                ArrayType::Normal, 0);
151519b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl
151619b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  IdentifierInfo *name = &ctx.Idents.get(D->getNameAsString() + "__initlist");
151719b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  TypeSourceInfo *sourceInfo = ctx.getTrivialTypeSourceInfo(
151819b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl                                              arrayType, D->getLocation());
151919b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  VarDecl *backingArray = VarDecl::Create(ctx, const_cast<DeclContext*>(
152019b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl                                                          D->getDeclContext()),
152119b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl                                          D->getLocStart(), D->getLocation(),
152219b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl                                          name, arrayType, sourceInfo,
152319b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl                                          SC_Static, SC_Static);
152419b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl
152519b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  // Now clone the InitListExpr to initialize the array instead.
152619b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  // Incredible hack: we want to use the existing InitListExpr here, so we need
152719b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  // to tell it that it no longer initializes a std::initializer_list.
15283b6bef9a213249c6ab6d67c07b1ac6380961be3eBenjamin Kramer  ArrayRef<Expr*> Inits(const_cast<InitListExpr*>(init)->getInits(),
15293b6bef9a213249c6ab6d67c07b1ac6380961be3eBenjamin Kramer                        init->getNumInits());
15303b6bef9a213249c6ab6d67c07b1ac6380961be3eBenjamin Kramer  Expr *arrayInit = new (ctx) InitListExpr(ctx, init->getLBraceLoc(), Inits,
15313b6bef9a213249c6ab6d67c07b1ac6380961be3eBenjamin Kramer                                           init->getRBraceLoc());
153219b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  arrayInit->setType(arrayType);
153319b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl
153419b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  if (!cleanups.empty())
153519b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    arrayInit = ExprWithCleanups::Create(ctx, arrayInit, cleanups);
153619b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl
153719b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  backingArray->setInit(arrayInit);
153819b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl
153919b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  // Emit the definition of the array.
154019b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  EmitGlobalVarDefinition(backingArray);
154119b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl
154219b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  // Inspect the initializer list to validate it and determine its type.
154319b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  // FIXME: doing this every time is probably inefficient; caching would be nice
154419b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  RecordDecl *record = init->getType()->castAs<RecordType>()->getDecl();
154519b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  RecordDecl::field_iterator field = record->field_begin();
154619b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  if (field == record->field_end()) {
154719b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    ErrorUnsupported(D, "weird std::initializer_list");
154819b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    return 0;
154919b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  }
155019b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  QualType elementPtr = ctx.getPointerType(elementType.withConst());
155119b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  // Start pointer.
155219b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  if (!ctx.hasSameType(field->getType(), elementPtr)) {
155319b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    ErrorUnsupported(D, "weird std::initializer_list");
155419b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    return 0;
155519b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  }
155619b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  ++field;
155719b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  if (field == record->field_end()) {
155819b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    ErrorUnsupported(D, "weird std::initializer_list");
155919b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    return 0;
156019b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  }
156119b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  bool isStartEnd = false;
156219b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  if (ctx.hasSameType(field->getType(), elementPtr)) {
156319b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    // End pointer.
156419b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    isStartEnd = true;
156519b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  } else if(!ctx.hasSameType(field->getType(), ctx.getSizeType())) {
156619b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    ErrorUnsupported(D, "weird std::initializer_list");
156719b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    return 0;
156819b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  }
156919b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl
157019b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  // Now build an APValue representing the std::initializer_list.
157119b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  APValue initListValue(APValue::UninitStruct(), 0, 2);
157219b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  APValue &startField = initListValue.getStructField(0);
157319b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  APValue::LValuePathEntry startOffsetPathEntry;
157419b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  startOffsetPathEntry.ArrayIndex = 0;
157519b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  startField = APValue(APValue::LValueBase(backingArray),
157619b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl                       CharUnits::fromQuantity(0),
157719b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl                       llvm::makeArrayRef(startOffsetPathEntry),
157819b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl                       /*IsOnePastTheEnd=*/false, 0);
157919b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl
158019b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  if (isStartEnd) {
158119b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    APValue &endField = initListValue.getStructField(1);
158219b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    APValue::LValuePathEntry endOffsetPathEntry;
158319b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    endOffsetPathEntry.ArrayIndex = numInits;
158419b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    endField = APValue(APValue::LValueBase(backingArray),
158519b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl                       ctx.getTypeSizeInChars(elementType) * numInits,
158619b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl                       llvm::makeArrayRef(endOffsetPathEntry),
158719b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl                       /*IsOnePastTheEnd=*/true, 0);
158819b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  } else {
158919b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    APValue &sizeField = initListValue.getStructField(1);
159019b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    sizeField = APValue(llvm::APSInt(numElements));
159119b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  }
159219b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl
159319b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  // Emit the constant for the initializer_list.
1594a3ca41f0c2bd1c4a752df88b283332f3b757d21eRichard Smith  llvm::Constant *llvmInit =
1595a3ca41f0c2bd1c4a752df88b283332f3b757d21eRichard Smith      EmitConstantValueForMemory(initListValue, D->getType());
159619b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  assert(llvmInit && "failed to initialize as constant");
159719b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  return llvmInit;
159819b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl}
159919b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl
16004dc34ebf2a0716bf77ba110dab6777a3fc4397ddPeter Collingbourneunsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
16014dc34ebf2a0716bf77ba110dab6777a3fc4397ddPeter Collingbourne                                                 unsigned AddrSpace) {
16024dc34ebf2a0716bf77ba110dab6777a3fc4397ddPeter Collingbourne  if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) {
16034dc34ebf2a0716bf77ba110dab6777a3fc4397ddPeter Collingbourne    if (D->hasAttr<CUDAConstantAttr>())
16044dc34ebf2a0716bf77ba110dab6777a3fc4397ddPeter Collingbourne      AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
16054dc34ebf2a0716bf77ba110dab6777a3fc4397ddPeter Collingbourne    else if (D->hasAttr<CUDASharedAttr>())
16064dc34ebf2a0716bf77ba110dab6777a3fc4397ddPeter Collingbourne      AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
16074dc34ebf2a0716bf77ba110dab6777a3fc4397ddPeter Collingbourne    else
16084dc34ebf2a0716bf77ba110dab6777a3fc4397ddPeter Collingbourne      AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
16094dc34ebf2a0716bf77ba110dab6777a3fc4397ddPeter Collingbourne  }
16104dc34ebf2a0716bf77ba110dab6777a3fc4397ddPeter Collingbourne
16114dc34ebf2a0716bf77ba110dab6777a3fc4397ddPeter Collingbourne  return AddrSpace;
16124dc34ebf2a0716bf77ba110dab6777a3fc4397ddPeter Collingbourne}
16134dc34ebf2a0716bf77ba110dab6777a3fc4397ddPeter Collingbourne
1614bd012ff1fa088181646a784f385b28867372d434Daniel Dunbarvoid CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
16158f32f7189b12f67aa4a19bc7c3855b599980eca0Chris Lattner  llvm::Constant *Init = 0;
161677ba708819285931932ecd33691a672bb59d221aEli Friedman  QualType ASTTy = D->getType();
16177ca4850a3e3530fa6c93b64b740446e32c97f992Richard Smith  CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
16187ca4850a3e3530fa6c93b64b740446e32c97f992Richard Smith  bool NeedsGlobalCtor = false;
16197ca4850a3e3530fa6c93b64b740446e32c97f992Richard Smith  bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
16201eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
16212d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith  const VarDecl *InitDecl;
16222d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith  const Expr *InitExpr = D->getAnyInitializer(InitDecl);
162319b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl
16243bb92693c3332c1e99870a4e45afff3892e1c6aeAnders Carlsson  if (!InitExpr) {
1625cd5f4aaf0c219189878126d556f35e38fdb8afa1Eli Friedman    // This is a tentative definition; tentative definitions are
162603f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // implicitly initialized with { 0 }.
162703f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    //
162803f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // Note that tentative definitions are only emitted at the end of
162903f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // a translation unit, so they should never have incomplete
163003f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // type. In addition, EmitTentativeDefinition makes sure that we
163103f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // never attempt to emit a tentative definition if a real one
163203f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // exists. A use may still exists, however, so we still may need
163303f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // to do a RAUW.
163403f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
1635b0d0ea042116c1f451d3db8ceff9f1dd92bc36d2Anders Carlsson    Init = EmitNullConstant(D->getType());
163677ba708819285931932ecd33691a672bb59d221aEli Friedman  } else {
163719b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    // If this is a std::initializer_list, emit the special initializer.
163819b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    Init = MaybeEmitGlobalStdInitializerListInitializer(D, InitExpr);
163919b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    // An empty init list will perform zero-initialization, which happens
164019b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    // to be exactly what we want.
164119b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    // FIXME: It does so in a global constructor, which is *not* what we
164219b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    // want.
164319b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl
16444904bf4e84cfb48080270ebaa9005327f18ab0e5Fariborz Jahanian    if (!Init) {
16454904bf4e84cfb48080270ebaa9005327f18ab0e5Fariborz Jahanian      initializedGlobalDecl = GlobalDecl(D);
164619b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl      Init = EmitConstantInit(*InitDecl);
16474904bf4e84cfb48080270ebaa9005327f18ab0e5Fariborz Jahanian    }
16486e656f45ae04b415ba7a4c0c25e55633e2d0ecd0Eli Friedman    if (!Init) {
16493bb92693c3332c1e99870a4e45afff3892e1c6aeAnders Carlsson      QualType T = InitExpr->getType();
1650c446d1816f46a4b6d2337102dfc001f55fc18211Douglas Gregor      if (D->getType()->isReferenceType())
1651c446d1816f46a4b6d2337102dfc001f55fc18211Douglas Gregor        T = D->getType();
16522d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith
16534e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie      if (getLangOpts().CPlusPlus) {
165489ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson        Init = EmitNullConstant(T);
16557ca4850a3e3530fa6c93b64b740446e32c97f992Richard Smith        NeedsGlobalCtor = true;
165689ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson      } else {
165789ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson        ErrorUnsupported(D, "static initializer");
165889ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson        Init = llvm::UndefValue::get(getTypes().ConvertType(T));
165989ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson      }
1660bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall    } else {
1661bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall      // We don't need an initializer, so remove the entry for the delayed
16627ca4850a3e3530fa6c93b64b740446e32c97f992Richard Smith      // initializer position (just in case this entry was delayed) if we
16637ca4850a3e3530fa6c93b64b740446e32c97f992Richard Smith      // also don't need to register a destructor.
16644e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie      if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
1665bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall        DelayedCXXInitPosition.erase(D);
16666e656f45ae04b415ba7a4c0c25e55633e2d0ecd0Eli Friedman    }
16678f32f7189b12f67aa4a19bc7c3855b599980eca0Chris Lattner  }
16688e53e720b3d7c962e91138a130dbd5d6c2def0e5Devang Patel
16692acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type* InitType = Init->getType();
1670570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
16711eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1672570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // Strip off a bitcast if we got one back.
1673570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
16749d4a15fd3b85434c43ea27562793de63a793321aChris Lattner    assert(CE->getOpcode() == llvm::Instruction::BitCast ||
16759d4a15fd3b85434c43ea27562793de63a793321aChris Lattner           // all zero index gep.
16769d4a15fd3b85434c43ea27562793de63a793321aChris Lattner           CE->getOpcode() == llvm::Instruction::GetElementPtr);
1677570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    Entry = CE->getOperand(0);
1678570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  }
16791eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1680570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // Entry is now either a Function or GlobalVariable.
1681570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
16821eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1683570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // We have a definition after a declaration with the wrong type.
1684570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // We must make a new GlobalVariable* and update everything that used OldGV
1685570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // (a declaration or tentative definition) with the new GlobalVariable*
1686570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // (which will be a definition).
1687570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  //
1688570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // This happens if there is a prototype for a global (e.g.
1689570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // "extern int x[];") and then a definition of a different type (e.g.
1690570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // "int x[10];"). This also happens when an initializer has a different type
1691570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // from the type of the global (this happens with unions).
1692570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  if (GV == 0 ||
1693570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner      GV->getType()->getElementType() != InitType ||
1694207f4d8543529221932af82836016a2ef066c917Peter Collingbourne      GV->getType()->getAddressSpace() !=
16954dc34ebf2a0716bf77ba110dab6777a3fc4397ddPeter Collingbourne       GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
16961eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1697f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    // Move the old entry aside so that we'll create a new one.
16985f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner    Entry->setName(StringRef());
1699232350d4faf46ec38d5ff60e11505f9c4fa9535bDaniel Dunbar
1700570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    // Make a new global with the correct type, this is now guaranteed to work.
1701570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
17020558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner
170377ba708819285931932ecd33691a672bb59d221aEli Friedman    // Replace all uses of the old global with the new global
17041eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    llvm::Constant *NewPtrForOldDecl =
17053c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson        llvm::ConstantExpr::getBitCast(GV, Entry->getType());
1706570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    Entry->replaceAllUsesWith(NewPtrForOldDecl);
170777ba708819285931932ecd33691a672bb59d221aEli Friedman
170877ba708819285931932ecd33691a672bb59d221aEli Friedman    // Erase the old global, since it is no longer used.
1709570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    cast<llvm::GlobalValue>(Entry)->eraseFromParent();
171077ba708819285931932ecd33691a672bb59d221aEli Friedman  }
171177ba708819285931932ecd33691a672bb59d221aEli Friedman
171277f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  if (D->hasAttr<AnnotateAttr>())
171377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    AddGlobalAnnotations(D, GV);
17148bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman
171588a69ad80e1550e9932666e6efa050a5b1223889Chris Lattner  GV->setInitializer(Init);
1716e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner
1717e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner  // If it is safe to mark the global 'constant', do so now.
1718a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith  GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
1719a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith                  isTypeConstant(D->getType(), true));
17201eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
17218b752f10c394b140f9ef89e049cbad1a7676fc25Ken Dyck  GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
1722a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith
172388a69ad80e1550e9932666e6efa050a5b1223889Chris Lattner  // Set the llvm linkage type as appropriate.
1724354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  llvm::GlobalValue::LinkageTypes Linkage =
1725354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    GetLLVMLinkageVarDefinition(D, GV);
1726354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  GV->setLinkage(Linkage);
1727354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  if (Linkage == llvm::GlobalVariable::CommonLinkage)
1728354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    // common vars aren't constant even if declared const.
1729354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    GV->setConstant(false);
1730354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian
1731354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  SetCommonAttributes(D, GV);
1732354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian
17333030eb82593097502469a8b3fc26112c79c75605John McCall  // Emit the initializer function if necessary.
17347ca4850a3e3530fa6c93b64b740446e32c97f992Richard Smith  if (NeedsGlobalCtor || NeedsGlobalDtor)
17357ca4850a3e3530fa6c93b64b740446e32c97f992Richard Smith    EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
17363030eb82593097502469a8b3fc26112c79c75605John McCall
173705c5ebc9bafe5613204eefb59a47ab878e4fbd0bKostya Serebryany  // If we are compiling with ASan, add metadata indicating dynamically
173805c5ebc9bafe5613204eefb59a47ab878e4fbd0bKostya Serebryany  // initialized globals.
173905c5ebc9bafe5613204eefb59a47ab878e4fbd0bKostya Serebryany  if (LangOpts.AddressSanitizer && NeedsGlobalCtor) {
174005c5ebc9bafe5613204eefb59a47ab878e4fbd0bKostya Serebryany    llvm::Module &M = getModule();
174105c5ebc9bafe5613204eefb59a47ab878e4fbd0bKostya Serebryany
174205c5ebc9bafe5613204eefb59a47ab878e4fbd0bKostya Serebryany    llvm::NamedMDNode *DynamicInitializers =
174305c5ebc9bafe5613204eefb59a47ab878e4fbd0bKostya Serebryany        M.getOrInsertNamedMetadata("llvm.asan.dynamically_initialized_globals");
174405c5ebc9bafe5613204eefb59a47ab878e4fbd0bKostya Serebryany    llvm::Value *GlobalToAdd[] = { GV };
174505c5ebc9bafe5613204eefb59a47ab878e4fbd0bKostya Serebryany    llvm::MDNode *ThisGlobal = llvm::MDNode::get(VMContext, GlobalToAdd);
174605c5ebc9bafe5613204eefb59a47ab878e4fbd0bKostya Serebryany    DynamicInitializers->addOperand(ThisGlobal);
174705c5ebc9bafe5613204eefb59a47ab878e4fbd0bKostya Serebryany  }
174805c5ebc9bafe5613204eefb59a47ab878e4fbd0bKostya Serebryany
1749354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  // Emit global variable debug information.
175073fb35003aad027492e661a3749e921b5d1ecaf9Eric Christopher  if (CGDebugInfo *DI = getModuleDebugInfo())
17514cdad3151bfb2075c6bdbfe89fbb08f31a90a45bDouglas Gregor    if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
1752fd00eecad6fa5400cf37269d84361a0551d0e6d3Alexey Samsonov      DI->EmitGlobalVariable(GV, D);
1753354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian}
1754354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian
1755354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanianllvm::GlobalValue::LinkageTypes
1756354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz JahanianCodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
1757354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian                                           llvm::GlobalVariable *GV) {
175890e99a84ddd020e8fda79643748243725a2ed071Argyrios Kyrtzidis  GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1759a0f00a71fcb0f98298709d5e5318339acf7958acDouglas Gregor  if (Linkage == GVA_Internal)
1760354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    return llvm::Function::InternalLinkage;
176140b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  else if (D->hasAttr<DLLImportAttr>())
1762354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    return llvm::Function::DLLImportLinkage;
176340b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  else if (D->hasAttr<DLLExportAttr>())
1764354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    return llvm::Function::DLLExportLinkage;
1765e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner  else if (D->hasAttr<WeakAttr>()) {
1766e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner    if (GV->isConstant())
1767354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian      return llvm::GlobalVariable::WeakODRLinkage;
1768e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner    else
1769354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian      return llvm::GlobalVariable::WeakAnyLinkage;
17708f51a4f2d00b0abda3cde7f3828fb2e2b9beafb5Douglas Gregor  } else if (Linkage == GVA_TemplateInstantiation ||
17718f51a4f2d00b0abda3cde7f3828fb2e2b9beafb5Douglas Gregor             Linkage == GVA_ExplicitTemplateInstantiation)
177299ace16bc6962f1fc3dc45bbbdf2eb74e555a8adJohn McCall    return llvm::GlobalVariable::WeakODRLinkage;
17734e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  else if (!getLangOpts().CPlusPlus &&
1774a6cf1e709b96865210b81bd611d41e9a2d41500aEric Christopher           ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
1775a6cf1e709b96865210b81bd611d41e9a2d41500aEric Christopher             D->getAttr<CommonAttr>()) &&
1776309457d0f1b416c1b379c9f3e172848adffedb23Chris Lattner           !D->hasExternalStorage() && !D->getInit() &&
1777ab27d6ea7b4ce2762a16905281de796db32bb6f2Fariborz Jahanian           !D->getAttr<SectionAttr>() && !D->isThreadSpecified() &&
1778ab27d6ea7b4ce2762a16905281de796db32bb6f2Fariborz Jahanian           !D->getAttr<WeakImportAttr>()) {
177991f31dc234bbc98f3dd20e6741a7b0b98c7916bfEric Christopher    // Thread local vars aren't considered common linkage.
1780354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    return llvm::GlobalVariable::CommonLinkage;
1781686226b538e72c5059ab7c9a8f87eb883193b645Sanjiv Gupta  }
1782354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  return llvm::GlobalVariable::ExternalLinkage;
178388a69ad80e1550e9932666e6efa050a5b1223889Chris Lattner}
17845f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
1785bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
1786bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// implement a function with no prototype, e.g. "int foo() {}".  If there are
1787bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// existing call uses of the old function in the module, this adjusts them to
1788bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// call the new function directly.
1789bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner///
1790bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// This is not just a cleanup: the always_inline pass requires direct calls to
1791bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// functions to be able to inline them.  If there is a bitcast in the way, it
1792bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// won't inline them.  Instcombine normally deletes these calls, but it isn't
1793bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// run at -O0.
1794bdb0132722082886558f31eccdba06ae1852c0eeChris Lattnerstatic void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1795bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner                                                      llvm::Function *NewFn) {
1796bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  // If we're redefining a global as a function, don't transform it.
1797bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
1798bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  if (OldFn == 0) return;
17991eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
18002acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type *NewRetTy = NewFn->getReturnType();
18015f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  SmallVector<llvm::Value*, 4> ArgList;
1802bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
1803bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
1804dbf02bccc9fc1115cb7dd45c84df77252d68f220Benjamin Kramer       UI != E; ) {
1805bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // TODO: Do invokes ever occur in C code?  If so, we should handle them too.
1806dbf02bccc9fc1115cb7dd45c84df77252d68f220Benjamin Kramer    llvm::Value::use_iterator I = UI++; // Increment before the CI is erased.
1807dbf02bccc9fc1115cb7dd45c84df77252d68f220Benjamin Kramer    llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I);
18088670cd3ea4dfbf86caacd270ec2441e9949bbb6aGabor Greif    if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I)
180935db3b9aad1829a1279b9e213ddee36395314a0bGabor Greif    llvm::CallSite CS(CI);
1810dbf02bccc9fc1115cb7dd45c84df77252d68f220Benjamin Kramer    if (!CI || !CS.isCallee(I)) continue;
18111eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1812bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // If the return types don't match exactly, and if the call isn't dead, then
1813bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // we can't transform this call.
1814bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    if (CI->getType() != NewRetTy && !CI->use_empty())
1815bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      continue;
1816bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
181740f9c302f23a35611cd354f40b22b37f2c554a40John McCall    // Get the attribute list.
181840f9c302f23a35611cd354f40b22b37f2c554a40John McCall    llvm::SmallVector<llvm::AttributeWithIndex, 8> AttrVec;
181940f9c302f23a35611cd354f40b22b37f2c554a40John McCall    llvm::AttrListPtr AttrList = CI->getAttributes();
182040f9c302f23a35611cd354f40b22b37f2c554a40John McCall
182140f9c302f23a35611cd354f40b22b37f2c554a40John McCall    // Get any return attributes.
182240f9c302f23a35611cd354f40b22b37f2c554a40John McCall    llvm::Attributes RAttrs = AttrList.getRetAttributes();
182340f9c302f23a35611cd354f40b22b37f2c554a40John McCall
182440f9c302f23a35611cd354f40b22b37f2c554a40John McCall    // Add the return attributes.
18254d68ed5f03ad1235946377eb32b5c4d0412f2e48Bill Wendling    if (RAttrs.hasAttributes())
182675d37b493e2282f993a19a166bd573b03a7535afBill Wendling      AttrVec.push_back(llvm::
182775d37b493e2282f993a19a166bd573b03a7535afBill Wendling                        AttributeWithIndex::get(llvm::AttrListPtr::ReturnIndex,
182875d37b493e2282f993a19a166bd573b03a7535afBill Wendling                                                RAttrs));
182940f9c302f23a35611cd354f40b22b37f2c554a40John McCall
1830bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // If the function was passed too few arguments, don't transform.  If extra
1831bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // arguments were passed, we silently drop them.  If any of the types
1832bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // mismatch, we don't transform.
1833bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    unsigned ArgNo = 0;
1834bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    bool DontTransform = false;
1835bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
1836bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner         E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
183735db3b9aad1829a1279b9e213ddee36395314a0bGabor Greif      if (CS.arg_size() == ArgNo ||
183835db3b9aad1829a1279b9e213ddee36395314a0bGabor Greif          CS.getArgument(ArgNo)->getType() != AI->getType()) {
1839bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner        DontTransform = true;
1840bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner        break;
1841bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      }
184240f9c302f23a35611cd354f40b22b37f2c554a40John McCall
184340f9c302f23a35611cd354f40b22b37f2c554a40John McCall      // Add any parameter attributes.
18444d68ed5f03ad1235946377eb32b5c4d0412f2e48Bill Wendling      llvm::Attributes PAttrs = AttrList.getParamAttributes(ArgNo + 1);
18454d68ed5f03ad1235946377eb32b5c4d0412f2e48Bill Wendling      if (PAttrs.hasAttributes())
184640f9c302f23a35611cd354f40b22b37f2c554a40John McCall        AttrVec.push_back(llvm::AttributeWithIndex::get(ArgNo + 1, PAttrs));
1847bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    }
1848bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    if (DontTransform)
1849bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      continue;
18501eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
18514d68ed5f03ad1235946377eb32b5c4d0412f2e48Bill Wendling    llvm::Attributes FnAttrs =  AttrList.getFnAttributes();
18524d68ed5f03ad1235946377eb32b5c4d0412f2e48Bill Wendling    if (FnAttrs.hasAttributes())
185375d37b493e2282f993a19a166bd573b03a7535afBill Wendling      AttrVec.push_back(llvm::
185475d37b493e2282f993a19a166bd573b03a7535afBill Wendling                       AttributeWithIndex::get(llvm::AttrListPtr::FunctionIndex,
185575d37b493e2282f993a19a166bd573b03a7535afBill Wendling                                               FnAttrs));
185640f9c302f23a35611cd354f40b22b37f2c554a40John McCall
1857bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // Okay, we can transform this.  Create the new call instruction and copy
1858bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // over the required information.
18596ba728d9687b2617793f5afd410650a8d6c71080Gabor Greif    ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo);
18604c7d9f1507d0f102bd4133bba63348636facd469Jay Foad    llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList, "", CI);
1861bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    ArgList.clear();
1862ffbb15e54a6dc120087003d1e42448b8705bd58aBenjamin Kramer    if (!NewCall->getType()->isVoidTy())
1863bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      NewCall->takeName(CI);
1864a61ab0521576e9e9e90cd2d482f8684e6070a93cChris Lattner    NewCall->setAttributes(llvm::AttrListPtr::get(AttrVec));
1865ca6408c3176783f0b29da4679a08512aa05f0c73Daniel Dunbar    NewCall->setCallingConv(CI->getCallingConv());
1866bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
1867bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // Finally, remove the old call, replacing any uses with the new one.
186800549fcec0490b2daf27543e532f94adbb186063Chris Lattner    if (!CI->use_empty())
186900549fcec0490b2daf27543e532f94adbb186063Chris Lattner      CI->replaceAllUsesWith(NewCall);
18703b122bc5f1203615e2128e0c1a63da438865b1ccDevang Patel
1871c60346388d60b1756f3675dabb60dc58da0728ecChris Lattner    // Copy debug location attached to CI.
1872c60346388d60b1756f3675dabb60dc58da0728ecChris Lattner    if (!CI->getDebugLoc().isUnknown())
1873c60346388d60b1756f3675dabb60dc58da0728ecChris Lattner      NewCall->setDebugLoc(CI->getDebugLoc());
1874bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    CI->eraseFromParent();
1875bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  }
1876bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner}
1877bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
1878025039377d7247620750205dbd61ca1ba336f7e0Rafael Espindolavoid CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
1879025039377d7247620750205dbd61ca1ba336f7e0Rafael Espindola  TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
1880025039377d7247620750205dbd61ca1ba336f7e0Rafael Espindola  // If we have a definition, this might be a deferred decl. If the
1881025039377d7247620750205dbd61ca1ba336f7e0Rafael Espindola  // instantiation is explicit, make sure we emit it at the end.
1882025039377d7247620750205dbd61ca1ba336f7e0Rafael Espindola  if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
1883025039377d7247620750205dbd61ca1ba336f7e0Rafael Espindola    GetAddrOfGlobalVar(VD);
1884234fe654a3dd2888be42ae5db34db96c5c2c4ba3Rafael Espindola}
1885bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
1886b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattnervoid CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
1887b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner  const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
1888d26bc76c98006609002d9930f8840490e88ac5b5John McCall
18891f6f961293da9c2b1c23da2411c1b439a9502ed0John McCall  // Compute the function info and LLVM type.
1890de5d3c717684f3821b8db58037bc7140acf134aaJohn McCall  const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
1891de5d3c717684f3821b8db58037bc7140acf134aaJohn McCall  llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
1892d26bc76c98006609002d9930f8840490e88ac5b5John McCall
18939fa959d5bfbbb17d7c6ba71252219201fc8dc971Chris Lattner  // Get or create the prototype for the function.
1894b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner  llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
18951eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
18960558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  // Strip off a bitcast if we got one back.
18970558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
18980558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    assert(CE->getOpcode() == llvm::Instruction::BitCast);
18990558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    Entry = CE->getOperand(0);
19000558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  }
19011eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
19021eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
19030558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
1904bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
19051eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
190642745815fa4e90bfb07e581d2e5152b2c2db08ffDaniel Dunbar    // If the types mismatch then we have to rewrite the definition.
1907bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    assert(OldFn->isDeclaration() &&
19080558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner           "Shouldn't replace non-declaration");
190934809507232bc4c3c4840c7d092c7440219fddafChris Lattner
191062b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // F is the Function* for the one with the wrong type, we must make a new
191162b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // Function* and update everything that used F (a declaration) with the new
191262b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // Function* (which will be a definition).
191362b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    //
191462b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // This happens if there is a prototype for a function
191562b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // (e.g. "int f()") and then a definition of a different type
1916f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    // (e.g. "int f(int x)").  Move the old function aside so that it
1917f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    // doesn't interfere with GetAddrOfFunction.
19185f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner    OldFn->setName(StringRef());
1919b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner    llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
19201eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1921bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // If this is an implementation of a function without a prototype, try to
1922bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // replace any existing uses of the function (which may be calls) with uses
1923bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // of the new function
19249fa959d5bfbbb17d7c6ba71252219201fc8dc971Chris Lattner    if (D->getType()->isFunctionNoProtoType()) {
1925bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
19269fa959d5bfbbb17d7c6ba71252219201fc8dc971Chris Lattner      OldFn->removeDeadConstantUsers();
19279fa959d5bfbbb17d7c6ba71252219201fc8dc971Chris Lattner    }
19281eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
192962b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // Replace uses of F with the Function we will endow with a body.
1930bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    if (!Entry->use_empty()) {
19311eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      llvm::Constant *NewPtrForOldDecl =
19323c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson        llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
1933bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      Entry->replaceAllUsesWith(NewPtrForOldDecl);
1934bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    }
19351eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
193662b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // Ok, delete the old function now, which is dead.
1937bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    OldFn->eraseFromParent();
19381eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
19390558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    Entry = NewFn;
1940bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar  }
19411eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1942112c967bd5c862a0f5d7913aa06700c048807db8John McCall  // We need to set linkage and visibility on the function before
1943112c967bd5c862a0f5d7913aa06700c048807db8John McCall  // generating code for it because various parts of IR generation
1944112c967bd5c862a0f5d7913aa06700c048807db8John McCall  // want to propagate this information down (e.g. to local static
1945112c967bd5c862a0f5d7913aa06700c048807db8John McCall  // declarations).
19460558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  llvm::Function *Fn = cast<llvm::Function>(Entry);
19478b2423361648c39a7d8a3c5e8129e12006deac32John McCall  setFunctionLinkage(D, Fn);
1948bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
1949112c967bd5c862a0f5d7913aa06700c048807db8John McCall  // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
19500ffeaad72cb335b926b064379be4c9886bbff004Anders Carlsson  setGlobalVisibility(Fn, D);
1951112c967bd5c862a0f5d7913aa06700c048807db8John McCall
1952d26bc76c98006609002d9930f8840490e88ac5b5John McCall  CodeGenFunction(*this).GenerateCode(D, Fn, FI);
19536379a7a15335e0af543a942efe9cfd514a83dab8Daniel Dunbar
19547c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  SetFunctionDefinitionAttributes(D, Fn);
19557c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  SetLLVMFunctionAttributesForDefinition(D, Fn);
19561eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
195740b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
1958219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar    AddGlobalCtor(Fn, CA->getPriority());
195940b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
1960219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar    AddGlobalDtor(Fn, DA->getPriority());
196177f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  if (D->hasAttr<AnnotateAttr>())
196277f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    AddGlobalAnnotations(D, Fn);
1963bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar}
1964bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
1965f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCallvoid CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
1966f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
196740b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  const AliasAttr *AA = D->getAttr<AliasAttr>();
1968bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  assert(AA && "Not an alias?");
1969bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner
19705f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  StringRef MangledName = getMangledName(GD);
1971f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall
1972f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  // If there is a definition in the module, then it wins over the alias.
1973f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  // This is dubious, but allow it to be safe.  Just ignore the alias.
1974f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1975f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  if (Entry && !Entry->isDeclaration())
1976f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    return;
19771eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
19782acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
1979bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner
1980bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  // Create a reference to the named value.  This ensures that it is emitted
1981bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  // if a deferred decl.
1982bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  llvm::Constant *Aliasee;
1983bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  if (isa<llvm::FunctionType>(DeclTy))
1984c857ce8b08397ed778928b8a000732ca90da2a8cAlex Rosenberg    Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
19851faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson                                      /*ForVTable=*/false);
1986bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  else
1987f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
198896e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson                                    llvm::PointerType::getUnqual(DeclTy), 0);
1989bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner
1990bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  // Create the new alias itself, but don't set a name yet.
19911eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  llvm::GlobalValue *GA =
1992bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    new llvm::GlobalAlias(Aliasee->getType(),
1993bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner                          llvm::Function::ExternalLinkage,
1994bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner                          "", Aliasee, &getModule());
19951eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1996bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  if (Entry) {
1997f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    assert(Entry->isDeclaration());
1998f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall
1999bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    // If there is a declaration in the module, then we had an extern followed
2000bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    // by the alias, as in:
2001bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    //   extern int test6();
2002bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    //   ...
2003bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    //   int test6() __attribute__((alias("test7")));
2004bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    //
2005bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    // Remove it and replace uses of it with the alias.
2006f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    GA->takeName(Entry);
20071eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
20083c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson    Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
2009bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner                                                          Entry->getType()));
2010bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    Entry->eraseFromParent();
2011f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  } else {
20129a20d55807cc2f6534a9c51a46cc8143ed16786dAnders Carlsson    GA->setName(MangledName);
2013bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  }
20141eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
20157c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // Set attributes which are particular to an alias; this is a
20167c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // specialization of the attributes which may be set on a global
20177c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // variable/function.
201840b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (D->hasAttr<DLLExportAttr>()) {
20197c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
20207c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar      // The dllexport attribute is ignored for undefined symbols.
202106a54a38be5054c910ffc92db60edab23f9ea105Argyrios Kyrtzidis      if (FD->hasBody())
20227c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar        GA->setLinkage(llvm::Function::DLLExportLinkage);
20237c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    } else {
20247c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar      GA->setLinkage(llvm::Function::DLLExportLinkage);
20257c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    }
20261eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  } else if (D->hasAttr<WeakAttr>() ||
202711e8ce7380856abee188b237c2600272df2ed09dRafael Espindola             D->hasAttr<WeakRefAttr>() ||
20280a0d2b179085a52c10402feebeb6db8b4d96a140Douglas Gregor             D->isWeakImported()) {
20297c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    GA->setLinkage(llvm::Function::WeakAnyLinkage);
20307c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  }
20317c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
20327c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  SetCommonAttributes(D, GA);
2033bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner}
2034bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner
20358dd55a3c3b28d195717c87bbc60e765951d408feBenjamin Kramerllvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
20362d3ba4f5a923a90c3fc290ddfba5e36c2d0a9b46Chris Lattner                                            ArrayRef<llvm::Type*> Tys) {
2037df983a8bcbbcea911b8dce283f044787df119d50Jay Foad  return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
20388dd55a3c3b28d195717c87bbc60e765951d408feBenjamin Kramer                                         Tys);
20397acda7c4a0e4aec6c003b3169ca45a5f3bc7e033Chris Lattner}
2040bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner
20411d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbarstatic llvm::StringMapEntry<llvm::Constant*> &
20421d5529132e4620562cab931c1f84c24e42f02741Daniel DunbarGetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
20431d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar                         const StringLiteral *Literal,
204470ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar                         bool TargetIsLSB,
20451d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar                         bool &IsUTF16,
20461d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar                         unsigned &StringLength) {
20475f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  StringRef String = Literal->getString();
20482f4eaef37476ae6891ede8ba215d0f6fd093629bBenjamin Kramer  unsigned NumBytes = String.size();
20491d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar
2050f015b034159d40e7033309e50036804eb1971787Daniel Dunbar  // Check for simple case.
2051f015b034159d40e7033309e50036804eb1971787Daniel Dunbar  if (!Literal->containsNonAsciiOrNull()) {
2052f015b034159d40e7033309e50036804eb1971787Daniel Dunbar    StringLength = NumBytes;
20532f4eaef37476ae6891ede8ba215d0f6fd093629bBenjamin Kramer    return Map.GetOrCreateValue(String);
2054f015b034159d40e7033309e50036804eb1971787Daniel Dunbar  }
2055f015b034159d40e7033309e50036804eb1971787Daniel Dunbar
205684392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling  // Otherwise, convert the UTF8 literals into a string of shorts.
205784392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling  IsUTF16 = true;
205884392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling
205984392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling  SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
206031ba6135375433b617a8587ea6cc836a014ebd86Roman Divacky  const UTF8 *FromPtr = (const UTF8 *)String.data();
20611d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  UTF16 *ToPtr = &ToBuf[0];
20621eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2063e7ddfb974884ec75ffd66953b79511ea457493baFariborz Jahanian  (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2064e7ddfb974884ec75ffd66953b79511ea457493baFariborz Jahanian                           &ToPtr, ToPtr + NumBytes,
2065e7ddfb974884ec75ffd66953b79511ea457493baFariborz Jahanian                           strictConversion);
20661eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
206770ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  // ConvertUTF8toUTF16 returns the length in ToPtr.
20681d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  StringLength = ToPtr - &ToBuf[0];
206970ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar
207084392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling  // Add an explicit null.
207184392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling  *ToPtr = 0;
207284392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling  return Map.
207384392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling    GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()),
207484392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling                               (StringLength + 1) * 2));
20751d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar}
20761d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar
2077cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanianstatic llvm::StringMapEntry<llvm::Constant*> &
2078cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz JahanianGetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
20798322c23956c4dea057a930753f23ff6467353e55Bill Wendling                       const StringLiteral *Literal,
20808322c23956c4dea057a930753f23ff6467353e55Bill Wendling                       unsigned &StringLength) {
20818322c23956c4dea057a930753f23ff6467353e55Bill Wendling  StringRef String = Literal->getString();
20828322c23956c4dea057a930753f23ff6467353e55Bill Wendling  StringLength = String.size();
20838322c23956c4dea057a930753f23ff6467353e55Bill Wendling  return Map.GetOrCreateValue(String);
2084cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian}
2085cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian
20861d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbarllvm::Constant *
20871d5529132e4620562cab931c1f84c24e42f02741Daniel DunbarCodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
20881d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  unsigned StringLength = 0;
20891d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  bool isUTF16 = false;
20901d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  llvm::StringMapEntry<llvm::Constant*> &Entry =
20911eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    GetConstantCFStringEntry(CFConstantStringMap, Literal,
209225a6a84cf5067b32c271e3ba078676dee838798dMicah Villmow                             getDataLayout().isLittleEndian(),
209370ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar                             isUTF16, StringLength);
20941eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
20951d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  if (llvm::Constant *C = Entry.getValue())
20961d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar    return C;
20971eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
20988b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
20993e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar  llvm::Constant *Zeros[] = { Zero, Zero };
21001eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
21019d4a15fd3b85434c43ea27562793de63a793321aChris Lattner  // If we don't already have it, get __CFConstantStringClassReference.
2102c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  if (!CFConstantStringClassRef) {
21032acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner    llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
210496e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson    Ty = llvm::ArrayType::get(Ty, 0);
21051eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    llvm::Constant *GV = CreateRuntimeVariable(Ty,
21069d4a15fd3b85434c43ea27562793de63a793321aChris Lattner                                           "__CFConstantStringClassReference");
21073e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar    // Decay array -> ptr
21083e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar    CFConstantStringClassRef =
2109a5c04344fa70d6eec34344760c1fe511e16f2d76Jay Foad      llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2110c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  }
21111eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2112e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson  QualType CFTy = getContext().getCFConstantStringType();
21133e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar
21142acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::StructType *STy =
2115e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson    cast<llvm::StructType>(getTypes().ConvertType(CFTy));
2116e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson
21171d236ab930816f5da27bade92904914c44b73b4cBenjamin Kramer  llvm::Constant *Fields[4];
211844b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor
2119c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  // Class pointer.
21205add6835b0c6b0f67e19fd5366825d3e41eb0dcfAnders Carlsson  Fields[0] = CFConstantStringClassRef;
21211eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2122c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  // Flags.
21232acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
21241eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
21255add6835b0c6b0f67e19fd5366825d3e41eb0dcfAnders Carlsson    llvm::ConstantInt::get(Ty, 0x07C8);
21265add6835b0c6b0f67e19fd5366825d3e41eb0dcfAnders Carlsson
2127c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  // String pointer.
212884392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling  llvm::Constant *C = 0;
212984392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling  if (isUTF16) {
213084392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling    ArrayRef<uint16_t> Arr =
213184392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling      llvm::makeArrayRef<uint16_t>((uint16_t*)Entry.getKey().data(),
213284392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling                                   Entry.getKey().size() / 2);
213384392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling    C = llvm::ConstantDataArray::get(VMContext, Arr);
213484392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling  } else {
213584392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling    C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
213684392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling  }
2137a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar
213895b851e55c328af4b69da7bfc1124bf258c0ffe5Chris Lattner  llvm::GlobalValue::LinkageTypes Linkage;
21391bf7a3fcc4e2ad30688f7b0db464ad1ccabe77e2Bill Wendling  if (isUTF16)
2140278b9f06933c385ffbccc15f8491787470cb4a1bChris Lattner    // FIXME: why do utf strings get "_" labels instead of "L" labels?
214195b851e55c328af4b69da7bfc1124bf258c0ffe5Chris Lattner    Linkage = llvm::GlobalValue::InternalLinkage;
21421bf7a3fcc4e2ad30688f7b0db464ad1ccabe77e2Bill Wendling  else
2143584acf2ded2c18a18d6da0e1c01f5859a384d99fRafael Espindola    // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error
2144584acf2ded2c18a18d6da0e1c01f5859a384d99fRafael Espindola    // when using private linkage. It is not clear if this is a bug in ld
2145584acf2ded2c18a18d6da0e1c01f5859a384d99fRafael Espindola    // or a reasonable new restriction.
2146dc0f137295bc7ec5b231ff1842388f149f43c0c8Rafael Espindola    Linkage = llvm::GlobalValue::LinkerPrivateLinkage;
2147278b9f06933c385ffbccc15f8491787470cb4a1bChris Lattner
21481bf7a3fcc4e2ad30688f7b0db464ad1ccabe77e2Bill Wendling  // Note: -fwritable-strings doesn't make the backing store strings of
21491bf7a3fcc4e2ad30688f7b0db464ad1ccabe77e2Bill Wendling  // CFStrings writable. (See <rdar://problem/10657500>)
21501eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  llvm::GlobalVariable *GV =
21511bf7a3fcc4e2ad30688f7b0db464ad1ccabe77e2Bill Wendling    new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
21521bf7a3fcc4e2ad30688f7b0db464ad1ccabe77e2Bill Wendling                             Linkage, C, ".str");
2153b266a1fce09ab4ee7033268199509aacfbef056aRafael Espindola  GV->setUnnamedAddr(true);
2154a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar  if (isUTF16) {
21554da244c23d6093adbbbc41654aa5c5111b38f431Ken Dyck    CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
21564da244c23d6093adbbbc41654aa5c5111b38f431Ken Dyck    GV->setAlignment(Align.getQuantity());
2157f7e903d7a30891083420c07ebeed281726a101d6Daniel Dunbar  } else {
2158f7e903d7a30891083420c07ebeed281726a101d6Daniel Dunbar    CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2159f7e903d7a30891083420c07ebeed281726a101d6Daniel Dunbar    GV->setAlignment(Align.getQuantity());
2160a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar  }
216184392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling
216284392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling  // String.
2163a5c04344fa70d6eec34344760c1fe511e16f2d76Jay Foad  Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
21645add6835b0c6b0f67e19fd5366825d3e41eb0dcfAnders Carlsson
216584392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling  if (isUTF16)
216684392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling    // Cast the UTF16 string to the correct type.
216784392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling    Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
216884392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling
2169c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  // String length.
2170c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  Ty = getTypes().ConvertType(getContext().LongTy);
21715add6835b0c6b0f67e19fd5366825d3e41eb0dcfAnders Carlsson  Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
21721eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2173c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  // The struct.
217408e252425ca2cbdc44ba65d9a657ed5398014e36Owen Anderson  C = llvm::ConstantStruct::get(STy, Fields);
21751eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
21761eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                llvm::GlobalVariable::PrivateLinkage, C,
217795b851e55c328af4b69da7bfc1124bf258c0ffe5Chris Lattner                                "_unnamed_cfstring_");
2178bcfd1f55bfbb3e5944cd5e03d07b343e280838c4Douglas Gregor  if (const char *Sect = getContext().getTargetInfo().getCFStringSection())
21798e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar    GV->setSection(Sect);
21801d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  Entry.setValue(GV);
21811eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
21820c67829763b98bc670062b553897a851fab17401Anders Carlsson  return GV;
2183c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson}
218445e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner
218545c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregorstatic RecordDecl *
218645c4ea75b235de94f44bf96843624e6a559e4c00Douglas GregorCreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
218745c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                 DeclContext *DC, IdentifierInfo *Id) {
218845c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor  SourceLocation Loc;
21894e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (Ctx.getLangOpts().CPlusPlus)
219045c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
219145c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor  else
219245c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
219345c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor}
219445c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor
219533e982bf782d851bfe5767acb1336fcf3419ac6bFariborz Jahanianllvm::Constant *
21964c73307c74764ba99e1379677fe92af72f676531Fariborz JahanianCodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
21972bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  unsigned StringLength = 0;
21982bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  llvm::StringMapEntry<llvm::Constant*> &Entry =
2199cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian    GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
22002bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
22012bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  if (llvm::Constant *C = Entry.getValue())
22022bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian    return C;
22032bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
2204812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner  llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
22052bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  llvm::Constant *Zeros[] = { Zero, Zero };
22062bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
2207ec951e0c2fc0db00c36bc60c900331dde32c1b43Fariborz Jahanian  // If we don't already have it, get _NSConstantStringClassReference.
22084c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian  if (!ConstantStringClassRef) {
22094e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie    std::string StringClass(getLangOpts().ObjCConstantStringClass);
22102acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner    llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
22114c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian    llvm::Constant *GV;
2212260611a32535c851237926bfcf78869b13c07d5bJohn McCall    if (LangOpts.ObjCRuntime.isNonFragile()) {
221325dba5d294364fa8339091e4d9e6a8f5db008377Fariborz Jahanian      std::string str =
221425dba5d294364fa8339091e4d9e6a8f5db008377Fariborz Jahanian        StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
221525dba5d294364fa8339091e4d9e6a8f5db008377Fariborz Jahanian                            : "OBJC_CLASS_$_" + StringClass;
22166f40e2244b0590f144c5ceee07981a962fbbc72eFariborz Jahanian      GV = getObjCRuntime().GetClassGlobal(str);
22176f40e2244b0590f144c5ceee07981a962fbbc72eFariborz Jahanian      // Make sure the result is of the correct type.
22182acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner      llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
22196f40e2244b0590f144c5ceee07981a962fbbc72eFariborz Jahanian      ConstantStringClassRef =
22206f40e2244b0590f144c5ceee07981a962fbbc72eFariborz Jahanian        llvm::ConstantExpr::getBitCast(GV, PTy);
22216f40e2244b0590f144c5ceee07981a962fbbc72eFariborz Jahanian    } else {
222225dba5d294364fa8339091e4d9e6a8f5db008377Fariborz Jahanian      std::string str =
222325dba5d294364fa8339091e4d9e6a8f5db008377Fariborz Jahanian        StringClass.empty() ? "_NSConstantStringClassReference"
222425dba5d294364fa8339091e4d9e6a8f5db008377Fariborz Jahanian                            : "_" + StringClass + "ClassReference";
22252acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner      llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
222625dba5d294364fa8339091e4d9e6a8f5db008377Fariborz Jahanian      GV = CreateRuntimeVariable(PTy, str);
22276f40e2244b0590f144c5ceee07981a962fbbc72eFariborz Jahanian      // Decay array -> ptr
22286f40e2244b0590f144c5ceee07981a962fbbc72eFariborz Jahanian      ConstantStringClassRef =
2229a5c04344fa70d6eec34344760c1fe511e16f2d76Jay Foad        llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
22304c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian    }
22312bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  }
223245c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor
223345c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor  if (!NSConstantStringType) {
223445c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    // Construct the type for a constant NSString.
223545c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
223645c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                                     Context.getTranslationUnitDecl(),
223745c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                                   &Context.Idents.get("__builtin_NSString"));
223845c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    D->startDefinition();
223945c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor
224045c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    QualType FieldTypes[3];
224145c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor
224245c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    // const int *isa;
224345c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
224445c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    // const char *str;
224545c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
224645c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    // unsigned int length;
224745c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    FieldTypes[2] = Context.UnsignedIntTy;
224845c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor
224945c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    // Create fields
225045c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    for (unsigned i = 0; i < 3; ++i) {
225145c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor      FieldDecl *Field = FieldDecl::Create(Context, D,
225245c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                                           SourceLocation(),
225345c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                                           SourceLocation(), 0,
225445c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                                           FieldTypes[i], /*TInfo=*/0,
225545c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                                           /*BitWidth=*/0,
225645c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                                           /*Mutable=*/false,
2257ca5233044ef679840d1ad1c46a36b16e2ee8a6e1Richard Smith                                           ICIS_NoInit);
225845c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor      Field->setAccess(AS_public);
225945c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor      D->addDecl(Field);
226045c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    }
226145c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor
226245c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    D->completeDefinition();
226345c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    QualType NSTy = Context.getTagDeclType(D);
226445c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
226545c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor  }
22662bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
22671d236ab930816f5da27bade92904914c44b73b4cBenjamin Kramer  llvm::Constant *Fields[3];
22682bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
22692bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  // Class pointer.
22704c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian  Fields[0] = ConstantStringClassRef;
22712bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
22722bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  // String pointer.
227394010695f7fce626e41ef045b60def9c912e9ce8Chris Lattner  llvm::Constant *C =
227494010695f7fce626e41ef045b60def9c912e9ce8Chris Lattner    llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
22752bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
22762bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  llvm::GlobalValue::LinkageTypes Linkage;
22772bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  bool isConstant;
2278cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian  Linkage = llvm::GlobalValue::PrivateLinkage;
22794e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  isConstant = !LangOpts.WritableStrings;
22802bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
22812bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  llvm::GlobalVariable *GV =
22822bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
22832bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian                           ".str");
2284803d307a5385059b1a84dfe9706ab158c80a20dcRafael Espindola  GV->setUnnamedAddr(true);
2285cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian  CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2286cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian  GV->setAlignment(Align.getQuantity());
2287a5c04344fa70d6eec34344760c1fe511e16f2d76Jay Foad  Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
22882bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
22892bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  // String length.
22902acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
22912bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
22922bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
22932bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  // The struct.
229445c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor  C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
22952bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
22962bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian                                llvm::GlobalVariable::PrivateLinkage, C,
22972bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian                                "_unnamed_nsstring_");
22982bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  // FIXME. Fix section.
2299ec951e0c2fc0db00c36bc60c900331dde32c1b43Fariborz Jahanian  if (const char *Sect =
2300260611a32535c851237926bfcf78869b13c07d5bJohn McCall        LangOpts.ObjCRuntime.isNonFragile()
2301bcfd1f55bfbb3e5944cd5e03d07b343e280838c4Douglas Gregor          ? getContext().getTargetInfo().getNSStringNonFragileABISection()
2302bcfd1f55bfbb3e5944cd5e03d07b343e280838c4Douglas Gregor          : getContext().getTargetInfo().getNSStringSection())
23032bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian    GV->setSection(Sect);
23042bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  Entry.setValue(GV);
23052bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
23062bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  return GV;
230733e982bf782d851bfe5767acb1336fcf3419ac6bFariborz Jahanian}
230833e982bf782d851bfe5767acb1336fcf3419ac6bFariborz Jahanian
23090815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas GregorQualType CodeGenModule::getObjCFastEnumerationStateType() {
23100815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor  if (ObjCFastEnumerationStateType.isNull()) {
23110815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
23120815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                                     Context.getTranslationUnitDecl(),
23130815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                      &Context.Idents.get("__objcFastEnumerationState"));
23140815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    D->startDefinition();
23150815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor
23160815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    QualType FieldTypes[] = {
23170815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor      Context.UnsignedLongTy,
23180815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor      Context.getPointerType(Context.getObjCIdType()),
23190815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor      Context.getPointerType(Context.UnsignedLongTy),
23200815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor      Context.getConstantArrayType(Context.UnsignedLongTy,
23210815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                           llvm::APInt(32, 5), ArrayType::Normal, 0)
23220815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    };
23230815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor
23240815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    for (size_t i = 0; i < 4; ++i) {
23250815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor      FieldDecl *Field = FieldDecl::Create(Context,
23260815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                                           D,
23270815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                                           SourceLocation(),
23280815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                                           SourceLocation(), 0,
23290815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                                           FieldTypes[i], /*TInfo=*/0,
23300815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                                           /*BitWidth=*/0,
23310815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                                           /*Mutable=*/false,
2332ca5233044ef679840d1ad1c46a36b16e2ee8a6e1Richard Smith                                           ICIS_NoInit);
23330815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor      Field->setAccess(AS_public);
23340815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor      D->addDecl(Field);
23350815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    }
23360815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor
23370815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    D->completeDefinition();
23380815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    ObjCFastEnumerationStateType = Context.getTagDeclType(D);
23390815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor  }
23400815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor
23410815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor  return ObjCFastEnumerationStateType;
23420815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor}
23430815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor
234464f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedmanllvm::Constant *
234564f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli FriedmanCodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
234664f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  assert(!E->getType()->isPointerType() && "Strings are always arrays");
234764f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman
234864f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  // Don't emit it as the address of the string, emit the string data itself
234964f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  // as an inline array.
2350812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner  if (E->getCharByteWidth() == 1) {
2351812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner    SmallString<64> Str(E->getString());
2352812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner
2353812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner    // Resize the string to the right size, which is indicated by its type.
2354812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner    const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
2355812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner    Str.resize(CAT->getSize().getZExtValue());
2356812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner    return llvm::ConstantDataArray::getString(VMContext, Str, false);
2357812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner  }
235894010695f7fce626e41ef045b60def9c912e9ce8Chris Lattner
235994010695f7fce626e41ef045b60def9c912e9ce8Chris Lattner  llvm::ArrayType *AType =
236094010695f7fce626e41ef045b60def9c912e9ce8Chris Lattner    cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
236194010695f7fce626e41ef045b60def9c912e9ce8Chris Lattner  llvm::Type *ElemTy = AType->getElementType();
236294010695f7fce626e41ef045b60def9c912e9ce8Chris Lattner  unsigned NumElements = AType->getNumElements();
2363d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner
2364d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner  // Wide strings have either 2-byte or 4-byte elements.
2365d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner  if (ElemTy->getPrimitiveSizeInBits() == 16) {
2366d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner    SmallVector<uint16_t, 32> Elements;
2367d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner    Elements.reserve(NumElements);
2368d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner
2369d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner    for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2370d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner      Elements.push_back(E->getCodeUnit(i));
2371d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner    Elements.resize(NumElements);
2372d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner    return llvm::ConstantDataArray::get(VMContext, Elements);
237394010695f7fce626e41ef045b60def9c912e9ce8Chris Lattner  }
237494010695f7fce626e41ef045b60def9c912e9ce8Chris Lattner
2375d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner  assert(ElemTy->getPrimitiveSizeInBits() == 32);
2376d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner  SmallVector<uint32_t, 32> Elements;
2377d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner  Elements.reserve(NumElements);
2378d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner
2379d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner  for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2380d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner    Elements.push_back(E->getCodeUnit(i));
2381d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner  Elements.resize(NumElements);
2382d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner  return llvm::ConstantDataArray::get(VMContext, Elements);
238364f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman}
238464f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman
23856143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
23866143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// constant array for the given string literal.
23876143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbarllvm::Constant *
23886143293fa4366ee95d7e47e61bd030a34bf68b55Daniel DunbarCodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
2389a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall  CharUnits Align = getContext().getTypeAlignInChars(S->getType());
239064f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  if (S->isAscii() || S->isUTF8()) {
2391812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner    SmallString<64> Str(S->getString());
2392812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner
2393812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner    // Resize the string to the right size, which is indicated by its type.
2394812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner    const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
2395812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner    Str.resize(CAT->getSize().getZExtValue());
2396812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner    return GetAddrOfConstantString(Str, /*GlobalName*/ 0, Align.getQuantity());
23977eb79c1010c8d30b852768bec96e81cd3e6def2eEli Friedman  }
239864f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman
2399812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner  // FIXME: the following does not memoize wide strings.
240064f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
240164f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  llvm::GlobalVariable *GV =
240264f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman    new llvm::GlobalVariable(getModule(),C->getType(),
24034e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie                             !LangOpts.WritableStrings,
240464f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman                             llvm::GlobalValue::PrivateLinkage,
240564f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman                             C,".str");
24067d6a7c004361c45a463874a58da28d9f3c35f2e6Seth Cantrell
240764f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  GV->setAlignment(Align.getQuantity());
240864f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  GV->setUnnamedAddr(true);
240964f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  return GV;
24106143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar}
24116143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar
2412eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
2413eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner/// array for the given ObjCEncodeExpr node.
2414eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattnerllvm::Constant *
2415eaf2bb89eb2aad3b80673de30febe52df43c10ecChris LattnerCodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
2416eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner  std::string Str;
2417eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner  getContext().getObjCEncodingForType(E->getEncodedType(), Str);
2418a210f350fa78c263caa26e0f999cce85bb235309Eli Friedman
2419a210f350fa78c263caa26e0f999cce85bb235309Eli Friedman  return GetAddrOfConstantCString(Str);
2420eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner}
2421eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner
2422eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner
2423a7ad98ff0919d6a24ea7c46634ea29bea551c1a0Chris Lattner/// GenerateWritableString -- Creates storage for a string literal.
2424a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCallstatic llvm::GlobalVariable *GenerateStringLiteral(StringRef str,
242545e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner                                             bool constant,
24265fabf9dbee29464bcd06cd09f8e569d1b850f948Daniel Dunbar                                             CodeGenModule &CGM,
2427a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall                                             const char *GlobalName,
2428a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall                                             unsigned Alignment) {
24296143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar  // Create Constant for this string literal. Don't add a '\0'.
24300032b2781b4deb131f8c9b7968f2030bf2489cddOwen Anderson  llvm::Constant *C =
243194010695f7fce626e41ef045b60def9c912e9ce8Chris Lattner      llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false);
24321eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
243345e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner  // Create a global variable for this string
24341257bc6ee76b931e3f8e51a88298b95379963d24Rafael Espindola  llvm::GlobalVariable *GV =
24351257bc6ee76b931e3f8e51a88298b95379963d24Rafael Espindola    new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
24361257bc6ee76b931e3f8e51a88298b95379963d24Rafael Espindola                             llvm::GlobalValue::PrivateLinkage,
24371257bc6ee76b931e3f8e51a88298b95379963d24Rafael Espindola                             C, GlobalName);
2438a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall  GV->setAlignment(Alignment);
24391257bc6ee76b931e3f8e51a88298b95379963d24Rafael Espindola  GV->setUnnamedAddr(true);
24401257bc6ee76b931e3f8e51a88298b95379963d24Rafael Espindola  return GV;
244145e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner}
244245e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner
24436143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// GetAddrOfConstantString - Returns a pointer to a character array
24446143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// containing the literal. This contents are exactly that of the
24456143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// given string, i.e. it will not be null terminated automatically;
24466143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// see GetAddrOfConstantCString. Note that whether the result is
24476143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// actually a pointer to an LLVM constant depends on
24486143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// Feature.WriteableStrings.
24496143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar///
24506143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// The result has pointer to array type.
24515f9e272e632e951b1efe824cd16acb4d96077930Chris Lattnerllvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str,
2452a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall                                                       const char *GlobalName,
2453a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall                                                       unsigned Alignment) {
24548e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar  // Get the default prefix if a name wasn't specified.
24558e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar  if (!GlobalName)
245695b851e55c328af4b69da7bfc1124bf258c0ffe5Chris Lattner    GlobalName = ".str";
24578e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar
24588e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar  // Don't share any string literals if strings aren't constant.
24594e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (LangOpts.WritableStrings)
2460a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall    return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment);
24611eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2462a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall  llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
24639de4342ef79a18c706e46bc23f8f579f5add2375Benjamin Kramer    ConstantStringMap.GetOrCreateValue(Str);
246445e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner
2465a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall  if (llvm::GlobalVariable *GV = Entry.getValue()) {
2466a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall    if (Alignment > GV->getAlignment()) {
2467a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall      GV->setAlignment(Alignment);
2468a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall    }
2469a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall    return GV;
2470a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall  }
247145e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner
247245e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner  // Create a global variable for this.
2473812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner  llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName,
2474812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner                                                   Alignment);
2475a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall  Entry.setValue(GV);
2476a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall  return GV;
247745e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner}
24786143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar
24796143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// GetAddrOfConstantCString - Returns a pointer to a character
24809de4342ef79a18c706e46bc23f8f579f5add2375Benjamin Kramer/// array containing the literal and a terminating '\0'
24816143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// character. The result has pointer to array type.
24829de4342ef79a18c706e46bc23f8f579f5add2375Benjamin Kramerllvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
2483a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall                                                        const char *GlobalName,
2484a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall                                                        unsigned Alignment) {
24855f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  StringRef StrWithNull(Str.c_str(), Str.size() + 1);
2486a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall  return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment);
24876143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar}
248841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
2489af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar/// EmitObjCPropertyImplementations - Emit information for synthesized
2490af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar/// properties for an implementation.
24911eb4433ac451dc16f4133a88af2d002ac26c58efMike Stumpvoid CodeGenModule::EmitObjCPropertyImplementations(const
2492af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar                                                    ObjCImplementationDecl *D) {
24931eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  for (ObjCImplementationDecl::propimpl_iterator
249417945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis         i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
2495581deb3da481053c4993c7600f97acf7768caac5David Blaikie    ObjCPropertyImplDecl *PID = *i;
24961eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2497af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    // Dynamic is just for type-checking.
2498af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
2499af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      ObjCPropertyDecl *PD = PID->getPropertyDecl();
2500af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar
2501af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      // Determine which methods need to be implemented, some may have
25021e4691b9d8e1bdcc8ef62b323969d702c51b3c08Jordan Rose      // been overridden. Note that ::isPropertyAccessor is not the method
2503af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      // we want, that just indicates if the decl came from a
2504af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      // property. What we want to know is if the method is defined in
2505af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      // this implementation.
250617945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis      if (!D->getInstanceMethod(PD->getGetterName()))
2507fef30b55230064d334a669a065a1c9acdb87cdfeFariborz Jahanian        CodeGenFunction(*this).GenerateObjCGetter(
2508fef30b55230064d334a669a065a1c9acdb87cdfeFariborz Jahanian                                 const_cast<ObjCImplementationDecl *>(D), PID);
2509af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      if (!PD->isReadOnly() &&
251017945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis          !D->getInstanceMethod(PD->getSetterName()))
2511fef30b55230064d334a669a065a1c9acdb87cdfeFariborz Jahanian        CodeGenFunction(*this).GenerateObjCSetter(
2512fef30b55230064d334a669a065a1c9acdb87cdfeFariborz Jahanian                                 const_cast<ObjCImplementationDecl *>(D), PID);
2513af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    }
2514af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar  }
2515af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar}
2516af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar
2517e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCallstatic bool needsDestructMethod(ObjCImplementationDecl *impl) {
2518db8264e4c5ffd7af6fbad4ca4306bd382bb02691Jordy Rose  const ObjCInterfaceDecl *iface = impl->getClassInterface();
2519db8264e4c5ffd7af6fbad4ca4306bd382bb02691Jordy Rose  for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
2520e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall       ivar; ivar = ivar->getNextIvar())
2521e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall    if (ivar->getType().isDestructedType())
2522e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall      return true;
2523e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall
2524e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  return false;
2525e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall}
2526e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall
2527109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian/// EmitObjCIvarInitializations - Emit information for ivar initialization
2528109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian/// for an implementation.
2529109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanianvoid CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
2530e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  // We might need a .cxx_destruct even if we don't have any ivar initializers.
2531e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  if (needsDestructMethod(D)) {
2532e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall    IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
2533e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall    Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2534e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall    ObjCMethodDecl *DTORMethod =
2535e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall      ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
253675cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis                             cxxSelector, getContext().VoidTy, 0, D,
253775cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis                             /*isInstance=*/true, /*isVariadic=*/false,
25381e4691b9d8e1bdcc8ef62b323969d702c51b3c08Jordan Rose                          /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
253975cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis                             /*isDefined=*/false, ObjCMethodDecl::Required);
2540e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall    D->addInstanceMethod(DTORMethod);
2541e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall    CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
2542b03527a9a395168762ad8e25e59a7a272dd74561John McCall    D->setHasDestructors(true);
2543e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  }
2544e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall
2545e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  // If the implementation doesn't have any ivar initializers, we don't need
2546e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  // a .cxx_construct.
2547827bbcc8a9115782693b21030a45378abe5c1862David Chisnall  if (D->getNumIvarInitializers() == 0)
2548109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian    return;
2549109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian
2550e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
2551e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2552109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian  // The constructor returns 'self'.
2553109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian  ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
2554109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian                                                D->getLocation(),
255511d77169555480ee0a04c6e5bc390d8fde41175dArgyrios Kyrtzidis                                                D->getLocation(),
255611d77169555480ee0a04c6e5bc390d8fde41175dArgyrios Kyrtzidis                                                cxxSelector,
2557109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian                                                getContext().getObjCIdType(), 0,
255875cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis                                                D, /*isInstance=*/true,
255975cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis                                                /*isVariadic=*/false,
25601e4691b9d8e1bdcc8ef62b323969d702c51b3c08Jordan Rose                                                /*isPropertyAccessor=*/true,
256175cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis                                                /*isImplicitlyDeclared=*/true,
256275cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis                                                /*isDefined=*/false,
2563109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian                                                ObjCMethodDecl::Required);
2564109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian  D->addInstanceMethod(CTORMethod);
2565109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian  CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
2566b03527a9a395168762ad8e25e59a7a272dd74561John McCall  D->setHasNonZeroConstructors(true);
2567109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian}
2568109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian
256991e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson/// EmitNamespace - Emit all declarations in a namespace.
2570984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlssonvoid CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
257117945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis  for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
2572984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlsson       I != E; ++I)
2573984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlsson    EmitTopLevelDecl(*I);
2574984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlsson}
2575984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlsson
257691e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson// EmitLinkageSpec - Emit all declarations in a linkage spec.
257791e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlssonvoid CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
2578f976be8a63f9e0d3bd50e33dadef02c3c9921747Eli Friedman  if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
2579f976be8a63f9e0d3bd50e33dadef02c3c9921747Eli Friedman      LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
258091e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson    ErrorUnsupported(LSD, "linkage spec");
258191e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson    return;
258291e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson  }
258391e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson
258417945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis  for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
2585c1868e533e63a1b7dad7a22714fc593c045382aeFariborz Jahanian       I != E; ++I) {
2586c1868e533e63a1b7dad7a22714fc593c045382aeFariborz Jahanian    if (ObjCImplDecl *OID = dyn_cast<ObjCImplDecl>(*I)) {
2587c1868e533e63a1b7dad7a22714fc593c045382aeFariborz Jahanian      for (ObjCContainerDecl::method_iterator M = OID->meth_begin(),
2588c1868e533e63a1b7dad7a22714fc593c045382aeFariborz Jahanian           MEnd = OID->meth_end();
2589c1868e533e63a1b7dad7a22714fc593c045382aeFariborz Jahanian           M != MEnd; ++M)
2590c1868e533e63a1b7dad7a22714fc593c045382aeFariborz Jahanian        EmitTopLevelDecl(*M);
2591c1868e533e63a1b7dad7a22714fc593c045382aeFariborz Jahanian    }
259291e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson    EmitTopLevelDecl(*I);
2593c1868e533e63a1b7dad7a22714fc593c045382aeFariborz Jahanian  }
259491e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson}
259591e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson
259641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar/// EmitTopLevelDecl - Emit code for a single top level declaration.
259741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbarvoid CodeGenModule::EmitTopLevelDecl(Decl *D) {
259841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  // If an error has occurred, stop code generation, but continue
259941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  // parsing and semantic analysis (to ensure all warnings and errors
260041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  // are emitted).
260141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  if (Diags.hasErrorOccurred())
260241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    return;
260341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
260416e8be2ac532358d4e413fdfa2643b1876edda78Douglas Gregor  // Ignore dependent declarations.
260516e8be2ac532358d4e413fdfa2643b1876edda78Douglas Gregor  if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
260616e8be2ac532358d4e413fdfa2643b1876edda78Douglas Gregor    return;
26071eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
260841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  switch (D->getKind()) {
2609293361afd4199c92aabff9267fddea890943c586Anders Carlsson  case Decl::CXXConversion:
26102b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson  case Decl::CXXMethod:
261141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::Function:
261216e8be2ac532358d4e413fdfa2643b1876edda78Douglas Gregor    // Skip function templates
26138387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichet    if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
26148387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichet        cast<FunctionDecl>(D)->isLateTemplateParsed())
261516e8be2ac532358d4e413fdfa2643b1876edda78Douglas Gregor      return;
26161eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2617555b4bb2749aea2ec8e2adc351a71ec1cb9bdc33Anders Carlsson    EmitGlobal(cast<FunctionDecl>(D));
2618555b4bb2749aea2ec8e2adc351a71ec1cb9bdc33Anders Carlsson    break;
2619555b4bb2749aea2ec8e2adc351a71ec1cb9bdc33Anders Carlsson
262041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::Var:
2621555b4bb2749aea2ec8e2adc351a71ec1cb9bdc33Anders Carlsson    EmitGlobal(cast<VarDecl>(D));
262241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
262341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
262426fbc72b33bdbd20b0145bf117c64d373f8051e3John McCall  // Indirect fields from global anonymous structs and unions can be
262526fbc72b33bdbd20b0145bf117c64d373f8051e3John McCall  // ignored; only the actual variable requires IR gen support.
262626fbc72b33bdbd20b0145bf117c64d373f8051e3John McCall  case Decl::IndirectField:
262726fbc72b33bdbd20b0145bf117c64d373f8051e3John McCall    break;
262826fbc72b33bdbd20b0145bf117c64d373f8051e3John McCall
262995d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson  // C++ Decls
263041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::Namespace:
2631984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlsson    EmitNamespace(cast<NamespaceDecl>(D));
263241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
26339cfbe48a7a20a217fdb2920b29b67ae7941cb116Douglas Gregor    // No code generation needed.
26349d0c6613ec040ad8d952556be909232a7f25dedeJohn McCall  case Decl::UsingShadow:
26359cfbe48a7a20a217fdb2920b29b67ae7941cb116Douglas Gregor  case Decl::Using:
2636dd9967a6374c9a44be4af02aaeee340ffb82848fDouglas Gregor  case Decl::UsingDirective:
2637127102b5196ffe04bdb70fd553fe62c265ab10a9Douglas Gregor  case Decl::ClassTemplate:
2638127102b5196ffe04bdb70fd553fe62c265ab10a9Douglas Gregor  case Decl::FunctionTemplate:
26393e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard Smith  case Decl::TypeAliasTemplate:
2640018837b081bd1a725bae1c020eb1649975b04d67Anders Carlsson  case Decl::NamespaceAlias:
26416a576ab708d3aa7d40e5d867ab1de5d3cb507553Douglas Gregor  case Decl::Block:
264215de72cf580840c61e5704c2f8a2b56f9d0638e1Douglas Gregor  case Decl::Import:
26439cfbe48a7a20a217fdb2920b29b67ae7941cb116Douglas Gregor    break;
264495d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson  case Decl::CXXConstructor:
26451fe598c026dc03fddbd65efb8119eb1afd9b1520Anders Carlsson    // Skip function templates
26468387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichet    if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
26478387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichet        cast<FunctionDecl>(D)->isLateTemplateParsed())
26481fe598c026dc03fddbd65efb8119eb1afd9b1520Anders Carlsson      return;
26491fe598c026dc03fddbd65efb8119eb1afd9b1520Anders Carlsson
265095d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson    EmitCXXConstructors(cast<CXXConstructorDecl>(D));
265195d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson    break;
265227ae53665f8b00fe4ba21da0fa79a4ce6e0b6cd5Anders Carlsson  case Decl::CXXDestructor:
26538387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichet    if (cast<FunctionDecl>(D)->isLateTemplateParsed())
26548387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichet      return;
265527ae53665f8b00fe4ba21da0fa79a4ce6e0b6cd5Anders Carlsson    EmitCXXDestructors(cast<CXXDestructorDecl>(D));
265627ae53665f8b00fe4ba21da0fa79a4ce6e0b6cd5Anders Carlsson    break;
265736674d2978eb53962218ac67bb4d352cc287ea05Anders Carlsson
265836674d2978eb53962218ac67bb4d352cc287ea05Anders Carlsson  case Decl::StaticAssert:
265936674d2978eb53962218ac67bb4d352cc287ea05Anders Carlsson    // Nothing to do.
266036674d2978eb53962218ac67bb4d352cc287ea05Anders Carlsson    break;
266136674d2978eb53962218ac67bb4d352cc287ea05Anders Carlsson
266295d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson  // Objective-C Decls
26631eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
266438e24c782c17b6058bf61d635747bbde19fb1bc7Fariborz Jahanian  // Forward declarations, no (immediate) code generation.
2665b31cb7f1752ea011fd06ac9574ce24667d11cbdbFariborz Jahanian  case Decl::ObjCInterface:
2666ffb0c3adc27d257c8453886957b8d220d1ad14d8Eric Christopher  case Decl::ObjCCategory:
266741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
2668285d0dba947b7c9960eaa88e8c4fced0398d4319Chris Lattner
2669bd9482d859a74bf2c45ef8b8aedec61c0e1c8374Douglas Gregor  case Decl::ObjCProtocol: {
2670bd9482d859a74bf2c45ef8b8aedec61c0e1c8374Douglas Gregor    ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(D);
2671bd9482d859a74bf2c45ef8b8aedec61c0e1c8374Douglas Gregor    if (Proto->isThisDeclarationADefinition())
2672bd9482d859a74bf2c45ef8b8aedec61c0e1c8374Douglas Gregor      ObjCRuntime->GenerateProtocol(Proto);
267341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
2674bd9482d859a74bf2c45ef8b8aedec61c0e1c8374Douglas Gregor  }
2675bd9482d859a74bf2c45ef8b8aedec61c0e1c8374Douglas Gregor
267641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::ObjCCategoryImpl:
2677af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    // Categories have properties but don't support synthesize so we
2678af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    // can ignore them here.
2679e926523105dd2604ccd5c101605dea43c5269965Peter Collingbourne    ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
268041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
268141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
2682af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar  case Decl::ObjCImplementation: {
2683af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
2684af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    EmitObjCPropertyImplementations(OMD);
2685109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian    EmitObjCIvarInitializations(OMD);
2686e926523105dd2604ccd5c101605dea43c5269965Peter Collingbourne    ObjCRuntime->GenerateClass(OMD);
2687be6c6869a993536d4cd007f04e84ef74a1c3b229Eric Christopher    // Emit global variable debug information.
2688be6c6869a993536d4cd007f04e84ef74a1c3b229Eric Christopher    if (CGDebugInfo *DI = getModuleDebugInfo())
2689be6c6869a993536d4cd007f04e84ef74a1c3b229Eric Christopher      DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(OMD->getClassInterface()),
2690be6c6869a993536d4cd007f04e84ef74a1c3b229Eric Christopher				   OMD->getLocation());
2691be6c6869a993536d4cd007f04e84ef74a1c3b229Eric Christopher
269241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
26931eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  }
269441071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::ObjCMethod: {
269541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
269641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    // If this is not a prototype, emit the body.
26976fb0aee4f9dc261bbec72e1283ad8dc0557a6d96Argyrios Kyrtzidis    if (OMD->getBody())
269841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar      CodeGenFunction(*this).GenerateObjCMethod(OMD);
269941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
270041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  }
27011eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  case Decl::ObjCCompatibleAlias:
270229254f4dd114fe2dd5c4e7a261ebea941973ad3dDavid Chisnall    ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
270341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
270441071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
270591e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson  case Decl::LinkageSpec:
270691e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson    EmitLinkageSpec(cast<LinkageSpecDecl>(D));
270741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
270841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
270941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::FileScopeAsm: {
271041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
27115f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner    StringRef AsmString = AD->getAsmString()->getString();
27121eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
271341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    const std::string &S = getModule().getModuleInlineAsm();
271441071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    if (S.empty())
271541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar      getModule().setModuleInlineAsm(AsmString);
27168ce9cca118b32604f481ad381eafab25b5798c9fJoerg Sonnenberger    else if (S.end()[-1] == '\n')
27179f5bff086cad25c15b4deb8a7763786097aadccdChris Lattner      getModule().setModuleInlineAsm(S + AsmString.str());
271841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    else
27198d04258483be6583f0865464234d014807a3e1ccBenjamin Kramer      getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
272041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
272141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  }
27221eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
27231eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  default:
2724f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump    // Make sure we handled everything we should, every other kind is a
2725f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump    // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
2726f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump    // function. Need to recode Decl::Kind to do that easily.
272741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    assert(isa<TypeDecl>(D) && "Unsupported decl kind");
272841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  }
272941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar}
2730744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2731744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// Turns the given pointer into a constant.
2732744016dde06fcffd50931e94a98c850f8b12cd87John McCallstatic llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
2733744016dde06fcffd50931e94a98c850f8b12cd87John McCall                                          const void *Ptr) {
2734744016dde06fcffd50931e94a98c850f8b12cd87John McCall  uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
27352acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
2736744016dde06fcffd50931e94a98c850f8b12cd87John McCall  return llvm::ConstantInt::get(i64, PtrInt);
2737744016dde06fcffd50931e94a98c850f8b12cd87John McCall}
2738744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2739744016dde06fcffd50931e94a98c850f8b12cd87John McCallstatic void EmitGlobalDeclMetadata(CodeGenModule &CGM,
2740744016dde06fcffd50931e94a98c850f8b12cd87John McCall                                   llvm::NamedMDNode *&GlobalMetadata,
2741744016dde06fcffd50931e94a98c850f8b12cd87John McCall                                   GlobalDecl D,
2742744016dde06fcffd50931e94a98c850f8b12cd87John McCall                                   llvm::GlobalValue *Addr) {
2743744016dde06fcffd50931e94a98c850f8b12cd87John McCall  if (!GlobalMetadata)
2744744016dde06fcffd50931e94a98c850f8b12cd87John McCall    GlobalMetadata =
2745744016dde06fcffd50931e94a98c850f8b12cd87John McCall      CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
2746744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2747744016dde06fcffd50931e94a98c850f8b12cd87John McCall  // TODO: should we report variant information for ctors/dtors?
2748744016dde06fcffd50931e94a98c850f8b12cd87John McCall  llvm::Value *Ops[] = {
2749744016dde06fcffd50931e94a98c850f8b12cd87John McCall    Addr,
2750744016dde06fcffd50931e94a98c850f8b12cd87John McCall    GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
2751744016dde06fcffd50931e94a98c850f8b12cd87John McCall  };
27526f141659cab11109d9931d92d0988f8850778de3Jay Foad  GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2753744016dde06fcffd50931e94a98c850f8b12cd87John McCall}
2754744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2755744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// Emits metadata nodes associating all the global values in the
2756744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// current module with the Decls they came from.  This is useful for
2757744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// projects using IR gen as a subroutine.
2758744016dde06fcffd50931e94a98c850f8b12cd87John McCall///
2759744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// Since there's currently no way to associate an MDNode directly
2760744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// with an llvm::GlobalValue, we create a global named metadata
2761744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// with the name 'clang.global.decl.ptrs'.
2762744016dde06fcffd50931e94a98c850f8b12cd87John McCallvoid CodeGenModule::EmitDeclMetadata() {
2763744016dde06fcffd50931e94a98c850f8b12cd87John McCall  llvm::NamedMDNode *GlobalMetadata = 0;
2764744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2765744016dde06fcffd50931e94a98c850f8b12cd87John McCall  // StaticLocalDeclMap
27665f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  for (llvm::DenseMap<GlobalDecl,StringRef>::iterator
2767744016dde06fcffd50931e94a98c850f8b12cd87John McCall         I = MangledDeclNames.begin(), E = MangledDeclNames.end();
2768744016dde06fcffd50931e94a98c850f8b12cd87John McCall       I != E; ++I) {
2769744016dde06fcffd50931e94a98c850f8b12cd87John McCall    llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
2770744016dde06fcffd50931e94a98c850f8b12cd87John McCall    EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
2771744016dde06fcffd50931e94a98c850f8b12cd87John McCall  }
2772744016dde06fcffd50931e94a98c850f8b12cd87John McCall}
2773744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2774744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// Emits metadata nodes for all the local variables in the current
2775744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// function.
2776744016dde06fcffd50931e94a98c850f8b12cd87John McCallvoid CodeGenFunction::EmitDeclMetadata() {
2777744016dde06fcffd50931e94a98c850f8b12cd87John McCall  if (LocalDeclMap.empty()) return;
2778744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2779744016dde06fcffd50931e94a98c850f8b12cd87John McCall  llvm::LLVMContext &Context = getLLVMContext();
2780744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2781744016dde06fcffd50931e94a98c850f8b12cd87John McCall  // Find the unique metadata ID for this name.
2782744016dde06fcffd50931e94a98c850f8b12cd87John McCall  unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
2783744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2784744016dde06fcffd50931e94a98c850f8b12cd87John McCall  llvm::NamedMDNode *GlobalMetadata = 0;
2785744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2786744016dde06fcffd50931e94a98c850f8b12cd87John McCall  for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
2787744016dde06fcffd50931e94a98c850f8b12cd87John McCall         I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
2788744016dde06fcffd50931e94a98c850f8b12cd87John McCall    const Decl *D = I->first;
2789744016dde06fcffd50931e94a98c850f8b12cd87John McCall    llvm::Value *Addr = I->second;
2790744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2791744016dde06fcffd50931e94a98c850f8b12cd87John McCall    if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
2792744016dde06fcffd50931e94a98c850f8b12cd87John McCall      llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
27936f141659cab11109d9931d92d0988f8850778de3Jay Foad      Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
2794744016dde06fcffd50931e94a98c850f8b12cd87John McCall    } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
2795744016dde06fcffd50931e94a98c850f8b12cd87John McCall      GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
2796744016dde06fcffd50931e94a98c850f8b12cd87John McCall      EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
2797744016dde06fcffd50931e94a98c850f8b12cd87John McCall    }
2798744016dde06fcffd50931e94a98c850f8b12cd87John McCall  }
2799744016dde06fcffd50931e94a98c850f8b12cd87John McCall}
2800673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar
28013dc05418538c719fea48b906bfa4febe5296e126Nick Lewyckyvoid CodeGenModule::EmitCoverageFile() {
28023dc05418538c719fea48b906bfa4febe5296e126Nick Lewycky  if (!getCodeGenOpts().CoverageFile.empty()) {
28035ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky    if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
28045ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky      llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
28055ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky      llvm::LLVMContext &Ctx = TheModule.getContext();
28063dc05418538c719fea48b906bfa4febe5296e126Nick Lewycky      llvm::MDString *CoverageFile =
28073dc05418538c719fea48b906bfa4febe5296e126Nick Lewycky          llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
28085ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky      for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
28095ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky        llvm::MDNode *CU = CUNode->getOperand(i);
28103dc05418538c719fea48b906bfa4febe5296e126Nick Lewycky        llvm::Value *node[] = { CoverageFile, CU };
28115ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky        llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
28125ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky        GCov->addOperand(N);
28135ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky      }
28145ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky    }
28155ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky  }
28165ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky}
2817c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber
2818c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weberllvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid,
2819c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber                                                     QualType GuidType) {
2820c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  // Sema has checked that all uuid strings are of the form
2821c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  // "12345678-1234-1234-1234-1234567890ab".
2822c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  assert(Uuid.size() == 36);
2823c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  const char *Uuidstr = Uuid.data();
2824c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  for (int i = 0; i < 36; ++i) {
2825c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber    if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuidstr[i] == '-');
2826c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber    else                                         assert(isxdigit(Uuidstr[i]));
2827c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  }
2828c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber
2829c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  llvm::APInt Field0(32, StringRef(Uuidstr     , 8), 16);
2830c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  llvm::APInt Field1(16, StringRef(Uuidstr +  9, 4), 16);
2831c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  llvm::APInt Field2(16, StringRef(Uuidstr + 14, 4), 16);
2832193646f16d90f004123965606ec3fae180beafe1Nico Weber  static const int Field3ValueOffsets[] = { 19, 21, 24, 26, 28, 30, 32, 34 };
2833c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber
2834c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  APValue InitStruct(APValue::UninitStruct(), /*NumBases=*/0, /*NumFields=*/4);
2835c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  InitStruct.getStructField(0) = APValue(llvm::APSInt(Field0));
2836c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  InitStruct.getStructField(1) = APValue(llvm::APSInt(Field1));
2837c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  InitStruct.getStructField(2) = APValue(llvm::APSInt(Field2));
2838c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  APValue& Arr = InitStruct.getStructField(3);
2839c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  Arr = APValue(APValue::UninitArray(), 8, 8);
2840c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  for (int t = 0; t < 8; ++t)
284143085815b1b377dc30176afab2b96d6b807d42deNico Weber    Arr.getArrayInitializedElt(t) = APValue(llvm::APSInt(
284243085815b1b377dc30176afab2b96d6b807d42deNico Weber          llvm::APInt(8, StringRef(Uuidstr + Field3ValueOffsets[t], 2), 16)));
2843c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber
2844c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  return EmitConstantValue(InitStruct, GuidType);
2845c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber}
2846