clang API Documentation

CodeGenModule.cpp
Go to the documentation of this file.
00001 //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This coordinates the per-module state used while generating code.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "CodeGenModule.h"
00015 #include "CGCUDARuntime.h"
00016 #include "CGCXXABI.h"
00017 #include "CGCall.h"
00018 #include "CGDebugInfo.h"
00019 #include "CGObjCRuntime.h"
00020 #include "CGOpenCLRuntime.h"
00021 #include "CGOpenMPRuntime.h"
00022 #include "CodeGenFunction.h"
00023 #include "CodeGenPGO.h"
00024 #include "CoverageMappingGen.h"
00025 #include "CodeGenTBAA.h"
00026 #include "TargetInfo.h"
00027 #include "clang/AST/ASTContext.h"
00028 #include "clang/AST/CharUnits.h"
00029 #include "clang/AST/DeclCXX.h"
00030 #include "clang/AST/DeclObjC.h"
00031 #include "clang/AST/DeclTemplate.h"
00032 #include "clang/AST/Mangle.h"
00033 #include "clang/AST/RecordLayout.h"
00034 #include "clang/AST/RecursiveASTVisitor.h"
00035 #include "clang/Basic/Builtins.h"
00036 #include "clang/Basic/CharInfo.h"
00037 #include "clang/Basic/Diagnostic.h"
00038 #include "clang/Basic/Module.h"
00039 #include "clang/Basic/SourceManager.h"
00040 #include "clang/Basic/TargetInfo.h"
00041 #include "clang/Basic/Version.h"
00042 #include "clang/Frontend/CodeGenOptions.h"
00043 #include "clang/Sema/SemaDiagnostic.h"
00044 #include "llvm/ADT/APSInt.h"
00045 #include "llvm/ADT/Triple.h"
00046 #include "llvm/IR/CallSite.h"
00047 #include "llvm/IR/CallingConv.h"
00048 #include "llvm/IR/DataLayout.h"
00049 #include "llvm/IR/Intrinsics.h"
00050 #include "llvm/IR/LLVMContext.h"
00051 #include "llvm/IR/Module.h"
00052 #include "llvm/ProfileData/InstrProfReader.h"
00053 #include "llvm/Support/ConvertUTF.h"
00054 #include "llvm/Support/ErrorHandling.h"
00055 
00056 using namespace clang;
00057 using namespace CodeGen;
00058 
00059 static const char AnnotationSection[] = "llvm.metadata";
00060 
00061 static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
00062   switch (CGM.getTarget().getCXXABI().getKind()) {
00063   case TargetCXXABI::GenericAArch64:
00064   case TargetCXXABI::GenericARM:
00065   case TargetCXXABI::iOS:
00066   case TargetCXXABI::iOS64:
00067   case TargetCXXABI::GenericItanium:
00068     return CreateItaniumCXXABI(CGM);
00069   case TargetCXXABI::Microsoft:
00070     return CreateMicrosoftCXXABI(CGM);
00071   }
00072 
00073   llvm_unreachable("invalid C++ ABI kind");
00074 }
00075 
00076 CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
00077                              llvm::Module &M, const llvm::DataLayout &TD,
00078                              DiagnosticsEngine &diags,
00079                              CoverageSourceInfo *CoverageInfo)
00080     : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M),
00081       Diags(diags), TheDataLayout(TD), Target(C.getTargetInfo()),
00082       ABI(createCXXABI(*this)), VMContext(M.getContext()), TBAA(nullptr),
00083       TheTargetCodeGenInfo(nullptr), Types(*this), VTables(*this),
00084       ObjCRuntime(nullptr), OpenCLRuntime(nullptr), OpenMPRuntime(nullptr),
00085       CUDARuntime(nullptr), DebugInfo(nullptr), ARCData(nullptr),
00086       NoObjCARCExceptionsMetadata(nullptr), RRData(nullptr), PGOReader(nullptr),
00087       CFConstantStringClassRef(nullptr), ConstantStringClassRef(nullptr),
00088       NSConstantStringType(nullptr), NSConcreteGlobalBlock(nullptr),
00089       NSConcreteStackBlock(nullptr), BlockObjectAssign(nullptr),
00090       BlockObjectDispose(nullptr), BlockDescriptorType(nullptr),
00091       GenericBlockLiteralType(nullptr), LifetimeStartFn(nullptr),
00092       LifetimeEndFn(nullptr), SanitizerMD(new SanitizerMetadata(*this)) {
00093 
00094   // Initialize the type cache.
00095   llvm::LLVMContext &LLVMContext = M.getContext();
00096   VoidTy = llvm::Type::getVoidTy(LLVMContext);
00097   Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
00098   Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
00099   Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
00100   Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
00101   FloatTy = llvm::Type::getFloatTy(LLVMContext);
00102   DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
00103   PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
00104   PointerAlignInBytes =
00105   C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
00106   IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
00107   IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
00108   Int8PtrTy = Int8Ty->getPointerTo(0);
00109   Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
00110 
00111   RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
00112 
00113   if (LangOpts.ObjC1)
00114     createObjCRuntime();
00115   if (LangOpts.OpenCL)
00116     createOpenCLRuntime();
00117   if (LangOpts.OpenMP)
00118     createOpenMPRuntime();
00119   if (LangOpts.CUDA)
00120     createCUDARuntime();
00121 
00122   // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
00123   if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
00124       (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
00125     TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
00126                            getCXXABI().getMangleContext());
00127 
00128   // If debug info or coverage generation is enabled, create the CGDebugInfo
00129   // object.
00130   if (CodeGenOpts.getDebugInfo() != CodeGenOptions::NoDebugInfo ||
00131       CodeGenOpts.EmitGcovArcs ||
00132       CodeGenOpts.EmitGcovNotes)
00133     DebugInfo = new CGDebugInfo(*this);
00134 
00135   Block.GlobalUniqueCount = 0;
00136 
00137   if (C.getLangOpts().ObjCAutoRefCount)
00138     ARCData = new ARCEntrypoints();
00139   RRData = new RREntrypoints();
00140 
00141   if (!CodeGenOpts.InstrProfileInput.empty()) {
00142     if (std::error_code EC = llvm::IndexedInstrProfReader::create(
00143             CodeGenOpts.InstrProfileInput, PGOReader)) {
00144       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
00145                                               "Could not read profile: %0");
00146       getDiags().Report(DiagID) << EC.message();
00147     }
00148   }
00149 
00150   // If coverage mapping generation is enabled, create the
00151   // CoverageMappingModuleGen object.
00152   if (CodeGenOpts.CoverageMapping)
00153     CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
00154 }
00155 
00156 CodeGenModule::~CodeGenModule() {
00157   delete ObjCRuntime;
00158   delete OpenCLRuntime;
00159   delete OpenMPRuntime;
00160   delete CUDARuntime;
00161   delete TheTargetCodeGenInfo;
00162   delete TBAA;
00163   delete DebugInfo;
00164   delete ARCData;
00165   delete RRData;
00166 }
00167 
00168 void CodeGenModule::createObjCRuntime() {
00169   // This is just isGNUFamily(), but we want to force implementors of
00170   // new ABIs to decide how best to do this.
00171   switch (LangOpts.ObjCRuntime.getKind()) {
00172   case ObjCRuntime::GNUstep:
00173   case ObjCRuntime::GCC:
00174   case ObjCRuntime::ObjFW:
00175     ObjCRuntime = CreateGNUObjCRuntime(*this);
00176     return;
00177 
00178   case ObjCRuntime::FragileMacOSX:
00179   case ObjCRuntime::MacOSX:
00180   case ObjCRuntime::iOS:
00181     ObjCRuntime = CreateMacObjCRuntime(*this);
00182     return;
00183   }
00184   llvm_unreachable("bad runtime kind");
00185 }
00186 
00187 void CodeGenModule::createOpenCLRuntime() {
00188   OpenCLRuntime = new CGOpenCLRuntime(*this);
00189 }
00190 
00191 void CodeGenModule::createOpenMPRuntime() {
00192   OpenMPRuntime = new CGOpenMPRuntime(*this);
00193 }
00194 
00195 void CodeGenModule::createCUDARuntime() {
00196   CUDARuntime = CreateNVCUDARuntime(*this);
00197 }
00198 
00199 void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
00200   Replacements[Name] = C;
00201 }
00202 
00203 void CodeGenModule::applyReplacements() {
00204   for (ReplacementsTy::iterator I = Replacements.begin(),
00205                                 E = Replacements.end();
00206        I != E; ++I) {
00207     StringRef MangledName = I->first();
00208     llvm::Constant *Replacement = I->second;
00209     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
00210     if (!Entry)
00211       continue;
00212     auto *OldF = cast<llvm::Function>(Entry);
00213     auto *NewF = dyn_cast<llvm::Function>(Replacement);
00214     if (!NewF) {
00215       if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
00216         NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
00217       } else {
00218         auto *CE = cast<llvm::ConstantExpr>(Replacement);
00219         assert(CE->getOpcode() == llvm::Instruction::BitCast ||
00220                CE->getOpcode() == llvm::Instruction::GetElementPtr);
00221         NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
00222       }
00223     }
00224 
00225     // Replace old with new, but keep the old order.
00226     OldF->replaceAllUsesWith(Replacement);
00227     if (NewF) {
00228       NewF->removeFromParent();
00229       OldF->getParent()->getFunctionList().insertAfter(OldF, NewF);
00230     }
00231     OldF->eraseFromParent();
00232   }
00233 }
00234 
00235 // This is only used in aliases that we created and we know they have a
00236 // linear structure.
00237 static const llvm::GlobalObject *getAliasedGlobal(const llvm::GlobalAlias &GA) {
00238   llvm::SmallPtrSet<const llvm::GlobalAlias*, 4> Visited;
00239   const llvm::Constant *C = &GA;
00240   for (;;) {
00241     C = C->stripPointerCasts();
00242     if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
00243       return GO;
00244     // stripPointerCasts will not walk over weak aliases.
00245     auto *GA2 = dyn_cast<llvm::GlobalAlias>(C);
00246     if (!GA2)
00247       return nullptr;
00248     if (!Visited.insert(GA2))
00249       return nullptr;
00250     C = GA2->getAliasee();
00251   }
00252 }
00253 
00254 void CodeGenModule::checkAliases() {
00255   // Check if the constructed aliases are well formed. It is really unfortunate
00256   // that we have to do this in CodeGen, but we only construct mangled names
00257   // and aliases during codegen.
00258   bool Error = false;
00259   DiagnosticsEngine &Diags = getDiags();
00260   for (std::vector<GlobalDecl>::iterator I = Aliases.begin(),
00261          E = Aliases.end(); I != E; ++I) {
00262     const GlobalDecl &GD = *I;
00263     const auto *D = cast<ValueDecl>(GD.getDecl());
00264     const AliasAttr *AA = D->getAttr<AliasAttr>();
00265     StringRef MangledName = getMangledName(GD);
00266     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
00267     auto *Alias = cast<llvm::GlobalAlias>(Entry);
00268     const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
00269     if (!GV) {
00270       Error = true;
00271       Diags.Report(AA->getLocation(), diag::err_cyclic_alias);
00272     } else if (GV->isDeclaration()) {
00273       Error = true;
00274       Diags.Report(AA->getLocation(), diag::err_alias_to_undefined);
00275     }
00276 
00277     llvm::Constant *Aliasee = Alias->getAliasee();
00278     llvm::GlobalValue *AliaseeGV;
00279     if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
00280       AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
00281     else
00282       AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
00283 
00284     if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
00285       StringRef AliasSection = SA->getName();
00286       if (AliasSection != AliaseeGV->getSection())
00287         Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
00288             << AliasSection;
00289     }
00290 
00291     // We have to handle alias to weak aliases in here. LLVM itself disallows
00292     // this since the object semantics would not match the IL one. For
00293     // compatibility with gcc we implement it by just pointing the alias
00294     // to its aliasee's aliasee. We also warn, since the user is probably
00295     // expecting the link to be weak.
00296     if (auto GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
00297       if (GA->mayBeOverridden()) {
00298         Diags.Report(AA->getLocation(), diag::warn_alias_to_weak_alias)
00299             << GV->getName() << GA->getName();
00300         Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
00301             GA->getAliasee(), Alias->getType());
00302         Alias->setAliasee(Aliasee);
00303       }
00304     }
00305   }
00306   if (!Error)
00307     return;
00308 
00309   for (std::vector<GlobalDecl>::iterator I = Aliases.begin(),
00310          E = Aliases.end(); I != E; ++I) {
00311     const GlobalDecl &GD = *I;
00312     StringRef MangledName = getMangledName(GD);
00313     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
00314     auto *Alias = cast<llvm::GlobalAlias>(Entry);
00315     Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
00316     Alias->eraseFromParent();
00317   }
00318 }
00319 
00320 void CodeGenModule::clear() {
00321   DeferredDeclsToEmit.clear();
00322 }
00323 
00324 void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
00325                                        StringRef MainFile) {
00326   if (!hasDiagnostics())
00327     return;
00328   if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
00329     if (MainFile.empty())
00330       MainFile = "<stdin>";
00331     Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
00332   } else
00333     Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Missing
00334                                                       << Mismatched;
00335 }
00336 
00337 void CodeGenModule::Release() {
00338   EmitDeferred();
00339   applyReplacements();
00340   checkAliases();
00341   EmitCXXGlobalInitFunc();
00342   EmitCXXGlobalDtorFunc();
00343   EmitCXXThreadLocalInitFunc();
00344   if (ObjCRuntime)
00345     if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
00346       AddGlobalCtor(ObjCInitFunction);
00347   if (getCodeGenOpts().ProfileInstrGenerate)
00348     if (llvm::Function *PGOInit = CodeGenPGO::emitInitialization(*this))
00349       AddGlobalCtor(PGOInit, 0);
00350   if (PGOReader && PGOStats.hasDiagnostics())
00351     PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
00352   EmitCtorList(GlobalCtors, "llvm.global_ctors");
00353   EmitCtorList(GlobalDtors, "llvm.global_dtors");
00354   EmitGlobalAnnotations();
00355   EmitStaticExternCAliases();
00356   EmitDeferredUnusedCoverageMappings();
00357   if (CoverageMapping)
00358     CoverageMapping->emit();
00359   emitLLVMUsed();
00360 
00361   if (CodeGenOpts.Autolink &&
00362       (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
00363     EmitModuleLinkOptions();
00364   }
00365   if (CodeGenOpts.DwarfVersion)
00366     // We actually want the latest version when there are conflicts.
00367     // We can change from Warning to Latest if such mode is supported.
00368     getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
00369                               CodeGenOpts.DwarfVersion);
00370   if (DebugInfo)
00371     // We support a single version in the linked module. The LLVM
00372     // parser will drop debug info with a different version number
00373     // (and warn about it, too).
00374     getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
00375                               llvm::DEBUG_METADATA_VERSION);
00376 
00377   // We need to record the widths of enums and wchar_t, so that we can generate
00378   // the correct build attributes in the ARM backend.
00379   llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
00380   if (   Arch == llvm::Triple::arm
00381       || Arch == llvm::Triple::armeb
00382       || Arch == llvm::Triple::thumb
00383       || Arch == llvm::Triple::thumbeb) {
00384     // Width of wchar_t in bytes
00385     uint64_t WCharWidth =
00386         Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
00387     getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
00388 
00389     // The minimum width of an enum in bytes
00390     uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
00391     getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
00392   }
00393 
00394   if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
00395     llvm::PICLevel::Level PL = llvm::PICLevel::Default;
00396     switch (PLevel) {
00397     case 0: break;
00398     case 1: PL = llvm::PICLevel::Small; break;
00399     case 2: PL = llvm::PICLevel::Large; break;
00400     default: llvm_unreachable("Invalid PIC Level");
00401     }
00402 
00403     getModule().setPICLevel(PL);
00404   }
00405 
00406   SimplifyPersonality();
00407 
00408   if (getCodeGenOpts().EmitDeclMetadata)
00409     EmitDeclMetadata();
00410 
00411   if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
00412     EmitCoverageFile();
00413 
00414   if (DebugInfo)
00415     DebugInfo->finalize();
00416 
00417   EmitVersionIdentMetadata();
00418 
00419   EmitTargetMetadata();
00420 }
00421 
00422 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
00423   // Make sure that this type is translated.
00424   Types.UpdateCompletedType(TD);
00425 }
00426 
00427 llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
00428   if (!TBAA)
00429     return nullptr;
00430   return TBAA->getTBAAInfo(QTy);
00431 }
00432 
00433 llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
00434   if (!TBAA)
00435     return nullptr;
00436   return TBAA->getTBAAInfoForVTablePtr();
00437 }
00438 
00439 llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
00440   if (!TBAA)
00441     return nullptr;
00442   return TBAA->getTBAAStructInfo(QTy);
00443 }
00444 
00445 llvm::MDNode *CodeGenModule::getTBAAStructTypeInfo(QualType QTy) {
00446   if (!TBAA)
00447     return nullptr;
00448   return TBAA->getTBAAStructTypeInfo(QTy);
00449 }
00450 
00451 llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
00452                                                   llvm::MDNode *AccessN,
00453                                                   uint64_t O) {
00454   if (!TBAA)
00455     return nullptr;
00456   return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
00457 }
00458 
00459 /// Decorate the instruction with a TBAA tag. For both scalar TBAA
00460 /// and struct-path aware TBAA, the tag has the same format:
00461 /// base type, access type and offset.
00462 /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
00463 void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
00464                                         llvm::MDNode *TBAAInfo,
00465                                         bool ConvertTypeToTag) {
00466   if (ConvertTypeToTag && TBAA)
00467     Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
00468                       TBAA->getTBAAScalarTagInfo(TBAAInfo));
00469   else
00470     Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
00471 }
00472 
00473 void CodeGenModule::Error(SourceLocation loc, StringRef message) {
00474   unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
00475   getDiags().Report(Context.getFullLoc(loc), diagID) << message;
00476 }
00477 
00478 /// ErrorUnsupported - Print out an error that codegen doesn't support the
00479 /// specified stmt yet.
00480 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
00481   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
00482                                                "cannot compile this %0 yet");
00483   std::string Msg = Type;
00484   getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
00485     << Msg << S->getSourceRange();
00486 }
00487 
00488 /// ErrorUnsupported - Print out an error that codegen doesn't support the
00489 /// specified decl yet.
00490 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
00491   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
00492                                                "cannot compile this %0 yet");
00493   std::string Msg = Type;
00494   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
00495 }
00496 
00497 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
00498   return llvm::ConstantInt::get(SizeTy, size.getQuantity());
00499 }
00500 
00501 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
00502                                         const NamedDecl *D) const {
00503   // Internal definitions always have default visibility.
00504   if (GV->hasLocalLinkage()) {
00505     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
00506     return;
00507   }
00508 
00509   // Set visibility for definitions.
00510   LinkageInfo LV = D->getLinkageAndVisibility();
00511   if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
00512     GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
00513 }
00514 
00515 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
00516   return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
00517       .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
00518       .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
00519       .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
00520       .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
00521 }
00522 
00523 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
00524     CodeGenOptions::TLSModel M) {
00525   switch (M) {
00526   case CodeGenOptions::GeneralDynamicTLSModel:
00527     return llvm::GlobalVariable::GeneralDynamicTLSModel;
00528   case CodeGenOptions::LocalDynamicTLSModel:
00529     return llvm::GlobalVariable::LocalDynamicTLSModel;
00530   case CodeGenOptions::InitialExecTLSModel:
00531     return llvm::GlobalVariable::InitialExecTLSModel;
00532   case CodeGenOptions::LocalExecTLSModel:
00533     return llvm::GlobalVariable::LocalExecTLSModel;
00534   }
00535   llvm_unreachable("Invalid TLS model!");
00536 }
00537 
00538 void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
00539   assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
00540 
00541   llvm::GlobalValue::ThreadLocalMode TLM;
00542   TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
00543 
00544   // Override the TLS model if it is explicitly specified.
00545   if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
00546     TLM = GetLLVMTLSModel(Attr->getModel());
00547   }
00548 
00549   GV->setThreadLocalMode(TLM);
00550 }
00551 
00552 StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
00553   StringRef &FoundStr = MangledDeclNames[GD.getCanonicalDecl()];
00554   if (!FoundStr.empty())
00555     return FoundStr;
00556 
00557   const auto *ND = cast<NamedDecl>(GD.getDecl());
00558   SmallString<256> Buffer;
00559   StringRef Str;
00560   if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
00561     llvm::raw_svector_ostream Out(Buffer);
00562     if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
00563       getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
00564     else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
00565       getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
00566     else
00567       getCXXABI().getMangleContext().mangleName(ND, Out);
00568     Str = Out.str();
00569   } else {
00570     IdentifierInfo *II = ND->getIdentifier();
00571     assert(II && "Attempt to mangle unnamed decl.");
00572     Str = II->getName();
00573   }
00574 
00575   // Keep the first result in the case of a mangling collision.
00576   auto Result = Manglings.insert(std::make_pair(Str, GD));
00577   return FoundStr = Result.first->first();
00578 }
00579 
00580 StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
00581                                              const BlockDecl *BD) {
00582   MangleContext &MangleCtx = getCXXABI().getMangleContext();
00583   const Decl *D = GD.getDecl();
00584 
00585   SmallString<256> Buffer;
00586   llvm::raw_svector_ostream Out(Buffer);
00587   if (!D)
00588     MangleCtx.mangleGlobalBlock(BD, 
00589       dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
00590   else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
00591     MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
00592   else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
00593     MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
00594   else
00595     MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
00596 
00597   auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
00598   return Result.first->first();
00599 }
00600 
00601 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
00602   return getModule().getNamedValue(Name);
00603 }
00604 
00605 /// AddGlobalCtor - Add a function to the list that will be called before
00606 /// main() runs.
00607 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
00608                                   llvm::Constant *AssociatedData) {
00609   // FIXME: Type coercion of void()* types.
00610   GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
00611 }
00612 
00613 /// AddGlobalDtor - Add a function to the list that will be called
00614 /// when the module is unloaded.
00615 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
00616   // FIXME: Type coercion of void()* types.
00617   GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
00618 }
00619 
00620 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
00621   // Ctor function type is void()*.
00622   llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
00623   llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
00624 
00625   // Get the type of a ctor entry, { i32, void ()*, i8* }.
00626   llvm::StructType *CtorStructTy = llvm::StructType::get(
00627       Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy, NULL);
00628 
00629   // Construct the constructor and destructor arrays.
00630   SmallVector<llvm::Constant*, 8> Ctors;
00631   for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
00632     llvm::Constant *S[] = {
00633       llvm::ConstantInt::get(Int32Ty, I->Priority, false),
00634       llvm::ConstantExpr::getBitCast(I->Initializer, CtorPFTy),
00635       (I->AssociatedData
00636            ? llvm::ConstantExpr::getBitCast(I->AssociatedData, VoidPtrTy)
00637            : llvm::Constant::getNullValue(VoidPtrTy))
00638     };
00639     Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
00640   }
00641 
00642   if (!Ctors.empty()) {
00643     llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
00644     new llvm::GlobalVariable(TheModule, AT, false,
00645                              llvm::GlobalValue::AppendingLinkage,
00646                              llvm::ConstantArray::get(AT, Ctors),
00647                              GlobalName);
00648   }
00649 }
00650 
00651 llvm::GlobalValue::LinkageTypes
00652 CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
00653   const auto *D = cast<FunctionDecl>(GD.getDecl());
00654 
00655   GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
00656 
00657   if (isa<CXXDestructorDecl>(D) &&
00658       getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
00659                                          GD.getDtorType())) {
00660     // Destructor variants in the Microsoft C++ ABI are always internal or
00661     // linkonce_odr thunks emitted on an as-needed basis.
00662     return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
00663                                    : llvm::GlobalValue::LinkOnceODRLinkage;
00664   }
00665 
00666   return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
00667 }
00668 
00669 void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D,
00670                                                     llvm::Function *F) {
00671   setNonAliasAttributes(D, F);
00672 }
00673 
00674 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
00675                                               const CGFunctionInfo &Info,
00676                                               llvm::Function *F) {
00677   unsigned CallingConv;
00678   AttributeListType AttributeList;
00679   ConstructAttributeList(Info, D, AttributeList, CallingConv, false);
00680   F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList));
00681   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
00682 }
00683 
00684 /// Determines whether the language options require us to model
00685 /// unwind exceptions.  We treat -fexceptions as mandating this
00686 /// except under the fragile ObjC ABI with only ObjC exceptions
00687 /// enabled.  This means, for example, that C with -fexceptions
00688 /// enables this.
00689 static bool hasUnwindExceptions(const LangOptions &LangOpts) {
00690   // If exceptions are completely disabled, obviously this is false.
00691   if (!LangOpts.Exceptions) return false;
00692 
00693   // If C++ exceptions are enabled, this is true.
00694   if (LangOpts.CXXExceptions) return true;
00695 
00696   // If ObjC exceptions are enabled, this depends on the ABI.
00697   if (LangOpts.ObjCExceptions) {
00698     return LangOpts.ObjCRuntime.hasUnwindExceptions();
00699   }
00700 
00701   return true;
00702 }
00703 
00704 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
00705                                                            llvm::Function *F) {
00706   llvm::AttrBuilder B;
00707 
00708   if (CodeGenOpts.UnwindTables)
00709     B.addAttribute(llvm::Attribute::UWTable);
00710 
00711   if (!hasUnwindExceptions(LangOpts))
00712     B.addAttribute(llvm::Attribute::NoUnwind);
00713 
00714   if (D->hasAttr<NakedAttr>()) {
00715     // Naked implies noinline: we should not be inlining such functions.
00716     B.addAttribute(llvm::Attribute::Naked);
00717     B.addAttribute(llvm::Attribute::NoInline);
00718   } else if (D->hasAttr<OptimizeNoneAttr>()) {
00719     // OptimizeNone implies noinline; we should not be inlining such functions.
00720     B.addAttribute(llvm::Attribute::OptimizeNone);
00721     B.addAttribute(llvm::Attribute::NoInline);
00722   } else if (D->hasAttr<NoDuplicateAttr>()) {
00723     B.addAttribute(llvm::Attribute::NoDuplicate);
00724   } else if (D->hasAttr<NoInlineAttr>()) {
00725     B.addAttribute(llvm::Attribute::NoInline);
00726   } else if (D->hasAttr<AlwaysInlineAttr>() &&
00727              !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex,
00728                                               llvm::Attribute::NoInline)) {
00729     // (noinline wins over always_inline, and we can't specify both in IR)
00730     B.addAttribute(llvm::Attribute::AlwaysInline);
00731   }
00732 
00733   if (D->hasAttr<ColdAttr>()) {
00734     B.addAttribute(llvm::Attribute::OptimizeForSize);
00735     B.addAttribute(llvm::Attribute::Cold);
00736   }
00737 
00738   if (D->hasAttr<MinSizeAttr>())
00739     B.addAttribute(llvm::Attribute::MinSize);
00740 
00741   if (D->hasAttr<OptimizeNoneAttr>()) {
00742     // OptimizeNone wins over OptimizeForSize and MinSize.
00743     B.removeAttribute(llvm::Attribute::OptimizeForSize);
00744     B.removeAttribute(llvm::Attribute::MinSize);
00745   }
00746 
00747   if (LangOpts.getStackProtector() == LangOptions::SSPOn)
00748     B.addAttribute(llvm::Attribute::StackProtect);
00749   else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
00750     B.addAttribute(llvm::Attribute::StackProtectStrong);
00751   else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
00752     B.addAttribute(llvm::Attribute::StackProtectReq);
00753 
00754   // Add sanitizer attributes if function is not blacklisted.
00755   if (!isInSanitizerBlacklist(F, D->getLocation())) {
00756     // When AddressSanitizer is enabled, set SanitizeAddress attribute
00757     // unless __attribute__((no_sanitize_address)) is used.
00758     if (LangOpts.Sanitize.has(SanitizerKind::Address) &&
00759         !D->hasAttr<NoSanitizeAddressAttr>())
00760       B.addAttribute(llvm::Attribute::SanitizeAddress);
00761     // Same for ThreadSanitizer and __attribute__((no_sanitize_thread))
00762     if (LangOpts.Sanitize.has(SanitizerKind::Thread) &&
00763         !D->hasAttr<NoSanitizeThreadAttr>())
00764       B.addAttribute(llvm::Attribute::SanitizeThread);
00765     // Same for MemorySanitizer and __attribute__((no_sanitize_memory))
00766     if (LangOpts.Sanitize.has(SanitizerKind::Memory) &&
00767         !D->hasAttr<NoSanitizeMemoryAttr>())
00768       B.addAttribute(llvm::Attribute::SanitizeMemory);
00769   }
00770 
00771   F->addAttributes(llvm::AttributeSet::FunctionIndex,
00772                    llvm::AttributeSet::get(
00773                        F->getContext(), llvm::AttributeSet::FunctionIndex, B));
00774 
00775   if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
00776     F->setUnnamedAddr(true);
00777   else if (const auto *MD = dyn_cast<CXXMethodDecl>(D))
00778     if (MD->isVirtual())
00779       F->setUnnamedAddr(true);
00780 
00781   unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
00782   if (alignment)
00783     F->setAlignment(alignment);
00784 
00785   // C++ ABI requires 2-byte alignment for member functions.
00786   if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
00787     F->setAlignment(2);
00788 }
00789 
00790 void CodeGenModule::SetCommonAttributes(const Decl *D,
00791                                         llvm::GlobalValue *GV) {
00792   if (const auto *ND = dyn_cast<NamedDecl>(D))
00793     setGlobalVisibility(GV, ND);
00794   else
00795     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
00796 
00797   if (D->hasAttr<UsedAttr>())
00798     addUsedGlobal(GV);
00799 }
00800 
00801 void CodeGenModule::setAliasAttributes(const Decl *D,
00802                                        llvm::GlobalValue *GV) {
00803   SetCommonAttributes(D, GV);
00804 
00805   // Process the dllexport attribute based on whether the original definition
00806   // (not necessarily the aliasee) was exported.
00807   if (D->hasAttr<DLLExportAttr>())
00808     GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
00809 }
00810 
00811 void CodeGenModule::setNonAliasAttributes(const Decl *D,
00812                                           llvm::GlobalObject *GO) {
00813   SetCommonAttributes(D, GO);
00814 
00815   if (const SectionAttr *SA = D->getAttr<SectionAttr>())
00816     GO->setSection(SA->getName());
00817 
00818   getTargetCodeGenInfo().SetTargetAttributes(D, GO, *this);
00819 }
00820 
00821 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
00822                                                   llvm::Function *F,
00823                                                   const CGFunctionInfo &FI) {
00824   SetLLVMFunctionAttributes(D, FI, F);
00825   SetLLVMFunctionAttributesForDefinition(D, F);
00826 
00827   F->setLinkage(llvm::Function::InternalLinkage);
00828 
00829   setNonAliasAttributes(D, F);
00830 }
00831 
00832 static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV,
00833                                          const NamedDecl *ND) {
00834   // Set linkage and visibility in case we never see a definition.
00835   LinkageInfo LV = ND->getLinkageAndVisibility();
00836   if (LV.getLinkage() != ExternalLinkage) {
00837     // Don't set internal linkage on declarations.
00838   } else {
00839     if (ND->hasAttr<DLLImportAttr>()) {
00840       GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
00841       GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
00842     } else if (ND->hasAttr<DLLExportAttr>()) {
00843       GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
00844       GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
00845     } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) {
00846       // "extern_weak" is overloaded in LLVM; we probably should have
00847       // separate linkage types for this.
00848       GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
00849     }
00850 
00851     // Set visibility on a declaration only if it's explicit.
00852     if (LV.isVisibilityExplicit())
00853       GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility()));
00854   }
00855 }
00856 
00857 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
00858                                           bool IsIncompleteFunction,
00859                                           bool IsThunk) {
00860   if (unsigned IID = F->getIntrinsicID()) {
00861     // If this is an intrinsic function, set the function's attributes
00862     // to the intrinsic's attributes.
00863     F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(),
00864                                                     (llvm::Intrinsic::ID)IID));
00865     return;
00866   }
00867 
00868   const auto *FD = cast<FunctionDecl>(GD.getDecl());
00869 
00870   if (!IsIncompleteFunction)
00871     SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
00872 
00873   // Add the Returned attribute for "this", except for iOS 5 and earlier
00874   // where substantial code, including the libstdc++ dylib, was compiled with
00875   // GCC and does not actually return "this".
00876   if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
00877       !(getTarget().getTriple().isiOS() &&
00878         getTarget().getTriple().isOSVersionLT(6))) {
00879     assert(!F->arg_empty() &&
00880            F->arg_begin()->getType()
00881              ->canLosslesslyBitCastTo(F->getReturnType()) &&
00882            "unexpected this return");
00883     F->addAttribute(1, llvm::Attribute::Returned);
00884   }
00885 
00886   // Only a few attributes are set on declarations; these may later be
00887   // overridden by a definition.
00888 
00889   setLinkageAndVisibilityForGV(F, FD);
00890 
00891   if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
00892     if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
00893       // Don't dllexport/import destructor thunks.
00894       F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
00895     }
00896   }
00897 
00898   if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
00899     F->setSection(SA->getName());
00900 
00901   // A replaceable global allocation function does not act like a builtin by
00902   // default, only if it is invoked by a new-expression or delete-expression.
00903   if (FD->isReplaceableGlobalAllocationFunction())
00904     F->addAttribute(llvm::AttributeSet::FunctionIndex,
00905                     llvm::Attribute::NoBuiltin);
00906 }
00907 
00908 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
00909   assert(!GV->isDeclaration() &&
00910          "Only globals with definition can force usage.");
00911   LLVMUsed.push_back(GV);
00912 }
00913 
00914 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
00915   assert(!GV->isDeclaration() &&
00916          "Only globals with definition can force usage.");
00917   LLVMCompilerUsed.push_back(GV);
00918 }
00919 
00920 static void emitUsed(CodeGenModule &CGM, StringRef Name,
00921                      std::vector<llvm::WeakVH> &List) {
00922   // Don't create llvm.used if there is no need.
00923   if (List.empty())
00924     return;
00925 
00926   // Convert List to what ConstantArray needs.
00927   SmallVector<llvm::Constant*, 8> UsedArray;
00928   UsedArray.resize(List.size());
00929   for (unsigned i = 0, e = List.size(); i != e; ++i) {
00930     UsedArray[i] =
00931      llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*List[i]),
00932                                     CGM.Int8PtrTy);
00933   }
00934 
00935   if (UsedArray.empty())
00936     return;
00937   llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
00938 
00939   auto *GV = new llvm::GlobalVariable(
00940       CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
00941       llvm::ConstantArray::get(ATy, UsedArray), Name);
00942 
00943   GV->setSection("llvm.metadata");
00944 }
00945 
00946 void CodeGenModule::emitLLVMUsed() {
00947   emitUsed(*this, "llvm.used", LLVMUsed);
00948   emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
00949 }
00950 
00951 void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
00952   llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
00953   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
00954 }
00955 
00956 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
00957   llvm::SmallString<32> Opt;
00958   getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
00959   llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
00960   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
00961 }
00962 
00963 void CodeGenModule::AddDependentLib(StringRef Lib) {
00964   llvm::SmallString<24> Opt;
00965   getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
00966   llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
00967   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
00968 }
00969 
00970 /// \brief Add link options implied by the given module, including modules
00971 /// it depends on, using a postorder walk.
00972 static void addLinkOptionsPostorder(CodeGenModule &CGM,
00973                                     Module *Mod,
00974                                     SmallVectorImpl<llvm::Value *> &Metadata,
00975                                     llvm::SmallPtrSet<Module *, 16> &Visited) {
00976   // Import this module's parent.
00977   if (Mod->Parent && Visited.insert(Mod->Parent)) {
00978     addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
00979   }
00980 
00981   // Import this module's dependencies.
00982   for (unsigned I = Mod->Imports.size(); I > 0; --I) {
00983     if (Visited.insert(Mod->Imports[I-1]))
00984       addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
00985   }
00986 
00987   // Add linker options to link against the libraries/frameworks
00988   // described by this module.
00989   llvm::LLVMContext &Context = CGM.getLLVMContext();
00990   for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
00991     // Link against a framework.  Frameworks are currently Darwin only, so we
00992     // don't to ask TargetCodeGenInfo for the spelling of the linker option.
00993     if (Mod->LinkLibraries[I-1].IsFramework) {
00994       llvm::Value *Args[2] = {
00995         llvm::MDString::get(Context, "-framework"),
00996         llvm::MDString::get(Context, Mod->LinkLibraries[I-1].Library)
00997       };
00998 
00999       Metadata.push_back(llvm::MDNode::get(Context, Args));
01000       continue;
01001     }
01002 
01003     // Link against a library.
01004     llvm::SmallString<24> Opt;
01005     CGM.getTargetCodeGenInfo().getDependentLibraryOption(
01006       Mod->LinkLibraries[I-1].Library, Opt);
01007     llvm::Value *OptString = llvm::MDString::get(Context, Opt);
01008     Metadata.push_back(llvm::MDNode::get(Context, OptString));
01009   }
01010 }
01011 
01012 void CodeGenModule::EmitModuleLinkOptions() {
01013   // Collect the set of all of the modules we want to visit to emit link
01014   // options, which is essentially the imported modules and all of their
01015   // non-explicit child modules.
01016   llvm::SetVector<clang::Module *> LinkModules;
01017   llvm::SmallPtrSet<clang::Module *, 16> Visited;
01018   SmallVector<clang::Module *, 16> Stack;
01019 
01020   // Seed the stack with imported modules.
01021   for (llvm::SetVector<clang::Module *>::iterator M = ImportedModules.begin(),
01022                                                MEnd = ImportedModules.end();
01023        M != MEnd; ++M) {
01024     if (Visited.insert(*M))
01025       Stack.push_back(*M);
01026   }
01027 
01028   // Find all of the modules to import, making a little effort to prune
01029   // non-leaf modules.
01030   while (!Stack.empty()) {
01031     clang::Module *Mod = Stack.pop_back_val();
01032 
01033     bool AnyChildren = false;
01034 
01035     // Visit the submodules of this module.
01036     for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
01037                                         SubEnd = Mod->submodule_end();
01038          Sub != SubEnd; ++Sub) {
01039       // Skip explicit children; they need to be explicitly imported to be
01040       // linked against.
01041       if ((*Sub)->IsExplicit)
01042         continue;
01043 
01044       if (Visited.insert(*Sub)) {
01045         Stack.push_back(*Sub);
01046         AnyChildren = true;
01047       }
01048     }
01049 
01050     // We didn't find any children, so add this module to the list of
01051     // modules to link against.
01052     if (!AnyChildren) {
01053       LinkModules.insert(Mod);
01054     }
01055   }
01056 
01057   // Add link options for all of the imported modules in reverse topological
01058   // order.  We don't do anything to try to order import link flags with respect
01059   // to linker options inserted by things like #pragma comment().
01060   SmallVector<llvm::Value *, 16> MetadataArgs;
01061   Visited.clear();
01062   for (llvm::SetVector<clang::Module *>::iterator M = LinkModules.begin(),
01063                                                MEnd = LinkModules.end();
01064        M != MEnd; ++M) {
01065     if (Visited.insert(*M))
01066       addLinkOptionsPostorder(*this, *M, MetadataArgs, Visited);
01067   }
01068   std::reverse(MetadataArgs.begin(), MetadataArgs.end());
01069   LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
01070 
01071   // Add the linker options metadata flag.
01072   getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
01073                             llvm::MDNode::get(getLLVMContext(),
01074                                               LinkerOptionsMetadata));
01075 }
01076 
01077 void CodeGenModule::EmitDeferred() {
01078   // Emit code for any potentially referenced deferred decls.  Since a
01079   // previously unused static decl may become used during the generation of code
01080   // for a static function, iterate until no changes are made.
01081 
01082   while (true) {
01083     if (!DeferredVTables.empty()) {
01084       EmitDeferredVTables();
01085 
01086       // Emitting a v-table doesn't directly cause more v-tables to
01087       // become deferred, although it can cause functions to be
01088       // emitted that then need those v-tables.
01089       assert(DeferredVTables.empty());
01090     }
01091 
01092     // Stop if we're out of both deferred v-tables and deferred declarations.
01093     if (DeferredDeclsToEmit.empty()) break;
01094 
01095     DeferredGlobal &G = DeferredDeclsToEmit.back();
01096     GlobalDecl D = G.GD;
01097     llvm::GlobalValue *GV = G.GV;
01098     DeferredDeclsToEmit.pop_back();
01099 
01100     assert(GV == GetGlobalValue(getMangledName(D)));
01101     // Check to see if we've already emitted this.  This is necessary
01102     // for a couple of reasons: first, decls can end up in the
01103     // deferred-decls queue multiple times, and second, decls can end
01104     // up with definitions in unusual ways (e.g. by an extern inline
01105     // function acquiring a strong function redefinition).  Just
01106     // ignore these cases.
01107     if(!GV->isDeclaration())
01108       continue;
01109 
01110     // Otherwise, emit the definition and move on to the next one.
01111     EmitGlobalDefinition(D, GV);
01112   }
01113 }
01114 
01115 void CodeGenModule::EmitGlobalAnnotations() {
01116   if (Annotations.empty())
01117     return;
01118 
01119   // Create a new global variable for the ConstantStruct in the Module.
01120   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
01121     Annotations[0]->getType(), Annotations.size()), Annotations);
01122   auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
01123                                       llvm::GlobalValue::AppendingLinkage,
01124                                       Array, "llvm.global.annotations");
01125   gv->setSection(AnnotationSection);
01126 }
01127 
01128 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
01129   llvm::Constant *&AStr = AnnotationStrings[Str];
01130   if (AStr)
01131     return AStr;
01132 
01133   // Not found yet, create a new global.
01134   llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
01135   auto *gv =
01136       new llvm::GlobalVariable(getModule(), s->getType(), true,
01137                                llvm::GlobalValue::PrivateLinkage, s, ".str");
01138   gv->setSection(AnnotationSection);
01139   gv->setUnnamedAddr(true);
01140   AStr = gv;
01141   return gv;
01142 }
01143 
01144 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
01145   SourceManager &SM = getContext().getSourceManager();
01146   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
01147   if (PLoc.isValid())
01148     return EmitAnnotationString(PLoc.getFilename());
01149   return EmitAnnotationString(SM.getBufferName(Loc));
01150 }
01151 
01152 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
01153   SourceManager &SM = getContext().getSourceManager();
01154   PresumedLoc PLoc = SM.getPresumedLoc(L);
01155   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
01156     SM.getExpansionLineNumber(L);
01157   return llvm::ConstantInt::get(Int32Ty, LineNo);
01158 }
01159 
01160 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
01161                                                 const AnnotateAttr *AA,
01162                                                 SourceLocation L) {
01163   // Get the globals for file name, annotation, and the line number.
01164   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
01165                  *UnitGV = EmitAnnotationUnit(L),
01166                  *LineNoCst = EmitAnnotationLineNo(L);
01167 
01168   // Create the ConstantStruct for the global annotation.
01169   llvm::Constant *Fields[4] = {
01170     llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
01171     llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
01172     llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
01173     LineNoCst
01174   };
01175   return llvm::ConstantStruct::getAnon(Fields);
01176 }
01177 
01178 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
01179                                          llvm::GlobalValue *GV) {
01180   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
01181   // Get the struct elements for these annotations.
01182   for (const auto *I : D->specific_attrs<AnnotateAttr>())
01183     Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
01184 }
01185 
01186 bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn,
01187                                            SourceLocation Loc) const {
01188   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
01189   // Blacklist by function name.
01190   if (SanitizerBL.isBlacklistedFunction(Fn->getName()))
01191     return true;
01192   // Blacklist by location.
01193   if (!Loc.isInvalid())
01194     return SanitizerBL.isBlacklistedLocation(Loc);
01195   // If location is unknown, this may be a compiler-generated function. Assume
01196   // it's located in the main file.
01197   auto &SM = Context.getSourceManager();
01198   if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
01199     return SanitizerBL.isBlacklistedFile(MainFile->getName());
01200   }
01201   return false;
01202 }
01203 
01204 bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
01205                                            SourceLocation Loc, QualType Ty,
01206                                            StringRef Category) const {
01207   // For now globals can be blacklisted only in ASan.
01208   if (!LangOpts.Sanitize.has(SanitizerKind::Address))
01209     return false;
01210   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
01211   if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category))
01212     return true;
01213   if (SanitizerBL.isBlacklistedLocation(Loc, Category))
01214     return true;
01215   // Check global type.
01216   if (!Ty.isNull()) {
01217     // Drill down the array types: if global variable of a fixed type is
01218     // blacklisted, we also don't instrument arrays of them.
01219     while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
01220       Ty = AT->getElementType();
01221     Ty = Ty.getCanonicalType().getUnqualifiedType();
01222     // We allow to blacklist only record types (classes, structs etc.)
01223     if (Ty->isRecordType()) {
01224       std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
01225       if (SanitizerBL.isBlacklistedType(TypeStr, Category))
01226         return true;
01227     }
01228   }
01229   return false;
01230 }
01231 
01232 bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
01233   // Never defer when EmitAllDecls is specified.
01234   if (LangOpts.EmitAllDecls)
01235     return false;
01236 
01237   return !getContext().DeclMustBeEmitted(Global);
01238 }
01239 
01240 llvm::Constant *CodeGenModule::GetAddrOfUuidDescriptor(
01241     const CXXUuidofExpr* E) {
01242   // Sema has verified that IIDSource has a __declspec(uuid()), and that its
01243   // well-formed.
01244   StringRef Uuid = E->getUuidAsStringRef(Context);
01245   std::string Name = "_GUID_" + Uuid.lower();
01246   std::replace(Name.begin(), Name.end(), '-', '_');
01247 
01248   // Look for an existing global.
01249   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
01250     return GV;
01251 
01252   llvm::Constant *Init = EmitUuidofInitializer(Uuid);
01253   assert(Init && "failed to initialize as constant");
01254 
01255   auto *GV = new llvm::GlobalVariable(
01256       getModule(), Init->getType(),
01257       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
01258   return GV;
01259 }
01260 
01261 llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
01262   const AliasAttr *AA = VD->getAttr<AliasAttr>();
01263   assert(AA && "No alias?");
01264 
01265   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
01266 
01267   // See if there is already something with the target's name in the module.
01268   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
01269   if (Entry) {
01270     unsigned AS = getContext().getTargetAddressSpace(VD->getType());
01271     return llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
01272   }
01273 
01274   llvm::Constant *Aliasee;
01275   if (isa<llvm::FunctionType>(DeclTy))
01276     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
01277                                       GlobalDecl(cast<FunctionDecl>(VD)),
01278                                       /*ForVTable=*/false);
01279   else
01280     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
01281                                     llvm::PointerType::getUnqual(DeclTy),
01282                                     nullptr);
01283 
01284   auto *F = cast<llvm::GlobalValue>(Aliasee);
01285   F->setLinkage(llvm::Function::ExternalWeakLinkage);
01286   WeakRefReferences.insert(F);
01287 
01288   return Aliasee;
01289 }
01290 
01291 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
01292   const auto *Global = cast<ValueDecl>(GD.getDecl());
01293 
01294   // Weak references don't produce any output by themselves.
01295   if (Global->hasAttr<WeakRefAttr>())
01296     return;
01297 
01298   // If this is an alias definition (which otherwise looks like a declaration)
01299   // emit it now.
01300   if (Global->hasAttr<AliasAttr>())
01301     return EmitAliasDefinition(GD);
01302 
01303   // If this is CUDA, be selective about which declarations we emit.
01304   if (LangOpts.CUDA) {
01305     if (CodeGenOpts.CUDAIsDevice) {
01306       if (!Global->hasAttr<CUDADeviceAttr>() &&
01307           !Global->hasAttr<CUDAGlobalAttr>() &&
01308           !Global->hasAttr<CUDAConstantAttr>() &&
01309           !Global->hasAttr<CUDASharedAttr>())
01310         return;
01311     } else {
01312       if (!Global->hasAttr<CUDAHostAttr>() && (
01313             Global->hasAttr<CUDADeviceAttr>() ||
01314             Global->hasAttr<CUDAConstantAttr>() ||
01315             Global->hasAttr<CUDASharedAttr>()))
01316         return;
01317     }
01318   }
01319 
01320   // Ignore declarations, they will be emitted on their first use.
01321   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
01322     // Forward declarations are emitted lazily on first use.
01323     if (!FD->doesThisDeclarationHaveABody()) {
01324       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
01325         return;
01326 
01327       StringRef MangledName = getMangledName(GD);
01328 
01329       // Compute the function info and LLVM type.
01330       const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
01331       llvm::Type *Ty = getTypes().GetFunctionType(FI);
01332 
01333       GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
01334                               /*DontDefer=*/false);
01335       return;
01336     }
01337   } else {
01338     const auto *VD = cast<VarDecl>(Global);
01339     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
01340 
01341     if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
01342         !Context.isMSStaticDataMemberInlineDefinition(VD))
01343       return;
01344   }
01345 
01346   // Defer code generation when possible if this is a static definition, inline
01347   // function etc.  These we only want to emit if they are used.
01348   if (!MayDeferGeneration(Global)) {
01349     // Emit the definition if it can't be deferred.
01350     EmitGlobalDefinition(GD);
01351     return;
01352   }
01353 
01354   // If we're deferring emission of a C++ variable with an
01355   // initializer, remember the order in which it appeared in the file.
01356   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
01357       cast<VarDecl>(Global)->hasInit()) {
01358     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
01359     CXXGlobalInits.push_back(nullptr);
01360   }
01361   
01362   // If the value has already been used, add it directly to the
01363   // DeferredDeclsToEmit list.
01364   StringRef MangledName = getMangledName(GD);
01365   if (llvm::GlobalValue *GV = GetGlobalValue(MangledName))
01366     addDeferredDeclToEmit(GV, GD);
01367   else {
01368     // Otherwise, remember that we saw a deferred decl with this name.  The
01369     // first use of the mangled name will cause it to move into
01370     // DeferredDeclsToEmit.
01371     DeferredDecls[MangledName] = GD;
01372   }
01373 }
01374 
01375 namespace {
01376   struct FunctionIsDirectlyRecursive :
01377     public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
01378     const StringRef Name;
01379     const Builtin::Context &BI;
01380     bool Result;
01381     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
01382       Name(N), BI(C), Result(false) {
01383     }
01384     typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
01385 
01386     bool TraverseCallExpr(CallExpr *E) {
01387       const FunctionDecl *FD = E->getDirectCallee();
01388       if (!FD)
01389         return true;
01390       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
01391       if (Attr && Name == Attr->getLabel()) {
01392         Result = true;
01393         return false;
01394       }
01395       unsigned BuiltinID = FD->getBuiltinID();
01396       if (!BuiltinID)
01397         return true;
01398       StringRef BuiltinName = BI.GetName(BuiltinID);
01399       if (BuiltinName.startswith("__builtin_") &&
01400           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
01401         Result = true;
01402         return false;
01403       }
01404       return true;
01405     }
01406   };
01407 }
01408 
01409 // isTriviallyRecursive - Check if this function calls another
01410 // decl that, because of the asm attribute or the other decl being a builtin,
01411 // ends up pointing to itself.
01412 bool
01413 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
01414   StringRef Name;
01415   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
01416     // asm labels are a special kind of mangling we have to support.
01417     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
01418     if (!Attr)
01419       return false;
01420     Name = Attr->getLabel();
01421   } else {
01422     Name = FD->getName();
01423   }
01424 
01425   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
01426   Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
01427   return Walker.Result;
01428 }
01429 
01430 bool
01431 CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
01432   if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
01433     return true;
01434   const auto *F = cast<FunctionDecl>(GD.getDecl());
01435   if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
01436     return false;
01437   // PR9614. Avoid cases where the source code is lying to us. An available
01438   // externally function should have an equivalent function somewhere else,
01439   // but a function that calls itself is clearly not equivalent to the real
01440   // implementation.
01441   // This happens in glibc's btowc and in some configure checks.
01442   return !isTriviallyRecursive(F);
01443 }
01444 
01445 /// If the type for the method's class was generated by
01446 /// CGDebugInfo::createContextChain(), the cache contains only a
01447 /// limited DIType without any declarations. Since EmitFunctionStart()
01448 /// needs to find the canonical declaration for each method, we need
01449 /// to construct the complete type prior to emitting the method.
01450 void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) {
01451   if (!D->isInstance())
01452     return;
01453 
01454   if (CGDebugInfo *DI = getModuleDebugInfo())
01455     if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
01456       const auto *ThisPtr = cast<PointerType>(D->getThisType(getContext()));
01457       DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation());
01458     }
01459 }
01460 
01461 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
01462   const auto *D = cast<ValueDecl>(GD.getDecl());
01463 
01464   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 
01465                                  Context.getSourceManager(),
01466                                  "Generating code for declaration");
01467   
01468   if (isa<FunctionDecl>(D)) {
01469     // At -O0, don't generate IR for functions with available_externally 
01470     // linkage.
01471     if (!shouldEmitFunction(GD))
01472       return;
01473 
01474     if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
01475       CompleteDIClassType(Method);
01476       // Make sure to emit the definition(s) before we emit the thunks.
01477       // This is necessary for the generation of certain thunks.
01478       if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
01479         ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
01480       else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
01481         ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
01482       else
01483         EmitGlobalFunctionDefinition(GD, GV);
01484 
01485       if (Method->isVirtual())
01486         getVTables().EmitThunks(GD);
01487 
01488       return;
01489     }
01490 
01491     return EmitGlobalFunctionDefinition(GD, GV);
01492   }
01493 
01494   if (const auto *VD = dyn_cast<VarDecl>(D))
01495     return EmitGlobalVarDefinition(VD);
01496   
01497   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
01498 }
01499 
01500 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
01501 /// module, create and return an llvm Function with the specified type. If there
01502 /// is something in the module with the specified name, return it potentially
01503 /// bitcasted to the right type.
01504 ///
01505 /// If D is non-null, it specifies a decl that correspond to this.  This is used
01506 /// to set the attributes on the function when it is first created.
01507 llvm::Constant *
01508 CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
01509                                        llvm::Type *Ty,
01510                                        GlobalDecl GD, bool ForVTable,
01511                                        bool DontDefer, bool IsThunk,
01512                                        llvm::AttributeSet ExtraAttrs) {
01513   const Decl *D = GD.getDecl();
01514 
01515   // Lookup the entry, lazily creating it if necessary.
01516   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
01517   if (Entry) {
01518     if (WeakRefReferences.erase(Entry)) {
01519       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
01520       if (FD && !FD->hasAttr<WeakAttr>())
01521         Entry->setLinkage(llvm::Function::ExternalLinkage);
01522     }
01523 
01524     // Handle dropped DLL attributes.
01525     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
01526       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
01527 
01528     if (Entry->getType()->getElementType() == Ty)
01529       return Entry;
01530 
01531     // Make sure the result is of the correct type.
01532     return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
01533   }
01534 
01535   // This function doesn't have a complete type (for example, the return
01536   // type is an incomplete struct). Use a fake type instead, and make
01537   // sure not to try to set attributes.
01538   bool IsIncompleteFunction = false;
01539 
01540   llvm::FunctionType *FTy;
01541   if (isa<llvm::FunctionType>(Ty)) {
01542     FTy = cast<llvm::FunctionType>(Ty);
01543   } else {
01544     FTy = llvm::FunctionType::get(VoidTy, false);
01545     IsIncompleteFunction = true;
01546   }
01547   
01548   llvm::Function *F = llvm::Function::Create(FTy,
01549                                              llvm::Function::ExternalLinkage,
01550                                              MangledName, &getModule());
01551   assert(F->getName() == MangledName && "name was uniqued!");
01552   if (D)
01553     SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
01554   if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) {
01555     llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex);
01556     F->addAttributes(llvm::AttributeSet::FunctionIndex,
01557                      llvm::AttributeSet::get(VMContext,
01558                                              llvm::AttributeSet::FunctionIndex,
01559                                              B));
01560   }
01561 
01562   if (!DontDefer) {
01563     // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
01564     // each other bottoming out with the base dtor.  Therefore we emit non-base
01565     // dtors on usage, even if there is no dtor definition in the TU.
01566     if (D && isa<CXXDestructorDecl>(D) &&
01567         getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
01568                                            GD.getDtorType()))
01569       addDeferredDeclToEmit(F, GD);
01570 
01571     // This is the first use or definition of a mangled name.  If there is a
01572     // deferred decl with this name, remember that we need to emit it at the end
01573     // of the file.
01574     auto DDI = DeferredDecls.find(MangledName);
01575     if (DDI != DeferredDecls.end()) {
01576       // Move the potentially referenced deferred decl to the
01577       // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
01578       // don't need it anymore).
01579       addDeferredDeclToEmit(F, DDI->second);
01580       DeferredDecls.erase(DDI);
01581 
01582       // Otherwise, if this is a sized deallocation function, emit a weak
01583       // definition
01584       // for it at the end of the translation unit.
01585     } else if (D && cast<FunctionDecl>(D)
01586                         ->getCorrespondingUnsizedGlobalDeallocationFunction()) {
01587       addDeferredDeclToEmit(F, GD);
01588 
01589       // Otherwise, there are cases we have to worry about where we're
01590       // using a declaration for which we must emit a definition but where
01591       // we might not find a top-level definition:
01592       //   - member functions defined inline in their classes
01593       //   - friend functions defined inline in some class
01594       //   - special member functions with implicit definitions
01595       // If we ever change our AST traversal to walk into class methods,
01596       // this will be unnecessary.
01597       //
01598       // We also don't emit a definition for a function if it's going to be an
01599       // entry in a vtable, unless it's already marked as used.
01600     } else if (getLangOpts().CPlusPlus && D) {
01601       // Look for a declaration that's lexically in a record.
01602       for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
01603            FD = FD->getPreviousDecl()) {
01604         if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
01605           if (FD->doesThisDeclarationHaveABody()) {
01606             addDeferredDeclToEmit(F, GD.getWithDecl(FD));
01607             break;
01608           }
01609         }
01610       }
01611     }
01612   }
01613 
01614   // Make sure the result is of the requested type.
01615   if (!IsIncompleteFunction) {
01616     assert(F->getType()->getElementType() == Ty);
01617     return F;
01618   }
01619 
01620   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
01621   return llvm::ConstantExpr::getBitCast(F, PTy);
01622 }
01623 
01624 /// GetAddrOfFunction - Return the address of the given function.  If Ty is
01625 /// non-null, then this function will use the specified type if it has to
01626 /// create it (this occurs when we see a definition of the function).
01627 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
01628                                                  llvm::Type *Ty,
01629                                                  bool ForVTable,
01630                                                  bool DontDefer) {
01631   // If there was no specific requested type, just convert it now.
01632   if (!Ty)
01633     Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
01634   
01635   StringRef MangledName = getMangledName(GD);
01636   return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer);
01637 }
01638 
01639 /// CreateRuntimeFunction - Create a new runtime function with the specified
01640 /// type and name.
01641 llvm::Constant *
01642 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
01643                                      StringRef Name,
01644                                      llvm::AttributeSet ExtraAttrs) {
01645   llvm::Constant *C =
01646       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
01647                               /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
01648   if (auto *F = dyn_cast<llvm::Function>(C))
01649     if (F->empty())
01650       F->setCallingConv(getRuntimeCC());
01651   return C;
01652 }
01653 
01654 /// isTypeConstant - Determine whether an object of this type can be emitted
01655 /// as a constant.
01656 ///
01657 /// If ExcludeCtor is true, the duration when the object's constructor runs
01658 /// will not be considered. The caller will need to verify that the object is
01659 /// not written to during its construction.
01660 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
01661   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
01662     return false;
01663 
01664   if (Context.getLangOpts().CPlusPlus) {
01665     if (const CXXRecordDecl *Record
01666           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
01667       return ExcludeCtor && !Record->hasMutableFields() &&
01668              Record->hasTrivialDestructor();
01669   }
01670 
01671   return true;
01672 }
01673 
01674 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
01675 /// create and return an llvm GlobalVariable with the specified type.  If there
01676 /// is something in the module with the specified name, return it potentially
01677 /// bitcasted to the right type.
01678 ///
01679 /// If D is non-null, it specifies a decl that correspond to this.  This is used
01680 /// to set the attributes on the global when it is first created.
01681 llvm::Constant *
01682 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
01683                                      llvm::PointerType *Ty,
01684                                      const VarDecl *D) {
01685   // Lookup the entry, lazily creating it if necessary.
01686   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
01687   if (Entry) {
01688     if (WeakRefReferences.erase(Entry)) {
01689       if (D && !D->hasAttr<WeakAttr>())
01690         Entry->setLinkage(llvm::Function::ExternalLinkage);
01691     }
01692 
01693     // Handle dropped DLL attributes.
01694     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
01695       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
01696 
01697     if (Entry->getType() == Ty)
01698       return Entry;
01699 
01700     // Make sure the result is of the correct type.
01701     if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
01702       return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
01703 
01704     return llvm::ConstantExpr::getBitCast(Entry, Ty);
01705   }
01706 
01707   unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
01708   auto *GV = new llvm::GlobalVariable(
01709       getModule(), Ty->getElementType(), false,
01710       llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
01711       llvm::GlobalVariable::NotThreadLocal, AddrSpace);
01712 
01713   // This is the first use or definition of a mangled name.  If there is a
01714   // deferred decl with this name, remember that we need to emit it at the end
01715   // of the file.
01716   auto DDI = DeferredDecls.find(MangledName);
01717   if (DDI != DeferredDecls.end()) {
01718     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
01719     // list, and remove it from DeferredDecls (since we don't need it anymore).
01720     addDeferredDeclToEmit(GV, DDI->second);
01721     DeferredDecls.erase(DDI);
01722   }
01723 
01724   // Handle things which are present even on external declarations.
01725   if (D) {
01726     // FIXME: This code is overly simple and should be merged with other global
01727     // handling.
01728     GV->setConstant(isTypeConstant(D->getType(), false));
01729 
01730     setLinkageAndVisibilityForGV(GV, D);
01731 
01732     if (D->getTLSKind()) {
01733       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
01734         CXXThreadLocals.push_back(std::make_pair(D, GV));
01735       setTLSMode(GV, *D);
01736     }
01737 
01738     // If required by the ABI, treat declarations of static data members with
01739     // inline initializers as definitions.
01740     if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
01741       EmitGlobalVarDefinition(D);
01742     }
01743 
01744     // Handle XCore specific ABI requirements.
01745     if (getTarget().getTriple().getArch() == llvm::Triple::xcore &&
01746         D->getLanguageLinkage() == CLanguageLinkage &&
01747         D->getType().isConstant(Context) &&
01748         isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
01749       GV->setSection(".cp.rodata");
01750   }
01751 
01752   if (AddrSpace != Ty->getAddressSpace())
01753     return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
01754 
01755   return GV;
01756 }
01757 
01758 
01759 llvm::GlobalVariable *
01760 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name, 
01761                                       llvm::Type *Ty,
01762                                       llvm::GlobalValue::LinkageTypes Linkage) {
01763   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
01764   llvm::GlobalVariable *OldGV = nullptr;
01765 
01766   if (GV) {
01767     // Check if the variable has the right type.
01768     if (GV->getType()->getElementType() == Ty)
01769       return GV;
01770 
01771     // Because C++ name mangling, the only way we can end up with an already
01772     // existing global with the same name is if it has been declared extern "C".
01773     assert(GV->isDeclaration() && "Declaration has wrong type!");
01774     OldGV = GV;
01775   }
01776   
01777   // Create a new variable.
01778   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
01779                                 Linkage, nullptr, Name);
01780 
01781   if (OldGV) {
01782     // Replace occurrences of the old variable if needed.
01783     GV->takeName(OldGV);
01784     
01785     if (!OldGV->use_empty()) {
01786       llvm::Constant *NewPtrForOldDecl =
01787       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
01788       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
01789     }
01790     
01791     OldGV->eraseFromParent();
01792   }
01793   
01794   return GV;
01795 }
01796 
01797 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
01798 /// given global variable.  If Ty is non-null and if the global doesn't exist,
01799 /// then it will be created with the specified type instead of whatever the
01800 /// normal requested type would be.
01801 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
01802                                                   llvm::Type *Ty) {
01803   assert(D->hasGlobalStorage() && "Not a global variable");
01804   QualType ASTTy = D->getType();
01805   if (!Ty)
01806     Ty = getTypes().ConvertTypeForMem(ASTTy);
01807 
01808   llvm::PointerType *PTy =
01809     llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
01810 
01811   StringRef MangledName = getMangledName(D);
01812   return GetOrCreateLLVMGlobal(MangledName, PTy, D);
01813 }
01814 
01815 /// CreateRuntimeVariable - Create a new runtime global variable with the
01816 /// specified type and name.
01817 llvm::Constant *
01818 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
01819                                      StringRef Name) {
01820   return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
01821 }
01822 
01823 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
01824   assert(!D->getInit() && "Cannot emit definite definitions here!");
01825 
01826   if (MayDeferGeneration(D)) {
01827     // If we have not seen a reference to this variable yet, place it
01828     // into the deferred declarations table to be emitted if needed
01829     // later.
01830     StringRef MangledName = getMangledName(D);
01831     if (!GetGlobalValue(MangledName)) {
01832       DeferredDecls[MangledName] = D;
01833       return;
01834     }
01835   }
01836 
01837   // The tentative definition is the only definition.
01838   EmitGlobalVarDefinition(D);
01839 }
01840 
01841 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
01842     return Context.toCharUnitsFromBits(
01843       TheDataLayout.getTypeStoreSizeInBits(Ty));
01844 }
01845 
01846 unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
01847                                                  unsigned AddrSpace) {
01848   if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) {
01849     if (D->hasAttr<CUDAConstantAttr>())
01850       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
01851     else if (D->hasAttr<CUDASharedAttr>())
01852       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
01853     else
01854       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
01855   }
01856 
01857   return AddrSpace;
01858 }
01859 
01860 template<typename SomeDecl>
01861 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
01862                                                llvm::GlobalValue *GV) {
01863   if (!getLangOpts().CPlusPlus)
01864     return;
01865 
01866   // Must have 'used' attribute, or else inline assembly can't rely on
01867   // the name existing.
01868   if (!D->template hasAttr<UsedAttr>())
01869     return;
01870 
01871   // Must have internal linkage and an ordinary name.
01872   if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
01873     return;
01874 
01875   // Must be in an extern "C" context. Entities declared directly within
01876   // a record are not extern "C" even if the record is in such a context.
01877   const SomeDecl *First = D->getFirstDecl();
01878   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
01879     return;
01880 
01881   // OK, this is an internal linkage entity inside an extern "C" linkage
01882   // specification. Make a note of that so we can give it the "expected"
01883   // mangled name if nothing else is using that name.
01884   std::pair<StaticExternCMap::iterator, bool> R =
01885       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
01886 
01887   // If we have multiple internal linkage entities with the same name
01888   // in extern "C" regions, none of them gets that name.
01889   if (!R.second)
01890     R.first->second = nullptr;
01891 }
01892 
01893 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
01894   llvm::Constant *Init = nullptr;
01895   QualType ASTTy = D->getType();
01896   CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
01897   bool NeedsGlobalCtor = false;
01898   bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
01899 
01900   const VarDecl *InitDecl;
01901   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
01902 
01903   if (!InitExpr) {
01904     // This is a tentative definition; tentative definitions are
01905     // implicitly initialized with { 0 }.
01906     //
01907     // Note that tentative definitions are only emitted at the end of
01908     // a translation unit, so they should never have incomplete
01909     // type. In addition, EmitTentativeDefinition makes sure that we
01910     // never attempt to emit a tentative definition if a real one
01911     // exists. A use may still exists, however, so we still may need
01912     // to do a RAUW.
01913     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
01914     Init = EmitNullConstant(D->getType());
01915   } else {
01916     initializedGlobalDecl = GlobalDecl(D);
01917     Init = EmitConstantInit(*InitDecl);
01918 
01919     if (!Init) {
01920       QualType T = InitExpr->getType();
01921       if (D->getType()->isReferenceType())
01922         T = D->getType();
01923 
01924       if (getLangOpts().CPlusPlus) {
01925         Init = EmitNullConstant(T);
01926         NeedsGlobalCtor = true;
01927       } else {
01928         ErrorUnsupported(D, "static initializer");
01929         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
01930       }
01931     } else {
01932       // We don't need an initializer, so remove the entry for the delayed
01933       // initializer position (just in case this entry was delayed) if we
01934       // also don't need to register a destructor.
01935       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
01936         DelayedCXXInitPosition.erase(D);
01937     }
01938   }
01939 
01940   llvm::Type* InitType = Init->getType();
01941   llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
01942 
01943   // Strip off a bitcast if we got one back.
01944   if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
01945     assert(CE->getOpcode() == llvm::Instruction::BitCast ||
01946            CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
01947            // All zero index gep.
01948            CE->getOpcode() == llvm::Instruction::GetElementPtr);
01949     Entry = CE->getOperand(0);
01950   }
01951 
01952   // Entry is now either a Function or GlobalVariable.
01953   auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
01954 
01955   // We have a definition after a declaration with the wrong type.
01956   // We must make a new GlobalVariable* and update everything that used OldGV
01957   // (a declaration or tentative definition) with the new GlobalVariable*
01958   // (which will be a definition).
01959   //
01960   // This happens if there is a prototype for a global (e.g.
01961   // "extern int x[];") and then a definition of a different type (e.g.
01962   // "int x[10];"). This also happens when an initializer has a different type
01963   // from the type of the global (this happens with unions).
01964   if (!GV ||
01965       GV->getType()->getElementType() != InitType ||
01966       GV->getType()->getAddressSpace() !=
01967        GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
01968 
01969     // Move the old entry aside so that we'll create a new one.
01970     Entry->setName(StringRef());
01971 
01972     // Make a new global with the correct type, this is now guaranteed to work.
01973     GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
01974 
01975     // Replace all uses of the old global with the new global
01976     llvm::Constant *NewPtrForOldDecl =
01977         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
01978     Entry->replaceAllUsesWith(NewPtrForOldDecl);
01979 
01980     // Erase the old global, since it is no longer used.
01981     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
01982   }
01983 
01984   MaybeHandleStaticInExternC(D, GV);
01985 
01986   if (D->hasAttr<AnnotateAttr>())
01987     AddGlobalAnnotations(D, GV);
01988 
01989   GV->setInitializer(Init);
01990 
01991   // If it is safe to mark the global 'constant', do so now.
01992   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
01993                   isTypeConstant(D->getType(), true));
01994 
01995   // If it is in a read-only section, mark it 'constant'.
01996   if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
01997     const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
01998     if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
01999       GV->setConstant(true);
02000   }
02001 
02002   GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
02003 
02004   // Set the llvm linkage type as appropriate.
02005   llvm::GlobalValue::LinkageTypes Linkage =
02006       getLLVMLinkageVarDefinition(D, GV->isConstant());
02007 
02008   // On Darwin, the backing variable for a C++11 thread_local variable always
02009   // has internal linkage; all accesses should just be calls to the
02010   // Itanium-specified entry point, which has the normal linkage of the
02011   // variable.
02012   if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
02013       Context.getTargetInfo().getTriple().isMacOSX())
02014     Linkage = llvm::GlobalValue::InternalLinkage;
02015 
02016   GV->setLinkage(Linkage);
02017   if (D->hasAttr<DLLImportAttr>())
02018     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
02019   else if (D->hasAttr<DLLExportAttr>())
02020     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
02021   else
02022     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
02023 
02024   if (Linkage == llvm::GlobalVariable::CommonLinkage)
02025     // common vars aren't constant even if declared const.
02026     GV->setConstant(false);
02027 
02028   setNonAliasAttributes(D, GV);
02029 
02030   if (D->getTLSKind() && !GV->isThreadLocal()) {
02031     if (D->getTLSKind() == VarDecl::TLS_Dynamic)
02032       CXXThreadLocals.push_back(std::make_pair(D, GV));
02033     setTLSMode(GV, *D);
02034   }
02035 
02036   // Emit the initializer function if necessary.
02037   if (NeedsGlobalCtor || NeedsGlobalDtor)
02038     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
02039 
02040   SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
02041 
02042   // Emit global variable debug information.
02043   if (CGDebugInfo *DI = getModuleDebugInfo())
02044     if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
02045       DI->EmitGlobalVariable(GV, D);
02046 }
02047 
02048 static bool isVarDeclStrongDefinition(const ASTContext &Context,
02049                                       const VarDecl *D, bool NoCommon) {
02050   // Don't give variables common linkage if -fno-common was specified unless it
02051   // was overridden by a NoCommon attribute.
02052   if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
02053     return true;
02054 
02055   // C11 6.9.2/2:
02056   //   A declaration of an identifier for an object that has file scope without
02057   //   an initializer, and without a storage-class specifier or with the
02058   //   storage-class specifier static, constitutes a tentative definition.
02059   if (D->getInit() || D->hasExternalStorage())
02060     return true;
02061 
02062   // A variable cannot be both common and exist in a section.
02063   if (D->hasAttr<SectionAttr>())
02064     return true;
02065 
02066   // Thread local vars aren't considered common linkage.
02067   if (D->getTLSKind())
02068     return true;
02069 
02070   // Tentative definitions marked with WeakImportAttr are true definitions.
02071   if (D->hasAttr<WeakImportAttr>())
02072     return true;
02073 
02074   // Declarations with a required alignment do not have common linakge in MSVC
02075   // mode.
02076   if (Context.getLangOpts().MSVCCompat &&
02077       (Context.isAlignmentRequired(D->getType()) || D->hasAttr<AlignedAttr>()))
02078     return true;
02079 
02080   return false;
02081 }
02082 
02083 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
02084     const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
02085   if (Linkage == GVA_Internal)
02086     return llvm::Function::InternalLinkage;
02087 
02088   if (D->hasAttr<WeakAttr>()) {
02089     if (IsConstantVariable)
02090       return llvm::GlobalVariable::WeakODRLinkage;
02091     else
02092       return llvm::GlobalVariable::WeakAnyLinkage;
02093   }
02094 
02095   // We are guaranteed to have a strong definition somewhere else,
02096   // so we can use available_externally linkage.
02097   if (Linkage == GVA_AvailableExternally)
02098     return llvm::Function::AvailableExternallyLinkage;
02099 
02100   // Note that Apple's kernel linker doesn't support symbol
02101   // coalescing, so we need to avoid linkonce and weak linkages there.
02102   // Normally, this means we just map to internal, but for explicit
02103   // instantiations we'll map to external.
02104 
02105   // In C++, the compiler has to emit a definition in every translation unit
02106   // that references the function.  We should use linkonce_odr because
02107   // a) if all references in this translation unit are optimized away, we
02108   // don't need to codegen it.  b) if the function persists, it needs to be
02109   // merged with other definitions. c) C++ has the ODR, so we know the
02110   // definition is dependable.
02111   if (Linkage == GVA_DiscardableODR)
02112     return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
02113                                             : llvm::Function::InternalLinkage;
02114 
02115   // An explicit instantiation of a template has weak linkage, since
02116   // explicit instantiations can occur in multiple translation units
02117   // and must all be equivalent. However, we are not allowed to
02118   // throw away these explicit instantiations.
02119   if (Linkage == GVA_StrongODR)
02120     return !Context.getLangOpts().AppleKext ? llvm::Function::WeakODRLinkage
02121                                             : llvm::Function::ExternalLinkage;
02122 
02123   // C++ doesn't have tentative definitions and thus cannot have common
02124   // linkage.
02125   if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
02126       !isVarDeclStrongDefinition(Context, cast<VarDecl>(D),
02127                                  CodeGenOpts.NoCommon))
02128     return llvm::GlobalVariable::CommonLinkage;
02129 
02130   // selectany symbols are externally visible, so use weak instead of
02131   // linkonce.  MSVC optimizes away references to const selectany globals, so
02132   // all definitions should be the same and ODR linkage should be used.
02133   // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
02134   if (D->hasAttr<SelectAnyAttr>())
02135     return llvm::GlobalVariable::WeakODRLinkage;
02136 
02137   // Otherwise, we have strong external linkage.
02138   assert(Linkage == GVA_StrongExternal);
02139   return llvm::GlobalVariable::ExternalLinkage;
02140 }
02141 
02142 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
02143     const VarDecl *VD, bool IsConstant) {
02144   GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
02145   return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
02146 }
02147 
02148 /// Replace the uses of a function that was declared with a non-proto type.
02149 /// We want to silently drop extra arguments from call sites
02150 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
02151                                           llvm::Function *newFn) {
02152   // Fast path.
02153   if (old->use_empty()) return;
02154 
02155   llvm::Type *newRetTy = newFn->getReturnType();
02156   SmallVector<llvm::Value*, 4> newArgs;
02157 
02158   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
02159          ui != ue; ) {
02160     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
02161     llvm::User *user = use->getUser();
02162 
02163     // Recognize and replace uses of bitcasts.  Most calls to
02164     // unprototyped functions will use bitcasts.
02165     if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
02166       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
02167         replaceUsesOfNonProtoConstant(bitcast, newFn);
02168       continue;
02169     }
02170 
02171     // Recognize calls to the function.
02172     llvm::CallSite callSite(user);
02173     if (!callSite) continue;
02174     if (!callSite.isCallee(&*use)) continue;
02175 
02176     // If the return types don't match exactly, then we can't
02177     // transform this call unless it's dead.
02178     if (callSite->getType() != newRetTy && !callSite->use_empty())
02179       continue;
02180 
02181     // Get the call site's attribute list.
02182     SmallVector<llvm::AttributeSet, 8> newAttrs;
02183     llvm::AttributeSet oldAttrs = callSite.getAttributes();
02184 
02185     // Collect any return attributes from the call.
02186     if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
02187       newAttrs.push_back(
02188         llvm::AttributeSet::get(newFn->getContext(),
02189                                 oldAttrs.getRetAttributes()));
02190 
02191     // If the function was passed too few arguments, don't transform.
02192     unsigned newNumArgs = newFn->arg_size();
02193     if (callSite.arg_size() < newNumArgs) continue;
02194 
02195     // If extra arguments were passed, we silently drop them.
02196     // If any of the types mismatch, we don't transform.
02197     unsigned argNo = 0;
02198     bool dontTransform = false;
02199     for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
02200            ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
02201       if (callSite.getArgument(argNo)->getType() != ai->getType()) {
02202         dontTransform = true;
02203         break;
02204       }
02205 
02206       // Add any parameter attributes.
02207       if (oldAttrs.hasAttributes(argNo + 1))
02208         newAttrs.
02209           push_back(llvm::
02210                     AttributeSet::get(newFn->getContext(),
02211                                       oldAttrs.getParamAttributes(argNo + 1)));
02212     }
02213     if (dontTransform)
02214       continue;
02215 
02216     if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
02217       newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
02218                                                  oldAttrs.getFnAttributes()));
02219 
02220     // Okay, we can transform this.  Create the new call instruction and copy
02221     // over the required information.
02222     newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
02223 
02224     llvm::CallSite newCall;
02225     if (callSite.isCall()) {
02226       newCall = llvm::CallInst::Create(newFn, newArgs, "",
02227                                        callSite.getInstruction());
02228     } else {
02229       auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
02230       newCall = llvm::InvokeInst::Create(newFn,
02231                                          oldInvoke->getNormalDest(),
02232                                          oldInvoke->getUnwindDest(),
02233                                          newArgs, "",
02234                                          callSite.getInstruction());
02235     }
02236     newArgs.clear(); // for the next iteration
02237 
02238     if (!newCall->getType()->isVoidTy())
02239       newCall->takeName(callSite.getInstruction());
02240     newCall.setAttributes(
02241                      llvm::AttributeSet::get(newFn->getContext(), newAttrs));
02242     newCall.setCallingConv(callSite.getCallingConv());
02243 
02244     // Finally, remove the old call, replacing any uses with the new one.
02245     if (!callSite->use_empty())
02246       callSite->replaceAllUsesWith(newCall.getInstruction());
02247 
02248     // Copy debug location attached to CI.
02249     if (!callSite->getDebugLoc().isUnknown())
02250       newCall->setDebugLoc(callSite->getDebugLoc());
02251     callSite->eraseFromParent();
02252   }
02253 }
02254 
02255 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
02256 /// implement a function with no prototype, e.g. "int foo() {}".  If there are
02257 /// existing call uses of the old function in the module, this adjusts them to
02258 /// call the new function directly.
02259 ///
02260 /// This is not just a cleanup: the always_inline pass requires direct calls to
02261 /// functions to be able to inline them.  If there is a bitcast in the way, it
02262 /// won't inline them.  Instcombine normally deletes these calls, but it isn't
02263 /// run at -O0.
02264 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
02265                                                       llvm::Function *NewFn) {
02266   // If we're redefining a global as a function, don't transform it.
02267   if (!isa<llvm::Function>(Old)) return;
02268 
02269   replaceUsesOfNonProtoConstant(Old, NewFn);
02270 }
02271 
02272 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
02273   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
02274   // If we have a definition, this might be a deferred decl. If the
02275   // instantiation is explicit, make sure we emit it at the end.
02276   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
02277     GetAddrOfGlobalVar(VD);
02278 
02279   EmitTopLevelDecl(VD);
02280 }
02281 
02282 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
02283                                                  llvm::GlobalValue *GV) {
02284   const auto *D = cast<FunctionDecl>(GD.getDecl());
02285 
02286   // Compute the function info and LLVM type.
02287   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
02288   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
02289 
02290   // Get or create the prototype for the function.
02291   if (!GV) {
02292     llvm::Constant *C =
02293         GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer*/ true);
02294 
02295     // Strip off a bitcast if we got one back.
02296     if (auto *CE = dyn_cast<llvm::ConstantExpr>(C)) {
02297       assert(CE->getOpcode() == llvm::Instruction::BitCast);
02298       GV = cast<llvm::GlobalValue>(CE->getOperand(0));
02299     } else {
02300       GV = cast<llvm::GlobalValue>(C);
02301     }
02302   }
02303 
02304   if (!GV->isDeclaration()) {
02305     getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name);
02306     GlobalDecl OldGD = Manglings.lookup(GV->getName());
02307     if (auto *Prev = OldGD.getDecl())
02308       getDiags().Report(Prev->getLocation(), diag::note_previous_definition);
02309     return;
02310   }
02311 
02312   if (GV->getType()->getElementType() != Ty) {
02313     // If the types mismatch then we have to rewrite the definition.
02314     assert(GV->isDeclaration() && "Shouldn't replace non-declaration");
02315 
02316     // F is the Function* for the one with the wrong type, we must make a new
02317     // Function* and update everything that used F (a declaration) with the new
02318     // Function* (which will be a definition).
02319     //
02320     // This happens if there is a prototype for a function
02321     // (e.g. "int f()") and then a definition of a different type
02322     // (e.g. "int f(int x)").  Move the old function aside so that it
02323     // doesn't interfere with GetAddrOfFunction.
02324     GV->setName(StringRef());
02325     auto *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
02326 
02327     // This might be an implementation of a function without a
02328     // prototype, in which case, try to do special replacement of
02329     // calls which match the new prototype.  The really key thing here
02330     // is that we also potentially drop arguments from the call site
02331     // so as to make a direct call, which makes the inliner happier
02332     // and suppresses a number of optimizer warnings (!) about
02333     // dropping arguments.
02334     if (!GV->use_empty()) {
02335       ReplaceUsesOfNonProtoTypeWithRealFunction(GV, NewFn);
02336       GV->removeDeadConstantUsers();
02337     }
02338 
02339     // Replace uses of F with the Function we will endow with a body.
02340     if (!GV->use_empty()) {
02341       llvm::Constant *NewPtrForOldDecl =
02342           llvm::ConstantExpr::getBitCast(NewFn, GV->getType());
02343       GV->replaceAllUsesWith(NewPtrForOldDecl);
02344     }
02345 
02346     // Ok, delete the old function now, which is dead.
02347     GV->eraseFromParent();
02348 
02349     GV = NewFn;
02350   }
02351 
02352   // We need to set linkage and visibility on the function before
02353   // generating code for it because various parts of IR generation
02354   // want to propagate this information down (e.g. to local static
02355   // declarations).
02356   auto *Fn = cast<llvm::Function>(GV);
02357   setFunctionLinkage(GD, Fn);
02358   if (D->hasAttr<DLLImportAttr>())
02359     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
02360   else if (D->hasAttr<DLLExportAttr>())
02361     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
02362   else
02363     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
02364 
02365   // FIXME: this is redundant with part of setFunctionDefinitionAttributes
02366   setGlobalVisibility(Fn, D);
02367 
02368   MaybeHandleStaticInExternC(D, Fn);
02369 
02370   CodeGenFunction(*this).GenerateCode(D, Fn, FI);
02371 
02372   setFunctionDefinitionAttributes(D, Fn);
02373   SetLLVMFunctionAttributesForDefinition(D, Fn);
02374 
02375   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
02376     AddGlobalCtor(Fn, CA->getPriority());
02377   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
02378     AddGlobalDtor(Fn, DA->getPriority());
02379   if (D->hasAttr<AnnotateAttr>())
02380     AddGlobalAnnotations(D, Fn);
02381 }
02382 
02383 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
02384   const auto *D = cast<ValueDecl>(GD.getDecl());
02385   const AliasAttr *AA = D->getAttr<AliasAttr>();
02386   assert(AA && "Not an alias?");
02387 
02388   StringRef MangledName = getMangledName(GD);
02389 
02390   // If there is a definition in the module, then it wins over the alias.
02391   // This is dubious, but allow it to be safe.  Just ignore the alias.
02392   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
02393   if (Entry && !Entry->isDeclaration())
02394     return;
02395 
02396   Aliases.push_back(GD);
02397 
02398   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
02399 
02400   // Create a reference to the named value.  This ensures that it is emitted
02401   // if a deferred decl.
02402   llvm::Constant *Aliasee;
02403   if (isa<llvm::FunctionType>(DeclTy))
02404     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
02405                                       /*ForVTable=*/false);
02406   else
02407     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
02408                                     llvm::PointerType::getUnqual(DeclTy),
02409                                     /*D=*/nullptr);
02410 
02411   // Create the new alias itself, but don't set a name yet.
02412   auto *GA = llvm::GlobalAlias::create(
02413       cast<llvm::PointerType>(Aliasee->getType())->getElementType(), 0,
02414       llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
02415 
02416   if (Entry) {
02417     if (GA->getAliasee() == Entry) {
02418       Diags.Report(AA->getLocation(), diag::err_cyclic_alias);
02419       return;
02420     }
02421 
02422     assert(Entry->isDeclaration());
02423 
02424     // If there is a declaration in the module, then we had an extern followed
02425     // by the alias, as in:
02426     //   extern int test6();
02427     //   ...
02428     //   int test6() __attribute__((alias("test7")));
02429     //
02430     // Remove it and replace uses of it with the alias.
02431     GA->takeName(Entry);
02432 
02433     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
02434                                                           Entry->getType()));
02435     Entry->eraseFromParent();
02436   } else {
02437     GA->setName(MangledName);
02438   }
02439 
02440   // Set attributes which are particular to an alias; this is a
02441   // specialization of the attributes which may be set on a global
02442   // variable/function.
02443   if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
02444       D->isWeakImported()) {
02445     GA->setLinkage(llvm::Function::WeakAnyLinkage);
02446   }
02447 
02448   if (const auto *VD = dyn_cast<VarDecl>(D))
02449     if (VD->getTLSKind())
02450       setTLSMode(GA, *VD);
02451 
02452   setAliasAttributes(D, GA);
02453 }
02454 
02455 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
02456                                             ArrayRef<llvm::Type*> Tys) {
02457   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
02458                                          Tys);
02459 }
02460 
02461 static llvm::StringMapEntry<llvm::Constant*> &
02462 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
02463                          const StringLiteral *Literal,
02464                          bool TargetIsLSB,
02465                          bool &IsUTF16,
02466                          unsigned &StringLength) {
02467   StringRef String = Literal->getString();
02468   unsigned NumBytes = String.size();
02469 
02470   // Check for simple case.
02471   if (!Literal->containsNonAsciiOrNull()) {
02472     StringLength = NumBytes;
02473     return Map.GetOrCreateValue(String);
02474   }
02475 
02476   // Otherwise, convert the UTF8 literals into a string of shorts.
02477   IsUTF16 = true;
02478 
02479   SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
02480   const UTF8 *FromPtr = (const UTF8 *)String.data();
02481   UTF16 *ToPtr = &ToBuf[0];
02482 
02483   (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
02484                            &ToPtr, ToPtr + NumBytes,
02485                            strictConversion);
02486 
02487   // ConvertUTF8toUTF16 returns the length in ToPtr.
02488   StringLength = ToPtr - &ToBuf[0];
02489 
02490   // Add an explicit null.
02491   *ToPtr = 0;
02492   return Map.
02493     GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()),
02494                                (StringLength + 1) * 2));
02495 }
02496 
02497 static llvm::StringMapEntry<llvm::Constant*> &
02498 GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
02499                        const StringLiteral *Literal,
02500                        unsigned &StringLength) {
02501   StringRef String = Literal->getString();
02502   StringLength = String.size();
02503   return Map.GetOrCreateValue(String);
02504 }
02505 
02506 llvm::Constant *
02507 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
02508   unsigned StringLength = 0;
02509   bool isUTF16 = false;
02510   llvm::StringMapEntry<llvm::Constant*> &Entry =
02511     GetConstantCFStringEntry(CFConstantStringMap, Literal,
02512                              getDataLayout().isLittleEndian(),
02513                              isUTF16, StringLength);
02514 
02515   if (llvm::Constant *C = Entry.getValue())
02516     return C;
02517 
02518   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
02519   llvm::Constant *Zeros[] = { Zero, Zero };
02520   llvm::Value *V;
02521   
02522   // If we don't already have it, get __CFConstantStringClassReference.
02523   if (!CFConstantStringClassRef) {
02524     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
02525     Ty = llvm::ArrayType::get(Ty, 0);
02526     llvm::Constant *GV = CreateRuntimeVariable(Ty,
02527                                            "__CFConstantStringClassReference");
02528     // Decay array -> ptr
02529     V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
02530     CFConstantStringClassRef = V;
02531   }
02532   else
02533     V = CFConstantStringClassRef;
02534 
02535   QualType CFTy = getContext().getCFConstantStringType();
02536 
02537   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
02538 
02539   llvm::Constant *Fields[4];
02540 
02541   // Class pointer.
02542   Fields[0] = cast<llvm::ConstantExpr>(V);
02543 
02544   // Flags.
02545   llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
02546   Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
02547     llvm::ConstantInt::get(Ty, 0x07C8);
02548 
02549   // String pointer.
02550   llvm::Constant *C = nullptr;
02551   if (isUTF16) {
02552     ArrayRef<uint16_t> Arr =
02553       llvm::makeArrayRef<uint16_t>(reinterpret_cast<uint16_t*>(
02554                                      const_cast<char *>(Entry.getKey().data())),
02555                                    Entry.getKey().size() / 2);
02556     C = llvm::ConstantDataArray::get(VMContext, Arr);
02557   } else {
02558     C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
02559   }
02560 
02561   // Note: -fwritable-strings doesn't make the backing store strings of
02562   // CFStrings writable. (See <rdar://problem/10657500>)
02563   auto *GV =
02564       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
02565                                llvm::GlobalValue::PrivateLinkage, C, ".str");
02566   GV->setUnnamedAddr(true);
02567   // Don't enforce the target's minimum global alignment, since the only use
02568   // of the string is via this class initializer.
02569   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. Without
02570   // it LLVM can merge the string with a non unnamed_addr one during LTO. Doing
02571   // that changes the section it ends in, which surprises ld64.
02572   if (isUTF16) {
02573     CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
02574     GV->setAlignment(Align.getQuantity());
02575     GV->setSection("__TEXT,__ustring");
02576   } else {
02577     CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
02578     GV->setAlignment(Align.getQuantity());
02579     GV->setSection("__TEXT,__cstring,cstring_literals");
02580   }
02581 
02582   // String.
02583   Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
02584 
02585   if (isUTF16)
02586     // Cast the UTF16 string to the correct type.
02587     Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
02588 
02589   // String length.
02590   Ty = getTypes().ConvertType(getContext().LongTy);
02591   Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
02592 
02593   // The struct.
02594   C = llvm::ConstantStruct::get(STy, Fields);
02595   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
02596                                 llvm::GlobalVariable::PrivateLinkage, C,
02597                                 "_unnamed_cfstring_");
02598   GV->setSection("__DATA,__cfstring");
02599   Entry.setValue(GV);
02600 
02601   return GV;
02602 }
02603 
02604 llvm::Constant *
02605 CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
02606   unsigned StringLength = 0;
02607   llvm::StringMapEntry<llvm::Constant*> &Entry =
02608     GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
02609   
02610   if (llvm::Constant *C = Entry.getValue())
02611     return C;
02612   
02613   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
02614   llvm::Constant *Zeros[] = { Zero, Zero };
02615   llvm::Value *V;
02616   // If we don't already have it, get _NSConstantStringClassReference.
02617   if (!ConstantStringClassRef) {
02618     std::string StringClass(getLangOpts().ObjCConstantStringClass);
02619     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
02620     llvm::Constant *GV;
02621     if (LangOpts.ObjCRuntime.isNonFragile()) {
02622       std::string str = 
02623         StringClass.empty() ? "OBJC_CLASS_$_NSConstantString" 
02624                             : "OBJC_CLASS_$_" + StringClass;
02625       GV = getObjCRuntime().GetClassGlobal(str);
02626       // Make sure the result is of the correct type.
02627       llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
02628       V = llvm::ConstantExpr::getBitCast(GV, PTy);
02629       ConstantStringClassRef = V;
02630     } else {
02631       std::string str =
02632         StringClass.empty() ? "_NSConstantStringClassReference"
02633                             : "_" + StringClass + "ClassReference";
02634       llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
02635       GV = CreateRuntimeVariable(PTy, str);
02636       // Decay array -> ptr
02637       V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
02638       ConstantStringClassRef = V;
02639     }
02640   }
02641   else
02642     V = ConstantStringClassRef;
02643 
02644   if (!NSConstantStringType) {
02645     // Construct the type for a constant NSString.
02646     RecordDecl *D = Context.buildImplicitRecord("__builtin_NSString");
02647     D->startDefinition();
02648       
02649     QualType FieldTypes[3];
02650     
02651     // const int *isa;
02652     FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
02653     // const char *str;
02654     FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
02655     // unsigned int length;
02656     FieldTypes[2] = Context.UnsignedIntTy;
02657     
02658     // Create fields
02659     for (unsigned i = 0; i < 3; ++i) {
02660       FieldDecl *Field = FieldDecl::Create(Context, D,
02661                                            SourceLocation(),
02662                                            SourceLocation(), nullptr,
02663                                            FieldTypes[i], /*TInfo=*/nullptr,
02664                                            /*BitWidth=*/nullptr,
02665                                            /*Mutable=*/false,
02666                                            ICIS_NoInit);
02667       Field->setAccess(AS_public);
02668       D->addDecl(Field);
02669     }
02670     
02671     D->completeDefinition();
02672     QualType NSTy = Context.getTagDeclType(D);
02673     NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
02674   }
02675   
02676   llvm::Constant *Fields[3];
02677   
02678   // Class pointer.
02679   Fields[0] = cast<llvm::ConstantExpr>(V);
02680   
02681   // String pointer.
02682   llvm::Constant *C =
02683     llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
02684   
02685   llvm::GlobalValue::LinkageTypes Linkage;
02686   bool isConstant;
02687   Linkage = llvm::GlobalValue::PrivateLinkage;
02688   isConstant = !LangOpts.WritableStrings;
02689 
02690   auto *GV = new llvm::GlobalVariable(getModule(), C->getType(), isConstant,
02691                                       Linkage, C, ".str");
02692   GV->setUnnamedAddr(true);
02693   // Don't enforce the target's minimum global alignment, since the only use
02694   // of the string is via this class initializer.
02695   CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
02696   GV->setAlignment(Align.getQuantity());
02697   Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
02698   
02699   // String length.
02700   llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
02701   Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
02702   
02703   // The struct.
02704   C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
02705   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
02706                                 llvm::GlobalVariable::PrivateLinkage, C,
02707                                 "_unnamed_nsstring_");
02708   const char *NSStringSection = "__OBJC,__cstring_object,regular,no_dead_strip";
02709   const char *NSStringNonFragileABISection =
02710       "__DATA,__objc_stringobj,regular,no_dead_strip";
02711   // FIXME. Fix section.
02712   GV->setSection(LangOpts.ObjCRuntime.isNonFragile()
02713                      ? NSStringNonFragileABISection
02714                      : NSStringSection);
02715   Entry.setValue(GV);
02716   
02717   return GV;
02718 }
02719 
02720 QualType CodeGenModule::getObjCFastEnumerationStateType() {
02721   if (ObjCFastEnumerationStateType.isNull()) {
02722     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
02723     D->startDefinition();
02724     
02725     QualType FieldTypes[] = {
02726       Context.UnsignedLongTy,
02727       Context.getPointerType(Context.getObjCIdType()),
02728       Context.getPointerType(Context.UnsignedLongTy),
02729       Context.getConstantArrayType(Context.UnsignedLongTy,
02730                            llvm::APInt(32, 5), ArrayType::Normal, 0)
02731     };
02732     
02733     for (size_t i = 0; i < 4; ++i) {
02734       FieldDecl *Field = FieldDecl::Create(Context,
02735                                            D,
02736                                            SourceLocation(),
02737                                            SourceLocation(), nullptr,
02738                                            FieldTypes[i], /*TInfo=*/nullptr,
02739                                            /*BitWidth=*/nullptr,
02740                                            /*Mutable=*/false,
02741                                            ICIS_NoInit);
02742       Field->setAccess(AS_public);
02743       D->addDecl(Field);
02744     }
02745     
02746     D->completeDefinition();
02747     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
02748   }
02749   
02750   return ObjCFastEnumerationStateType;
02751 }
02752 
02753 llvm::Constant *
02754 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
02755   assert(!E->getType()->isPointerType() && "Strings are always arrays");
02756   
02757   // Don't emit it as the address of the string, emit the string data itself
02758   // as an inline array.
02759   if (E->getCharByteWidth() == 1) {
02760     SmallString<64> Str(E->getString());
02761 
02762     // Resize the string to the right size, which is indicated by its type.
02763     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
02764     Str.resize(CAT->getSize().getZExtValue());
02765     return llvm::ConstantDataArray::getString(VMContext, Str, false);
02766   }
02767 
02768   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
02769   llvm::Type *ElemTy = AType->getElementType();
02770   unsigned NumElements = AType->getNumElements();
02771 
02772   // Wide strings have either 2-byte or 4-byte elements.
02773   if (ElemTy->getPrimitiveSizeInBits() == 16) {
02774     SmallVector<uint16_t, 32> Elements;
02775     Elements.reserve(NumElements);
02776 
02777     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
02778       Elements.push_back(E->getCodeUnit(i));
02779     Elements.resize(NumElements);
02780     return llvm::ConstantDataArray::get(VMContext, Elements);
02781   }
02782   
02783   assert(ElemTy->getPrimitiveSizeInBits() == 32);
02784   SmallVector<uint32_t, 32> Elements;
02785   Elements.reserve(NumElements);
02786   
02787   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
02788     Elements.push_back(E->getCodeUnit(i));
02789   Elements.resize(NumElements);
02790   return llvm::ConstantDataArray::get(VMContext, Elements);
02791 }
02792 
02793 static llvm::GlobalVariable *
02794 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
02795                       CodeGenModule &CGM, StringRef GlobalName,
02796                       unsigned Alignment) {
02797   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
02798   unsigned AddrSpace = 0;
02799   if (CGM.getLangOpts().OpenCL)
02800     AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
02801 
02802   // Create a global variable for this string
02803   auto *GV = new llvm::GlobalVariable(
02804       CGM.getModule(), C->getType(), !CGM.getLangOpts().WritableStrings, LT, C,
02805       GlobalName, nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
02806   GV->setAlignment(Alignment);
02807   GV->setUnnamedAddr(true);
02808   return GV;
02809 }
02810 
02811 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
02812 /// constant array for the given string literal.
02813 llvm::GlobalVariable *
02814 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
02815                                                   StringRef Name) {
02816   auto Alignment =
02817       getContext().getAlignOfGlobalVarInChars(S->getType()).getQuantity();
02818 
02819   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
02820   llvm::GlobalVariable **Entry = nullptr;
02821   if (!LangOpts.WritableStrings) {
02822     Entry = &ConstantStringMap[C];
02823     if (auto GV = *Entry) {
02824       if (Alignment > GV->getAlignment())
02825         GV->setAlignment(Alignment);
02826       return GV;
02827     }
02828   }
02829 
02830   SmallString<256> MangledNameBuffer;
02831   StringRef GlobalVariableName;
02832   llvm::GlobalValue::LinkageTypes LT;
02833 
02834   // Mangle the string literal if the ABI allows for it.  However, we cannot
02835   // do this if  we are compiling with ASan or -fwritable-strings because they
02836   // rely on strings having normal linkage.
02837   if (!LangOpts.WritableStrings &&
02838       !LangOpts.Sanitize.has(SanitizerKind::Address) &&
02839       getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
02840     llvm::raw_svector_ostream Out(MangledNameBuffer);
02841     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
02842     Out.flush();
02843 
02844     LT = llvm::GlobalValue::LinkOnceODRLinkage;
02845     GlobalVariableName = MangledNameBuffer;
02846   } else {
02847     LT = llvm::GlobalValue::PrivateLinkage;
02848     GlobalVariableName = Name;
02849   }
02850 
02851   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
02852   if (Entry)
02853     *Entry = GV;
02854 
02855   SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
02856                                   QualType());
02857   return GV;
02858 }
02859 
02860 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
02861 /// array for the given ObjCEncodeExpr node.
02862 llvm::GlobalVariable *
02863 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
02864   std::string Str;
02865   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
02866 
02867   return GetAddrOfConstantCString(Str);
02868 }
02869 
02870 /// GetAddrOfConstantCString - Returns a pointer to a character array containing
02871 /// the literal and a terminating '\0' character.
02872 /// The result has pointer to array type.
02873 llvm::GlobalVariable *CodeGenModule::GetAddrOfConstantCString(
02874     const std::string &Str, const char *GlobalName, unsigned Alignment) {
02875   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
02876   if (Alignment == 0) {
02877     Alignment = getContext()
02878                     .getAlignOfGlobalVarInChars(getContext().CharTy)
02879                     .getQuantity();
02880   }
02881 
02882   llvm::Constant *C =
02883       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
02884 
02885   // Don't share any string literals if strings aren't constant.
02886   llvm::GlobalVariable **Entry = nullptr;
02887   if (!LangOpts.WritableStrings) {
02888     Entry = &ConstantStringMap[C];
02889     if (auto GV = *Entry) {
02890       if (Alignment > GV->getAlignment())
02891         GV->setAlignment(Alignment);
02892       return GV;
02893     }
02894   }
02895 
02896   // Get the default prefix if a name wasn't specified.
02897   if (!GlobalName)
02898     GlobalName = ".str";
02899   // Create a global variable for this.
02900   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
02901                                   GlobalName, Alignment);
02902   if (Entry)
02903     *Entry = GV;
02904   return GV;
02905 }
02906 
02907 llvm::Constant *CodeGenModule::GetAddrOfGlobalTemporary(
02908     const MaterializeTemporaryExpr *E, const Expr *Init) {
02909   assert((E->getStorageDuration() == SD_Static ||
02910           E->getStorageDuration() == SD_Thread) && "not a global temporary");
02911   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
02912 
02913   // If we're not materializing a subobject of the temporary, keep the
02914   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
02915   QualType MaterializedType = Init->getType();
02916   if (Init == E->GetTemporaryExpr())
02917     MaterializedType = E->getType();
02918 
02919   llvm::Constant *&Slot = MaterializedGlobalTemporaryMap[E];
02920   if (Slot)
02921     return Slot;
02922 
02923   // FIXME: If an externally-visible declaration extends multiple temporaries,
02924   // we need to give each temporary the same name in every translation unit (and
02925   // we also need to make the temporaries externally-visible).
02926   SmallString<256> Name;
02927   llvm::raw_svector_ostream Out(Name);
02928   getCXXABI().getMangleContext().mangleReferenceTemporary(
02929       VD, E->getManglingNumber(), Out);
02930   Out.flush();
02931 
02932   APValue *Value = nullptr;
02933   if (E->getStorageDuration() == SD_Static) {
02934     // We might have a cached constant initializer for this temporary. Note
02935     // that this might have a different value from the value computed by
02936     // evaluating the initializer if the surrounding constant expression
02937     // modifies the temporary.
02938     Value = getContext().getMaterializedTemporaryValue(E, false);
02939     if (Value && Value->isUninit())
02940       Value = nullptr;
02941   }
02942 
02943   // Try evaluating it now, it might have a constant initializer.
02944   Expr::EvalResult EvalResult;
02945   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
02946       !EvalResult.hasSideEffects())
02947     Value = &EvalResult.Val;
02948 
02949   llvm::Constant *InitialValue = nullptr;
02950   bool Constant = false;
02951   llvm::Type *Type;
02952   if (Value) {
02953     // The temporary has a constant initializer, use it.
02954     InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr);
02955     Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
02956     Type = InitialValue->getType();
02957   } else {
02958     // No initializer, the initialization will be provided when we
02959     // initialize the declaration which performed lifetime extension.
02960     Type = getTypes().ConvertTypeForMem(MaterializedType);
02961   }
02962 
02963   // Create a global variable for this lifetime-extended temporary.
02964   llvm::GlobalValue::LinkageTypes Linkage =
02965       getLLVMLinkageVarDefinition(VD, Constant);
02966   // There is no need for this temporary to have global linkage if the global
02967   // variable has external linkage.
02968   if (Linkage == llvm::GlobalVariable::ExternalLinkage)
02969     Linkage = llvm::GlobalVariable::PrivateLinkage;
02970   unsigned AddrSpace = GetGlobalVarAddressSpace(
02971       VD, getContext().getTargetAddressSpace(MaterializedType));
02972   auto *GV = new llvm::GlobalVariable(
02973       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
02974       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
02975       AddrSpace);
02976   setGlobalVisibility(GV, VD);
02977   GV->setAlignment(
02978       getContext().getTypeAlignInChars(MaterializedType).getQuantity());
02979   if (VD->getTLSKind())
02980     setTLSMode(GV, *VD);
02981   Slot = GV;
02982   return GV;
02983 }
02984 
02985 /// EmitObjCPropertyImplementations - Emit information for synthesized
02986 /// properties for an implementation.
02987 void CodeGenModule::EmitObjCPropertyImplementations(const
02988                                                     ObjCImplementationDecl *D) {
02989   for (const auto *PID : D->property_impls()) {
02990     // Dynamic is just for type-checking.
02991     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
02992       ObjCPropertyDecl *PD = PID->getPropertyDecl();
02993 
02994       // Determine which methods need to be implemented, some may have
02995       // been overridden. Note that ::isPropertyAccessor is not the method
02996       // we want, that just indicates if the decl came from a
02997       // property. What we want to know is if the method is defined in
02998       // this implementation.
02999       if (!D->getInstanceMethod(PD->getGetterName()))
03000         CodeGenFunction(*this).GenerateObjCGetter(
03001                                  const_cast<ObjCImplementationDecl *>(D), PID);
03002       if (!PD->isReadOnly() &&
03003           !D->getInstanceMethod(PD->getSetterName()))
03004         CodeGenFunction(*this).GenerateObjCSetter(
03005                                  const_cast<ObjCImplementationDecl *>(D), PID);
03006     }
03007   }
03008 }
03009 
03010 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
03011   const ObjCInterfaceDecl *iface = impl->getClassInterface();
03012   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
03013        ivar; ivar = ivar->getNextIvar())
03014     if (ivar->getType().isDestructedType())
03015       return true;
03016 
03017   return false;
03018 }
03019 
03020 static bool AllTrivialInitializers(CodeGenModule &CGM,
03021                                    ObjCImplementationDecl *D) {
03022   CodeGenFunction CGF(CGM);
03023   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
03024        E = D->init_end(); B != E; ++B) {
03025     CXXCtorInitializer *CtorInitExp = *B;
03026     Expr *Init = CtorInitExp->getInit();
03027     if (!CGF.isTrivialInitializer(Init))
03028       return false;
03029   }
03030   return true;
03031 }
03032 
03033 /// EmitObjCIvarInitializations - Emit information for ivar initialization
03034 /// for an implementation.
03035 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
03036   // We might need a .cxx_destruct even if we don't have any ivar initializers.
03037   if (needsDestructMethod(D)) {
03038     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
03039     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
03040     ObjCMethodDecl *DTORMethod =
03041       ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
03042                              cxxSelector, getContext().VoidTy, nullptr, D,
03043                              /*isInstance=*/true, /*isVariadic=*/false,
03044                           /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
03045                              /*isDefined=*/false, ObjCMethodDecl::Required);
03046     D->addInstanceMethod(DTORMethod);
03047     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
03048     D->setHasDestructors(true);
03049   }
03050 
03051   // If the implementation doesn't have any ivar initializers, we don't need
03052   // a .cxx_construct.
03053   if (D->getNumIvarInitializers() == 0 ||
03054       AllTrivialInitializers(*this, D))
03055     return;
03056   
03057   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
03058   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
03059   // The constructor returns 'self'.
03060   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(), 
03061                                                 D->getLocation(),
03062                                                 D->getLocation(),
03063                                                 cxxSelector,
03064                                                 getContext().getObjCIdType(),
03065                                                 nullptr, D, /*isInstance=*/true,
03066                                                 /*isVariadic=*/false,
03067                                                 /*isPropertyAccessor=*/true,
03068                                                 /*isImplicitlyDeclared=*/true,
03069                                                 /*isDefined=*/false,
03070                                                 ObjCMethodDecl::Required);
03071   D->addInstanceMethod(CTORMethod);
03072   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
03073   D->setHasNonZeroConstructors(true);
03074 }
03075 
03076 /// EmitNamespace - Emit all declarations in a namespace.
03077 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
03078   for (auto *I : ND->decls()) {
03079     if (const auto *VD = dyn_cast<VarDecl>(I))
03080       if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
03081           VD->getTemplateSpecializationKind() != TSK_Undeclared)
03082         continue;
03083     EmitTopLevelDecl(I);
03084   }
03085 }
03086 
03087 // EmitLinkageSpec - Emit all declarations in a linkage spec.
03088 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
03089   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
03090       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
03091     ErrorUnsupported(LSD, "linkage spec");
03092     return;
03093   }
03094 
03095   for (auto *I : LSD->decls()) {
03096     // Meta-data for ObjC class includes references to implemented methods.
03097     // Generate class's method definitions first.
03098     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
03099       for (auto *M : OID->methods())
03100         EmitTopLevelDecl(M);
03101     }
03102     EmitTopLevelDecl(I);
03103   }
03104 }
03105 
03106 /// EmitTopLevelDecl - Emit code for a single top level declaration.
03107 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
03108   // Ignore dependent declarations.
03109   if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
03110     return;
03111 
03112   switch (D->getKind()) {
03113   case Decl::CXXConversion:
03114   case Decl::CXXMethod:
03115   case Decl::Function:
03116     // Skip function templates
03117     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
03118         cast<FunctionDecl>(D)->isLateTemplateParsed())
03119       return;
03120 
03121     EmitGlobal(cast<FunctionDecl>(D));
03122     // Always provide some coverage mapping
03123     // even for the functions that aren't emitted.
03124     AddDeferredUnusedCoverageMapping(D);
03125     break;
03126 
03127   case Decl::Var:
03128     // Skip variable templates
03129     if (cast<VarDecl>(D)->getDescribedVarTemplate())
03130       return;
03131   case Decl::VarTemplateSpecialization:
03132     EmitGlobal(cast<VarDecl>(D));
03133     break;
03134 
03135   // Indirect fields from global anonymous structs and unions can be
03136   // ignored; only the actual variable requires IR gen support.
03137   case Decl::IndirectField:
03138     break;
03139 
03140   // C++ Decls
03141   case Decl::Namespace:
03142     EmitNamespace(cast<NamespaceDecl>(D));
03143     break;
03144     // No code generation needed.
03145   case Decl::UsingShadow:
03146   case Decl::ClassTemplate:
03147   case Decl::VarTemplate:
03148   case Decl::VarTemplatePartialSpecialization:
03149   case Decl::FunctionTemplate:
03150   case Decl::TypeAliasTemplate:
03151   case Decl::Block:
03152   case Decl::Empty:
03153     break;
03154   case Decl::Using:          // using X; [C++]
03155     if (CGDebugInfo *DI = getModuleDebugInfo())
03156         DI->EmitUsingDecl(cast<UsingDecl>(*D));
03157     return;
03158   case Decl::NamespaceAlias:
03159     if (CGDebugInfo *DI = getModuleDebugInfo())
03160         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
03161     return;
03162   case Decl::UsingDirective: // using namespace X; [C++]
03163     if (CGDebugInfo *DI = getModuleDebugInfo())
03164       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
03165     return;
03166   case Decl::CXXConstructor:
03167     // Skip function templates
03168     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
03169         cast<FunctionDecl>(D)->isLateTemplateParsed())
03170       return;
03171       
03172     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
03173     break;
03174   case Decl::CXXDestructor:
03175     if (cast<FunctionDecl>(D)->isLateTemplateParsed())
03176       return;
03177     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
03178     break;
03179 
03180   case Decl::StaticAssert:
03181     // Nothing to do.
03182     break;
03183 
03184   // Objective-C Decls
03185 
03186   // Forward declarations, no (immediate) code generation.
03187   case Decl::ObjCInterface:
03188   case Decl::ObjCCategory:
03189     break;
03190 
03191   case Decl::ObjCProtocol: {
03192     auto *Proto = cast<ObjCProtocolDecl>(D);
03193     if (Proto->isThisDeclarationADefinition())
03194       ObjCRuntime->GenerateProtocol(Proto);
03195     break;
03196   }
03197       
03198   case Decl::ObjCCategoryImpl:
03199     // Categories have properties but don't support synthesize so we
03200     // can ignore them here.
03201     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
03202     break;
03203 
03204   case Decl::ObjCImplementation: {
03205     auto *OMD = cast<ObjCImplementationDecl>(D);
03206     EmitObjCPropertyImplementations(OMD);
03207     EmitObjCIvarInitializations(OMD);
03208     ObjCRuntime->GenerateClass(OMD);
03209     // Emit global variable debug information.
03210     if (CGDebugInfo *DI = getModuleDebugInfo())
03211       if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
03212         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
03213             OMD->getClassInterface()), OMD->getLocation());
03214     break;
03215   }
03216   case Decl::ObjCMethod: {
03217     auto *OMD = cast<ObjCMethodDecl>(D);
03218     // If this is not a prototype, emit the body.
03219     if (OMD->getBody())
03220       CodeGenFunction(*this).GenerateObjCMethod(OMD);
03221     break;
03222   }
03223   case Decl::ObjCCompatibleAlias:
03224     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
03225     break;
03226 
03227   case Decl::LinkageSpec:
03228     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
03229     break;
03230 
03231   case Decl::FileScopeAsm: {
03232     auto *AD = cast<FileScopeAsmDecl>(D);
03233     StringRef AsmString = AD->getAsmString()->getString();
03234 
03235     const std::string &S = getModule().getModuleInlineAsm();
03236     if (S.empty())
03237       getModule().setModuleInlineAsm(AsmString);
03238     else if (S.end()[-1] == '\n')
03239       getModule().setModuleInlineAsm(S + AsmString.str());
03240     else
03241       getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
03242     break;
03243   }
03244 
03245   case Decl::Import: {
03246     auto *Import = cast<ImportDecl>(D);
03247 
03248     // Ignore import declarations that come from imported modules.
03249     if (clang::Module *Owner = Import->getOwningModule()) {
03250       if (getLangOpts().CurrentModule.empty() ||
03251           Owner->getTopLevelModule()->Name == getLangOpts().CurrentModule)
03252         break;
03253     }
03254 
03255     ImportedModules.insert(Import->getImportedModule());
03256     break;
03257   }
03258 
03259   case Decl::OMPThreadPrivate:
03260     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
03261     break;
03262 
03263   case Decl::ClassTemplateSpecialization: {
03264     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
03265     if (DebugInfo &&
03266         Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition)
03267       DebugInfo->completeTemplateDefinition(*Spec);
03268   }
03269 
03270   default:
03271     // Make sure we handled everything we should, every other kind is a
03272     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
03273     // function. Need to recode Decl::Kind to do that easily.
03274     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
03275   }
03276 }
03277 
03278 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
03279   // Do we need to generate coverage mapping?
03280   if (!CodeGenOpts.CoverageMapping)
03281     return;
03282   switch (D->getKind()) {
03283   case Decl::CXXConversion:
03284   case Decl::CXXMethod:
03285   case Decl::Function:
03286   case Decl::ObjCMethod:
03287   case Decl::CXXConstructor:
03288   case Decl::CXXDestructor: {
03289     if (!cast<FunctionDecl>(D)->hasBody())
03290       return;
03291     auto I = DeferredEmptyCoverageMappingDecls.find(D);
03292     if (I == DeferredEmptyCoverageMappingDecls.end())
03293       DeferredEmptyCoverageMappingDecls[D] = true;
03294     break;
03295   }
03296   default:
03297     break;
03298   };
03299 }
03300 
03301 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
03302   // Do we need to generate coverage mapping?
03303   if (!CodeGenOpts.CoverageMapping)
03304     return;
03305   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
03306     if (Fn->isTemplateInstantiation())
03307       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
03308   }
03309   auto I = DeferredEmptyCoverageMappingDecls.find(D);
03310   if (I == DeferredEmptyCoverageMappingDecls.end())
03311     DeferredEmptyCoverageMappingDecls[D] = false;
03312   else
03313     I->second = false;
03314 }
03315 
03316 void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
03317   std::vector<const Decl *> DeferredDecls;
03318   for (const auto I : DeferredEmptyCoverageMappingDecls) {
03319     if (!I.second)
03320       continue;
03321     DeferredDecls.push_back(I.first);
03322   }
03323   // Sort the declarations by their location to make sure that the tests get a
03324   // predictable order for the coverage mapping for the unused declarations.
03325   if (CodeGenOpts.DumpCoverageMapping)
03326     std::sort(DeferredDecls.begin(), DeferredDecls.end(),
03327               [] (const Decl *LHS, const Decl *RHS) {
03328       return LHS->getLocStart() < RHS->getLocStart();
03329     });
03330   for (const auto *D : DeferredDecls) {
03331     switch (D->getKind()) {
03332     case Decl::CXXConversion:
03333     case Decl::CXXMethod:
03334     case Decl::Function:
03335     case Decl::ObjCMethod: {
03336       CodeGenPGO PGO(*this);
03337       GlobalDecl GD(cast<FunctionDecl>(D));
03338       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
03339                                   getFunctionLinkage(GD));
03340       break;
03341     }
03342     case Decl::CXXConstructor: {
03343       CodeGenPGO PGO(*this);
03344       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
03345       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
03346                                   getFunctionLinkage(GD));
03347       break;
03348     }
03349     case Decl::CXXDestructor: {
03350       CodeGenPGO PGO(*this);
03351       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
03352       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
03353                                   getFunctionLinkage(GD));
03354       break;
03355     }
03356     default:
03357       break;
03358     };
03359   }
03360 }
03361 
03362 /// Turns the given pointer into a constant.
03363 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
03364                                           const void *Ptr) {
03365   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
03366   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
03367   return llvm::ConstantInt::get(i64, PtrInt);
03368 }
03369 
03370 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
03371                                    llvm::NamedMDNode *&GlobalMetadata,
03372                                    GlobalDecl D,
03373                                    llvm::GlobalValue *Addr) {
03374   if (!GlobalMetadata)
03375     GlobalMetadata =
03376       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
03377 
03378   // TODO: should we report variant information for ctors/dtors?
03379   llvm::Value *Ops[] = {
03380     Addr,
03381     GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
03382   };
03383   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
03384 }
03385 
03386 /// For each function which is declared within an extern "C" region and marked
03387 /// as 'used', but has internal linkage, create an alias from the unmangled
03388 /// name to the mangled name if possible. People expect to be able to refer
03389 /// to such functions with an unmangled name from inline assembly within the
03390 /// same translation unit.
03391 void CodeGenModule::EmitStaticExternCAliases() {
03392   for (StaticExternCMap::iterator I = StaticExternCValues.begin(),
03393                                   E = StaticExternCValues.end();
03394        I != E; ++I) {
03395     IdentifierInfo *Name = I->first;
03396     llvm::GlobalValue *Val = I->second;
03397     if (Val && !getModule().getNamedValue(Name->getName()))
03398       addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
03399   }
03400 }
03401 
03402 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
03403                                              GlobalDecl &Result) const {
03404   auto Res = Manglings.find(MangledName);
03405   if (Res == Manglings.end())
03406     return false;
03407   Result = Res->getValue();
03408   return true;
03409 }
03410 
03411 /// Emits metadata nodes associating all the global values in the
03412 /// current module with the Decls they came from.  This is useful for
03413 /// projects using IR gen as a subroutine.
03414 ///
03415 /// Since there's currently no way to associate an MDNode directly
03416 /// with an llvm::GlobalValue, we create a global named metadata
03417 /// with the name 'clang.global.decl.ptrs'.
03418 void CodeGenModule::EmitDeclMetadata() {
03419   llvm::NamedMDNode *GlobalMetadata = nullptr;
03420 
03421   // StaticLocalDeclMap
03422   for (auto &I : MangledDeclNames) {
03423     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
03424     EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
03425   }
03426 }
03427 
03428 /// Emits metadata nodes for all the local variables in the current
03429 /// function.
03430 void CodeGenFunction::EmitDeclMetadata() {
03431   if (LocalDeclMap.empty()) return;
03432 
03433   llvm::LLVMContext &Context = getLLVMContext();
03434 
03435   // Find the unique metadata ID for this name.
03436   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
03437 
03438   llvm::NamedMDNode *GlobalMetadata = nullptr;
03439 
03440   for (auto &I : LocalDeclMap) {
03441     const Decl *D = I.first;
03442     llvm::Value *Addr = I.second;
03443     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
03444       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
03445       Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
03446     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
03447       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
03448       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
03449     }
03450   }
03451 }
03452 
03453 void CodeGenModule::EmitVersionIdentMetadata() {
03454   llvm::NamedMDNode *IdentMetadata =
03455     TheModule.getOrInsertNamedMetadata("llvm.ident");
03456   std::string Version = getClangFullVersion();
03457   llvm::LLVMContext &Ctx = TheModule.getContext();
03458 
03459   llvm::Value *IdentNode[] = {
03460     llvm::MDString::get(Ctx, Version)
03461   };
03462   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
03463 }
03464 
03465 void CodeGenModule::EmitTargetMetadata() {
03466   // Warning, new MangledDeclNames may be appended within this loop.
03467   // We rely on MapVector insertions adding new elements to the end
03468   // of the container.
03469   // FIXME: Move this loop into the one target that needs it, and only
03470   // loop over those declarations for which we couldn't emit the target
03471   // metadata when we emitted the declaration.
03472   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
03473     auto Val = *(MangledDeclNames.begin() + I);
03474     const Decl *D = Val.first.getDecl()->getMostRecentDecl();
03475     llvm::GlobalValue *GV = GetGlobalValue(Val.second);
03476     getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
03477   }
03478 }
03479 
03480 void CodeGenModule::EmitCoverageFile() {
03481   if (!getCodeGenOpts().CoverageFile.empty()) {
03482     if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
03483       llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
03484       llvm::LLVMContext &Ctx = TheModule.getContext();
03485       llvm::MDString *CoverageFile =
03486           llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
03487       for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
03488         llvm::MDNode *CU = CUNode->getOperand(i);
03489         llvm::Value *node[] = { CoverageFile, CU };
03490         llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
03491         GCov->addOperand(N);
03492       }
03493     }
03494   }
03495 }
03496 
03497 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
03498   // Sema has checked that all uuid strings are of the form
03499   // "12345678-1234-1234-1234-1234567890ab".
03500   assert(Uuid.size() == 36);
03501   for (unsigned i = 0; i < 36; ++i) {
03502     if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
03503     else                                         assert(isHexDigit(Uuid[i]));
03504   }
03505 
03506   // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
03507   const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
03508 
03509   llvm::Constant *Field3[8];
03510   for (unsigned Idx = 0; Idx < 8; ++Idx)
03511     Field3[Idx] = llvm::ConstantInt::get(
03512         Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
03513 
03514   llvm::Constant *Fields[4] = {
03515     llvm::ConstantInt::get(Int32Ty, Uuid.substr(0,  8), 16),
03516     llvm::ConstantInt::get(Int16Ty, Uuid.substr(9,  4), 16),
03517     llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
03518     llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
03519   };
03520 
03521   return llvm::ConstantStruct::getAnon(Fields);
03522 }
03523 
03524 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
03525                                                        bool ForEH) {
03526   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
03527   // FIXME: should we even be calling this method if RTTI is disabled
03528   // and it's not for EH?
03529   if (!ForEH && !getLangOpts().RTTI)
03530     return llvm::Constant::getNullValue(Int8PtrTy);
03531   
03532   if (ForEH && Ty->isObjCObjectPointerType() &&
03533       LangOpts.ObjCRuntime.isGNUFamily())
03534     return ObjCRuntime->GetEHType(Ty);
03535 
03536   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
03537 }
03538 
03539 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
03540   for (auto RefExpr : D->varlists()) {
03541     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
03542     bool PerformInit =
03543         VD->getAnyInitializer() &&
03544         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
03545                                                         /*ForRef=*/false);
03546     if (auto InitFunction =
03547             getOpenMPRuntime().EmitOMPThreadPrivateVarDefinition(
03548                 VD, GetAddrOfGlobalVar(VD), RefExpr->getLocStart(),
03549                 PerformInit))
03550       CXXGlobalInits.push_back(InitFunction);
03551   }
03552 }
03553