1*67e74705SXin Li //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2*67e74705SXin Li //
3*67e74705SXin Li // The LLVM Compiler Infrastructure
4*67e74705SXin Li //
5*67e74705SXin Li // This file is distributed under the University of Illinois Open Source
6*67e74705SXin Li // License. See LICENSE.TXT for details.
7*67e74705SXin Li //
8*67e74705SXin Li //===----------------------------------------------------------------------===//
9*67e74705SXin Li //
10*67e74705SXin Li // This coordinates the per-module state used while generating code.
11*67e74705SXin Li //
12*67e74705SXin Li //===----------------------------------------------------------------------===//
13*67e74705SXin Li
14*67e74705SXin Li #include "CodeGenModule.h"
15*67e74705SXin Li #include "CGBlocks.h"
16*67e74705SXin Li #include "CGCUDARuntime.h"
17*67e74705SXin Li #include "CGCXXABI.h"
18*67e74705SXin Li #include "CGCall.h"
19*67e74705SXin Li #include "CGDebugInfo.h"
20*67e74705SXin Li #include "CGObjCRuntime.h"
21*67e74705SXin Li #include "CGOpenCLRuntime.h"
22*67e74705SXin Li #include "CGOpenMPRuntime.h"
23*67e74705SXin Li #include "CGOpenMPRuntimeNVPTX.h"
24*67e74705SXin Li #include "CodeGenFunction.h"
25*67e74705SXin Li #include "CodeGenPGO.h"
26*67e74705SXin Li #include "CodeGenTBAA.h"
27*67e74705SXin Li #include "CoverageMappingGen.h"
28*67e74705SXin Li #include "TargetInfo.h"
29*67e74705SXin Li #include "clang/AST/ASTContext.h"
30*67e74705SXin Li #include "clang/AST/CharUnits.h"
31*67e74705SXin Li #include "clang/AST/DeclCXX.h"
32*67e74705SXin Li #include "clang/AST/DeclObjC.h"
33*67e74705SXin Li #include "clang/AST/DeclTemplate.h"
34*67e74705SXin Li #include "clang/AST/Mangle.h"
35*67e74705SXin Li #include "clang/AST/RecordLayout.h"
36*67e74705SXin Li #include "clang/AST/RecursiveASTVisitor.h"
37*67e74705SXin Li #include "clang/Basic/Builtins.h"
38*67e74705SXin Li #include "clang/Basic/CharInfo.h"
39*67e74705SXin Li #include "clang/Basic/Diagnostic.h"
40*67e74705SXin Li #include "clang/Basic/Module.h"
41*67e74705SXin Li #include "clang/Basic/SourceManager.h"
42*67e74705SXin Li #include "clang/Basic/TargetInfo.h"
43*67e74705SXin Li #include "clang/Basic/Version.h"
44*67e74705SXin Li #include "clang/Frontend/CodeGenOptions.h"
45*67e74705SXin Li #include "clang/Sema/SemaDiagnostic.h"
46*67e74705SXin Li #include "llvm/ADT/APSInt.h"
47*67e74705SXin Li #include "llvm/ADT/Triple.h"
48*67e74705SXin Li #include "llvm/IR/CallSite.h"
49*67e74705SXin Li #include "llvm/IR/CallingConv.h"
50*67e74705SXin Li #include "llvm/IR/DataLayout.h"
51*67e74705SXin Li #include "llvm/IR/Intrinsics.h"
52*67e74705SXin Li #include "llvm/IR/LLVMContext.h"
53*67e74705SXin Li #include "llvm/IR/Module.h"
54*67e74705SXin Li #include "llvm/ProfileData/InstrProfReader.h"
55*67e74705SXin Li #include "llvm/Support/ConvertUTF.h"
56*67e74705SXin Li #include "llvm/Support/ErrorHandling.h"
57*67e74705SXin Li #include "llvm/Support/MD5.h"
58*67e74705SXin Li
59*67e74705SXin Li using namespace clang;
60*67e74705SXin Li using namespace CodeGen;
61*67e74705SXin Li
62*67e74705SXin Li static const char AnnotationSection[] = "llvm.metadata";
63*67e74705SXin Li
createCXXABI(CodeGenModule & CGM)64*67e74705SXin Li static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
65*67e74705SXin Li switch (CGM.getTarget().getCXXABI().getKind()) {
66*67e74705SXin Li case TargetCXXABI::GenericAArch64:
67*67e74705SXin Li case TargetCXXABI::GenericARM:
68*67e74705SXin Li case TargetCXXABI::iOS:
69*67e74705SXin Li case TargetCXXABI::iOS64:
70*67e74705SXin Li case TargetCXXABI::WatchOS:
71*67e74705SXin Li case TargetCXXABI::GenericMIPS:
72*67e74705SXin Li case TargetCXXABI::GenericItanium:
73*67e74705SXin Li case TargetCXXABI::WebAssembly:
74*67e74705SXin Li return CreateItaniumCXXABI(CGM);
75*67e74705SXin Li case TargetCXXABI::Microsoft:
76*67e74705SXin Li return CreateMicrosoftCXXABI(CGM);
77*67e74705SXin Li }
78*67e74705SXin Li
79*67e74705SXin Li llvm_unreachable("invalid C++ ABI kind");
80*67e74705SXin Li }
81*67e74705SXin Li
CodeGenModule(ASTContext & C,const HeaderSearchOptions & HSO,const PreprocessorOptions & PPO,const CodeGenOptions & CGO,llvm::Module & M,DiagnosticsEngine & diags,CoverageSourceInfo * CoverageInfo)82*67e74705SXin Li CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
83*67e74705SXin Li const PreprocessorOptions &PPO,
84*67e74705SXin Li const CodeGenOptions &CGO, llvm::Module &M,
85*67e74705SXin Li DiagnosticsEngine &diags,
86*67e74705SXin Li CoverageSourceInfo *CoverageInfo)
87*67e74705SXin Li : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
88*67e74705SXin Li PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
89*67e74705SXin Li Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
90*67e74705SXin Li VMContext(M.getContext()), Types(*this), VTables(*this),
91*67e74705SXin Li SanitizerMD(new SanitizerMetadata(*this)) {
92*67e74705SXin Li
93*67e74705SXin Li // Initialize the type cache.
94*67e74705SXin Li llvm::LLVMContext &LLVMContext = M.getContext();
95*67e74705SXin Li VoidTy = llvm::Type::getVoidTy(LLVMContext);
96*67e74705SXin Li Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
97*67e74705SXin Li Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
98*67e74705SXin Li Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
99*67e74705SXin Li Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
100*67e74705SXin Li FloatTy = llvm::Type::getFloatTy(LLVMContext);
101*67e74705SXin Li DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
102*67e74705SXin Li PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
103*67e74705SXin Li PointerAlignInBytes =
104*67e74705SXin Li C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
105*67e74705SXin Li IntAlignInBytes =
106*67e74705SXin Li C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
107*67e74705SXin Li IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
108*67e74705SXin Li IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
109*67e74705SXin Li Int8PtrTy = Int8Ty->getPointerTo(0);
110*67e74705SXin Li Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
111*67e74705SXin Li
112*67e74705SXin Li RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
113*67e74705SXin Li BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC();
114*67e74705SXin Li
115*67e74705SXin Li if (LangOpts.ObjC1)
116*67e74705SXin Li createObjCRuntime();
117*67e74705SXin Li if (LangOpts.OpenCL)
118*67e74705SXin Li createOpenCLRuntime();
119*67e74705SXin Li if (LangOpts.OpenMP)
120*67e74705SXin Li createOpenMPRuntime();
121*67e74705SXin Li if (LangOpts.CUDA)
122*67e74705SXin Li createCUDARuntime();
123*67e74705SXin Li
124*67e74705SXin Li // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
125*67e74705SXin Li if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
126*67e74705SXin Li (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
127*67e74705SXin Li TBAA.reset(new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
128*67e74705SXin Li getCXXABI().getMangleContext()));
129*67e74705SXin Li
130*67e74705SXin Li // If debug info or coverage generation is enabled, create the CGDebugInfo
131*67e74705SXin Li // object.
132*67e74705SXin Li if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
133*67e74705SXin Li CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
134*67e74705SXin Li DebugInfo.reset(new CGDebugInfo(*this));
135*67e74705SXin Li
136*67e74705SXin Li Block.GlobalUniqueCount = 0;
137*67e74705SXin Li
138*67e74705SXin Li if (C.getLangOpts().ObjC1)
139*67e74705SXin Li ObjCData.reset(new ObjCEntrypoints());
140*67e74705SXin Li
141*67e74705SXin Li if (CodeGenOpts.hasProfileClangUse()) {
142*67e74705SXin Li auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
143*67e74705SXin Li CodeGenOpts.ProfileInstrumentUsePath);
144*67e74705SXin Li if (auto E = ReaderOrErr.takeError()) {
145*67e74705SXin Li unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
146*67e74705SXin Li "Could not read profile %0: %1");
147*67e74705SXin Li llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
148*67e74705SXin Li getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
149*67e74705SXin Li << EI.message();
150*67e74705SXin Li });
151*67e74705SXin Li } else
152*67e74705SXin Li PGOReader = std::move(ReaderOrErr.get());
153*67e74705SXin Li }
154*67e74705SXin Li
155*67e74705SXin Li // If coverage mapping generation is enabled, create the
156*67e74705SXin Li // CoverageMappingModuleGen object.
157*67e74705SXin Li if (CodeGenOpts.CoverageMapping)
158*67e74705SXin Li CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
159*67e74705SXin Li }
160*67e74705SXin Li
~CodeGenModule()161*67e74705SXin Li CodeGenModule::~CodeGenModule() {}
162*67e74705SXin Li
createObjCRuntime()163*67e74705SXin Li void CodeGenModule::createObjCRuntime() {
164*67e74705SXin Li // This is just isGNUFamily(), but we want to force implementors of
165*67e74705SXin Li // new ABIs to decide how best to do this.
166*67e74705SXin Li switch (LangOpts.ObjCRuntime.getKind()) {
167*67e74705SXin Li case ObjCRuntime::GNUstep:
168*67e74705SXin Li case ObjCRuntime::GCC:
169*67e74705SXin Li case ObjCRuntime::ObjFW:
170*67e74705SXin Li ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
171*67e74705SXin Li return;
172*67e74705SXin Li
173*67e74705SXin Li case ObjCRuntime::FragileMacOSX:
174*67e74705SXin Li case ObjCRuntime::MacOSX:
175*67e74705SXin Li case ObjCRuntime::iOS:
176*67e74705SXin Li case ObjCRuntime::WatchOS:
177*67e74705SXin Li ObjCRuntime.reset(CreateMacObjCRuntime(*this));
178*67e74705SXin Li return;
179*67e74705SXin Li }
180*67e74705SXin Li llvm_unreachable("bad runtime kind");
181*67e74705SXin Li }
182*67e74705SXin Li
createOpenCLRuntime()183*67e74705SXin Li void CodeGenModule::createOpenCLRuntime() {
184*67e74705SXin Li OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
185*67e74705SXin Li }
186*67e74705SXin Li
createOpenMPRuntime()187*67e74705SXin Li void CodeGenModule::createOpenMPRuntime() {
188*67e74705SXin Li // Select a specialized code generation class based on the target, if any.
189*67e74705SXin Li // If it does not exist use the default implementation.
190*67e74705SXin Li switch (getTarget().getTriple().getArch()) {
191*67e74705SXin Li
192*67e74705SXin Li case llvm::Triple::nvptx:
193*67e74705SXin Li case llvm::Triple::nvptx64:
194*67e74705SXin Li assert(getLangOpts().OpenMPIsDevice &&
195*67e74705SXin Li "OpenMP NVPTX is only prepared to deal with device code.");
196*67e74705SXin Li OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
197*67e74705SXin Li break;
198*67e74705SXin Li default:
199*67e74705SXin Li OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
200*67e74705SXin Li break;
201*67e74705SXin Li }
202*67e74705SXin Li }
203*67e74705SXin Li
createCUDARuntime()204*67e74705SXin Li void CodeGenModule::createCUDARuntime() {
205*67e74705SXin Li CUDARuntime.reset(CreateNVCUDARuntime(*this));
206*67e74705SXin Li }
207*67e74705SXin Li
addReplacement(StringRef Name,llvm::Constant * C)208*67e74705SXin Li void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
209*67e74705SXin Li Replacements[Name] = C;
210*67e74705SXin Li }
211*67e74705SXin Li
applyReplacements()212*67e74705SXin Li void CodeGenModule::applyReplacements() {
213*67e74705SXin Li for (auto &I : Replacements) {
214*67e74705SXin Li StringRef MangledName = I.first();
215*67e74705SXin Li llvm::Constant *Replacement = I.second;
216*67e74705SXin Li llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
217*67e74705SXin Li if (!Entry)
218*67e74705SXin Li continue;
219*67e74705SXin Li auto *OldF = cast<llvm::Function>(Entry);
220*67e74705SXin Li auto *NewF = dyn_cast<llvm::Function>(Replacement);
221*67e74705SXin Li if (!NewF) {
222*67e74705SXin Li if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
223*67e74705SXin Li NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
224*67e74705SXin Li } else {
225*67e74705SXin Li auto *CE = cast<llvm::ConstantExpr>(Replacement);
226*67e74705SXin Li assert(CE->getOpcode() == llvm::Instruction::BitCast ||
227*67e74705SXin Li CE->getOpcode() == llvm::Instruction::GetElementPtr);
228*67e74705SXin Li NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
229*67e74705SXin Li }
230*67e74705SXin Li }
231*67e74705SXin Li
232*67e74705SXin Li // Replace old with new, but keep the old order.
233*67e74705SXin Li OldF->replaceAllUsesWith(Replacement);
234*67e74705SXin Li if (NewF) {
235*67e74705SXin Li NewF->removeFromParent();
236*67e74705SXin Li OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
237*67e74705SXin Li NewF);
238*67e74705SXin Li }
239*67e74705SXin Li OldF->eraseFromParent();
240*67e74705SXin Li }
241*67e74705SXin Li }
242*67e74705SXin Li
addGlobalValReplacement(llvm::GlobalValue * GV,llvm::Constant * C)243*67e74705SXin Li void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
244*67e74705SXin Li GlobalValReplacements.push_back(std::make_pair(GV, C));
245*67e74705SXin Li }
246*67e74705SXin Li
applyGlobalValReplacements()247*67e74705SXin Li void CodeGenModule::applyGlobalValReplacements() {
248*67e74705SXin Li for (auto &I : GlobalValReplacements) {
249*67e74705SXin Li llvm::GlobalValue *GV = I.first;
250*67e74705SXin Li llvm::Constant *C = I.second;
251*67e74705SXin Li
252*67e74705SXin Li GV->replaceAllUsesWith(C);
253*67e74705SXin Li GV->eraseFromParent();
254*67e74705SXin Li }
255*67e74705SXin Li }
256*67e74705SXin Li
257*67e74705SXin Li // This is only used in aliases that we created and we know they have a
258*67e74705SXin Li // linear structure.
getAliasedGlobal(const llvm::GlobalIndirectSymbol & GIS)259*67e74705SXin Li static const llvm::GlobalObject *getAliasedGlobal(
260*67e74705SXin Li const llvm::GlobalIndirectSymbol &GIS) {
261*67e74705SXin Li llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
262*67e74705SXin Li const llvm::Constant *C = &GIS;
263*67e74705SXin Li for (;;) {
264*67e74705SXin Li C = C->stripPointerCasts();
265*67e74705SXin Li if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
266*67e74705SXin Li return GO;
267*67e74705SXin Li // stripPointerCasts will not walk over weak aliases.
268*67e74705SXin Li auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
269*67e74705SXin Li if (!GIS2)
270*67e74705SXin Li return nullptr;
271*67e74705SXin Li if (!Visited.insert(GIS2).second)
272*67e74705SXin Li return nullptr;
273*67e74705SXin Li C = GIS2->getIndirectSymbol();
274*67e74705SXin Li }
275*67e74705SXin Li }
276*67e74705SXin Li
checkAliases()277*67e74705SXin Li void CodeGenModule::checkAliases() {
278*67e74705SXin Li // Check if the constructed aliases are well formed. It is really unfortunate
279*67e74705SXin Li // that we have to do this in CodeGen, but we only construct mangled names
280*67e74705SXin Li // and aliases during codegen.
281*67e74705SXin Li bool Error = false;
282*67e74705SXin Li DiagnosticsEngine &Diags = getDiags();
283*67e74705SXin Li for (const GlobalDecl &GD : Aliases) {
284*67e74705SXin Li const auto *D = cast<ValueDecl>(GD.getDecl());
285*67e74705SXin Li SourceLocation Location;
286*67e74705SXin Li bool IsIFunc = D->hasAttr<IFuncAttr>();
287*67e74705SXin Li if (const Attr *A = D->getDefiningAttr())
288*67e74705SXin Li Location = A->getLocation();
289*67e74705SXin Li else
290*67e74705SXin Li llvm_unreachable("Not an alias or ifunc?");
291*67e74705SXin Li StringRef MangledName = getMangledName(GD);
292*67e74705SXin Li llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
293*67e74705SXin Li auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry);
294*67e74705SXin Li const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
295*67e74705SXin Li if (!GV) {
296*67e74705SXin Li Error = true;
297*67e74705SXin Li Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
298*67e74705SXin Li } else if (GV->isDeclaration()) {
299*67e74705SXin Li Error = true;
300*67e74705SXin Li Diags.Report(Location, diag::err_alias_to_undefined)
301*67e74705SXin Li << IsIFunc << IsIFunc;
302*67e74705SXin Li } else if (IsIFunc) {
303*67e74705SXin Li // Check resolver function type.
304*67e74705SXin Li llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
305*67e74705SXin Li GV->getType()->getPointerElementType());
306*67e74705SXin Li assert(FTy);
307*67e74705SXin Li if (!FTy->getReturnType()->isPointerTy())
308*67e74705SXin Li Diags.Report(Location, diag::err_ifunc_resolver_return);
309*67e74705SXin Li if (FTy->getNumParams())
310*67e74705SXin Li Diags.Report(Location, diag::err_ifunc_resolver_params);
311*67e74705SXin Li }
312*67e74705SXin Li
313*67e74705SXin Li llvm::Constant *Aliasee = Alias->getIndirectSymbol();
314*67e74705SXin Li llvm::GlobalValue *AliaseeGV;
315*67e74705SXin Li if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
316*67e74705SXin Li AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
317*67e74705SXin Li else
318*67e74705SXin Li AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
319*67e74705SXin Li
320*67e74705SXin Li if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
321*67e74705SXin Li StringRef AliasSection = SA->getName();
322*67e74705SXin Li if (AliasSection != AliaseeGV->getSection())
323*67e74705SXin Li Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
324*67e74705SXin Li << AliasSection << IsIFunc << IsIFunc;
325*67e74705SXin Li }
326*67e74705SXin Li
327*67e74705SXin Li // We have to handle alias to weak aliases in here. LLVM itself disallows
328*67e74705SXin Li // this since the object semantics would not match the IL one. For
329*67e74705SXin Li // compatibility with gcc we implement it by just pointing the alias
330*67e74705SXin Li // to its aliasee's aliasee. We also warn, since the user is probably
331*67e74705SXin Li // expecting the link to be weak.
332*67e74705SXin Li if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
333*67e74705SXin Li if (GA->isInterposable()) {
334*67e74705SXin Li Diags.Report(Location, diag::warn_alias_to_weak_alias)
335*67e74705SXin Li << GV->getName() << GA->getName() << IsIFunc;
336*67e74705SXin Li Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
337*67e74705SXin Li GA->getIndirectSymbol(), Alias->getType());
338*67e74705SXin Li Alias->setIndirectSymbol(Aliasee);
339*67e74705SXin Li }
340*67e74705SXin Li }
341*67e74705SXin Li }
342*67e74705SXin Li if (!Error)
343*67e74705SXin Li return;
344*67e74705SXin Li
345*67e74705SXin Li for (const GlobalDecl &GD : Aliases) {
346*67e74705SXin Li StringRef MangledName = getMangledName(GD);
347*67e74705SXin Li llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
348*67e74705SXin Li auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
349*67e74705SXin Li Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
350*67e74705SXin Li Alias->eraseFromParent();
351*67e74705SXin Li }
352*67e74705SXin Li }
353*67e74705SXin Li
clear()354*67e74705SXin Li void CodeGenModule::clear() {
355*67e74705SXin Li DeferredDeclsToEmit.clear();
356*67e74705SXin Li if (OpenMPRuntime)
357*67e74705SXin Li OpenMPRuntime->clear();
358*67e74705SXin Li }
359*67e74705SXin Li
reportDiagnostics(DiagnosticsEngine & Diags,StringRef MainFile)360*67e74705SXin Li void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
361*67e74705SXin Li StringRef MainFile) {
362*67e74705SXin Li if (!hasDiagnostics())
363*67e74705SXin Li return;
364*67e74705SXin Li if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
365*67e74705SXin Li if (MainFile.empty())
366*67e74705SXin Li MainFile = "<stdin>";
367*67e74705SXin Li Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
368*67e74705SXin Li } else
369*67e74705SXin Li Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Missing
370*67e74705SXin Li << Mismatched;
371*67e74705SXin Li }
372*67e74705SXin Li
Release()373*67e74705SXin Li void CodeGenModule::Release() {
374*67e74705SXin Li EmitDeferred();
375*67e74705SXin Li applyGlobalValReplacements();
376*67e74705SXin Li applyReplacements();
377*67e74705SXin Li checkAliases();
378*67e74705SXin Li EmitCXXGlobalInitFunc();
379*67e74705SXin Li EmitCXXGlobalDtorFunc();
380*67e74705SXin Li EmitCXXThreadLocalInitFunc();
381*67e74705SXin Li if (ObjCRuntime)
382*67e74705SXin Li if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
383*67e74705SXin Li AddGlobalCtor(ObjCInitFunction);
384*67e74705SXin Li if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
385*67e74705SXin Li CUDARuntime) {
386*67e74705SXin Li if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction())
387*67e74705SXin Li AddGlobalCtor(CudaCtorFunction);
388*67e74705SXin Li if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction())
389*67e74705SXin Li AddGlobalDtor(CudaDtorFunction);
390*67e74705SXin Li }
391*67e74705SXin Li if (OpenMPRuntime)
392*67e74705SXin Li if (llvm::Function *OpenMPRegistrationFunction =
393*67e74705SXin Li OpenMPRuntime->emitRegistrationFunction())
394*67e74705SXin Li AddGlobalCtor(OpenMPRegistrationFunction, 0);
395*67e74705SXin Li if (PGOReader) {
396*67e74705SXin Li getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext));
397*67e74705SXin Li if (PGOStats.hasDiagnostics())
398*67e74705SXin Li PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
399*67e74705SXin Li }
400*67e74705SXin Li EmitCtorList(GlobalCtors, "llvm.global_ctors");
401*67e74705SXin Li EmitCtorList(GlobalDtors, "llvm.global_dtors");
402*67e74705SXin Li EmitGlobalAnnotations();
403*67e74705SXin Li EmitStaticExternCAliases();
404*67e74705SXin Li EmitDeferredUnusedCoverageMappings();
405*67e74705SXin Li if (CoverageMapping)
406*67e74705SXin Li CoverageMapping->emit();
407*67e74705SXin Li if (CodeGenOpts.SanitizeCfiCrossDso)
408*67e74705SXin Li CodeGenFunction(*this).EmitCfiCheckFail();
409*67e74705SXin Li emitLLVMUsed();
410*67e74705SXin Li if (SanStats)
411*67e74705SXin Li SanStats->finish();
412*67e74705SXin Li
413*67e74705SXin Li if (CodeGenOpts.Autolink &&
414*67e74705SXin Li (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
415*67e74705SXin Li EmitModuleLinkOptions();
416*67e74705SXin Li }
417*67e74705SXin Li if (CodeGenOpts.DwarfVersion) {
418*67e74705SXin Li // We actually want the latest version when there are conflicts.
419*67e74705SXin Li // We can change from Warning to Latest if such mode is supported.
420*67e74705SXin Li getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
421*67e74705SXin Li CodeGenOpts.DwarfVersion);
422*67e74705SXin Li }
423*67e74705SXin Li if (CodeGenOpts.EmitCodeView) {
424*67e74705SXin Li // Indicate that we want CodeView in the metadata.
425*67e74705SXin Li getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
426*67e74705SXin Li }
427*67e74705SXin Li if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
428*67e74705SXin Li // We don't support LTO with 2 with different StrictVTablePointers
429*67e74705SXin Li // FIXME: we could support it by stripping all the information introduced
430*67e74705SXin Li // by StrictVTablePointers.
431*67e74705SXin Li
432*67e74705SXin Li getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
433*67e74705SXin Li
434*67e74705SXin Li llvm::Metadata *Ops[2] = {
435*67e74705SXin Li llvm::MDString::get(VMContext, "StrictVTablePointers"),
436*67e74705SXin Li llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
437*67e74705SXin Li llvm::Type::getInt32Ty(VMContext), 1))};
438*67e74705SXin Li
439*67e74705SXin Li getModule().addModuleFlag(llvm::Module::Require,
440*67e74705SXin Li "StrictVTablePointersRequirement",
441*67e74705SXin Li llvm::MDNode::get(VMContext, Ops));
442*67e74705SXin Li }
443*67e74705SXin Li if (DebugInfo)
444*67e74705SXin Li // We support a single version in the linked module. The LLVM
445*67e74705SXin Li // parser will drop debug info with a different version number
446*67e74705SXin Li // (and warn about it, too).
447*67e74705SXin Li getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
448*67e74705SXin Li llvm::DEBUG_METADATA_VERSION);
449*67e74705SXin Li
450*67e74705SXin Li // We need to record the widths of enums and wchar_t, so that we can generate
451*67e74705SXin Li // the correct build attributes in the ARM backend.
452*67e74705SXin Li llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
453*67e74705SXin Li if ( Arch == llvm::Triple::arm
454*67e74705SXin Li || Arch == llvm::Triple::armeb
455*67e74705SXin Li || Arch == llvm::Triple::thumb
456*67e74705SXin Li || Arch == llvm::Triple::thumbeb) {
457*67e74705SXin Li // Width of wchar_t in bytes
458*67e74705SXin Li uint64_t WCharWidth =
459*67e74705SXin Li Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
460*67e74705SXin Li getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
461*67e74705SXin Li
462*67e74705SXin Li // The minimum width of an enum in bytes
463*67e74705SXin Li uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
464*67e74705SXin Li getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
465*67e74705SXin Li }
466*67e74705SXin Li
467*67e74705SXin Li if (CodeGenOpts.SanitizeCfiCrossDso) {
468*67e74705SXin Li // Indicate that we want cross-DSO control flow integrity checks.
469*67e74705SXin Li getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
470*67e74705SXin Li }
471*67e74705SXin Li
472*67e74705SXin Li if (LangOpts.CUDAIsDevice && getTarget().getTriple().isNVPTX()) {
473*67e74705SXin Li // Indicate whether __nvvm_reflect should be configured to flush denormal
474*67e74705SXin Li // floating point values to 0. (This corresponds to its "__CUDA_FTZ"
475*67e74705SXin Li // property.)
476*67e74705SXin Li getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
477*67e74705SXin Li LangOpts.CUDADeviceFlushDenormalsToZero ? 1 : 0);
478*67e74705SXin Li }
479*67e74705SXin Li
480*67e74705SXin Li if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
481*67e74705SXin Li assert(PLevel < 3 && "Invalid PIC Level");
482*67e74705SXin Li getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
483*67e74705SXin Li if (Context.getLangOpts().PIE)
484*67e74705SXin Li getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
485*67e74705SXin Li }
486*67e74705SXin Li
487*67e74705SXin Li SimplifyPersonality();
488*67e74705SXin Li
489*67e74705SXin Li if (getCodeGenOpts().EmitDeclMetadata)
490*67e74705SXin Li EmitDeclMetadata();
491*67e74705SXin Li
492*67e74705SXin Li if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
493*67e74705SXin Li EmitCoverageFile();
494*67e74705SXin Li
495*67e74705SXin Li if (DebugInfo)
496*67e74705SXin Li DebugInfo->finalize();
497*67e74705SXin Li
498*67e74705SXin Li EmitVersionIdentMetadata();
499*67e74705SXin Li
500*67e74705SXin Li EmitTargetMetadata();
501*67e74705SXin Li }
502*67e74705SXin Li
UpdateCompletedType(const TagDecl * TD)503*67e74705SXin Li void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
504*67e74705SXin Li // Make sure that this type is translated.
505*67e74705SXin Li Types.UpdateCompletedType(TD);
506*67e74705SXin Li }
507*67e74705SXin Li
RefreshTypeCacheForClass(const CXXRecordDecl * RD)508*67e74705SXin Li void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
509*67e74705SXin Li // Make sure that this type is translated.
510*67e74705SXin Li Types.RefreshTypeCacheForClass(RD);
511*67e74705SXin Li }
512*67e74705SXin Li
getTBAAInfo(QualType QTy)513*67e74705SXin Li llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
514*67e74705SXin Li if (!TBAA)
515*67e74705SXin Li return nullptr;
516*67e74705SXin Li return TBAA->getTBAAInfo(QTy);
517*67e74705SXin Li }
518*67e74705SXin Li
getTBAAInfoForVTablePtr()519*67e74705SXin Li llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
520*67e74705SXin Li if (!TBAA)
521*67e74705SXin Li return nullptr;
522*67e74705SXin Li return TBAA->getTBAAInfoForVTablePtr();
523*67e74705SXin Li }
524*67e74705SXin Li
getTBAAStructInfo(QualType QTy)525*67e74705SXin Li llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
526*67e74705SXin Li if (!TBAA)
527*67e74705SXin Li return nullptr;
528*67e74705SXin Li return TBAA->getTBAAStructInfo(QTy);
529*67e74705SXin Li }
530*67e74705SXin Li
getTBAAStructTagInfo(QualType BaseTy,llvm::MDNode * AccessN,uint64_t O)531*67e74705SXin Li llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
532*67e74705SXin Li llvm::MDNode *AccessN,
533*67e74705SXin Li uint64_t O) {
534*67e74705SXin Li if (!TBAA)
535*67e74705SXin Li return nullptr;
536*67e74705SXin Li return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
537*67e74705SXin Li }
538*67e74705SXin Li
539*67e74705SXin Li /// Decorate the instruction with a TBAA tag. For both scalar TBAA
540*67e74705SXin Li /// and struct-path aware TBAA, the tag has the same format:
541*67e74705SXin Li /// base type, access type and offset.
542*67e74705SXin Li /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
DecorateInstructionWithTBAA(llvm::Instruction * Inst,llvm::MDNode * TBAAInfo,bool ConvertTypeToTag)543*67e74705SXin Li void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
544*67e74705SXin Li llvm::MDNode *TBAAInfo,
545*67e74705SXin Li bool ConvertTypeToTag) {
546*67e74705SXin Li if (ConvertTypeToTag && TBAA)
547*67e74705SXin Li Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
548*67e74705SXin Li TBAA->getTBAAScalarTagInfo(TBAAInfo));
549*67e74705SXin Li else
550*67e74705SXin Li Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
551*67e74705SXin Li }
552*67e74705SXin Li
DecorateInstructionWithInvariantGroup(llvm::Instruction * I,const CXXRecordDecl * RD)553*67e74705SXin Li void CodeGenModule::DecorateInstructionWithInvariantGroup(
554*67e74705SXin Li llvm::Instruction *I, const CXXRecordDecl *RD) {
555*67e74705SXin Li llvm::Metadata *MD = CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
556*67e74705SXin Li auto *MetaDataNode = dyn_cast<llvm::MDNode>(MD);
557*67e74705SXin Li // Check if we have to wrap MDString in MDNode.
558*67e74705SXin Li if (!MetaDataNode)
559*67e74705SXin Li MetaDataNode = llvm::MDNode::get(getLLVMContext(), MD);
560*67e74705SXin Li I->setMetadata(llvm::LLVMContext::MD_invariant_group, MetaDataNode);
561*67e74705SXin Li }
562*67e74705SXin Li
Error(SourceLocation loc,StringRef message)563*67e74705SXin Li void CodeGenModule::Error(SourceLocation loc, StringRef message) {
564*67e74705SXin Li unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
565*67e74705SXin Li getDiags().Report(Context.getFullLoc(loc), diagID) << message;
566*67e74705SXin Li }
567*67e74705SXin Li
568*67e74705SXin Li /// ErrorUnsupported - Print out an error that codegen doesn't support the
569*67e74705SXin Li /// specified stmt yet.
ErrorUnsupported(const Stmt * S,const char * Type)570*67e74705SXin Li void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
571*67e74705SXin Li unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
572*67e74705SXin Li "cannot compile this %0 yet");
573*67e74705SXin Li std::string Msg = Type;
574*67e74705SXin Li getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
575*67e74705SXin Li << Msg << S->getSourceRange();
576*67e74705SXin Li }
577*67e74705SXin Li
578*67e74705SXin Li /// ErrorUnsupported - Print out an error that codegen doesn't support the
579*67e74705SXin Li /// specified decl yet.
ErrorUnsupported(const Decl * D,const char * Type)580*67e74705SXin Li void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
581*67e74705SXin Li unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
582*67e74705SXin Li "cannot compile this %0 yet");
583*67e74705SXin Li std::string Msg = Type;
584*67e74705SXin Li getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
585*67e74705SXin Li }
586*67e74705SXin Li
getSize(CharUnits size)587*67e74705SXin Li llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
588*67e74705SXin Li return llvm::ConstantInt::get(SizeTy, size.getQuantity());
589*67e74705SXin Li }
590*67e74705SXin Li
setGlobalVisibility(llvm::GlobalValue * GV,const NamedDecl * D) const591*67e74705SXin Li void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
592*67e74705SXin Li const NamedDecl *D) const {
593*67e74705SXin Li // Internal definitions always have default visibility.
594*67e74705SXin Li if (GV->hasLocalLinkage()) {
595*67e74705SXin Li GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
596*67e74705SXin Li return;
597*67e74705SXin Li }
598*67e74705SXin Li
599*67e74705SXin Li // Set visibility for definitions.
600*67e74705SXin Li LinkageInfo LV = D->getLinkageAndVisibility();
601*67e74705SXin Li if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
602*67e74705SXin Li GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
603*67e74705SXin Li }
604*67e74705SXin Li
GetLLVMTLSModel(StringRef S)605*67e74705SXin Li static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
606*67e74705SXin Li return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
607*67e74705SXin Li .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
608*67e74705SXin Li .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
609*67e74705SXin Li .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
610*67e74705SXin Li .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
611*67e74705SXin Li }
612*67e74705SXin Li
GetLLVMTLSModel(CodeGenOptions::TLSModel M)613*67e74705SXin Li static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
614*67e74705SXin Li CodeGenOptions::TLSModel M) {
615*67e74705SXin Li switch (M) {
616*67e74705SXin Li case CodeGenOptions::GeneralDynamicTLSModel:
617*67e74705SXin Li return llvm::GlobalVariable::GeneralDynamicTLSModel;
618*67e74705SXin Li case CodeGenOptions::LocalDynamicTLSModel:
619*67e74705SXin Li return llvm::GlobalVariable::LocalDynamicTLSModel;
620*67e74705SXin Li case CodeGenOptions::InitialExecTLSModel:
621*67e74705SXin Li return llvm::GlobalVariable::InitialExecTLSModel;
622*67e74705SXin Li case CodeGenOptions::LocalExecTLSModel:
623*67e74705SXin Li return llvm::GlobalVariable::LocalExecTLSModel;
624*67e74705SXin Li }
625*67e74705SXin Li llvm_unreachable("Invalid TLS model!");
626*67e74705SXin Li }
627*67e74705SXin Li
setTLSMode(llvm::GlobalValue * GV,const VarDecl & D) const628*67e74705SXin Li void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
629*67e74705SXin Li assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
630*67e74705SXin Li
631*67e74705SXin Li llvm::GlobalValue::ThreadLocalMode TLM;
632*67e74705SXin Li TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
633*67e74705SXin Li
634*67e74705SXin Li // Override the TLS model if it is explicitly specified.
635*67e74705SXin Li if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
636*67e74705SXin Li TLM = GetLLVMTLSModel(Attr->getModel());
637*67e74705SXin Li }
638*67e74705SXin Li
639*67e74705SXin Li GV->setThreadLocalMode(TLM);
640*67e74705SXin Li }
641*67e74705SXin Li
getMangledName(GlobalDecl GD)642*67e74705SXin Li StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
643*67e74705SXin Li GlobalDecl CanonicalGD = GD.getCanonicalDecl();
644*67e74705SXin Li
645*67e74705SXin Li // Some ABIs don't have constructor variants. Make sure that base and
646*67e74705SXin Li // complete constructors get mangled the same.
647*67e74705SXin Li if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
648*67e74705SXin Li if (!getTarget().getCXXABI().hasConstructorVariants()) {
649*67e74705SXin Li CXXCtorType OrigCtorType = GD.getCtorType();
650*67e74705SXin Li assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
651*67e74705SXin Li if (OrigCtorType == Ctor_Base)
652*67e74705SXin Li CanonicalGD = GlobalDecl(CD, Ctor_Complete);
653*67e74705SXin Li }
654*67e74705SXin Li }
655*67e74705SXin Li
656*67e74705SXin Li StringRef &FoundStr = MangledDeclNames[CanonicalGD];
657*67e74705SXin Li if (!FoundStr.empty())
658*67e74705SXin Li return FoundStr;
659*67e74705SXin Li
660*67e74705SXin Li const auto *ND = cast<NamedDecl>(GD.getDecl());
661*67e74705SXin Li SmallString<256> Buffer;
662*67e74705SXin Li StringRef Str;
663*67e74705SXin Li if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
664*67e74705SXin Li llvm::raw_svector_ostream Out(Buffer);
665*67e74705SXin Li if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
666*67e74705SXin Li getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
667*67e74705SXin Li else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
668*67e74705SXin Li getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
669*67e74705SXin Li else
670*67e74705SXin Li getCXXABI().getMangleContext().mangleName(ND, Out);
671*67e74705SXin Li Str = Out.str();
672*67e74705SXin Li } else {
673*67e74705SXin Li IdentifierInfo *II = ND->getIdentifier();
674*67e74705SXin Li assert(II && "Attempt to mangle unnamed decl.");
675*67e74705SXin Li Str = II->getName();
676*67e74705SXin Li }
677*67e74705SXin Li
678*67e74705SXin Li // Keep the first result in the case of a mangling collision.
679*67e74705SXin Li auto Result = Manglings.insert(std::make_pair(Str, GD));
680*67e74705SXin Li return FoundStr = Result.first->first();
681*67e74705SXin Li }
682*67e74705SXin Li
getBlockMangledName(GlobalDecl GD,const BlockDecl * BD)683*67e74705SXin Li StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
684*67e74705SXin Li const BlockDecl *BD) {
685*67e74705SXin Li MangleContext &MangleCtx = getCXXABI().getMangleContext();
686*67e74705SXin Li const Decl *D = GD.getDecl();
687*67e74705SXin Li
688*67e74705SXin Li SmallString<256> Buffer;
689*67e74705SXin Li llvm::raw_svector_ostream Out(Buffer);
690*67e74705SXin Li if (!D)
691*67e74705SXin Li MangleCtx.mangleGlobalBlock(BD,
692*67e74705SXin Li dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
693*67e74705SXin Li else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
694*67e74705SXin Li MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
695*67e74705SXin Li else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
696*67e74705SXin Li MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
697*67e74705SXin Li else
698*67e74705SXin Li MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
699*67e74705SXin Li
700*67e74705SXin Li auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
701*67e74705SXin Li return Result.first->first();
702*67e74705SXin Li }
703*67e74705SXin Li
GetGlobalValue(StringRef Name)704*67e74705SXin Li llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
705*67e74705SXin Li return getModule().getNamedValue(Name);
706*67e74705SXin Li }
707*67e74705SXin Li
708*67e74705SXin Li /// AddGlobalCtor - Add a function to the list that will be called before
709*67e74705SXin Li /// main() runs.
AddGlobalCtor(llvm::Function * Ctor,int Priority,llvm::Constant * AssociatedData)710*67e74705SXin Li void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
711*67e74705SXin Li llvm::Constant *AssociatedData) {
712*67e74705SXin Li // FIXME: Type coercion of void()* types.
713*67e74705SXin Li GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
714*67e74705SXin Li }
715*67e74705SXin Li
716*67e74705SXin Li /// AddGlobalDtor - Add a function to the list that will be called
717*67e74705SXin Li /// when the module is unloaded.
AddGlobalDtor(llvm::Function * Dtor,int Priority)718*67e74705SXin Li void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
719*67e74705SXin Li // FIXME: Type coercion of void()* types.
720*67e74705SXin Li GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
721*67e74705SXin Li }
722*67e74705SXin Li
EmitCtorList(const CtorList & Fns,const char * GlobalName)723*67e74705SXin Li void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
724*67e74705SXin Li // Ctor function type is void()*.
725*67e74705SXin Li llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
726*67e74705SXin Li llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
727*67e74705SXin Li
728*67e74705SXin Li // Get the type of a ctor entry, { i32, void ()*, i8* }.
729*67e74705SXin Li llvm::StructType *CtorStructTy = llvm::StructType::get(
730*67e74705SXin Li Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy, nullptr);
731*67e74705SXin Li
732*67e74705SXin Li // Construct the constructor and destructor arrays.
733*67e74705SXin Li SmallVector<llvm::Constant *, 8> Ctors;
734*67e74705SXin Li for (const auto &I : Fns) {
735*67e74705SXin Li llvm::Constant *S[] = {
736*67e74705SXin Li llvm::ConstantInt::get(Int32Ty, I.Priority, false),
737*67e74705SXin Li llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy),
738*67e74705SXin Li (I.AssociatedData
739*67e74705SXin Li ? llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy)
740*67e74705SXin Li : llvm::Constant::getNullValue(VoidPtrTy))};
741*67e74705SXin Li Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
742*67e74705SXin Li }
743*67e74705SXin Li
744*67e74705SXin Li if (!Ctors.empty()) {
745*67e74705SXin Li llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
746*67e74705SXin Li new llvm::GlobalVariable(TheModule, AT, false,
747*67e74705SXin Li llvm::GlobalValue::AppendingLinkage,
748*67e74705SXin Li llvm::ConstantArray::get(AT, Ctors),
749*67e74705SXin Li GlobalName);
750*67e74705SXin Li }
751*67e74705SXin Li }
752*67e74705SXin Li
753*67e74705SXin Li llvm::GlobalValue::LinkageTypes
getFunctionLinkage(GlobalDecl GD)754*67e74705SXin Li CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
755*67e74705SXin Li const auto *D = cast<FunctionDecl>(GD.getDecl());
756*67e74705SXin Li
757*67e74705SXin Li GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
758*67e74705SXin Li
759*67e74705SXin Li if (isa<CXXDestructorDecl>(D) &&
760*67e74705SXin Li getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
761*67e74705SXin Li GD.getDtorType())) {
762*67e74705SXin Li // Destructor variants in the Microsoft C++ ABI are always internal or
763*67e74705SXin Li // linkonce_odr thunks emitted on an as-needed basis.
764*67e74705SXin Li return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
765*67e74705SXin Li : llvm::GlobalValue::LinkOnceODRLinkage;
766*67e74705SXin Li }
767*67e74705SXin Li
768*67e74705SXin Li if (isa<CXXConstructorDecl>(D) &&
769*67e74705SXin Li cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
770*67e74705SXin Li Context.getTargetInfo().getCXXABI().isMicrosoft()) {
771*67e74705SXin Li // Our approach to inheriting constructors is fundamentally different from
772*67e74705SXin Li // that used by the MS ABI, so keep our inheriting constructor thunks
773*67e74705SXin Li // internal rather than trying to pick an unambiguous mangling for them.
774*67e74705SXin Li return llvm::GlobalValue::InternalLinkage;
775*67e74705SXin Li }
776*67e74705SXin Li
777*67e74705SXin Li return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
778*67e74705SXin Li }
779*67e74705SXin Li
setFunctionDLLStorageClass(GlobalDecl GD,llvm::Function * F)780*67e74705SXin Li void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) {
781*67e74705SXin Li const auto *FD = cast<FunctionDecl>(GD.getDecl());
782*67e74705SXin Li
783*67e74705SXin Li if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
784*67e74705SXin Li if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
785*67e74705SXin Li // Don't dllexport/import destructor thunks.
786*67e74705SXin Li F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
787*67e74705SXin Li return;
788*67e74705SXin Li }
789*67e74705SXin Li }
790*67e74705SXin Li
791*67e74705SXin Li if (FD->hasAttr<DLLImportAttr>())
792*67e74705SXin Li F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
793*67e74705SXin Li else if (FD->hasAttr<DLLExportAttr>())
794*67e74705SXin Li F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
795*67e74705SXin Li else
796*67e74705SXin Li F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
797*67e74705SXin Li }
798*67e74705SXin Li
CreateCrossDsoCfiTypeId(llvm::Metadata * MD)799*67e74705SXin Li llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
800*67e74705SXin Li llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
801*67e74705SXin Li if (!MDS) return nullptr;
802*67e74705SXin Li
803*67e74705SXin Li llvm::MD5 md5;
804*67e74705SXin Li llvm::MD5::MD5Result result;
805*67e74705SXin Li md5.update(MDS->getString());
806*67e74705SXin Li md5.final(result);
807*67e74705SXin Li uint64_t id = 0;
808*67e74705SXin Li for (int i = 0; i < 8; ++i)
809*67e74705SXin Li id |= static_cast<uint64_t>(result[i]) << (i * 8);
810*67e74705SXin Li return llvm::ConstantInt::get(Int64Ty, id);
811*67e74705SXin Li }
812*67e74705SXin Li
setFunctionDefinitionAttributes(const FunctionDecl * D,llvm::Function * F)813*67e74705SXin Li void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D,
814*67e74705SXin Li llvm::Function *F) {
815*67e74705SXin Li setNonAliasAttributes(D, F);
816*67e74705SXin Li }
817*67e74705SXin Li
SetLLVMFunctionAttributes(const Decl * D,const CGFunctionInfo & Info,llvm::Function * F)818*67e74705SXin Li void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
819*67e74705SXin Li const CGFunctionInfo &Info,
820*67e74705SXin Li llvm::Function *F) {
821*67e74705SXin Li unsigned CallingConv;
822*67e74705SXin Li AttributeListType AttributeList;
823*67e74705SXin Li ConstructAttributeList(F->getName(), Info, D, AttributeList, CallingConv,
824*67e74705SXin Li false);
825*67e74705SXin Li F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList));
826*67e74705SXin Li F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
827*67e74705SXin Li }
828*67e74705SXin Li
829*67e74705SXin Li /// Determines whether the language options require us to model
830*67e74705SXin Li /// unwind exceptions. We treat -fexceptions as mandating this
831*67e74705SXin Li /// except under the fragile ObjC ABI with only ObjC exceptions
832*67e74705SXin Li /// enabled. This means, for example, that C with -fexceptions
833*67e74705SXin Li /// enables this.
hasUnwindExceptions(const LangOptions & LangOpts)834*67e74705SXin Li static bool hasUnwindExceptions(const LangOptions &LangOpts) {
835*67e74705SXin Li // If exceptions are completely disabled, obviously this is false.
836*67e74705SXin Li if (!LangOpts.Exceptions) return false;
837*67e74705SXin Li
838*67e74705SXin Li // If C++ exceptions are enabled, this is true.
839*67e74705SXin Li if (LangOpts.CXXExceptions) return true;
840*67e74705SXin Li
841*67e74705SXin Li // If ObjC exceptions are enabled, this depends on the ABI.
842*67e74705SXin Li if (LangOpts.ObjCExceptions) {
843*67e74705SXin Li return LangOpts.ObjCRuntime.hasUnwindExceptions();
844*67e74705SXin Li }
845*67e74705SXin Li
846*67e74705SXin Li return true;
847*67e74705SXin Li }
848*67e74705SXin Li
SetLLVMFunctionAttributesForDefinition(const Decl * D,llvm::Function * F)849*67e74705SXin Li void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
850*67e74705SXin Li llvm::Function *F) {
851*67e74705SXin Li llvm::AttrBuilder B;
852*67e74705SXin Li
853*67e74705SXin Li if (CodeGenOpts.UnwindTables)
854*67e74705SXin Li B.addAttribute(llvm::Attribute::UWTable);
855*67e74705SXin Li
856*67e74705SXin Li if (!hasUnwindExceptions(LangOpts))
857*67e74705SXin Li B.addAttribute(llvm::Attribute::NoUnwind);
858*67e74705SXin Li
859*67e74705SXin Li if (LangOpts.getStackProtector() == LangOptions::SSPOn)
860*67e74705SXin Li B.addAttribute(llvm::Attribute::StackProtect);
861*67e74705SXin Li else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
862*67e74705SXin Li B.addAttribute(llvm::Attribute::StackProtectStrong);
863*67e74705SXin Li else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
864*67e74705SXin Li B.addAttribute(llvm::Attribute::StackProtectReq);
865*67e74705SXin Li
866*67e74705SXin Li if (!D) {
867*67e74705SXin Li F->addAttributes(llvm::AttributeSet::FunctionIndex,
868*67e74705SXin Li llvm::AttributeSet::get(
869*67e74705SXin Li F->getContext(),
870*67e74705SXin Li llvm::AttributeSet::FunctionIndex, B));
871*67e74705SXin Li return;
872*67e74705SXin Li }
873*67e74705SXin Li
874*67e74705SXin Li if (D->hasAttr<NakedAttr>()) {
875*67e74705SXin Li // Naked implies noinline: we should not be inlining such functions.
876*67e74705SXin Li B.addAttribute(llvm::Attribute::Naked);
877*67e74705SXin Li B.addAttribute(llvm::Attribute::NoInline);
878*67e74705SXin Li } else if (D->hasAttr<NoDuplicateAttr>()) {
879*67e74705SXin Li B.addAttribute(llvm::Attribute::NoDuplicate);
880*67e74705SXin Li } else if (D->hasAttr<NoInlineAttr>()) {
881*67e74705SXin Li B.addAttribute(llvm::Attribute::NoInline);
882*67e74705SXin Li } else if (D->hasAttr<AlwaysInlineAttr>() &&
883*67e74705SXin Li !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex,
884*67e74705SXin Li llvm::Attribute::NoInline)) {
885*67e74705SXin Li // (noinline wins over always_inline, and we can't specify both in IR)
886*67e74705SXin Li B.addAttribute(llvm::Attribute::AlwaysInline);
887*67e74705SXin Li }
888*67e74705SXin Li
889*67e74705SXin Li if (D->hasAttr<ColdAttr>()) {
890*67e74705SXin Li if (!D->hasAttr<OptimizeNoneAttr>())
891*67e74705SXin Li B.addAttribute(llvm::Attribute::OptimizeForSize);
892*67e74705SXin Li B.addAttribute(llvm::Attribute::Cold);
893*67e74705SXin Li }
894*67e74705SXin Li
895*67e74705SXin Li if (D->hasAttr<MinSizeAttr>())
896*67e74705SXin Li B.addAttribute(llvm::Attribute::MinSize);
897*67e74705SXin Li
898*67e74705SXin Li F->addAttributes(llvm::AttributeSet::FunctionIndex,
899*67e74705SXin Li llvm::AttributeSet::get(
900*67e74705SXin Li F->getContext(), llvm::AttributeSet::FunctionIndex, B));
901*67e74705SXin Li
902*67e74705SXin Li if (D->hasAttr<OptimizeNoneAttr>()) {
903*67e74705SXin Li // OptimizeNone implies noinline; we should not be inlining such functions.
904*67e74705SXin Li F->addFnAttr(llvm::Attribute::OptimizeNone);
905*67e74705SXin Li F->addFnAttr(llvm::Attribute::NoInline);
906*67e74705SXin Li
907*67e74705SXin Li // OptimizeNone wins over OptimizeForSize, MinSize, AlwaysInline.
908*67e74705SXin Li F->removeFnAttr(llvm::Attribute::OptimizeForSize);
909*67e74705SXin Li F->removeFnAttr(llvm::Attribute::MinSize);
910*67e74705SXin Li assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
911*67e74705SXin Li "OptimizeNone and AlwaysInline on same function!");
912*67e74705SXin Li
913*67e74705SXin Li // Attribute 'inlinehint' has no effect on 'optnone' functions.
914*67e74705SXin Li // Explicitly remove it from the set of function attributes.
915*67e74705SXin Li F->removeFnAttr(llvm::Attribute::InlineHint);
916*67e74705SXin Li }
917*67e74705SXin Li
918*67e74705SXin Li unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
919*67e74705SXin Li if (alignment)
920*67e74705SXin Li F->setAlignment(alignment);
921*67e74705SXin Li
922*67e74705SXin Li // Some C++ ABIs require 2-byte alignment for member functions, in order to
923*67e74705SXin Li // reserve a bit for differentiating between virtual and non-virtual member
924*67e74705SXin Li // functions. If the current target's C++ ABI requires this and this is a
925*67e74705SXin Li // member function, set its alignment accordingly.
926*67e74705SXin Li if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
927*67e74705SXin Li if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
928*67e74705SXin Li F->setAlignment(2);
929*67e74705SXin Li }
930*67e74705SXin Li }
931*67e74705SXin Li
SetCommonAttributes(const Decl * D,llvm::GlobalValue * GV)932*67e74705SXin Li void CodeGenModule::SetCommonAttributes(const Decl *D,
933*67e74705SXin Li llvm::GlobalValue *GV) {
934*67e74705SXin Li if (const auto *ND = dyn_cast_or_null<NamedDecl>(D))
935*67e74705SXin Li setGlobalVisibility(GV, ND);
936*67e74705SXin Li else
937*67e74705SXin Li GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
938*67e74705SXin Li
939*67e74705SXin Li if (D && D->hasAttr<UsedAttr>())
940*67e74705SXin Li addUsedGlobal(GV);
941*67e74705SXin Li }
942*67e74705SXin Li
setAliasAttributes(const Decl * D,llvm::GlobalValue * GV)943*67e74705SXin Li void CodeGenModule::setAliasAttributes(const Decl *D,
944*67e74705SXin Li llvm::GlobalValue *GV) {
945*67e74705SXin Li SetCommonAttributes(D, GV);
946*67e74705SXin Li
947*67e74705SXin Li // Process the dllexport attribute based on whether the original definition
948*67e74705SXin Li // (not necessarily the aliasee) was exported.
949*67e74705SXin Li if (D->hasAttr<DLLExportAttr>())
950*67e74705SXin Li GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
951*67e74705SXin Li }
952*67e74705SXin Li
setNonAliasAttributes(const Decl * D,llvm::GlobalObject * GO)953*67e74705SXin Li void CodeGenModule::setNonAliasAttributes(const Decl *D,
954*67e74705SXin Li llvm::GlobalObject *GO) {
955*67e74705SXin Li SetCommonAttributes(D, GO);
956*67e74705SXin Li
957*67e74705SXin Li if (D)
958*67e74705SXin Li if (const SectionAttr *SA = D->getAttr<SectionAttr>())
959*67e74705SXin Li GO->setSection(SA->getName());
960*67e74705SXin Li
961*67e74705SXin Li getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
962*67e74705SXin Li }
963*67e74705SXin Li
SetInternalFunctionAttributes(const Decl * D,llvm::Function * F,const CGFunctionInfo & FI)964*67e74705SXin Li void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
965*67e74705SXin Li llvm::Function *F,
966*67e74705SXin Li const CGFunctionInfo &FI) {
967*67e74705SXin Li SetLLVMFunctionAttributes(D, FI, F);
968*67e74705SXin Li SetLLVMFunctionAttributesForDefinition(D, F);
969*67e74705SXin Li
970*67e74705SXin Li F->setLinkage(llvm::Function::InternalLinkage);
971*67e74705SXin Li
972*67e74705SXin Li setNonAliasAttributes(D, F);
973*67e74705SXin Li }
974*67e74705SXin Li
setLinkageAndVisibilityForGV(llvm::GlobalValue * GV,const NamedDecl * ND)975*67e74705SXin Li static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV,
976*67e74705SXin Li const NamedDecl *ND) {
977*67e74705SXin Li // Set linkage and visibility in case we never see a definition.
978*67e74705SXin Li LinkageInfo LV = ND->getLinkageAndVisibility();
979*67e74705SXin Li if (LV.getLinkage() != ExternalLinkage) {
980*67e74705SXin Li // Don't set internal linkage on declarations.
981*67e74705SXin Li } else {
982*67e74705SXin Li if (ND->hasAttr<DLLImportAttr>()) {
983*67e74705SXin Li GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
984*67e74705SXin Li GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
985*67e74705SXin Li } else if (ND->hasAttr<DLLExportAttr>()) {
986*67e74705SXin Li GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
987*67e74705SXin Li GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
988*67e74705SXin Li } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) {
989*67e74705SXin Li // "extern_weak" is overloaded in LLVM; we probably should have
990*67e74705SXin Li // separate linkage types for this.
991*67e74705SXin Li GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
992*67e74705SXin Li }
993*67e74705SXin Li
994*67e74705SXin Li // Set visibility on a declaration only if it's explicit.
995*67e74705SXin Li if (LV.isVisibilityExplicit())
996*67e74705SXin Li GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility()));
997*67e74705SXin Li }
998*67e74705SXin Li }
999*67e74705SXin Li
CreateFunctionTypeMetadata(const FunctionDecl * FD,llvm::Function * F)1000*67e74705SXin Li void CodeGenModule::CreateFunctionTypeMetadata(const FunctionDecl *FD,
1001*67e74705SXin Li llvm::Function *F) {
1002*67e74705SXin Li // Only if we are checking indirect calls.
1003*67e74705SXin Li if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
1004*67e74705SXin Li return;
1005*67e74705SXin Li
1006*67e74705SXin Li // Non-static class methods are handled via vtable pointer checks elsewhere.
1007*67e74705SXin Li if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
1008*67e74705SXin Li return;
1009*67e74705SXin Li
1010*67e74705SXin Li // Additionally, if building with cross-DSO support...
1011*67e74705SXin Li if (CodeGenOpts.SanitizeCfiCrossDso) {
1012*67e74705SXin Li // Don't emit entries for function declarations. In cross-DSO mode these are
1013*67e74705SXin Li // handled with better precision at run time.
1014*67e74705SXin Li if (!FD->hasBody())
1015*67e74705SXin Li return;
1016*67e74705SXin Li // Skip available_externally functions. They won't be codegen'ed in the
1017*67e74705SXin Li // current module anyway.
1018*67e74705SXin Li if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
1019*67e74705SXin Li return;
1020*67e74705SXin Li }
1021*67e74705SXin Li
1022*67e74705SXin Li llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
1023*67e74705SXin Li F->addTypeMetadata(0, MD);
1024*67e74705SXin Li
1025*67e74705SXin Li // Emit a hash-based bit set entry for cross-DSO calls.
1026*67e74705SXin Li if (CodeGenOpts.SanitizeCfiCrossDso)
1027*67e74705SXin Li if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
1028*67e74705SXin Li F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
1029*67e74705SXin Li }
1030*67e74705SXin Li
SetFunctionAttributes(GlobalDecl GD,llvm::Function * F,bool IsIncompleteFunction,bool IsThunk)1031*67e74705SXin Li void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1032*67e74705SXin Li bool IsIncompleteFunction,
1033*67e74705SXin Li bool IsThunk) {
1034*67e74705SXin Li if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
1035*67e74705SXin Li // If this is an intrinsic function, set the function's attributes
1036*67e74705SXin Li // to the intrinsic's attributes.
1037*67e74705SXin Li F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
1038*67e74705SXin Li return;
1039*67e74705SXin Li }
1040*67e74705SXin Li
1041*67e74705SXin Li const auto *FD = cast<FunctionDecl>(GD.getDecl());
1042*67e74705SXin Li
1043*67e74705SXin Li if (!IsIncompleteFunction)
1044*67e74705SXin Li SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
1045*67e74705SXin Li
1046*67e74705SXin Li // Add the Returned attribute for "this", except for iOS 5 and earlier
1047*67e74705SXin Li // where substantial code, including the libstdc++ dylib, was compiled with
1048*67e74705SXin Li // GCC and does not actually return "this".
1049*67e74705SXin Li if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
1050*67e74705SXin Li !(getTarget().getTriple().isiOS() &&
1051*67e74705SXin Li getTarget().getTriple().isOSVersionLT(6))) {
1052*67e74705SXin Li assert(!F->arg_empty() &&
1053*67e74705SXin Li F->arg_begin()->getType()
1054*67e74705SXin Li ->canLosslesslyBitCastTo(F->getReturnType()) &&
1055*67e74705SXin Li "unexpected this return");
1056*67e74705SXin Li F->addAttribute(1, llvm::Attribute::Returned);
1057*67e74705SXin Li }
1058*67e74705SXin Li
1059*67e74705SXin Li // Only a few attributes are set on declarations; these may later be
1060*67e74705SXin Li // overridden by a definition.
1061*67e74705SXin Li
1062*67e74705SXin Li setLinkageAndVisibilityForGV(F, FD);
1063*67e74705SXin Li
1064*67e74705SXin Li if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
1065*67e74705SXin Li F->setSection(SA->getName());
1066*67e74705SXin Li
1067*67e74705SXin Li if (FD->isReplaceableGlobalAllocationFunction()) {
1068*67e74705SXin Li // A replaceable global allocation function does not act like a builtin by
1069*67e74705SXin Li // default, only if it is invoked by a new-expression or delete-expression.
1070*67e74705SXin Li F->addAttribute(llvm::AttributeSet::FunctionIndex,
1071*67e74705SXin Li llvm::Attribute::NoBuiltin);
1072*67e74705SXin Li
1073*67e74705SXin Li // A sane operator new returns a non-aliasing pointer.
1074*67e74705SXin Li // FIXME: Also add NonNull attribute to the return value
1075*67e74705SXin Li // for the non-nothrow forms?
1076*67e74705SXin Li auto Kind = FD->getDeclName().getCXXOverloadedOperator();
1077*67e74705SXin Li if (getCodeGenOpts().AssumeSaneOperatorNew &&
1078*67e74705SXin Li (Kind == OO_New || Kind == OO_Array_New))
1079*67e74705SXin Li F->addAttribute(llvm::AttributeSet::ReturnIndex,
1080*67e74705SXin Li llvm::Attribute::NoAlias);
1081*67e74705SXin Li }
1082*67e74705SXin Li
1083*67e74705SXin Li if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
1084*67e74705SXin Li F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1085*67e74705SXin Li else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1086*67e74705SXin Li if (MD->isVirtual())
1087*67e74705SXin Li F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1088*67e74705SXin Li
1089*67e74705SXin Li CreateFunctionTypeMetadata(FD, F);
1090*67e74705SXin Li }
1091*67e74705SXin Li
addUsedGlobal(llvm::GlobalValue * GV)1092*67e74705SXin Li void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
1093*67e74705SXin Li assert(!GV->isDeclaration() &&
1094*67e74705SXin Li "Only globals with definition can force usage.");
1095*67e74705SXin Li LLVMUsed.emplace_back(GV);
1096*67e74705SXin Li }
1097*67e74705SXin Li
addCompilerUsedGlobal(llvm::GlobalValue * GV)1098*67e74705SXin Li void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
1099*67e74705SXin Li assert(!GV->isDeclaration() &&
1100*67e74705SXin Li "Only globals with definition can force usage.");
1101*67e74705SXin Li LLVMCompilerUsed.emplace_back(GV);
1102*67e74705SXin Li }
1103*67e74705SXin Li
emitUsed(CodeGenModule & CGM,StringRef Name,std::vector<llvm::WeakVH> & List)1104*67e74705SXin Li static void emitUsed(CodeGenModule &CGM, StringRef Name,
1105*67e74705SXin Li std::vector<llvm::WeakVH> &List) {
1106*67e74705SXin Li // Don't create llvm.used if there is no need.
1107*67e74705SXin Li if (List.empty())
1108*67e74705SXin Li return;
1109*67e74705SXin Li
1110*67e74705SXin Li // Convert List to what ConstantArray needs.
1111*67e74705SXin Li SmallVector<llvm::Constant*, 8> UsedArray;
1112*67e74705SXin Li UsedArray.resize(List.size());
1113*67e74705SXin Li for (unsigned i = 0, e = List.size(); i != e; ++i) {
1114*67e74705SXin Li UsedArray[i] =
1115*67e74705SXin Li llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1116*67e74705SXin Li cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
1117*67e74705SXin Li }
1118*67e74705SXin Li
1119*67e74705SXin Li if (UsedArray.empty())
1120*67e74705SXin Li return;
1121*67e74705SXin Li llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
1122*67e74705SXin Li
1123*67e74705SXin Li auto *GV = new llvm::GlobalVariable(
1124*67e74705SXin Li CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
1125*67e74705SXin Li llvm::ConstantArray::get(ATy, UsedArray), Name);
1126*67e74705SXin Li
1127*67e74705SXin Li GV->setSection("llvm.metadata");
1128*67e74705SXin Li }
1129*67e74705SXin Li
emitLLVMUsed()1130*67e74705SXin Li void CodeGenModule::emitLLVMUsed() {
1131*67e74705SXin Li emitUsed(*this, "llvm.used", LLVMUsed);
1132*67e74705SXin Li emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
1133*67e74705SXin Li }
1134*67e74705SXin Li
AppendLinkerOptions(StringRef Opts)1135*67e74705SXin Li void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
1136*67e74705SXin Li auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
1137*67e74705SXin Li LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1138*67e74705SXin Li }
1139*67e74705SXin Li
AddDetectMismatch(StringRef Name,StringRef Value)1140*67e74705SXin Li void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
1141*67e74705SXin Li llvm::SmallString<32> Opt;
1142*67e74705SXin Li getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
1143*67e74705SXin Li auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1144*67e74705SXin Li LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1145*67e74705SXin Li }
1146*67e74705SXin Li
AddDependentLib(StringRef Lib)1147*67e74705SXin Li void CodeGenModule::AddDependentLib(StringRef Lib) {
1148*67e74705SXin Li llvm::SmallString<24> Opt;
1149*67e74705SXin Li getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
1150*67e74705SXin Li auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1151*67e74705SXin Li LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1152*67e74705SXin Li }
1153*67e74705SXin Li
1154*67e74705SXin Li /// \brief Add link options implied by the given module, including modules
1155*67e74705SXin Li /// it depends on, using a postorder walk.
addLinkOptionsPostorder(CodeGenModule & CGM,Module * Mod,SmallVectorImpl<llvm::Metadata * > & Metadata,llvm::SmallPtrSet<Module *,16> & Visited)1156*67e74705SXin Li static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
1157*67e74705SXin Li SmallVectorImpl<llvm::Metadata *> &Metadata,
1158*67e74705SXin Li llvm::SmallPtrSet<Module *, 16> &Visited) {
1159*67e74705SXin Li // Import this module's parent.
1160*67e74705SXin Li if (Mod->Parent && Visited.insert(Mod->Parent).second) {
1161*67e74705SXin Li addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
1162*67e74705SXin Li }
1163*67e74705SXin Li
1164*67e74705SXin Li // Import this module's dependencies.
1165*67e74705SXin Li for (unsigned I = Mod->Imports.size(); I > 0; --I) {
1166*67e74705SXin Li if (Visited.insert(Mod->Imports[I - 1]).second)
1167*67e74705SXin Li addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
1168*67e74705SXin Li }
1169*67e74705SXin Li
1170*67e74705SXin Li // Add linker options to link against the libraries/frameworks
1171*67e74705SXin Li // described by this module.
1172*67e74705SXin Li llvm::LLVMContext &Context = CGM.getLLVMContext();
1173*67e74705SXin Li for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
1174*67e74705SXin Li // Link against a framework. Frameworks are currently Darwin only, so we
1175*67e74705SXin Li // don't to ask TargetCodeGenInfo for the spelling of the linker option.
1176*67e74705SXin Li if (Mod->LinkLibraries[I-1].IsFramework) {
1177*67e74705SXin Li llvm::Metadata *Args[2] = {
1178*67e74705SXin Li llvm::MDString::get(Context, "-framework"),
1179*67e74705SXin Li llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
1180*67e74705SXin Li
1181*67e74705SXin Li Metadata.push_back(llvm::MDNode::get(Context, Args));
1182*67e74705SXin Li continue;
1183*67e74705SXin Li }
1184*67e74705SXin Li
1185*67e74705SXin Li // Link against a library.
1186*67e74705SXin Li llvm::SmallString<24> Opt;
1187*67e74705SXin Li CGM.getTargetCodeGenInfo().getDependentLibraryOption(
1188*67e74705SXin Li Mod->LinkLibraries[I-1].Library, Opt);
1189*67e74705SXin Li auto *OptString = llvm::MDString::get(Context, Opt);
1190*67e74705SXin Li Metadata.push_back(llvm::MDNode::get(Context, OptString));
1191*67e74705SXin Li }
1192*67e74705SXin Li }
1193*67e74705SXin Li
EmitModuleLinkOptions()1194*67e74705SXin Li void CodeGenModule::EmitModuleLinkOptions() {
1195*67e74705SXin Li // Collect the set of all of the modules we want to visit to emit link
1196*67e74705SXin Li // options, which is essentially the imported modules and all of their
1197*67e74705SXin Li // non-explicit child modules.
1198*67e74705SXin Li llvm::SetVector<clang::Module *> LinkModules;
1199*67e74705SXin Li llvm::SmallPtrSet<clang::Module *, 16> Visited;
1200*67e74705SXin Li SmallVector<clang::Module *, 16> Stack;
1201*67e74705SXin Li
1202*67e74705SXin Li // Seed the stack with imported modules.
1203*67e74705SXin Li for (Module *M : ImportedModules)
1204*67e74705SXin Li if (Visited.insert(M).second)
1205*67e74705SXin Li Stack.push_back(M);
1206*67e74705SXin Li
1207*67e74705SXin Li // Find all of the modules to import, making a little effort to prune
1208*67e74705SXin Li // non-leaf modules.
1209*67e74705SXin Li while (!Stack.empty()) {
1210*67e74705SXin Li clang::Module *Mod = Stack.pop_back_val();
1211*67e74705SXin Li
1212*67e74705SXin Li bool AnyChildren = false;
1213*67e74705SXin Li
1214*67e74705SXin Li // Visit the submodules of this module.
1215*67e74705SXin Li for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
1216*67e74705SXin Li SubEnd = Mod->submodule_end();
1217*67e74705SXin Li Sub != SubEnd; ++Sub) {
1218*67e74705SXin Li // Skip explicit children; they need to be explicitly imported to be
1219*67e74705SXin Li // linked against.
1220*67e74705SXin Li if ((*Sub)->IsExplicit)
1221*67e74705SXin Li continue;
1222*67e74705SXin Li
1223*67e74705SXin Li if (Visited.insert(*Sub).second) {
1224*67e74705SXin Li Stack.push_back(*Sub);
1225*67e74705SXin Li AnyChildren = true;
1226*67e74705SXin Li }
1227*67e74705SXin Li }
1228*67e74705SXin Li
1229*67e74705SXin Li // We didn't find any children, so add this module to the list of
1230*67e74705SXin Li // modules to link against.
1231*67e74705SXin Li if (!AnyChildren) {
1232*67e74705SXin Li LinkModules.insert(Mod);
1233*67e74705SXin Li }
1234*67e74705SXin Li }
1235*67e74705SXin Li
1236*67e74705SXin Li // Add link options for all of the imported modules in reverse topological
1237*67e74705SXin Li // order. We don't do anything to try to order import link flags with respect
1238*67e74705SXin Li // to linker options inserted by things like #pragma comment().
1239*67e74705SXin Li SmallVector<llvm::Metadata *, 16> MetadataArgs;
1240*67e74705SXin Li Visited.clear();
1241*67e74705SXin Li for (Module *M : LinkModules)
1242*67e74705SXin Li if (Visited.insert(M).second)
1243*67e74705SXin Li addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
1244*67e74705SXin Li std::reverse(MetadataArgs.begin(), MetadataArgs.end());
1245*67e74705SXin Li LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
1246*67e74705SXin Li
1247*67e74705SXin Li // Add the linker options metadata flag.
1248*67e74705SXin Li getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
1249*67e74705SXin Li llvm::MDNode::get(getLLVMContext(),
1250*67e74705SXin Li LinkerOptionsMetadata));
1251*67e74705SXin Li }
1252*67e74705SXin Li
EmitDeferred()1253*67e74705SXin Li void CodeGenModule::EmitDeferred() {
1254*67e74705SXin Li // Emit code for any potentially referenced deferred decls. Since a
1255*67e74705SXin Li // previously unused static decl may become used during the generation of code
1256*67e74705SXin Li // for a static function, iterate until no changes are made.
1257*67e74705SXin Li
1258*67e74705SXin Li if (!DeferredVTables.empty()) {
1259*67e74705SXin Li EmitDeferredVTables();
1260*67e74705SXin Li
1261*67e74705SXin Li // Emitting a vtable doesn't directly cause more vtables to
1262*67e74705SXin Li // become deferred, although it can cause functions to be
1263*67e74705SXin Li // emitted that then need those vtables.
1264*67e74705SXin Li assert(DeferredVTables.empty());
1265*67e74705SXin Li }
1266*67e74705SXin Li
1267*67e74705SXin Li // Stop if we're out of both deferred vtables and deferred declarations.
1268*67e74705SXin Li if (DeferredDeclsToEmit.empty())
1269*67e74705SXin Li return;
1270*67e74705SXin Li
1271*67e74705SXin Li // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
1272*67e74705SXin Li // work, it will not interfere with this.
1273*67e74705SXin Li std::vector<DeferredGlobal> CurDeclsToEmit;
1274*67e74705SXin Li CurDeclsToEmit.swap(DeferredDeclsToEmit);
1275*67e74705SXin Li
1276*67e74705SXin Li for (DeferredGlobal &G : CurDeclsToEmit) {
1277*67e74705SXin Li GlobalDecl D = G.GD;
1278*67e74705SXin Li G.GV = nullptr;
1279*67e74705SXin Li
1280*67e74705SXin Li // We should call GetAddrOfGlobal with IsForDefinition set to true in order
1281*67e74705SXin Li // to get GlobalValue with exactly the type we need, not something that
1282*67e74705SXin Li // might had been created for another decl with the same mangled name but
1283*67e74705SXin Li // different type.
1284*67e74705SXin Li llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
1285*67e74705SXin Li GetAddrOfGlobal(D, /*IsForDefinition=*/true));
1286*67e74705SXin Li
1287*67e74705SXin Li // In case of different address spaces, we may still get a cast, even with
1288*67e74705SXin Li // IsForDefinition equal to true. Query mangled names table to get
1289*67e74705SXin Li // GlobalValue.
1290*67e74705SXin Li if (!GV)
1291*67e74705SXin Li GV = GetGlobalValue(getMangledName(D));
1292*67e74705SXin Li
1293*67e74705SXin Li // Make sure GetGlobalValue returned non-null.
1294*67e74705SXin Li assert(GV);
1295*67e74705SXin Li
1296*67e74705SXin Li // Check to see if we've already emitted this. This is necessary
1297*67e74705SXin Li // for a couple of reasons: first, decls can end up in the
1298*67e74705SXin Li // deferred-decls queue multiple times, and second, decls can end
1299*67e74705SXin Li // up with definitions in unusual ways (e.g. by an extern inline
1300*67e74705SXin Li // function acquiring a strong function redefinition). Just
1301*67e74705SXin Li // ignore these cases.
1302*67e74705SXin Li if (!GV->isDeclaration())
1303*67e74705SXin Li continue;
1304*67e74705SXin Li
1305*67e74705SXin Li // Otherwise, emit the definition and move on to the next one.
1306*67e74705SXin Li EmitGlobalDefinition(D, GV);
1307*67e74705SXin Li
1308*67e74705SXin Li // If we found out that we need to emit more decls, do that recursively.
1309*67e74705SXin Li // This has the advantage that the decls are emitted in a DFS and related
1310*67e74705SXin Li // ones are close together, which is convenient for testing.
1311*67e74705SXin Li if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
1312*67e74705SXin Li EmitDeferred();
1313*67e74705SXin Li assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
1314*67e74705SXin Li }
1315*67e74705SXin Li }
1316*67e74705SXin Li }
1317*67e74705SXin Li
EmitGlobalAnnotations()1318*67e74705SXin Li void CodeGenModule::EmitGlobalAnnotations() {
1319*67e74705SXin Li if (Annotations.empty())
1320*67e74705SXin Li return;
1321*67e74705SXin Li
1322*67e74705SXin Li // Create a new global variable for the ConstantStruct in the Module.
1323*67e74705SXin Li llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1324*67e74705SXin Li Annotations[0]->getType(), Annotations.size()), Annotations);
1325*67e74705SXin Li auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
1326*67e74705SXin Li llvm::GlobalValue::AppendingLinkage,
1327*67e74705SXin Li Array, "llvm.global.annotations");
1328*67e74705SXin Li gv->setSection(AnnotationSection);
1329*67e74705SXin Li }
1330*67e74705SXin Li
EmitAnnotationString(StringRef Str)1331*67e74705SXin Li llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
1332*67e74705SXin Li llvm::Constant *&AStr = AnnotationStrings[Str];
1333*67e74705SXin Li if (AStr)
1334*67e74705SXin Li return AStr;
1335*67e74705SXin Li
1336*67e74705SXin Li // Not found yet, create a new global.
1337*67e74705SXin Li llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
1338*67e74705SXin Li auto *gv =
1339*67e74705SXin Li new llvm::GlobalVariable(getModule(), s->getType(), true,
1340*67e74705SXin Li llvm::GlobalValue::PrivateLinkage, s, ".str");
1341*67e74705SXin Li gv->setSection(AnnotationSection);
1342*67e74705SXin Li gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1343*67e74705SXin Li AStr = gv;
1344*67e74705SXin Li return gv;
1345*67e74705SXin Li }
1346*67e74705SXin Li
EmitAnnotationUnit(SourceLocation Loc)1347*67e74705SXin Li llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
1348*67e74705SXin Li SourceManager &SM = getContext().getSourceManager();
1349*67e74705SXin Li PresumedLoc PLoc = SM.getPresumedLoc(Loc);
1350*67e74705SXin Li if (PLoc.isValid())
1351*67e74705SXin Li return EmitAnnotationString(PLoc.getFilename());
1352*67e74705SXin Li return EmitAnnotationString(SM.getBufferName(Loc));
1353*67e74705SXin Li }
1354*67e74705SXin Li
EmitAnnotationLineNo(SourceLocation L)1355*67e74705SXin Li llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
1356*67e74705SXin Li SourceManager &SM = getContext().getSourceManager();
1357*67e74705SXin Li PresumedLoc PLoc = SM.getPresumedLoc(L);
1358*67e74705SXin Li unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
1359*67e74705SXin Li SM.getExpansionLineNumber(L);
1360*67e74705SXin Li return llvm::ConstantInt::get(Int32Ty, LineNo);
1361*67e74705SXin Li }
1362*67e74705SXin Li
EmitAnnotateAttr(llvm::GlobalValue * GV,const AnnotateAttr * AA,SourceLocation L)1363*67e74705SXin Li llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
1364*67e74705SXin Li const AnnotateAttr *AA,
1365*67e74705SXin Li SourceLocation L) {
1366*67e74705SXin Li // Get the globals for file name, annotation, and the line number.
1367*67e74705SXin Li llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
1368*67e74705SXin Li *UnitGV = EmitAnnotationUnit(L),
1369*67e74705SXin Li *LineNoCst = EmitAnnotationLineNo(L);
1370*67e74705SXin Li
1371*67e74705SXin Li // Create the ConstantStruct for the global annotation.
1372*67e74705SXin Li llvm::Constant *Fields[4] = {
1373*67e74705SXin Li llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
1374*67e74705SXin Li llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
1375*67e74705SXin Li llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
1376*67e74705SXin Li LineNoCst
1377*67e74705SXin Li };
1378*67e74705SXin Li return llvm::ConstantStruct::getAnon(Fields);
1379*67e74705SXin Li }
1380*67e74705SXin Li
AddGlobalAnnotations(const ValueDecl * D,llvm::GlobalValue * GV)1381*67e74705SXin Li void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
1382*67e74705SXin Li llvm::GlobalValue *GV) {
1383*67e74705SXin Li assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1384*67e74705SXin Li // Get the struct elements for these annotations.
1385*67e74705SXin Li for (const auto *I : D->specific_attrs<AnnotateAttr>())
1386*67e74705SXin Li Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
1387*67e74705SXin Li }
1388*67e74705SXin Li
isInSanitizerBlacklist(llvm::Function * Fn,SourceLocation Loc) const1389*67e74705SXin Li bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn,
1390*67e74705SXin Li SourceLocation Loc) const {
1391*67e74705SXin Li const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1392*67e74705SXin Li // Blacklist by function name.
1393*67e74705SXin Li if (SanitizerBL.isBlacklistedFunction(Fn->getName()))
1394*67e74705SXin Li return true;
1395*67e74705SXin Li // Blacklist by location.
1396*67e74705SXin Li if (Loc.isValid())
1397*67e74705SXin Li return SanitizerBL.isBlacklistedLocation(Loc);
1398*67e74705SXin Li // If location is unknown, this may be a compiler-generated function. Assume
1399*67e74705SXin Li // it's located in the main file.
1400*67e74705SXin Li auto &SM = Context.getSourceManager();
1401*67e74705SXin Li if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1402*67e74705SXin Li return SanitizerBL.isBlacklistedFile(MainFile->getName());
1403*67e74705SXin Li }
1404*67e74705SXin Li return false;
1405*67e74705SXin Li }
1406*67e74705SXin Li
isInSanitizerBlacklist(llvm::GlobalVariable * GV,SourceLocation Loc,QualType Ty,StringRef Category) const1407*67e74705SXin Li bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
1408*67e74705SXin Li SourceLocation Loc, QualType Ty,
1409*67e74705SXin Li StringRef Category) const {
1410*67e74705SXin Li // For now globals can be blacklisted only in ASan and KASan.
1411*67e74705SXin Li if (!LangOpts.Sanitize.hasOneOf(
1412*67e74705SXin Li SanitizerKind::Address | SanitizerKind::KernelAddress))
1413*67e74705SXin Li return false;
1414*67e74705SXin Li const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1415*67e74705SXin Li if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category))
1416*67e74705SXin Li return true;
1417*67e74705SXin Li if (SanitizerBL.isBlacklistedLocation(Loc, Category))
1418*67e74705SXin Li return true;
1419*67e74705SXin Li // Check global type.
1420*67e74705SXin Li if (!Ty.isNull()) {
1421*67e74705SXin Li // Drill down the array types: if global variable of a fixed type is
1422*67e74705SXin Li // blacklisted, we also don't instrument arrays of them.
1423*67e74705SXin Li while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
1424*67e74705SXin Li Ty = AT->getElementType();
1425*67e74705SXin Li Ty = Ty.getCanonicalType().getUnqualifiedType();
1426*67e74705SXin Li // We allow to blacklist only record types (classes, structs etc.)
1427*67e74705SXin Li if (Ty->isRecordType()) {
1428*67e74705SXin Li std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
1429*67e74705SXin Li if (SanitizerBL.isBlacklistedType(TypeStr, Category))
1430*67e74705SXin Li return true;
1431*67e74705SXin Li }
1432*67e74705SXin Li }
1433*67e74705SXin Li return false;
1434*67e74705SXin Li }
1435*67e74705SXin Li
MustBeEmitted(const ValueDecl * Global)1436*67e74705SXin Li bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
1437*67e74705SXin Li // Never defer when EmitAllDecls is specified.
1438*67e74705SXin Li if (LangOpts.EmitAllDecls)
1439*67e74705SXin Li return true;
1440*67e74705SXin Li
1441*67e74705SXin Li return getContext().DeclMustBeEmitted(Global);
1442*67e74705SXin Li }
1443*67e74705SXin Li
MayBeEmittedEagerly(const ValueDecl * Global)1444*67e74705SXin Li bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
1445*67e74705SXin Li if (const auto *FD = dyn_cast<FunctionDecl>(Global))
1446*67e74705SXin Li if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1447*67e74705SXin Li // Implicit template instantiations may change linkage if they are later
1448*67e74705SXin Li // explicitly instantiated, so they should not be emitted eagerly.
1449*67e74705SXin Li return false;
1450*67e74705SXin Li if (const auto *VD = dyn_cast<VarDecl>(Global))
1451*67e74705SXin Li if (Context.getInlineVariableDefinitionKind(VD) ==
1452*67e74705SXin Li ASTContext::InlineVariableDefinitionKind::WeakUnknown)
1453*67e74705SXin Li // A definition of an inline constexpr static data member may change
1454*67e74705SXin Li // linkage later if it's redeclared outside the class.
1455*67e74705SXin Li return false;
1456*67e74705SXin Li // If OpenMP is enabled and threadprivates must be generated like TLS, delay
1457*67e74705SXin Li // codegen for global variables, because they may be marked as threadprivate.
1458*67e74705SXin Li if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
1459*67e74705SXin Li getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global))
1460*67e74705SXin Li return false;
1461*67e74705SXin Li
1462*67e74705SXin Li return true;
1463*67e74705SXin Li }
1464*67e74705SXin Li
GetAddrOfUuidDescriptor(const CXXUuidofExpr * E)1465*67e74705SXin Li ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
1466*67e74705SXin Li const CXXUuidofExpr* E) {
1467*67e74705SXin Li // Sema has verified that IIDSource has a __declspec(uuid()), and that its
1468*67e74705SXin Li // well-formed.
1469*67e74705SXin Li StringRef Uuid = E->getUuidStr();
1470*67e74705SXin Li std::string Name = "_GUID_" + Uuid.lower();
1471*67e74705SXin Li std::replace(Name.begin(), Name.end(), '-', '_');
1472*67e74705SXin Li
1473*67e74705SXin Li // The UUID descriptor should be pointer aligned.
1474*67e74705SXin Li CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
1475*67e74705SXin Li
1476*67e74705SXin Li // Look for an existing global.
1477*67e74705SXin Li if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
1478*67e74705SXin Li return ConstantAddress(GV, Alignment);
1479*67e74705SXin Li
1480*67e74705SXin Li llvm::Constant *Init = EmitUuidofInitializer(Uuid);
1481*67e74705SXin Li assert(Init && "failed to initialize as constant");
1482*67e74705SXin Li
1483*67e74705SXin Li auto *GV = new llvm::GlobalVariable(
1484*67e74705SXin Li getModule(), Init->getType(),
1485*67e74705SXin Li /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
1486*67e74705SXin Li if (supportsCOMDAT())
1487*67e74705SXin Li GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
1488*67e74705SXin Li return ConstantAddress(GV, Alignment);
1489*67e74705SXin Li }
1490*67e74705SXin Li
GetWeakRefReference(const ValueDecl * VD)1491*67e74705SXin Li ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1492*67e74705SXin Li const AliasAttr *AA = VD->getAttr<AliasAttr>();
1493*67e74705SXin Li assert(AA && "No alias?");
1494*67e74705SXin Li
1495*67e74705SXin Li CharUnits Alignment = getContext().getDeclAlign(VD);
1496*67e74705SXin Li llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
1497*67e74705SXin Li
1498*67e74705SXin Li // See if there is already something with the target's name in the module.
1499*67e74705SXin Li llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
1500*67e74705SXin Li if (Entry) {
1501*67e74705SXin Li unsigned AS = getContext().getTargetAddressSpace(VD->getType());
1502*67e74705SXin Li auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
1503*67e74705SXin Li return ConstantAddress(Ptr, Alignment);
1504*67e74705SXin Li }
1505*67e74705SXin Li
1506*67e74705SXin Li llvm::Constant *Aliasee;
1507*67e74705SXin Li if (isa<llvm::FunctionType>(DeclTy))
1508*67e74705SXin Li Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1509*67e74705SXin Li GlobalDecl(cast<FunctionDecl>(VD)),
1510*67e74705SXin Li /*ForVTable=*/false);
1511*67e74705SXin Li else
1512*67e74705SXin Li Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1513*67e74705SXin Li llvm::PointerType::getUnqual(DeclTy),
1514*67e74705SXin Li nullptr);
1515*67e74705SXin Li
1516*67e74705SXin Li auto *F = cast<llvm::GlobalValue>(Aliasee);
1517*67e74705SXin Li F->setLinkage(llvm::Function::ExternalWeakLinkage);
1518*67e74705SXin Li WeakRefReferences.insert(F);
1519*67e74705SXin Li
1520*67e74705SXin Li return ConstantAddress(Aliasee, Alignment);
1521*67e74705SXin Li }
1522*67e74705SXin Li
EmitGlobal(GlobalDecl GD)1523*67e74705SXin Li void CodeGenModule::EmitGlobal(GlobalDecl GD) {
1524*67e74705SXin Li const auto *Global = cast<ValueDecl>(GD.getDecl());
1525*67e74705SXin Li
1526*67e74705SXin Li // Weak references don't produce any output by themselves.
1527*67e74705SXin Li if (Global->hasAttr<WeakRefAttr>())
1528*67e74705SXin Li return;
1529*67e74705SXin Li
1530*67e74705SXin Li // If this is an alias definition (which otherwise looks like a declaration)
1531*67e74705SXin Li // emit it now.
1532*67e74705SXin Li if (Global->hasAttr<AliasAttr>())
1533*67e74705SXin Li return EmitAliasDefinition(GD);
1534*67e74705SXin Li
1535*67e74705SXin Li // IFunc like an alias whose value is resolved at runtime by calling resolver.
1536*67e74705SXin Li if (Global->hasAttr<IFuncAttr>())
1537*67e74705SXin Li return emitIFuncDefinition(GD);
1538*67e74705SXin Li
1539*67e74705SXin Li // If this is CUDA, be selective about which declarations we emit.
1540*67e74705SXin Li if (LangOpts.CUDA) {
1541*67e74705SXin Li if (LangOpts.CUDAIsDevice) {
1542*67e74705SXin Li if (!Global->hasAttr<CUDADeviceAttr>() &&
1543*67e74705SXin Li !Global->hasAttr<CUDAGlobalAttr>() &&
1544*67e74705SXin Li !Global->hasAttr<CUDAConstantAttr>() &&
1545*67e74705SXin Li !Global->hasAttr<CUDASharedAttr>())
1546*67e74705SXin Li return;
1547*67e74705SXin Li } else {
1548*67e74705SXin Li // We need to emit host-side 'shadows' for all global
1549*67e74705SXin Li // device-side variables because the CUDA runtime needs their
1550*67e74705SXin Li // size and host-side address in order to provide access to
1551*67e74705SXin Li // their device-side incarnations.
1552*67e74705SXin Li
1553*67e74705SXin Li // So device-only functions are the only things we skip.
1554*67e74705SXin Li if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
1555*67e74705SXin Li Global->hasAttr<CUDADeviceAttr>())
1556*67e74705SXin Li return;
1557*67e74705SXin Li
1558*67e74705SXin Li assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
1559*67e74705SXin Li "Expected Variable or Function");
1560*67e74705SXin Li }
1561*67e74705SXin Li }
1562*67e74705SXin Li
1563*67e74705SXin Li if (LangOpts.OpenMP) {
1564*67e74705SXin Li // If this is OpenMP device, check if it is legal to emit this global
1565*67e74705SXin Li // normally.
1566*67e74705SXin Li if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
1567*67e74705SXin Li return;
1568*67e74705SXin Li if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
1569*67e74705SXin Li if (MustBeEmitted(Global))
1570*67e74705SXin Li EmitOMPDeclareReduction(DRD);
1571*67e74705SXin Li return;
1572*67e74705SXin Li }
1573*67e74705SXin Li }
1574*67e74705SXin Li
1575*67e74705SXin Li // Ignore declarations, they will be emitted on their first use.
1576*67e74705SXin Li if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
1577*67e74705SXin Li // Forward declarations are emitted lazily on first use.
1578*67e74705SXin Li if (!FD->doesThisDeclarationHaveABody()) {
1579*67e74705SXin Li if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1580*67e74705SXin Li return;
1581*67e74705SXin Li
1582*67e74705SXin Li StringRef MangledName = getMangledName(GD);
1583*67e74705SXin Li
1584*67e74705SXin Li // Compute the function info and LLVM type.
1585*67e74705SXin Li const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
1586*67e74705SXin Li llvm::Type *Ty = getTypes().GetFunctionType(FI);
1587*67e74705SXin Li
1588*67e74705SXin Li GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
1589*67e74705SXin Li /*DontDefer=*/false);
1590*67e74705SXin Li return;
1591*67e74705SXin Li }
1592*67e74705SXin Li } else {
1593*67e74705SXin Li const auto *VD = cast<VarDecl>(Global);
1594*67e74705SXin Li assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1595*67e74705SXin Li // We need to emit device-side global CUDA variables even if a
1596*67e74705SXin Li // variable does not have a definition -- we still need to define
1597*67e74705SXin Li // host-side shadow for it.
1598*67e74705SXin Li bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
1599*67e74705SXin Li !VD->hasDefinition() &&
1600*67e74705SXin Li (VD->hasAttr<CUDAConstantAttr>() ||
1601*67e74705SXin Li VD->hasAttr<CUDADeviceAttr>());
1602*67e74705SXin Li if (!MustEmitForCuda &&
1603*67e74705SXin Li VD->isThisDeclarationADefinition() != VarDecl::Definition &&
1604*67e74705SXin Li !Context.isMSStaticDataMemberInlineDefinition(VD)) {
1605*67e74705SXin Li // If this declaration may have caused an inline variable definition to
1606*67e74705SXin Li // change linkage, make sure that it's emitted.
1607*67e74705SXin Li if (Context.getInlineVariableDefinitionKind(VD) ==
1608*67e74705SXin Li ASTContext::InlineVariableDefinitionKind::Strong)
1609*67e74705SXin Li GetAddrOfGlobalVar(VD);
1610*67e74705SXin Li return;
1611*67e74705SXin Li }
1612*67e74705SXin Li }
1613*67e74705SXin Li
1614*67e74705SXin Li // Defer code generation to first use when possible, e.g. if this is an inline
1615*67e74705SXin Li // function. If the global must always be emitted, do it eagerly if possible
1616*67e74705SXin Li // to benefit from cache locality.
1617*67e74705SXin Li if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
1618*67e74705SXin Li // Emit the definition if it can't be deferred.
1619*67e74705SXin Li EmitGlobalDefinition(GD);
1620*67e74705SXin Li return;
1621*67e74705SXin Li }
1622*67e74705SXin Li
1623*67e74705SXin Li // If we're deferring emission of a C++ variable with an
1624*67e74705SXin Li // initializer, remember the order in which it appeared in the file.
1625*67e74705SXin Li if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
1626*67e74705SXin Li cast<VarDecl>(Global)->hasInit()) {
1627*67e74705SXin Li DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
1628*67e74705SXin Li CXXGlobalInits.push_back(nullptr);
1629*67e74705SXin Li }
1630*67e74705SXin Li
1631*67e74705SXin Li StringRef MangledName = getMangledName(GD);
1632*67e74705SXin Li if (llvm::GlobalValue *GV = GetGlobalValue(MangledName)) {
1633*67e74705SXin Li // The value has already been used and should therefore be emitted.
1634*67e74705SXin Li addDeferredDeclToEmit(GV, GD);
1635*67e74705SXin Li } else if (MustBeEmitted(Global)) {
1636*67e74705SXin Li // The value must be emitted, but cannot be emitted eagerly.
1637*67e74705SXin Li assert(!MayBeEmittedEagerly(Global));
1638*67e74705SXin Li addDeferredDeclToEmit(/*GV=*/nullptr, GD);
1639*67e74705SXin Li } else {
1640*67e74705SXin Li // Otherwise, remember that we saw a deferred decl with this name. The
1641*67e74705SXin Li // first use of the mangled name will cause it to move into
1642*67e74705SXin Li // DeferredDeclsToEmit.
1643*67e74705SXin Li DeferredDecls[MangledName] = GD;
1644*67e74705SXin Li }
1645*67e74705SXin Li }
1646*67e74705SXin Li
1647*67e74705SXin Li namespace {
1648*67e74705SXin Li struct FunctionIsDirectlyRecursive :
1649*67e74705SXin Li public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1650*67e74705SXin Li const StringRef Name;
1651*67e74705SXin Li const Builtin::Context &BI;
1652*67e74705SXin Li bool Result;
FunctionIsDirectlyRecursive__anon8a9ecb110211::FunctionIsDirectlyRecursive1653*67e74705SXin Li FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1654*67e74705SXin Li Name(N), BI(C), Result(false) {
1655*67e74705SXin Li }
1656*67e74705SXin Li typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1657*67e74705SXin Li
TraverseCallExpr__anon8a9ecb110211::FunctionIsDirectlyRecursive1658*67e74705SXin Li bool TraverseCallExpr(CallExpr *E) {
1659*67e74705SXin Li const FunctionDecl *FD = E->getDirectCallee();
1660*67e74705SXin Li if (!FD)
1661*67e74705SXin Li return true;
1662*67e74705SXin Li AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1663*67e74705SXin Li if (Attr && Name == Attr->getLabel()) {
1664*67e74705SXin Li Result = true;
1665*67e74705SXin Li return false;
1666*67e74705SXin Li }
1667*67e74705SXin Li unsigned BuiltinID = FD->getBuiltinID();
1668*67e74705SXin Li if (!BuiltinID || !BI.isLibFunction(BuiltinID))
1669*67e74705SXin Li return true;
1670*67e74705SXin Li StringRef BuiltinName = BI.getName(BuiltinID);
1671*67e74705SXin Li if (BuiltinName.startswith("__builtin_") &&
1672*67e74705SXin Li Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
1673*67e74705SXin Li Result = true;
1674*67e74705SXin Li return false;
1675*67e74705SXin Li }
1676*67e74705SXin Li return true;
1677*67e74705SXin Li }
1678*67e74705SXin Li };
1679*67e74705SXin Li
1680*67e74705SXin Li struct DLLImportFunctionVisitor
1681*67e74705SXin Li : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
1682*67e74705SXin Li bool SafeToInline = true;
1683*67e74705SXin Li
VisitVarDecl__anon8a9ecb110211::DLLImportFunctionVisitor1684*67e74705SXin Li bool VisitVarDecl(VarDecl *VD) {
1685*67e74705SXin Li // A thread-local variable cannot be imported.
1686*67e74705SXin Li SafeToInline = !VD->getTLSKind();
1687*67e74705SXin Li return SafeToInline;
1688*67e74705SXin Li }
1689*67e74705SXin Li
1690*67e74705SXin Li // Make sure we're not referencing non-imported vars or functions.
VisitDeclRefExpr__anon8a9ecb110211::DLLImportFunctionVisitor1691*67e74705SXin Li bool VisitDeclRefExpr(DeclRefExpr *E) {
1692*67e74705SXin Li ValueDecl *VD = E->getDecl();
1693*67e74705SXin Li if (isa<FunctionDecl>(VD))
1694*67e74705SXin Li SafeToInline = VD->hasAttr<DLLImportAttr>();
1695*67e74705SXin Li else if (VarDecl *V = dyn_cast<VarDecl>(VD))
1696*67e74705SXin Li SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
1697*67e74705SXin Li return SafeToInline;
1698*67e74705SXin Li }
VisitCXXDeleteExpr__anon8a9ecb110211::DLLImportFunctionVisitor1699*67e74705SXin Li bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
1700*67e74705SXin Li SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
1701*67e74705SXin Li return SafeToInline;
1702*67e74705SXin Li }
VisitCXXNewExpr__anon8a9ecb110211::DLLImportFunctionVisitor1703*67e74705SXin Li bool VisitCXXNewExpr(CXXNewExpr *E) {
1704*67e74705SXin Li SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
1705*67e74705SXin Li return SafeToInline;
1706*67e74705SXin Li }
1707*67e74705SXin Li };
1708*67e74705SXin Li }
1709*67e74705SXin Li
1710*67e74705SXin Li // isTriviallyRecursive - Check if this function calls another
1711*67e74705SXin Li // decl that, because of the asm attribute or the other decl being a builtin,
1712*67e74705SXin Li // ends up pointing to itself.
1713*67e74705SXin Li bool
isTriviallyRecursive(const FunctionDecl * FD)1714*67e74705SXin Li CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1715*67e74705SXin Li StringRef Name;
1716*67e74705SXin Li if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
1717*67e74705SXin Li // asm labels are a special kind of mangling we have to support.
1718*67e74705SXin Li AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1719*67e74705SXin Li if (!Attr)
1720*67e74705SXin Li return false;
1721*67e74705SXin Li Name = Attr->getLabel();
1722*67e74705SXin Li } else {
1723*67e74705SXin Li Name = FD->getName();
1724*67e74705SXin Li }
1725*67e74705SXin Li
1726*67e74705SXin Li FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1727*67e74705SXin Li Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
1728*67e74705SXin Li return Walker.Result;
1729*67e74705SXin Li }
1730*67e74705SXin Li
1731*67e74705SXin Li bool
shouldEmitFunction(GlobalDecl GD)1732*67e74705SXin Li CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
1733*67e74705SXin Li if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
1734*67e74705SXin Li return true;
1735*67e74705SXin Li const auto *F = cast<FunctionDecl>(GD.getDecl());
1736*67e74705SXin Li if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
1737*67e74705SXin Li return false;
1738*67e74705SXin Li
1739*67e74705SXin Li if (F->hasAttr<DLLImportAttr>()) {
1740*67e74705SXin Li // Check whether it would be safe to inline this dllimport function.
1741*67e74705SXin Li DLLImportFunctionVisitor Visitor;
1742*67e74705SXin Li Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
1743*67e74705SXin Li if (!Visitor.SafeToInline)
1744*67e74705SXin Li return false;
1745*67e74705SXin Li }
1746*67e74705SXin Li
1747*67e74705SXin Li // PR9614. Avoid cases where the source code is lying to us. An available
1748*67e74705SXin Li // externally function should have an equivalent function somewhere else,
1749*67e74705SXin Li // but a function that calls itself is clearly not equivalent to the real
1750*67e74705SXin Li // implementation.
1751*67e74705SXin Li // This happens in glibc's btowc and in some configure checks.
1752*67e74705SXin Li return !isTriviallyRecursive(F);
1753*67e74705SXin Li }
1754*67e74705SXin Li
1755*67e74705SXin Li /// If the type for the method's class was generated by
1756*67e74705SXin Li /// CGDebugInfo::createContextChain(), the cache contains only a
1757*67e74705SXin Li /// limited DIType without any declarations. Since EmitFunctionStart()
1758*67e74705SXin Li /// needs to find the canonical declaration for each method, we need
1759*67e74705SXin Li /// to construct the complete type prior to emitting the method.
CompleteDIClassType(const CXXMethodDecl * D)1760*67e74705SXin Li void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) {
1761*67e74705SXin Li if (!D->isInstance())
1762*67e74705SXin Li return;
1763*67e74705SXin Li
1764*67e74705SXin Li if (CGDebugInfo *DI = getModuleDebugInfo())
1765*67e74705SXin Li if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) {
1766*67e74705SXin Li const auto *ThisPtr = cast<PointerType>(D->getThisType(getContext()));
1767*67e74705SXin Li DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation());
1768*67e74705SXin Li }
1769*67e74705SXin Li }
1770*67e74705SXin Li
EmitGlobalDefinition(GlobalDecl GD,llvm::GlobalValue * GV)1771*67e74705SXin Li void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
1772*67e74705SXin Li const auto *D = cast<ValueDecl>(GD.getDecl());
1773*67e74705SXin Li
1774*67e74705SXin Li PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
1775*67e74705SXin Li Context.getSourceManager(),
1776*67e74705SXin Li "Generating code for declaration");
1777*67e74705SXin Li
1778*67e74705SXin Li if (isa<FunctionDecl>(D)) {
1779*67e74705SXin Li // At -O0, don't generate IR for functions with available_externally
1780*67e74705SXin Li // linkage.
1781*67e74705SXin Li if (!shouldEmitFunction(GD))
1782*67e74705SXin Li return;
1783*67e74705SXin Li
1784*67e74705SXin Li if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
1785*67e74705SXin Li CompleteDIClassType(Method);
1786*67e74705SXin Li // Make sure to emit the definition(s) before we emit the thunks.
1787*67e74705SXin Li // This is necessary for the generation of certain thunks.
1788*67e74705SXin Li if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
1789*67e74705SXin Li ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
1790*67e74705SXin Li else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
1791*67e74705SXin Li ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
1792*67e74705SXin Li else
1793*67e74705SXin Li EmitGlobalFunctionDefinition(GD, GV);
1794*67e74705SXin Li
1795*67e74705SXin Li if (Method->isVirtual())
1796*67e74705SXin Li getVTables().EmitThunks(GD);
1797*67e74705SXin Li
1798*67e74705SXin Li return;
1799*67e74705SXin Li }
1800*67e74705SXin Li
1801*67e74705SXin Li return EmitGlobalFunctionDefinition(GD, GV);
1802*67e74705SXin Li }
1803*67e74705SXin Li
1804*67e74705SXin Li if (const auto *VD = dyn_cast<VarDecl>(D))
1805*67e74705SXin Li return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
1806*67e74705SXin Li
1807*67e74705SXin Li llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
1808*67e74705SXin Li }
1809*67e74705SXin Li
1810*67e74705SXin Li static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1811*67e74705SXin Li llvm::Function *NewFn);
1812*67e74705SXin Li
1813*67e74705SXin Li /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1814*67e74705SXin Li /// module, create and return an llvm Function with the specified type. If there
1815*67e74705SXin Li /// is something in the module with the specified name, return it potentially
1816*67e74705SXin Li /// bitcasted to the right type.
1817*67e74705SXin Li ///
1818*67e74705SXin Li /// If D is non-null, it specifies a decl that correspond to this. This is used
1819*67e74705SXin Li /// to set the attributes on the function when it is first created.
1820*67e74705SXin Li llvm::Constant *
GetOrCreateLLVMFunction(StringRef MangledName,llvm::Type * Ty,GlobalDecl GD,bool ForVTable,bool DontDefer,bool IsThunk,llvm::AttributeSet ExtraAttrs,bool IsForDefinition)1821*67e74705SXin Li CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
1822*67e74705SXin Li llvm::Type *Ty,
1823*67e74705SXin Li GlobalDecl GD, bool ForVTable,
1824*67e74705SXin Li bool DontDefer, bool IsThunk,
1825*67e74705SXin Li llvm::AttributeSet ExtraAttrs,
1826*67e74705SXin Li bool IsForDefinition) {
1827*67e74705SXin Li const Decl *D = GD.getDecl();
1828*67e74705SXin Li
1829*67e74705SXin Li // Lookup the entry, lazily creating it if necessary.
1830*67e74705SXin Li llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1831*67e74705SXin Li if (Entry) {
1832*67e74705SXin Li if (WeakRefReferences.erase(Entry)) {
1833*67e74705SXin Li const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
1834*67e74705SXin Li if (FD && !FD->hasAttr<WeakAttr>())
1835*67e74705SXin Li Entry->setLinkage(llvm::Function::ExternalLinkage);
1836*67e74705SXin Li }
1837*67e74705SXin Li
1838*67e74705SXin Li // Handle dropped DLL attributes.
1839*67e74705SXin Li if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
1840*67e74705SXin Li Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
1841*67e74705SXin Li
1842*67e74705SXin Li // If there are two attempts to define the same mangled name, issue an
1843*67e74705SXin Li // error.
1844*67e74705SXin Li if (IsForDefinition && !Entry->isDeclaration()) {
1845*67e74705SXin Li GlobalDecl OtherGD;
1846*67e74705SXin Li // Check that GD is not yet in DiagnosedConflictingDefinitions is required
1847*67e74705SXin Li // to make sure that we issue an error only once.
1848*67e74705SXin Li if (lookupRepresentativeDecl(MangledName, OtherGD) &&
1849*67e74705SXin Li (GD.getCanonicalDecl().getDecl() !=
1850*67e74705SXin Li OtherGD.getCanonicalDecl().getDecl()) &&
1851*67e74705SXin Li DiagnosedConflictingDefinitions.insert(GD).second) {
1852*67e74705SXin Li getDiags().Report(D->getLocation(),
1853*67e74705SXin Li diag::err_duplicate_mangled_name);
1854*67e74705SXin Li getDiags().Report(OtherGD.getDecl()->getLocation(),
1855*67e74705SXin Li diag::note_previous_definition);
1856*67e74705SXin Li }
1857*67e74705SXin Li }
1858*67e74705SXin Li
1859*67e74705SXin Li if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
1860*67e74705SXin Li (Entry->getType()->getElementType() == Ty)) {
1861*67e74705SXin Li return Entry;
1862*67e74705SXin Li }
1863*67e74705SXin Li
1864*67e74705SXin Li // Make sure the result is of the correct type.
1865*67e74705SXin Li // (If function is requested for a definition, we always need to create a new
1866*67e74705SXin Li // function, not just return a bitcast.)
1867*67e74705SXin Li if (!IsForDefinition)
1868*67e74705SXin Li return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
1869*67e74705SXin Li }
1870*67e74705SXin Li
1871*67e74705SXin Li // This function doesn't have a complete type (for example, the return
1872*67e74705SXin Li // type is an incomplete struct). Use a fake type instead, and make
1873*67e74705SXin Li // sure not to try to set attributes.
1874*67e74705SXin Li bool IsIncompleteFunction = false;
1875*67e74705SXin Li
1876*67e74705SXin Li llvm::FunctionType *FTy;
1877*67e74705SXin Li if (isa<llvm::FunctionType>(Ty)) {
1878*67e74705SXin Li FTy = cast<llvm::FunctionType>(Ty);
1879*67e74705SXin Li } else {
1880*67e74705SXin Li FTy = llvm::FunctionType::get(VoidTy, false);
1881*67e74705SXin Li IsIncompleteFunction = true;
1882*67e74705SXin Li }
1883*67e74705SXin Li
1884*67e74705SXin Li llvm::Function *F =
1885*67e74705SXin Li llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
1886*67e74705SXin Li Entry ? StringRef() : MangledName, &getModule());
1887*67e74705SXin Li
1888*67e74705SXin Li // If we already created a function with the same mangled name (but different
1889*67e74705SXin Li // type) before, take its name and add it to the list of functions to be
1890*67e74705SXin Li // replaced with F at the end of CodeGen.
1891*67e74705SXin Li //
1892*67e74705SXin Li // This happens if there is a prototype for a function (e.g. "int f()") and
1893*67e74705SXin Li // then a definition of a different type (e.g. "int f(int x)").
1894*67e74705SXin Li if (Entry) {
1895*67e74705SXin Li F->takeName(Entry);
1896*67e74705SXin Li
1897*67e74705SXin Li // This might be an implementation of a function without a prototype, in
1898*67e74705SXin Li // which case, try to do special replacement of calls which match the new
1899*67e74705SXin Li // prototype. The really key thing here is that we also potentially drop
1900*67e74705SXin Li // arguments from the call site so as to make a direct call, which makes the
1901*67e74705SXin Li // inliner happier and suppresses a number of optimizer warnings (!) about
1902*67e74705SXin Li // dropping arguments.
1903*67e74705SXin Li if (!Entry->use_empty()) {
1904*67e74705SXin Li ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
1905*67e74705SXin Li Entry->removeDeadConstantUsers();
1906*67e74705SXin Li }
1907*67e74705SXin Li
1908*67e74705SXin Li llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
1909*67e74705SXin Li F, Entry->getType()->getElementType()->getPointerTo());
1910*67e74705SXin Li addGlobalValReplacement(Entry, BC);
1911*67e74705SXin Li }
1912*67e74705SXin Li
1913*67e74705SXin Li assert(F->getName() == MangledName && "name was uniqued!");
1914*67e74705SXin Li if (D)
1915*67e74705SXin Li SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
1916*67e74705SXin Li if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) {
1917*67e74705SXin Li llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex);
1918*67e74705SXin Li F->addAttributes(llvm::AttributeSet::FunctionIndex,
1919*67e74705SXin Li llvm::AttributeSet::get(VMContext,
1920*67e74705SXin Li llvm::AttributeSet::FunctionIndex,
1921*67e74705SXin Li B));
1922*67e74705SXin Li }
1923*67e74705SXin Li
1924*67e74705SXin Li if (!DontDefer) {
1925*67e74705SXin Li // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
1926*67e74705SXin Li // each other bottoming out with the base dtor. Therefore we emit non-base
1927*67e74705SXin Li // dtors on usage, even if there is no dtor definition in the TU.
1928*67e74705SXin Li if (D && isa<CXXDestructorDecl>(D) &&
1929*67e74705SXin Li getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
1930*67e74705SXin Li GD.getDtorType()))
1931*67e74705SXin Li addDeferredDeclToEmit(F, GD);
1932*67e74705SXin Li
1933*67e74705SXin Li // This is the first use or definition of a mangled name. If there is a
1934*67e74705SXin Li // deferred decl with this name, remember that we need to emit it at the end
1935*67e74705SXin Li // of the file.
1936*67e74705SXin Li auto DDI = DeferredDecls.find(MangledName);
1937*67e74705SXin Li if (DDI != DeferredDecls.end()) {
1938*67e74705SXin Li // Move the potentially referenced deferred decl to the
1939*67e74705SXin Li // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
1940*67e74705SXin Li // don't need it anymore).
1941*67e74705SXin Li addDeferredDeclToEmit(F, DDI->second);
1942*67e74705SXin Li DeferredDecls.erase(DDI);
1943*67e74705SXin Li
1944*67e74705SXin Li // Otherwise, there are cases we have to worry about where we're
1945*67e74705SXin Li // using a declaration for which we must emit a definition but where
1946*67e74705SXin Li // we might not find a top-level definition:
1947*67e74705SXin Li // - member functions defined inline in their classes
1948*67e74705SXin Li // - friend functions defined inline in some class
1949*67e74705SXin Li // - special member functions with implicit definitions
1950*67e74705SXin Li // If we ever change our AST traversal to walk into class methods,
1951*67e74705SXin Li // this will be unnecessary.
1952*67e74705SXin Li //
1953*67e74705SXin Li // We also don't emit a definition for a function if it's going to be an
1954*67e74705SXin Li // entry in a vtable, unless it's already marked as used.
1955*67e74705SXin Li } else if (getLangOpts().CPlusPlus && D) {
1956*67e74705SXin Li // Look for a declaration that's lexically in a record.
1957*67e74705SXin Li for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
1958*67e74705SXin Li FD = FD->getPreviousDecl()) {
1959*67e74705SXin Li if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
1960*67e74705SXin Li if (FD->doesThisDeclarationHaveABody()) {
1961*67e74705SXin Li addDeferredDeclToEmit(F, GD.getWithDecl(FD));
1962*67e74705SXin Li break;
1963*67e74705SXin Li }
1964*67e74705SXin Li }
1965*67e74705SXin Li }
1966*67e74705SXin Li }
1967*67e74705SXin Li }
1968*67e74705SXin Li
1969*67e74705SXin Li // Make sure the result is of the requested type.
1970*67e74705SXin Li if (!IsIncompleteFunction) {
1971*67e74705SXin Li assert(F->getType()->getElementType() == Ty);
1972*67e74705SXin Li return F;
1973*67e74705SXin Li }
1974*67e74705SXin Li
1975*67e74705SXin Li llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
1976*67e74705SXin Li return llvm::ConstantExpr::getBitCast(F, PTy);
1977*67e74705SXin Li }
1978*67e74705SXin Li
1979*67e74705SXin Li /// GetAddrOfFunction - Return the address of the given function. If Ty is
1980*67e74705SXin Li /// non-null, then this function will use the specified type if it has to
1981*67e74705SXin Li /// create it (this occurs when we see a definition of the function).
GetAddrOfFunction(GlobalDecl GD,llvm::Type * Ty,bool ForVTable,bool DontDefer,bool IsForDefinition)1982*67e74705SXin Li llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
1983*67e74705SXin Li llvm::Type *Ty,
1984*67e74705SXin Li bool ForVTable,
1985*67e74705SXin Li bool DontDefer,
1986*67e74705SXin Li bool IsForDefinition) {
1987*67e74705SXin Li // If there was no specific requested type, just convert it now.
1988*67e74705SXin Li if (!Ty) {
1989*67e74705SXin Li const auto *FD = cast<FunctionDecl>(GD.getDecl());
1990*67e74705SXin Li auto CanonTy = Context.getCanonicalType(FD->getType());
1991*67e74705SXin Li Ty = getTypes().ConvertFunctionType(CanonTy, FD);
1992*67e74705SXin Li }
1993*67e74705SXin Li
1994*67e74705SXin Li StringRef MangledName = getMangledName(GD);
1995*67e74705SXin Li return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
1996*67e74705SXin Li /*IsThunk=*/false, llvm::AttributeSet(),
1997*67e74705SXin Li IsForDefinition);
1998*67e74705SXin Li }
1999*67e74705SXin Li
2000*67e74705SXin Li /// CreateRuntimeFunction - Create a new runtime function with the specified
2001*67e74705SXin Li /// type and name.
2002*67e74705SXin Li llvm::Constant *
CreateRuntimeFunction(llvm::FunctionType * FTy,StringRef Name,llvm::AttributeSet ExtraAttrs)2003*67e74705SXin Li CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
2004*67e74705SXin Li StringRef Name,
2005*67e74705SXin Li llvm::AttributeSet ExtraAttrs) {
2006*67e74705SXin Li llvm::Constant *C =
2007*67e74705SXin Li GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
2008*67e74705SXin Li /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
2009*67e74705SXin Li if (auto *F = dyn_cast<llvm::Function>(C))
2010*67e74705SXin Li if (F->empty())
2011*67e74705SXin Li F->setCallingConv(getRuntimeCC());
2012*67e74705SXin Li return C;
2013*67e74705SXin Li }
2014*67e74705SXin Li
2015*67e74705SXin Li /// CreateBuiltinFunction - Create a new builtin function with the specified
2016*67e74705SXin Li /// type and name.
2017*67e74705SXin Li llvm::Constant *
CreateBuiltinFunction(llvm::FunctionType * FTy,StringRef Name,llvm::AttributeSet ExtraAttrs)2018*67e74705SXin Li CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy,
2019*67e74705SXin Li StringRef Name,
2020*67e74705SXin Li llvm::AttributeSet ExtraAttrs) {
2021*67e74705SXin Li llvm::Constant *C =
2022*67e74705SXin Li GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
2023*67e74705SXin Li /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
2024*67e74705SXin Li if (auto *F = dyn_cast<llvm::Function>(C))
2025*67e74705SXin Li if (F->empty())
2026*67e74705SXin Li F->setCallingConv(getBuiltinCC());
2027*67e74705SXin Li return C;
2028*67e74705SXin Li }
2029*67e74705SXin Li
2030*67e74705SXin Li /// isTypeConstant - Determine whether an object of this type can be emitted
2031*67e74705SXin Li /// as a constant.
2032*67e74705SXin Li ///
2033*67e74705SXin Li /// If ExcludeCtor is true, the duration when the object's constructor runs
2034*67e74705SXin Li /// will not be considered. The caller will need to verify that the object is
2035*67e74705SXin Li /// not written to during its construction.
isTypeConstant(QualType Ty,bool ExcludeCtor)2036*67e74705SXin Li bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
2037*67e74705SXin Li if (!Ty.isConstant(Context) && !Ty->isReferenceType())
2038*67e74705SXin Li return false;
2039*67e74705SXin Li
2040*67e74705SXin Li if (Context.getLangOpts().CPlusPlus) {
2041*67e74705SXin Li if (const CXXRecordDecl *Record
2042*67e74705SXin Li = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
2043*67e74705SXin Li return ExcludeCtor && !Record->hasMutableFields() &&
2044*67e74705SXin Li Record->hasTrivialDestructor();
2045*67e74705SXin Li }
2046*67e74705SXin Li
2047*67e74705SXin Li return true;
2048*67e74705SXin Li }
2049*67e74705SXin Li
2050*67e74705SXin Li /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
2051*67e74705SXin Li /// create and return an llvm GlobalVariable with the specified type. If there
2052*67e74705SXin Li /// is something in the module with the specified name, return it potentially
2053*67e74705SXin Li /// bitcasted to the right type.
2054*67e74705SXin Li ///
2055*67e74705SXin Li /// If D is non-null, it specifies a decl that correspond to this. This is used
2056*67e74705SXin Li /// to set the attributes on the global when it is first created.
2057*67e74705SXin Li ///
2058*67e74705SXin Li /// If IsForDefinition is true, it is guranteed that an actual global with
2059*67e74705SXin Li /// type Ty will be returned, not conversion of a variable with the same
2060*67e74705SXin Li /// mangled name but some other type.
2061*67e74705SXin Li llvm::Constant *
GetOrCreateLLVMGlobal(StringRef MangledName,llvm::PointerType * Ty,const VarDecl * D,bool IsForDefinition)2062*67e74705SXin Li CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
2063*67e74705SXin Li llvm::PointerType *Ty,
2064*67e74705SXin Li const VarDecl *D,
2065*67e74705SXin Li bool IsForDefinition) {
2066*67e74705SXin Li // Lookup the entry, lazily creating it if necessary.
2067*67e74705SXin Li llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2068*67e74705SXin Li if (Entry) {
2069*67e74705SXin Li if (WeakRefReferences.erase(Entry)) {
2070*67e74705SXin Li if (D && !D->hasAttr<WeakAttr>())
2071*67e74705SXin Li Entry->setLinkage(llvm::Function::ExternalLinkage);
2072*67e74705SXin Li }
2073*67e74705SXin Li
2074*67e74705SXin Li // Handle dropped DLL attributes.
2075*67e74705SXin Li if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
2076*67e74705SXin Li Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2077*67e74705SXin Li
2078*67e74705SXin Li if (Entry->getType() == Ty)
2079*67e74705SXin Li return Entry;
2080*67e74705SXin Li
2081*67e74705SXin Li // If there are two attempts to define the same mangled name, issue an
2082*67e74705SXin Li // error.
2083*67e74705SXin Li if (IsForDefinition && !Entry->isDeclaration()) {
2084*67e74705SXin Li GlobalDecl OtherGD;
2085*67e74705SXin Li const VarDecl *OtherD;
2086*67e74705SXin Li
2087*67e74705SXin Li // Check that D is not yet in DiagnosedConflictingDefinitions is required
2088*67e74705SXin Li // to make sure that we issue an error only once.
2089*67e74705SXin Li if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
2090*67e74705SXin Li (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
2091*67e74705SXin Li (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
2092*67e74705SXin Li OtherD->hasInit() &&
2093*67e74705SXin Li DiagnosedConflictingDefinitions.insert(D).second) {
2094*67e74705SXin Li getDiags().Report(D->getLocation(),
2095*67e74705SXin Li diag::err_duplicate_mangled_name);
2096*67e74705SXin Li getDiags().Report(OtherGD.getDecl()->getLocation(),
2097*67e74705SXin Li diag::note_previous_definition);
2098*67e74705SXin Li }
2099*67e74705SXin Li }
2100*67e74705SXin Li
2101*67e74705SXin Li // Make sure the result is of the correct type.
2102*67e74705SXin Li if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
2103*67e74705SXin Li return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
2104*67e74705SXin Li
2105*67e74705SXin Li // (If global is requested for a definition, we always need to create a new
2106*67e74705SXin Li // global, not just return a bitcast.)
2107*67e74705SXin Li if (!IsForDefinition)
2108*67e74705SXin Li return llvm::ConstantExpr::getBitCast(Entry, Ty);
2109*67e74705SXin Li }
2110*67e74705SXin Li
2111*67e74705SXin Li unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
2112*67e74705SXin Li auto *GV = new llvm::GlobalVariable(
2113*67e74705SXin Li getModule(), Ty->getElementType(), false,
2114*67e74705SXin Li llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
2115*67e74705SXin Li llvm::GlobalVariable::NotThreadLocal, AddrSpace);
2116*67e74705SXin Li
2117*67e74705SXin Li // If we already created a global with the same mangled name (but different
2118*67e74705SXin Li // type) before, take its name and remove it from its parent.
2119*67e74705SXin Li if (Entry) {
2120*67e74705SXin Li GV->takeName(Entry);
2121*67e74705SXin Li
2122*67e74705SXin Li if (!Entry->use_empty()) {
2123*67e74705SXin Li llvm::Constant *NewPtrForOldDecl =
2124*67e74705SXin Li llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2125*67e74705SXin Li Entry->replaceAllUsesWith(NewPtrForOldDecl);
2126*67e74705SXin Li }
2127*67e74705SXin Li
2128*67e74705SXin Li Entry->eraseFromParent();
2129*67e74705SXin Li }
2130*67e74705SXin Li
2131*67e74705SXin Li // This is the first use or definition of a mangled name. If there is a
2132*67e74705SXin Li // deferred decl with this name, remember that we need to emit it at the end
2133*67e74705SXin Li // of the file.
2134*67e74705SXin Li auto DDI = DeferredDecls.find(MangledName);
2135*67e74705SXin Li if (DDI != DeferredDecls.end()) {
2136*67e74705SXin Li // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
2137*67e74705SXin Li // list, and remove it from DeferredDecls (since we don't need it anymore).
2138*67e74705SXin Li addDeferredDeclToEmit(GV, DDI->second);
2139*67e74705SXin Li DeferredDecls.erase(DDI);
2140*67e74705SXin Li }
2141*67e74705SXin Li
2142*67e74705SXin Li // Handle things which are present even on external declarations.
2143*67e74705SXin Li if (D) {
2144*67e74705SXin Li // FIXME: This code is overly simple and should be merged with other global
2145*67e74705SXin Li // handling.
2146*67e74705SXin Li GV->setConstant(isTypeConstant(D->getType(), false));
2147*67e74705SXin Li
2148*67e74705SXin Li GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2149*67e74705SXin Li
2150*67e74705SXin Li setLinkageAndVisibilityForGV(GV, D);
2151*67e74705SXin Li
2152*67e74705SXin Li if (D->getTLSKind()) {
2153*67e74705SXin Li if (D->getTLSKind() == VarDecl::TLS_Dynamic)
2154*67e74705SXin Li CXXThreadLocals.push_back(D);
2155*67e74705SXin Li setTLSMode(GV, *D);
2156*67e74705SXin Li }
2157*67e74705SXin Li
2158*67e74705SXin Li // If required by the ABI, treat declarations of static data members with
2159*67e74705SXin Li // inline initializers as definitions.
2160*67e74705SXin Li if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
2161*67e74705SXin Li EmitGlobalVarDefinition(D);
2162*67e74705SXin Li }
2163*67e74705SXin Li
2164*67e74705SXin Li // Handle XCore specific ABI requirements.
2165*67e74705SXin Li if (getTarget().getTriple().getArch() == llvm::Triple::xcore &&
2166*67e74705SXin Li D->getLanguageLinkage() == CLanguageLinkage &&
2167*67e74705SXin Li D->getType().isConstant(Context) &&
2168*67e74705SXin Li isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
2169*67e74705SXin Li GV->setSection(".cp.rodata");
2170*67e74705SXin Li }
2171*67e74705SXin Li
2172*67e74705SXin Li if (AddrSpace != Ty->getAddressSpace())
2173*67e74705SXin Li return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
2174*67e74705SXin Li
2175*67e74705SXin Li return GV;
2176*67e74705SXin Li }
2177*67e74705SXin Li
2178*67e74705SXin Li llvm::Constant *
GetAddrOfGlobal(GlobalDecl GD,bool IsForDefinition)2179*67e74705SXin Li CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
2180*67e74705SXin Li bool IsForDefinition) {
2181*67e74705SXin Li if (isa<CXXConstructorDecl>(GD.getDecl()))
2182*67e74705SXin Li return getAddrOfCXXStructor(cast<CXXConstructorDecl>(GD.getDecl()),
2183*67e74705SXin Li getFromCtorType(GD.getCtorType()),
2184*67e74705SXin Li /*FnInfo=*/nullptr, /*FnType=*/nullptr,
2185*67e74705SXin Li /*DontDefer=*/false, IsForDefinition);
2186*67e74705SXin Li else if (isa<CXXDestructorDecl>(GD.getDecl()))
2187*67e74705SXin Li return getAddrOfCXXStructor(cast<CXXDestructorDecl>(GD.getDecl()),
2188*67e74705SXin Li getFromDtorType(GD.getDtorType()),
2189*67e74705SXin Li /*FnInfo=*/nullptr, /*FnType=*/nullptr,
2190*67e74705SXin Li /*DontDefer=*/false, IsForDefinition);
2191*67e74705SXin Li else if (isa<CXXMethodDecl>(GD.getDecl())) {
2192*67e74705SXin Li auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
2193*67e74705SXin Li cast<CXXMethodDecl>(GD.getDecl()));
2194*67e74705SXin Li auto Ty = getTypes().GetFunctionType(*FInfo);
2195*67e74705SXin Li return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
2196*67e74705SXin Li IsForDefinition);
2197*67e74705SXin Li } else if (isa<FunctionDecl>(GD.getDecl())) {
2198*67e74705SXin Li const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2199*67e74705SXin Li llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2200*67e74705SXin Li return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
2201*67e74705SXin Li IsForDefinition);
2202*67e74705SXin Li } else
2203*67e74705SXin Li return GetAddrOfGlobalVar(cast<VarDecl>(GD.getDecl()), /*Ty=*/nullptr,
2204*67e74705SXin Li IsForDefinition);
2205*67e74705SXin Li }
2206*67e74705SXin Li
2207*67e74705SXin Li llvm::GlobalVariable *
CreateOrReplaceCXXRuntimeVariable(StringRef Name,llvm::Type * Ty,llvm::GlobalValue::LinkageTypes Linkage)2208*67e74705SXin Li CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
2209*67e74705SXin Li llvm::Type *Ty,
2210*67e74705SXin Li llvm::GlobalValue::LinkageTypes Linkage) {
2211*67e74705SXin Li llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
2212*67e74705SXin Li llvm::GlobalVariable *OldGV = nullptr;
2213*67e74705SXin Li
2214*67e74705SXin Li if (GV) {
2215*67e74705SXin Li // Check if the variable has the right type.
2216*67e74705SXin Li if (GV->getType()->getElementType() == Ty)
2217*67e74705SXin Li return GV;
2218*67e74705SXin Li
2219*67e74705SXin Li // Because C++ name mangling, the only way we can end up with an already
2220*67e74705SXin Li // existing global with the same name is if it has been declared extern "C".
2221*67e74705SXin Li assert(GV->isDeclaration() && "Declaration has wrong type!");
2222*67e74705SXin Li OldGV = GV;
2223*67e74705SXin Li }
2224*67e74705SXin Li
2225*67e74705SXin Li // Create a new variable.
2226*67e74705SXin Li GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
2227*67e74705SXin Li Linkage, nullptr, Name);
2228*67e74705SXin Li
2229*67e74705SXin Li if (OldGV) {
2230*67e74705SXin Li // Replace occurrences of the old variable if needed.
2231*67e74705SXin Li GV->takeName(OldGV);
2232*67e74705SXin Li
2233*67e74705SXin Li if (!OldGV->use_empty()) {
2234*67e74705SXin Li llvm::Constant *NewPtrForOldDecl =
2235*67e74705SXin Li llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2236*67e74705SXin Li OldGV->replaceAllUsesWith(NewPtrForOldDecl);
2237*67e74705SXin Li }
2238*67e74705SXin Li
2239*67e74705SXin Li OldGV->eraseFromParent();
2240*67e74705SXin Li }
2241*67e74705SXin Li
2242*67e74705SXin Li if (supportsCOMDAT() && GV->isWeakForLinker() &&
2243*67e74705SXin Li !GV->hasAvailableExternallyLinkage())
2244*67e74705SXin Li GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2245*67e74705SXin Li
2246*67e74705SXin Li return GV;
2247*67e74705SXin Li }
2248*67e74705SXin Li
2249*67e74705SXin Li /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
2250*67e74705SXin Li /// given global variable. If Ty is non-null and if the global doesn't exist,
2251*67e74705SXin Li /// then it will be created with the specified type instead of whatever the
2252*67e74705SXin Li /// normal requested type would be. If IsForDefinition is true, it is guranteed
2253*67e74705SXin Li /// that an actual global with type Ty will be returned, not conversion of a
2254*67e74705SXin Li /// variable with the same mangled name but some other type.
GetAddrOfGlobalVar(const VarDecl * D,llvm::Type * Ty,bool IsForDefinition)2255*67e74705SXin Li llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
2256*67e74705SXin Li llvm::Type *Ty,
2257*67e74705SXin Li bool IsForDefinition) {
2258*67e74705SXin Li assert(D->hasGlobalStorage() && "Not a global variable");
2259*67e74705SXin Li QualType ASTTy = D->getType();
2260*67e74705SXin Li if (!Ty)
2261*67e74705SXin Li Ty = getTypes().ConvertTypeForMem(ASTTy);
2262*67e74705SXin Li
2263*67e74705SXin Li llvm::PointerType *PTy =
2264*67e74705SXin Li llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
2265*67e74705SXin Li
2266*67e74705SXin Li StringRef MangledName = getMangledName(D);
2267*67e74705SXin Li return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
2268*67e74705SXin Li }
2269*67e74705SXin Li
2270*67e74705SXin Li /// CreateRuntimeVariable - Create a new runtime global variable with the
2271*67e74705SXin Li /// specified type and name.
2272*67e74705SXin Li llvm::Constant *
CreateRuntimeVariable(llvm::Type * Ty,StringRef Name)2273*67e74705SXin Li CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
2274*67e74705SXin Li StringRef Name) {
2275*67e74705SXin Li return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
2276*67e74705SXin Li }
2277*67e74705SXin Li
EmitTentativeDefinition(const VarDecl * D)2278*67e74705SXin Li void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
2279*67e74705SXin Li assert(!D->getInit() && "Cannot emit definite definitions here!");
2280*67e74705SXin Li
2281*67e74705SXin Li StringRef MangledName = getMangledName(D);
2282*67e74705SXin Li llvm::GlobalValue *GV = GetGlobalValue(MangledName);
2283*67e74705SXin Li
2284*67e74705SXin Li // We already have a definition, not declaration, with the same mangled name.
2285*67e74705SXin Li // Emitting of declaration is not required (and actually overwrites emitted
2286*67e74705SXin Li // definition).
2287*67e74705SXin Li if (GV && !GV->isDeclaration())
2288*67e74705SXin Li return;
2289*67e74705SXin Li
2290*67e74705SXin Li // If we have not seen a reference to this variable yet, place it into the
2291*67e74705SXin Li // deferred declarations table to be emitted if needed later.
2292*67e74705SXin Li if (!MustBeEmitted(D) && !GV) {
2293*67e74705SXin Li DeferredDecls[MangledName] = D;
2294*67e74705SXin Li return;
2295*67e74705SXin Li }
2296*67e74705SXin Li
2297*67e74705SXin Li // The tentative definition is the only definition.
2298*67e74705SXin Li EmitGlobalVarDefinition(D);
2299*67e74705SXin Li }
2300*67e74705SXin Li
GetTargetTypeStoreSize(llvm::Type * Ty) const2301*67e74705SXin Li CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
2302*67e74705SXin Li return Context.toCharUnitsFromBits(
2303*67e74705SXin Li getDataLayout().getTypeStoreSizeInBits(Ty));
2304*67e74705SXin Li }
2305*67e74705SXin Li
GetGlobalVarAddressSpace(const VarDecl * D,unsigned AddrSpace)2306*67e74705SXin Li unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
2307*67e74705SXin Li unsigned AddrSpace) {
2308*67e74705SXin Li if (D && LangOpts.CUDA && LangOpts.CUDAIsDevice) {
2309*67e74705SXin Li if (D->hasAttr<CUDAConstantAttr>())
2310*67e74705SXin Li AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
2311*67e74705SXin Li else if (D->hasAttr<CUDASharedAttr>())
2312*67e74705SXin Li AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
2313*67e74705SXin Li else
2314*67e74705SXin Li AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
2315*67e74705SXin Li }
2316*67e74705SXin Li
2317*67e74705SXin Li return AddrSpace;
2318*67e74705SXin Li }
2319*67e74705SXin Li
2320*67e74705SXin Li template<typename SomeDecl>
MaybeHandleStaticInExternC(const SomeDecl * D,llvm::GlobalValue * GV)2321*67e74705SXin Li void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
2322*67e74705SXin Li llvm::GlobalValue *GV) {
2323*67e74705SXin Li if (!getLangOpts().CPlusPlus)
2324*67e74705SXin Li return;
2325*67e74705SXin Li
2326*67e74705SXin Li // Must have 'used' attribute, or else inline assembly can't rely on
2327*67e74705SXin Li // the name existing.
2328*67e74705SXin Li if (!D->template hasAttr<UsedAttr>())
2329*67e74705SXin Li return;
2330*67e74705SXin Li
2331*67e74705SXin Li // Must have internal linkage and an ordinary name.
2332*67e74705SXin Li if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
2333*67e74705SXin Li return;
2334*67e74705SXin Li
2335*67e74705SXin Li // Must be in an extern "C" context. Entities declared directly within
2336*67e74705SXin Li // a record are not extern "C" even if the record is in such a context.
2337*67e74705SXin Li const SomeDecl *First = D->getFirstDecl();
2338*67e74705SXin Li if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
2339*67e74705SXin Li return;
2340*67e74705SXin Li
2341*67e74705SXin Li // OK, this is an internal linkage entity inside an extern "C" linkage
2342*67e74705SXin Li // specification. Make a note of that so we can give it the "expected"
2343*67e74705SXin Li // mangled name if nothing else is using that name.
2344*67e74705SXin Li std::pair<StaticExternCMap::iterator, bool> R =
2345*67e74705SXin Li StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
2346*67e74705SXin Li
2347*67e74705SXin Li // If we have multiple internal linkage entities with the same name
2348*67e74705SXin Li // in extern "C" regions, none of them gets that name.
2349*67e74705SXin Li if (!R.second)
2350*67e74705SXin Li R.first->second = nullptr;
2351*67e74705SXin Li }
2352*67e74705SXin Li
shouldBeInCOMDAT(CodeGenModule & CGM,const Decl & D)2353*67e74705SXin Li static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
2354*67e74705SXin Li if (!CGM.supportsCOMDAT())
2355*67e74705SXin Li return false;
2356*67e74705SXin Li
2357*67e74705SXin Li if (D.hasAttr<SelectAnyAttr>())
2358*67e74705SXin Li return true;
2359*67e74705SXin Li
2360*67e74705SXin Li GVALinkage Linkage;
2361*67e74705SXin Li if (auto *VD = dyn_cast<VarDecl>(&D))
2362*67e74705SXin Li Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
2363*67e74705SXin Li else
2364*67e74705SXin Li Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
2365*67e74705SXin Li
2366*67e74705SXin Li switch (Linkage) {
2367*67e74705SXin Li case GVA_Internal:
2368*67e74705SXin Li case GVA_AvailableExternally:
2369*67e74705SXin Li case GVA_StrongExternal:
2370*67e74705SXin Li return false;
2371*67e74705SXin Li case GVA_DiscardableODR:
2372*67e74705SXin Li case GVA_StrongODR:
2373*67e74705SXin Li return true;
2374*67e74705SXin Li }
2375*67e74705SXin Li llvm_unreachable("No such linkage");
2376*67e74705SXin Li }
2377*67e74705SXin Li
maybeSetTrivialComdat(const Decl & D,llvm::GlobalObject & GO)2378*67e74705SXin Li void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
2379*67e74705SXin Li llvm::GlobalObject &GO) {
2380*67e74705SXin Li if (!shouldBeInCOMDAT(*this, D))
2381*67e74705SXin Li return;
2382*67e74705SXin Li GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
2383*67e74705SXin Li }
2384*67e74705SXin Li
2385*67e74705SXin Li /// Pass IsTentative as true if you want to create a tentative definition.
EmitGlobalVarDefinition(const VarDecl * D,bool IsTentative)2386*67e74705SXin Li void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
2387*67e74705SXin Li bool IsTentative) {
2388*67e74705SXin Li llvm::Constant *Init = nullptr;
2389*67e74705SXin Li QualType ASTTy = D->getType();
2390*67e74705SXin Li CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2391*67e74705SXin Li bool NeedsGlobalCtor = false;
2392*67e74705SXin Li bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
2393*67e74705SXin Li
2394*67e74705SXin Li const VarDecl *InitDecl;
2395*67e74705SXin Li const Expr *InitExpr = D->getAnyInitializer(InitDecl);
2396*67e74705SXin Li
2397*67e74705SXin Li // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
2398*67e74705SXin Li // as part of their declaration." Sema has already checked for
2399*67e74705SXin Li // error cases, so we just need to set Init to UndefValue.
2400*67e74705SXin Li if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
2401*67e74705SXin Li D->hasAttr<CUDASharedAttr>())
2402*67e74705SXin Li Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
2403*67e74705SXin Li else if (!InitExpr) {
2404*67e74705SXin Li // This is a tentative definition; tentative definitions are
2405*67e74705SXin Li // implicitly initialized with { 0 }.
2406*67e74705SXin Li //
2407*67e74705SXin Li // Note that tentative definitions are only emitted at the end of
2408*67e74705SXin Li // a translation unit, so they should never have incomplete
2409*67e74705SXin Li // type. In addition, EmitTentativeDefinition makes sure that we
2410*67e74705SXin Li // never attempt to emit a tentative definition if a real one
2411*67e74705SXin Li // exists. A use may still exists, however, so we still may need
2412*67e74705SXin Li // to do a RAUW.
2413*67e74705SXin Li assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
2414*67e74705SXin Li Init = EmitNullConstant(D->getType());
2415*67e74705SXin Li } else {
2416*67e74705SXin Li initializedGlobalDecl = GlobalDecl(D);
2417*67e74705SXin Li Init = EmitConstantInit(*InitDecl);
2418*67e74705SXin Li
2419*67e74705SXin Li if (!Init) {
2420*67e74705SXin Li QualType T = InitExpr->getType();
2421*67e74705SXin Li if (D->getType()->isReferenceType())
2422*67e74705SXin Li T = D->getType();
2423*67e74705SXin Li
2424*67e74705SXin Li if (getLangOpts().CPlusPlus) {
2425*67e74705SXin Li Init = EmitNullConstant(T);
2426*67e74705SXin Li NeedsGlobalCtor = true;
2427*67e74705SXin Li } else {
2428*67e74705SXin Li ErrorUnsupported(D, "static initializer");
2429*67e74705SXin Li Init = llvm::UndefValue::get(getTypes().ConvertType(T));
2430*67e74705SXin Li }
2431*67e74705SXin Li } else {
2432*67e74705SXin Li // We don't need an initializer, so remove the entry for the delayed
2433*67e74705SXin Li // initializer position (just in case this entry was delayed) if we
2434*67e74705SXin Li // also don't need to register a destructor.
2435*67e74705SXin Li if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
2436*67e74705SXin Li DelayedCXXInitPosition.erase(D);
2437*67e74705SXin Li }
2438*67e74705SXin Li }
2439*67e74705SXin Li
2440*67e74705SXin Li llvm::Type* InitType = Init->getType();
2441*67e74705SXin Li llvm::Constant *Entry =
2442*67e74705SXin Li GetAddrOfGlobalVar(D, InitType, /*IsForDefinition=*/!IsTentative);
2443*67e74705SXin Li
2444*67e74705SXin Li // Strip off a bitcast if we got one back.
2445*67e74705SXin Li if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2446*67e74705SXin Li assert(CE->getOpcode() == llvm::Instruction::BitCast ||
2447*67e74705SXin Li CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
2448*67e74705SXin Li // All zero index gep.
2449*67e74705SXin Li CE->getOpcode() == llvm::Instruction::GetElementPtr);
2450*67e74705SXin Li Entry = CE->getOperand(0);
2451*67e74705SXin Li }
2452*67e74705SXin Li
2453*67e74705SXin Li // Entry is now either a Function or GlobalVariable.
2454*67e74705SXin Li auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
2455*67e74705SXin Li
2456*67e74705SXin Li // We have a definition after a declaration with the wrong type.
2457*67e74705SXin Li // We must make a new GlobalVariable* and update everything that used OldGV
2458*67e74705SXin Li // (a declaration or tentative definition) with the new GlobalVariable*
2459*67e74705SXin Li // (which will be a definition).
2460*67e74705SXin Li //
2461*67e74705SXin Li // This happens if there is a prototype for a global (e.g.
2462*67e74705SXin Li // "extern int x[];") and then a definition of a different type (e.g.
2463*67e74705SXin Li // "int x[10];"). This also happens when an initializer has a different type
2464*67e74705SXin Li // from the type of the global (this happens with unions).
2465*67e74705SXin Li if (!GV ||
2466*67e74705SXin Li GV->getType()->getElementType() != InitType ||
2467*67e74705SXin Li GV->getType()->getAddressSpace() !=
2468*67e74705SXin Li GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
2469*67e74705SXin Li
2470*67e74705SXin Li // Move the old entry aside so that we'll create a new one.
2471*67e74705SXin Li Entry->setName(StringRef());
2472*67e74705SXin Li
2473*67e74705SXin Li // Make a new global with the correct type, this is now guaranteed to work.
2474*67e74705SXin Li GV = cast<llvm::GlobalVariable>(
2475*67e74705SXin Li GetAddrOfGlobalVar(D, InitType, /*IsForDefinition=*/!IsTentative));
2476*67e74705SXin Li
2477*67e74705SXin Li // Replace all uses of the old global with the new global
2478*67e74705SXin Li llvm::Constant *NewPtrForOldDecl =
2479*67e74705SXin Li llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2480*67e74705SXin Li Entry->replaceAllUsesWith(NewPtrForOldDecl);
2481*67e74705SXin Li
2482*67e74705SXin Li // Erase the old global, since it is no longer used.
2483*67e74705SXin Li cast<llvm::GlobalValue>(Entry)->eraseFromParent();
2484*67e74705SXin Li }
2485*67e74705SXin Li
2486*67e74705SXin Li MaybeHandleStaticInExternC(D, GV);
2487*67e74705SXin Li
2488*67e74705SXin Li if (D->hasAttr<AnnotateAttr>())
2489*67e74705SXin Li AddGlobalAnnotations(D, GV);
2490*67e74705SXin Li
2491*67e74705SXin Li // Set the llvm linkage type as appropriate.
2492*67e74705SXin Li llvm::GlobalValue::LinkageTypes Linkage =
2493*67e74705SXin Li getLLVMLinkageVarDefinition(D, GV->isConstant());
2494*67e74705SXin Li
2495*67e74705SXin Li // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
2496*67e74705SXin Li // the device. [...]"
2497*67e74705SXin Li // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
2498*67e74705SXin Li // __device__, declares a variable that: [...]
2499*67e74705SXin Li // Is accessible from all the threads within the grid and from the host
2500*67e74705SXin Li // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
2501*67e74705SXin Li // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
2502*67e74705SXin Li if (GV && LangOpts.CUDA) {
2503*67e74705SXin Li if (LangOpts.CUDAIsDevice) {
2504*67e74705SXin Li if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
2505*67e74705SXin Li GV->setExternallyInitialized(true);
2506*67e74705SXin Li } else {
2507*67e74705SXin Li // Host-side shadows of external declarations of device-side
2508*67e74705SXin Li // global variables become internal definitions. These have to
2509*67e74705SXin Li // be internal in order to prevent name conflicts with global
2510*67e74705SXin Li // host variables with the same name in a different TUs.
2511*67e74705SXin Li if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
2512*67e74705SXin Li Linkage = llvm::GlobalValue::InternalLinkage;
2513*67e74705SXin Li
2514*67e74705SXin Li // Shadow variables and their properties must be registered
2515*67e74705SXin Li // with CUDA runtime.
2516*67e74705SXin Li unsigned Flags = 0;
2517*67e74705SXin Li if (!D->hasDefinition())
2518*67e74705SXin Li Flags |= CGCUDARuntime::ExternDeviceVar;
2519*67e74705SXin Li if (D->hasAttr<CUDAConstantAttr>())
2520*67e74705SXin Li Flags |= CGCUDARuntime::ConstantDeviceVar;
2521*67e74705SXin Li getCUDARuntime().registerDeviceVar(*GV, Flags);
2522*67e74705SXin Li } else if (D->hasAttr<CUDASharedAttr>())
2523*67e74705SXin Li // __shared__ variables are odd. Shadows do get created, but
2524*67e74705SXin Li // they are not registered with the CUDA runtime, so they
2525*67e74705SXin Li // can't really be used to access their device-side
2526*67e74705SXin Li // counterparts. It's not clear yet whether it's nvcc's bug or
2527*67e74705SXin Li // a feature, but we've got to do the same for compatibility.
2528*67e74705SXin Li Linkage = llvm::GlobalValue::InternalLinkage;
2529*67e74705SXin Li }
2530*67e74705SXin Li }
2531*67e74705SXin Li GV->setInitializer(Init);
2532*67e74705SXin Li
2533*67e74705SXin Li // If it is safe to mark the global 'constant', do so now.
2534*67e74705SXin Li GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
2535*67e74705SXin Li isTypeConstant(D->getType(), true));
2536*67e74705SXin Li
2537*67e74705SXin Li // If it is in a read-only section, mark it 'constant'.
2538*67e74705SXin Li if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
2539*67e74705SXin Li const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
2540*67e74705SXin Li if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
2541*67e74705SXin Li GV->setConstant(true);
2542*67e74705SXin Li }
2543*67e74705SXin Li
2544*67e74705SXin Li GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2545*67e74705SXin Li
2546*67e74705SXin Li
2547*67e74705SXin Li // On Darwin, if the normal linkage of a C++ thread_local variable is
2548*67e74705SXin Li // LinkOnce or Weak, we keep the normal linkage to prevent multiple
2549*67e74705SXin Li // copies within a linkage unit; otherwise, the backing variable has
2550*67e74705SXin Li // internal linkage and all accesses should just be calls to the
2551*67e74705SXin Li // Itanium-specified entry point, which has the normal linkage of the
2552*67e74705SXin Li // variable. This is to preserve the ability to change the implementation
2553*67e74705SXin Li // behind the scenes.
2554*67e74705SXin Li if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
2555*67e74705SXin Li Context.getTargetInfo().getTriple().isOSDarwin() &&
2556*67e74705SXin Li !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
2557*67e74705SXin Li !llvm::GlobalVariable::isWeakLinkage(Linkage))
2558*67e74705SXin Li Linkage = llvm::GlobalValue::InternalLinkage;
2559*67e74705SXin Li
2560*67e74705SXin Li GV->setLinkage(Linkage);
2561*67e74705SXin Li if (D->hasAttr<DLLImportAttr>())
2562*67e74705SXin Li GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2563*67e74705SXin Li else if (D->hasAttr<DLLExportAttr>())
2564*67e74705SXin Li GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
2565*67e74705SXin Li else
2566*67e74705SXin Li GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
2567*67e74705SXin Li
2568*67e74705SXin Li if (Linkage == llvm::GlobalVariable::CommonLinkage)
2569*67e74705SXin Li // common vars aren't constant even if declared const.
2570*67e74705SXin Li GV->setConstant(false);
2571*67e74705SXin Li
2572*67e74705SXin Li setNonAliasAttributes(D, GV);
2573*67e74705SXin Li
2574*67e74705SXin Li if (D->getTLSKind() && !GV->isThreadLocal()) {
2575*67e74705SXin Li if (D->getTLSKind() == VarDecl::TLS_Dynamic)
2576*67e74705SXin Li CXXThreadLocals.push_back(D);
2577*67e74705SXin Li setTLSMode(GV, *D);
2578*67e74705SXin Li }
2579*67e74705SXin Li
2580*67e74705SXin Li maybeSetTrivialComdat(*D, *GV);
2581*67e74705SXin Li
2582*67e74705SXin Li // Emit the initializer function if necessary.
2583*67e74705SXin Li if (NeedsGlobalCtor || NeedsGlobalDtor)
2584*67e74705SXin Li EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
2585*67e74705SXin Li
2586*67e74705SXin Li SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
2587*67e74705SXin Li
2588*67e74705SXin Li // Emit global variable debug information.
2589*67e74705SXin Li if (CGDebugInfo *DI = getModuleDebugInfo())
2590*67e74705SXin Li if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
2591*67e74705SXin Li DI->EmitGlobalVariable(GV, D);
2592*67e74705SXin Li }
2593*67e74705SXin Li
isVarDeclStrongDefinition(const ASTContext & Context,CodeGenModule & CGM,const VarDecl * D,bool NoCommon)2594*67e74705SXin Li static bool isVarDeclStrongDefinition(const ASTContext &Context,
2595*67e74705SXin Li CodeGenModule &CGM, const VarDecl *D,
2596*67e74705SXin Li bool NoCommon) {
2597*67e74705SXin Li // Don't give variables common linkage if -fno-common was specified unless it
2598*67e74705SXin Li // was overridden by a NoCommon attribute.
2599*67e74705SXin Li if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
2600*67e74705SXin Li return true;
2601*67e74705SXin Li
2602*67e74705SXin Li // C11 6.9.2/2:
2603*67e74705SXin Li // A declaration of an identifier for an object that has file scope without
2604*67e74705SXin Li // an initializer, and without a storage-class specifier or with the
2605*67e74705SXin Li // storage-class specifier static, constitutes a tentative definition.
2606*67e74705SXin Li if (D->getInit() || D->hasExternalStorage())
2607*67e74705SXin Li return true;
2608*67e74705SXin Li
2609*67e74705SXin Li // A variable cannot be both common and exist in a section.
2610*67e74705SXin Li if (D->hasAttr<SectionAttr>())
2611*67e74705SXin Li return true;
2612*67e74705SXin Li
2613*67e74705SXin Li // Thread local vars aren't considered common linkage.
2614*67e74705SXin Li if (D->getTLSKind())
2615*67e74705SXin Li return true;
2616*67e74705SXin Li
2617*67e74705SXin Li // Tentative definitions marked with WeakImportAttr are true definitions.
2618*67e74705SXin Li if (D->hasAttr<WeakImportAttr>())
2619*67e74705SXin Li return true;
2620*67e74705SXin Li
2621*67e74705SXin Li // A variable cannot be both common and exist in a comdat.
2622*67e74705SXin Li if (shouldBeInCOMDAT(CGM, *D))
2623*67e74705SXin Li return true;
2624*67e74705SXin Li
2625*67e74705SXin Li // Declarations with a required alignment do not have common linkage in MSVC
2626*67e74705SXin Li // mode.
2627*67e74705SXin Li if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2628*67e74705SXin Li if (D->hasAttr<AlignedAttr>())
2629*67e74705SXin Li return true;
2630*67e74705SXin Li QualType VarType = D->getType();
2631*67e74705SXin Li if (Context.isAlignmentRequired(VarType))
2632*67e74705SXin Li return true;
2633*67e74705SXin Li
2634*67e74705SXin Li if (const auto *RT = VarType->getAs<RecordType>()) {
2635*67e74705SXin Li const RecordDecl *RD = RT->getDecl();
2636*67e74705SXin Li for (const FieldDecl *FD : RD->fields()) {
2637*67e74705SXin Li if (FD->isBitField())
2638*67e74705SXin Li continue;
2639*67e74705SXin Li if (FD->hasAttr<AlignedAttr>())
2640*67e74705SXin Li return true;
2641*67e74705SXin Li if (Context.isAlignmentRequired(FD->getType()))
2642*67e74705SXin Li return true;
2643*67e74705SXin Li }
2644*67e74705SXin Li }
2645*67e74705SXin Li }
2646*67e74705SXin Li
2647*67e74705SXin Li return false;
2648*67e74705SXin Li }
2649*67e74705SXin Li
getLLVMLinkageForDeclarator(const DeclaratorDecl * D,GVALinkage Linkage,bool IsConstantVariable)2650*67e74705SXin Li llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
2651*67e74705SXin Li const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
2652*67e74705SXin Li if (Linkage == GVA_Internal)
2653*67e74705SXin Li return llvm::Function::InternalLinkage;
2654*67e74705SXin Li
2655*67e74705SXin Li if (D->hasAttr<WeakAttr>()) {
2656*67e74705SXin Li if (IsConstantVariable)
2657*67e74705SXin Li return llvm::GlobalVariable::WeakODRLinkage;
2658*67e74705SXin Li else
2659*67e74705SXin Li return llvm::GlobalVariable::WeakAnyLinkage;
2660*67e74705SXin Li }
2661*67e74705SXin Li
2662*67e74705SXin Li // We are guaranteed to have a strong definition somewhere else,
2663*67e74705SXin Li // so we can use available_externally linkage.
2664*67e74705SXin Li if (Linkage == GVA_AvailableExternally)
2665*67e74705SXin Li return llvm::Function::AvailableExternallyLinkage;
2666*67e74705SXin Li
2667*67e74705SXin Li // Note that Apple's kernel linker doesn't support symbol
2668*67e74705SXin Li // coalescing, so we need to avoid linkonce and weak linkages there.
2669*67e74705SXin Li // Normally, this means we just map to internal, but for explicit
2670*67e74705SXin Li // instantiations we'll map to external.
2671*67e74705SXin Li
2672*67e74705SXin Li // In C++, the compiler has to emit a definition in every translation unit
2673*67e74705SXin Li // that references the function. We should use linkonce_odr because
2674*67e74705SXin Li // a) if all references in this translation unit are optimized away, we
2675*67e74705SXin Li // don't need to codegen it. b) if the function persists, it needs to be
2676*67e74705SXin Li // merged with other definitions. c) C++ has the ODR, so we know the
2677*67e74705SXin Li // definition is dependable.
2678*67e74705SXin Li if (Linkage == GVA_DiscardableODR)
2679*67e74705SXin Li return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
2680*67e74705SXin Li : llvm::Function::InternalLinkage;
2681*67e74705SXin Li
2682*67e74705SXin Li // An explicit instantiation of a template has weak linkage, since
2683*67e74705SXin Li // explicit instantiations can occur in multiple translation units
2684*67e74705SXin Li // and must all be equivalent. However, we are not allowed to
2685*67e74705SXin Li // throw away these explicit instantiations.
2686*67e74705SXin Li //
2687*67e74705SXin Li // We don't currently support CUDA device code spread out across multiple TUs,
2688*67e74705SXin Li // so say that CUDA templates are either external (for kernels) or internal.
2689*67e74705SXin Li // This lets llvm perform aggressive inter-procedural optimizations.
2690*67e74705SXin Li if (Linkage == GVA_StrongODR) {
2691*67e74705SXin Li if (Context.getLangOpts().AppleKext)
2692*67e74705SXin Li return llvm::Function::ExternalLinkage;
2693*67e74705SXin Li if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
2694*67e74705SXin Li return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
2695*67e74705SXin Li : llvm::Function::InternalLinkage;
2696*67e74705SXin Li return llvm::Function::WeakODRLinkage;
2697*67e74705SXin Li }
2698*67e74705SXin Li
2699*67e74705SXin Li // C++ doesn't have tentative definitions and thus cannot have common
2700*67e74705SXin Li // linkage.
2701*67e74705SXin Li if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
2702*67e74705SXin Li !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
2703*67e74705SXin Li CodeGenOpts.NoCommon))
2704*67e74705SXin Li return llvm::GlobalVariable::CommonLinkage;
2705*67e74705SXin Li
2706*67e74705SXin Li // selectany symbols are externally visible, so use weak instead of
2707*67e74705SXin Li // linkonce. MSVC optimizes away references to const selectany globals, so
2708*67e74705SXin Li // all definitions should be the same and ODR linkage should be used.
2709*67e74705SXin Li // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
2710*67e74705SXin Li if (D->hasAttr<SelectAnyAttr>())
2711*67e74705SXin Li return llvm::GlobalVariable::WeakODRLinkage;
2712*67e74705SXin Li
2713*67e74705SXin Li // Otherwise, we have strong external linkage.
2714*67e74705SXin Li assert(Linkage == GVA_StrongExternal);
2715*67e74705SXin Li return llvm::GlobalVariable::ExternalLinkage;
2716*67e74705SXin Li }
2717*67e74705SXin Li
getLLVMLinkageVarDefinition(const VarDecl * VD,bool IsConstant)2718*67e74705SXin Li llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
2719*67e74705SXin Li const VarDecl *VD, bool IsConstant) {
2720*67e74705SXin Li GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
2721*67e74705SXin Li return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
2722*67e74705SXin Li }
2723*67e74705SXin Li
2724*67e74705SXin Li /// Replace the uses of a function that was declared with a non-proto type.
2725*67e74705SXin Li /// We want to silently drop extra arguments from call sites
replaceUsesOfNonProtoConstant(llvm::Constant * old,llvm::Function * newFn)2726*67e74705SXin Li static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
2727*67e74705SXin Li llvm::Function *newFn) {
2728*67e74705SXin Li // Fast path.
2729*67e74705SXin Li if (old->use_empty()) return;
2730*67e74705SXin Li
2731*67e74705SXin Li llvm::Type *newRetTy = newFn->getReturnType();
2732*67e74705SXin Li SmallVector<llvm::Value*, 4> newArgs;
2733*67e74705SXin Li SmallVector<llvm::OperandBundleDef, 1> newBundles;
2734*67e74705SXin Li
2735*67e74705SXin Li for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
2736*67e74705SXin Li ui != ue; ) {
2737*67e74705SXin Li llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
2738*67e74705SXin Li llvm::User *user = use->getUser();
2739*67e74705SXin Li
2740*67e74705SXin Li // Recognize and replace uses of bitcasts. Most calls to
2741*67e74705SXin Li // unprototyped functions will use bitcasts.
2742*67e74705SXin Li if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
2743*67e74705SXin Li if (bitcast->getOpcode() == llvm::Instruction::BitCast)
2744*67e74705SXin Li replaceUsesOfNonProtoConstant(bitcast, newFn);
2745*67e74705SXin Li continue;
2746*67e74705SXin Li }
2747*67e74705SXin Li
2748*67e74705SXin Li // Recognize calls to the function.
2749*67e74705SXin Li llvm::CallSite callSite(user);
2750*67e74705SXin Li if (!callSite) continue;
2751*67e74705SXin Li if (!callSite.isCallee(&*use)) continue;
2752*67e74705SXin Li
2753*67e74705SXin Li // If the return types don't match exactly, then we can't
2754*67e74705SXin Li // transform this call unless it's dead.
2755*67e74705SXin Li if (callSite->getType() != newRetTy && !callSite->use_empty())
2756*67e74705SXin Li continue;
2757*67e74705SXin Li
2758*67e74705SXin Li // Get the call site's attribute list.
2759*67e74705SXin Li SmallVector<llvm::AttributeSet, 8> newAttrs;
2760*67e74705SXin Li llvm::AttributeSet oldAttrs = callSite.getAttributes();
2761*67e74705SXin Li
2762*67e74705SXin Li // Collect any return attributes from the call.
2763*67e74705SXin Li if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
2764*67e74705SXin Li newAttrs.push_back(
2765*67e74705SXin Li llvm::AttributeSet::get(newFn->getContext(),
2766*67e74705SXin Li oldAttrs.getRetAttributes()));
2767*67e74705SXin Li
2768*67e74705SXin Li // If the function was passed too few arguments, don't transform.
2769*67e74705SXin Li unsigned newNumArgs = newFn->arg_size();
2770*67e74705SXin Li if (callSite.arg_size() < newNumArgs) continue;
2771*67e74705SXin Li
2772*67e74705SXin Li // If extra arguments were passed, we silently drop them.
2773*67e74705SXin Li // If any of the types mismatch, we don't transform.
2774*67e74705SXin Li unsigned argNo = 0;
2775*67e74705SXin Li bool dontTransform = false;
2776*67e74705SXin Li for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
2777*67e74705SXin Li ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
2778*67e74705SXin Li if (callSite.getArgument(argNo)->getType() != ai->getType()) {
2779*67e74705SXin Li dontTransform = true;
2780*67e74705SXin Li break;
2781*67e74705SXin Li }
2782*67e74705SXin Li
2783*67e74705SXin Li // Add any parameter attributes.
2784*67e74705SXin Li if (oldAttrs.hasAttributes(argNo + 1))
2785*67e74705SXin Li newAttrs.
2786*67e74705SXin Li push_back(llvm::
2787*67e74705SXin Li AttributeSet::get(newFn->getContext(),
2788*67e74705SXin Li oldAttrs.getParamAttributes(argNo + 1)));
2789*67e74705SXin Li }
2790*67e74705SXin Li if (dontTransform)
2791*67e74705SXin Li continue;
2792*67e74705SXin Li
2793*67e74705SXin Li if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
2794*67e74705SXin Li newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
2795*67e74705SXin Li oldAttrs.getFnAttributes()));
2796*67e74705SXin Li
2797*67e74705SXin Li // Okay, we can transform this. Create the new call instruction and copy
2798*67e74705SXin Li // over the required information.
2799*67e74705SXin Li newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
2800*67e74705SXin Li
2801*67e74705SXin Li // Copy over any operand bundles.
2802*67e74705SXin Li callSite.getOperandBundlesAsDefs(newBundles);
2803*67e74705SXin Li
2804*67e74705SXin Li llvm::CallSite newCall;
2805*67e74705SXin Li if (callSite.isCall()) {
2806*67e74705SXin Li newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
2807*67e74705SXin Li callSite.getInstruction());
2808*67e74705SXin Li } else {
2809*67e74705SXin Li auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
2810*67e74705SXin Li newCall = llvm::InvokeInst::Create(newFn,
2811*67e74705SXin Li oldInvoke->getNormalDest(),
2812*67e74705SXin Li oldInvoke->getUnwindDest(),
2813*67e74705SXin Li newArgs, newBundles, "",
2814*67e74705SXin Li callSite.getInstruction());
2815*67e74705SXin Li }
2816*67e74705SXin Li newArgs.clear(); // for the next iteration
2817*67e74705SXin Li
2818*67e74705SXin Li if (!newCall->getType()->isVoidTy())
2819*67e74705SXin Li newCall->takeName(callSite.getInstruction());
2820*67e74705SXin Li newCall.setAttributes(
2821*67e74705SXin Li llvm::AttributeSet::get(newFn->getContext(), newAttrs));
2822*67e74705SXin Li newCall.setCallingConv(callSite.getCallingConv());
2823*67e74705SXin Li
2824*67e74705SXin Li // Finally, remove the old call, replacing any uses with the new one.
2825*67e74705SXin Li if (!callSite->use_empty())
2826*67e74705SXin Li callSite->replaceAllUsesWith(newCall.getInstruction());
2827*67e74705SXin Li
2828*67e74705SXin Li // Copy debug location attached to CI.
2829*67e74705SXin Li if (callSite->getDebugLoc())
2830*67e74705SXin Li newCall->setDebugLoc(callSite->getDebugLoc());
2831*67e74705SXin Li
2832*67e74705SXin Li callSite->eraseFromParent();
2833*67e74705SXin Li }
2834*67e74705SXin Li }
2835*67e74705SXin Li
2836*67e74705SXin Li /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
2837*67e74705SXin Li /// implement a function with no prototype, e.g. "int foo() {}". If there are
2838*67e74705SXin Li /// existing call uses of the old function in the module, this adjusts them to
2839*67e74705SXin Li /// call the new function directly.
2840*67e74705SXin Li ///
2841*67e74705SXin Li /// This is not just a cleanup: the always_inline pass requires direct calls to
2842*67e74705SXin Li /// functions to be able to inline them. If there is a bitcast in the way, it
2843*67e74705SXin Li /// won't inline them. Instcombine normally deletes these calls, but it isn't
2844*67e74705SXin Li /// run at -O0.
ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue * Old,llvm::Function * NewFn)2845*67e74705SXin Li static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2846*67e74705SXin Li llvm::Function *NewFn) {
2847*67e74705SXin Li // If we're redefining a global as a function, don't transform it.
2848*67e74705SXin Li if (!isa<llvm::Function>(Old)) return;
2849*67e74705SXin Li
2850*67e74705SXin Li replaceUsesOfNonProtoConstant(Old, NewFn);
2851*67e74705SXin Li }
2852*67e74705SXin Li
HandleCXXStaticMemberVarInstantiation(VarDecl * VD)2853*67e74705SXin Li void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
2854*67e74705SXin Li auto DK = VD->isThisDeclarationADefinition();
2855*67e74705SXin Li if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
2856*67e74705SXin Li return;
2857*67e74705SXin Li
2858*67e74705SXin Li TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
2859*67e74705SXin Li // If we have a definition, this might be a deferred decl. If the
2860*67e74705SXin Li // instantiation is explicit, make sure we emit it at the end.
2861*67e74705SXin Li if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
2862*67e74705SXin Li GetAddrOfGlobalVar(VD);
2863*67e74705SXin Li
2864*67e74705SXin Li EmitTopLevelDecl(VD);
2865*67e74705SXin Li }
2866*67e74705SXin Li
EmitGlobalFunctionDefinition(GlobalDecl GD,llvm::GlobalValue * GV)2867*67e74705SXin Li void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
2868*67e74705SXin Li llvm::GlobalValue *GV) {
2869*67e74705SXin Li const auto *D = cast<FunctionDecl>(GD.getDecl());
2870*67e74705SXin Li
2871*67e74705SXin Li // Compute the function info and LLVM type.
2872*67e74705SXin Li const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2873*67e74705SXin Li llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2874*67e74705SXin Li
2875*67e74705SXin Li // Get or create the prototype for the function.
2876*67e74705SXin Li if (!GV || (GV->getType()->getElementType() != Ty))
2877*67e74705SXin Li GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
2878*67e74705SXin Li /*DontDefer=*/true,
2879*67e74705SXin Li /*IsForDefinition=*/true));
2880*67e74705SXin Li
2881*67e74705SXin Li // Already emitted.
2882*67e74705SXin Li if (!GV->isDeclaration())
2883*67e74705SXin Li return;
2884*67e74705SXin Li
2885*67e74705SXin Li // We need to set linkage and visibility on the function before
2886*67e74705SXin Li // generating code for it because various parts of IR generation
2887*67e74705SXin Li // want to propagate this information down (e.g. to local static
2888*67e74705SXin Li // declarations).
2889*67e74705SXin Li auto *Fn = cast<llvm::Function>(GV);
2890*67e74705SXin Li setFunctionLinkage(GD, Fn);
2891*67e74705SXin Li setFunctionDLLStorageClass(GD, Fn);
2892*67e74705SXin Li
2893*67e74705SXin Li // FIXME: this is redundant with part of setFunctionDefinitionAttributes
2894*67e74705SXin Li setGlobalVisibility(Fn, D);
2895*67e74705SXin Li
2896*67e74705SXin Li MaybeHandleStaticInExternC(D, Fn);
2897*67e74705SXin Li
2898*67e74705SXin Li maybeSetTrivialComdat(*D, *Fn);
2899*67e74705SXin Li
2900*67e74705SXin Li CodeGenFunction(*this).GenerateCode(D, Fn, FI);
2901*67e74705SXin Li
2902*67e74705SXin Li setFunctionDefinitionAttributes(D, Fn);
2903*67e74705SXin Li SetLLVMFunctionAttributesForDefinition(D, Fn);
2904*67e74705SXin Li
2905*67e74705SXin Li if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
2906*67e74705SXin Li AddGlobalCtor(Fn, CA->getPriority());
2907*67e74705SXin Li if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
2908*67e74705SXin Li AddGlobalDtor(Fn, DA->getPriority());
2909*67e74705SXin Li if (D->hasAttr<AnnotateAttr>())
2910*67e74705SXin Li AddGlobalAnnotations(D, Fn);
2911*67e74705SXin Li }
2912*67e74705SXin Li
EmitAliasDefinition(GlobalDecl GD)2913*67e74705SXin Li void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
2914*67e74705SXin Li const auto *D = cast<ValueDecl>(GD.getDecl());
2915*67e74705SXin Li const AliasAttr *AA = D->getAttr<AliasAttr>();
2916*67e74705SXin Li assert(AA && "Not an alias?");
2917*67e74705SXin Li
2918*67e74705SXin Li StringRef MangledName = getMangledName(GD);
2919*67e74705SXin Li
2920*67e74705SXin Li if (AA->getAliasee() == MangledName) {
2921*67e74705SXin Li Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
2922*67e74705SXin Li return;
2923*67e74705SXin Li }
2924*67e74705SXin Li
2925*67e74705SXin Li // If there is a definition in the module, then it wins over the alias.
2926*67e74705SXin Li // This is dubious, but allow it to be safe. Just ignore the alias.
2927*67e74705SXin Li llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2928*67e74705SXin Li if (Entry && !Entry->isDeclaration())
2929*67e74705SXin Li return;
2930*67e74705SXin Li
2931*67e74705SXin Li Aliases.push_back(GD);
2932*67e74705SXin Li
2933*67e74705SXin Li llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
2934*67e74705SXin Li
2935*67e74705SXin Li // Create a reference to the named value. This ensures that it is emitted
2936*67e74705SXin Li // if a deferred decl.
2937*67e74705SXin Li llvm::Constant *Aliasee;
2938*67e74705SXin Li if (isa<llvm::FunctionType>(DeclTy))
2939*67e74705SXin Li Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
2940*67e74705SXin Li /*ForVTable=*/false);
2941*67e74705SXin Li else
2942*67e74705SXin Li Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
2943*67e74705SXin Li llvm::PointerType::getUnqual(DeclTy),
2944*67e74705SXin Li /*D=*/nullptr);
2945*67e74705SXin Li
2946*67e74705SXin Li // Create the new alias itself, but don't set a name yet.
2947*67e74705SXin Li auto *GA = llvm::GlobalAlias::create(
2948*67e74705SXin Li DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
2949*67e74705SXin Li
2950*67e74705SXin Li if (Entry) {
2951*67e74705SXin Li if (GA->getAliasee() == Entry) {
2952*67e74705SXin Li Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
2953*67e74705SXin Li return;
2954*67e74705SXin Li }
2955*67e74705SXin Li
2956*67e74705SXin Li assert(Entry->isDeclaration());
2957*67e74705SXin Li
2958*67e74705SXin Li // If there is a declaration in the module, then we had an extern followed
2959*67e74705SXin Li // by the alias, as in:
2960*67e74705SXin Li // extern int test6();
2961*67e74705SXin Li // ...
2962*67e74705SXin Li // int test6() __attribute__((alias("test7")));
2963*67e74705SXin Li //
2964*67e74705SXin Li // Remove it and replace uses of it with the alias.
2965*67e74705SXin Li GA->takeName(Entry);
2966*67e74705SXin Li
2967*67e74705SXin Li Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
2968*67e74705SXin Li Entry->getType()));
2969*67e74705SXin Li Entry->eraseFromParent();
2970*67e74705SXin Li } else {
2971*67e74705SXin Li GA->setName(MangledName);
2972*67e74705SXin Li }
2973*67e74705SXin Li
2974*67e74705SXin Li // Set attributes which are particular to an alias; this is a
2975*67e74705SXin Li // specialization of the attributes which may be set on a global
2976*67e74705SXin Li // variable/function.
2977*67e74705SXin Li if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
2978*67e74705SXin Li D->isWeakImported()) {
2979*67e74705SXin Li GA->setLinkage(llvm::Function::WeakAnyLinkage);
2980*67e74705SXin Li }
2981*67e74705SXin Li
2982*67e74705SXin Li if (const auto *VD = dyn_cast<VarDecl>(D))
2983*67e74705SXin Li if (VD->getTLSKind())
2984*67e74705SXin Li setTLSMode(GA, *VD);
2985*67e74705SXin Li
2986*67e74705SXin Li setAliasAttributes(D, GA);
2987*67e74705SXin Li }
2988*67e74705SXin Li
emitIFuncDefinition(GlobalDecl GD)2989*67e74705SXin Li void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
2990*67e74705SXin Li const auto *D = cast<ValueDecl>(GD.getDecl());
2991*67e74705SXin Li const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
2992*67e74705SXin Li assert(IFA && "Not an ifunc?");
2993*67e74705SXin Li
2994*67e74705SXin Li StringRef MangledName = getMangledName(GD);
2995*67e74705SXin Li
2996*67e74705SXin Li if (IFA->getResolver() == MangledName) {
2997*67e74705SXin Li Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
2998*67e74705SXin Li return;
2999*67e74705SXin Li }
3000*67e74705SXin Li
3001*67e74705SXin Li // Report an error if some definition overrides ifunc.
3002*67e74705SXin Li llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3003*67e74705SXin Li if (Entry && !Entry->isDeclaration()) {
3004*67e74705SXin Li GlobalDecl OtherGD;
3005*67e74705SXin Li if (lookupRepresentativeDecl(MangledName, OtherGD) &&
3006*67e74705SXin Li DiagnosedConflictingDefinitions.insert(GD).second) {
3007*67e74705SXin Li Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name);
3008*67e74705SXin Li Diags.Report(OtherGD.getDecl()->getLocation(),
3009*67e74705SXin Li diag::note_previous_definition);
3010*67e74705SXin Li }
3011*67e74705SXin Li return;
3012*67e74705SXin Li }
3013*67e74705SXin Li
3014*67e74705SXin Li Aliases.push_back(GD);
3015*67e74705SXin Li
3016*67e74705SXin Li llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3017*67e74705SXin Li llvm::Constant *Resolver =
3018*67e74705SXin Li GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
3019*67e74705SXin Li /*ForVTable=*/false);
3020*67e74705SXin Li llvm::GlobalIFunc *GIF =
3021*67e74705SXin Li llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
3022*67e74705SXin Li "", Resolver, &getModule());
3023*67e74705SXin Li if (Entry) {
3024*67e74705SXin Li if (GIF->getResolver() == Entry) {
3025*67e74705SXin Li Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3026*67e74705SXin Li return;
3027*67e74705SXin Li }
3028*67e74705SXin Li assert(Entry->isDeclaration());
3029*67e74705SXin Li
3030*67e74705SXin Li // If there is a declaration in the module, then we had an extern followed
3031*67e74705SXin Li // by the ifunc, as in:
3032*67e74705SXin Li // extern int test();
3033*67e74705SXin Li // ...
3034*67e74705SXin Li // int test() __attribute__((ifunc("resolver")));
3035*67e74705SXin Li //
3036*67e74705SXin Li // Remove it and replace uses of it with the ifunc.
3037*67e74705SXin Li GIF->takeName(Entry);
3038*67e74705SXin Li
3039*67e74705SXin Li Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
3040*67e74705SXin Li Entry->getType()));
3041*67e74705SXin Li Entry->eraseFromParent();
3042*67e74705SXin Li } else
3043*67e74705SXin Li GIF->setName(MangledName);
3044*67e74705SXin Li
3045*67e74705SXin Li SetCommonAttributes(D, GIF);
3046*67e74705SXin Li }
3047*67e74705SXin Li
getIntrinsic(unsigned IID,ArrayRef<llvm::Type * > Tys)3048*67e74705SXin Li llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
3049*67e74705SXin Li ArrayRef<llvm::Type*> Tys) {
3050*67e74705SXin Li return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
3051*67e74705SXin Li Tys);
3052*67e74705SXin Li }
3053*67e74705SXin Li
3054*67e74705SXin Li static llvm::StringMapEntry<llvm::GlobalVariable *> &
GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable * > & Map,const StringLiteral * Literal,bool TargetIsLSB,bool & IsUTF16,unsigned & StringLength)3055*67e74705SXin Li GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
3056*67e74705SXin Li const StringLiteral *Literal, bool TargetIsLSB,
3057*67e74705SXin Li bool &IsUTF16, unsigned &StringLength) {
3058*67e74705SXin Li StringRef String = Literal->getString();
3059*67e74705SXin Li unsigned NumBytes = String.size();
3060*67e74705SXin Li
3061*67e74705SXin Li // Check for simple case.
3062*67e74705SXin Li if (!Literal->containsNonAsciiOrNull()) {
3063*67e74705SXin Li StringLength = NumBytes;
3064*67e74705SXin Li return *Map.insert(std::make_pair(String, nullptr)).first;
3065*67e74705SXin Li }
3066*67e74705SXin Li
3067*67e74705SXin Li // Otherwise, convert the UTF8 literals into a string of shorts.
3068*67e74705SXin Li IsUTF16 = true;
3069*67e74705SXin Li
3070*67e74705SXin Li SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
3071*67e74705SXin Li const UTF8 *FromPtr = (const UTF8 *)String.data();
3072*67e74705SXin Li UTF16 *ToPtr = &ToBuf[0];
3073*67e74705SXin Li
3074*67e74705SXin Li (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
3075*67e74705SXin Li &ToPtr, ToPtr + NumBytes,
3076*67e74705SXin Li strictConversion);
3077*67e74705SXin Li
3078*67e74705SXin Li // ConvertUTF8toUTF16 returns the length in ToPtr.
3079*67e74705SXin Li StringLength = ToPtr - &ToBuf[0];
3080*67e74705SXin Li
3081*67e74705SXin Li // Add an explicit null.
3082*67e74705SXin Li *ToPtr = 0;
3083*67e74705SXin Li return *Map.insert(std::make_pair(
3084*67e74705SXin Li StringRef(reinterpret_cast<const char *>(ToBuf.data()),
3085*67e74705SXin Li (StringLength + 1) * 2),
3086*67e74705SXin Li nullptr)).first;
3087*67e74705SXin Li }
3088*67e74705SXin Li
3089*67e74705SXin Li static llvm::StringMapEntry<llvm::GlobalVariable *> &
GetConstantStringEntry(llvm::StringMap<llvm::GlobalVariable * > & Map,const StringLiteral * Literal,unsigned & StringLength)3090*67e74705SXin Li GetConstantStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
3091*67e74705SXin Li const StringLiteral *Literal, unsigned &StringLength) {
3092*67e74705SXin Li StringRef String = Literal->getString();
3093*67e74705SXin Li StringLength = String.size();
3094*67e74705SXin Li return *Map.insert(std::make_pair(String, nullptr)).first;
3095*67e74705SXin Li }
3096*67e74705SXin Li
3097*67e74705SXin Li ConstantAddress
GetAddrOfConstantCFString(const StringLiteral * Literal)3098*67e74705SXin Li CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
3099*67e74705SXin Li unsigned StringLength = 0;
3100*67e74705SXin Li bool isUTF16 = false;
3101*67e74705SXin Li llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
3102*67e74705SXin Li GetConstantCFStringEntry(CFConstantStringMap, Literal,
3103*67e74705SXin Li getDataLayout().isLittleEndian(), isUTF16,
3104*67e74705SXin Li StringLength);
3105*67e74705SXin Li
3106*67e74705SXin Li if (auto *C = Entry.second)
3107*67e74705SXin Li return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
3108*67e74705SXin Li
3109*67e74705SXin Li llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
3110*67e74705SXin Li llvm::Constant *Zeros[] = { Zero, Zero };
3111*67e74705SXin Li llvm::Value *V;
3112*67e74705SXin Li
3113*67e74705SXin Li // If we don't already have it, get __CFConstantStringClassReference.
3114*67e74705SXin Li if (!CFConstantStringClassRef) {
3115*67e74705SXin Li llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
3116*67e74705SXin Li Ty = llvm::ArrayType::get(Ty, 0);
3117*67e74705SXin Li llvm::Constant *GV =
3118*67e74705SXin Li CreateRuntimeVariable(Ty, "__CFConstantStringClassReference");
3119*67e74705SXin Li
3120*67e74705SXin Li if (getTarget().getTriple().isOSBinFormatCOFF()) {
3121*67e74705SXin Li IdentifierInfo &II = getContext().Idents.get(GV->getName());
3122*67e74705SXin Li TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl();
3123*67e74705SXin Li DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
3124*67e74705SXin Li llvm::GlobalValue *CGV = cast<llvm::GlobalValue>(GV);
3125*67e74705SXin Li
3126*67e74705SXin Li const VarDecl *VD = nullptr;
3127*67e74705SXin Li for (const auto &Result : DC->lookup(&II))
3128*67e74705SXin Li if ((VD = dyn_cast<VarDecl>(Result)))
3129*67e74705SXin Li break;
3130*67e74705SXin Li
3131*67e74705SXin Li if (!VD || !VD->hasAttr<DLLExportAttr>()) {
3132*67e74705SXin Li CGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3133*67e74705SXin Li CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3134*67e74705SXin Li } else {
3135*67e74705SXin Li CGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3136*67e74705SXin Li CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3137*67e74705SXin Li }
3138*67e74705SXin Li }
3139*67e74705SXin Li
3140*67e74705SXin Li // Decay array -> ptr
3141*67e74705SXin Li V = llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
3142*67e74705SXin Li CFConstantStringClassRef = V;
3143*67e74705SXin Li } else {
3144*67e74705SXin Li V = CFConstantStringClassRef;
3145*67e74705SXin Li }
3146*67e74705SXin Li
3147*67e74705SXin Li QualType CFTy = getContext().getCFConstantStringType();
3148*67e74705SXin Li
3149*67e74705SXin Li auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
3150*67e74705SXin Li
3151*67e74705SXin Li llvm::Constant *Fields[4];
3152*67e74705SXin Li
3153*67e74705SXin Li // Class pointer.
3154*67e74705SXin Li Fields[0] = cast<llvm::ConstantExpr>(V);
3155*67e74705SXin Li
3156*67e74705SXin Li // Flags.
3157*67e74705SXin Li llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
3158*67e74705SXin Li Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0)
3159*67e74705SXin Li : llvm::ConstantInt::get(Ty, 0x07C8);
3160*67e74705SXin Li
3161*67e74705SXin Li // String pointer.
3162*67e74705SXin Li llvm::Constant *C = nullptr;
3163*67e74705SXin Li if (isUTF16) {
3164*67e74705SXin Li auto Arr = llvm::makeArrayRef(
3165*67e74705SXin Li reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
3166*67e74705SXin Li Entry.first().size() / 2);
3167*67e74705SXin Li C = llvm::ConstantDataArray::get(VMContext, Arr);
3168*67e74705SXin Li } else {
3169*67e74705SXin Li C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
3170*67e74705SXin Li }
3171*67e74705SXin Li
3172*67e74705SXin Li // Note: -fwritable-strings doesn't make the backing store strings of
3173*67e74705SXin Li // CFStrings writable. (See <rdar://problem/10657500>)
3174*67e74705SXin Li auto *GV =
3175*67e74705SXin Li new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
3176*67e74705SXin Li llvm::GlobalValue::PrivateLinkage, C, ".str");
3177*67e74705SXin Li GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3178*67e74705SXin Li // Don't enforce the target's minimum global alignment, since the only use
3179*67e74705SXin Li // of the string is via this class initializer.
3180*67e74705SXin Li CharUnits Align = isUTF16
3181*67e74705SXin Li ? getContext().getTypeAlignInChars(getContext().ShortTy)
3182*67e74705SXin Li : getContext().getTypeAlignInChars(getContext().CharTy);
3183*67e74705SXin Li GV->setAlignment(Align.getQuantity());
3184*67e74705SXin Li
3185*67e74705SXin Li // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
3186*67e74705SXin Li // Without it LLVM can merge the string with a non unnamed_addr one during
3187*67e74705SXin Li // LTO. Doing that changes the section it ends in, which surprises ld64.
3188*67e74705SXin Li if (getTarget().getTriple().isOSBinFormatMachO())
3189*67e74705SXin Li GV->setSection(isUTF16 ? "__TEXT,__ustring"
3190*67e74705SXin Li : "__TEXT,__cstring,cstring_literals");
3191*67e74705SXin Li
3192*67e74705SXin Li // String.
3193*67e74705SXin Li Fields[2] =
3194*67e74705SXin Li llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
3195*67e74705SXin Li
3196*67e74705SXin Li if (isUTF16)
3197*67e74705SXin Li // Cast the UTF16 string to the correct type.
3198*67e74705SXin Li Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
3199*67e74705SXin Li
3200*67e74705SXin Li // String length.
3201*67e74705SXin Li Ty = getTypes().ConvertType(getContext().LongTy);
3202*67e74705SXin Li Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
3203*67e74705SXin Li
3204*67e74705SXin Li CharUnits Alignment = getPointerAlign();
3205*67e74705SXin Li
3206*67e74705SXin Li // The struct.
3207*67e74705SXin Li C = llvm::ConstantStruct::get(STy, Fields);
3208*67e74705SXin Li GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
3209*67e74705SXin Li llvm::GlobalVariable::PrivateLinkage, C,
3210*67e74705SXin Li "_unnamed_cfstring_");
3211*67e74705SXin Li GV->setAlignment(Alignment.getQuantity());
3212*67e74705SXin Li switch (getTarget().getTriple().getObjectFormat()) {
3213*67e74705SXin Li case llvm::Triple::UnknownObjectFormat:
3214*67e74705SXin Li llvm_unreachable("unknown file format");
3215*67e74705SXin Li case llvm::Triple::COFF:
3216*67e74705SXin Li case llvm::Triple::ELF:
3217*67e74705SXin Li GV->setSection("cfstring");
3218*67e74705SXin Li break;
3219*67e74705SXin Li case llvm::Triple::MachO:
3220*67e74705SXin Li GV->setSection("__DATA,__cfstring");
3221*67e74705SXin Li break;
3222*67e74705SXin Li }
3223*67e74705SXin Li Entry.second = GV;
3224*67e74705SXin Li
3225*67e74705SXin Li return ConstantAddress(GV, Alignment);
3226*67e74705SXin Li }
3227*67e74705SXin Li
3228*67e74705SXin Li ConstantAddress
GetAddrOfConstantString(const StringLiteral * Literal)3229*67e74705SXin Li CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
3230*67e74705SXin Li unsigned StringLength = 0;
3231*67e74705SXin Li llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
3232*67e74705SXin Li GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
3233*67e74705SXin Li
3234*67e74705SXin Li if (auto *C = Entry.second)
3235*67e74705SXin Li return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
3236*67e74705SXin Li
3237*67e74705SXin Li llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
3238*67e74705SXin Li llvm::Constant *Zeros[] = { Zero, Zero };
3239*67e74705SXin Li llvm::Value *V;
3240*67e74705SXin Li // If we don't already have it, get _NSConstantStringClassReference.
3241*67e74705SXin Li if (!ConstantStringClassRef) {
3242*67e74705SXin Li std::string StringClass(getLangOpts().ObjCConstantStringClass);
3243*67e74705SXin Li llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
3244*67e74705SXin Li llvm::Constant *GV;
3245*67e74705SXin Li if (LangOpts.ObjCRuntime.isNonFragile()) {
3246*67e74705SXin Li std::string str =
3247*67e74705SXin Li StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
3248*67e74705SXin Li : "OBJC_CLASS_$_" + StringClass;
3249*67e74705SXin Li GV = getObjCRuntime().GetClassGlobal(str);
3250*67e74705SXin Li // Make sure the result is of the correct type.
3251*67e74705SXin Li llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
3252*67e74705SXin Li V = llvm::ConstantExpr::getBitCast(GV, PTy);
3253*67e74705SXin Li ConstantStringClassRef = V;
3254*67e74705SXin Li } else {
3255*67e74705SXin Li std::string str =
3256*67e74705SXin Li StringClass.empty() ? "_NSConstantStringClassReference"
3257*67e74705SXin Li : "_" + StringClass + "ClassReference";
3258*67e74705SXin Li llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
3259*67e74705SXin Li GV = CreateRuntimeVariable(PTy, str);
3260*67e74705SXin Li // Decay array -> ptr
3261*67e74705SXin Li V = llvm::ConstantExpr::getGetElementPtr(PTy, GV, Zeros);
3262*67e74705SXin Li ConstantStringClassRef = V;
3263*67e74705SXin Li }
3264*67e74705SXin Li } else
3265*67e74705SXin Li V = ConstantStringClassRef;
3266*67e74705SXin Li
3267*67e74705SXin Li if (!NSConstantStringType) {
3268*67e74705SXin Li // Construct the type for a constant NSString.
3269*67e74705SXin Li RecordDecl *D = Context.buildImplicitRecord("__builtin_NSString");
3270*67e74705SXin Li D->startDefinition();
3271*67e74705SXin Li
3272*67e74705SXin Li QualType FieldTypes[3];
3273*67e74705SXin Li
3274*67e74705SXin Li // const int *isa;
3275*67e74705SXin Li FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
3276*67e74705SXin Li // const char *str;
3277*67e74705SXin Li FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
3278*67e74705SXin Li // unsigned int length;
3279*67e74705SXin Li FieldTypes[2] = Context.UnsignedIntTy;
3280*67e74705SXin Li
3281*67e74705SXin Li // Create fields
3282*67e74705SXin Li for (unsigned i = 0; i < 3; ++i) {
3283*67e74705SXin Li FieldDecl *Field = FieldDecl::Create(Context, D,
3284*67e74705SXin Li SourceLocation(),
3285*67e74705SXin Li SourceLocation(), nullptr,
3286*67e74705SXin Li FieldTypes[i], /*TInfo=*/nullptr,
3287*67e74705SXin Li /*BitWidth=*/nullptr,
3288*67e74705SXin Li /*Mutable=*/false,
3289*67e74705SXin Li ICIS_NoInit);
3290*67e74705SXin Li Field->setAccess(AS_public);
3291*67e74705SXin Li D->addDecl(Field);
3292*67e74705SXin Li }
3293*67e74705SXin Li
3294*67e74705SXin Li D->completeDefinition();
3295*67e74705SXin Li QualType NSTy = Context.getTagDeclType(D);
3296*67e74705SXin Li NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
3297*67e74705SXin Li }
3298*67e74705SXin Li
3299*67e74705SXin Li llvm::Constant *Fields[3];
3300*67e74705SXin Li
3301*67e74705SXin Li // Class pointer.
3302*67e74705SXin Li Fields[0] = cast<llvm::ConstantExpr>(V);
3303*67e74705SXin Li
3304*67e74705SXin Li // String pointer.
3305*67e74705SXin Li llvm::Constant *C =
3306*67e74705SXin Li llvm::ConstantDataArray::getString(VMContext, Entry.first());
3307*67e74705SXin Li
3308*67e74705SXin Li llvm::GlobalValue::LinkageTypes Linkage;
3309*67e74705SXin Li bool isConstant;
3310*67e74705SXin Li Linkage = llvm::GlobalValue::PrivateLinkage;
3311*67e74705SXin Li isConstant = !LangOpts.WritableStrings;
3312*67e74705SXin Li
3313*67e74705SXin Li auto *GV = new llvm::GlobalVariable(getModule(), C->getType(), isConstant,
3314*67e74705SXin Li Linkage, C, ".str");
3315*67e74705SXin Li GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3316*67e74705SXin Li // Don't enforce the target's minimum global alignment, since the only use
3317*67e74705SXin Li // of the string is via this class initializer.
3318*67e74705SXin Li CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
3319*67e74705SXin Li GV->setAlignment(Align.getQuantity());
3320*67e74705SXin Li Fields[1] =
3321*67e74705SXin Li llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
3322*67e74705SXin Li
3323*67e74705SXin Li // String length.
3324*67e74705SXin Li llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
3325*67e74705SXin Li Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
3326*67e74705SXin Li
3327*67e74705SXin Li // The struct.
3328*67e74705SXin Li CharUnits Alignment = getPointerAlign();
3329*67e74705SXin Li C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
3330*67e74705SXin Li GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
3331*67e74705SXin Li llvm::GlobalVariable::PrivateLinkage, C,
3332*67e74705SXin Li "_unnamed_nsstring_");
3333*67e74705SXin Li GV->setAlignment(Alignment.getQuantity());
3334*67e74705SXin Li const char *NSStringSection = "__OBJC,__cstring_object,regular,no_dead_strip";
3335*67e74705SXin Li const char *NSStringNonFragileABISection =
3336*67e74705SXin Li "__DATA,__objc_stringobj,regular,no_dead_strip";
3337*67e74705SXin Li // FIXME. Fix section.
3338*67e74705SXin Li GV->setSection(LangOpts.ObjCRuntime.isNonFragile()
3339*67e74705SXin Li ? NSStringNonFragileABISection
3340*67e74705SXin Li : NSStringSection);
3341*67e74705SXin Li Entry.second = GV;
3342*67e74705SXin Li
3343*67e74705SXin Li return ConstantAddress(GV, Alignment);
3344*67e74705SXin Li }
3345*67e74705SXin Li
getObjCFastEnumerationStateType()3346*67e74705SXin Li QualType CodeGenModule::getObjCFastEnumerationStateType() {
3347*67e74705SXin Li if (ObjCFastEnumerationStateType.isNull()) {
3348*67e74705SXin Li RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
3349*67e74705SXin Li D->startDefinition();
3350*67e74705SXin Li
3351*67e74705SXin Li QualType FieldTypes[] = {
3352*67e74705SXin Li Context.UnsignedLongTy,
3353*67e74705SXin Li Context.getPointerType(Context.getObjCIdType()),
3354*67e74705SXin Li Context.getPointerType(Context.UnsignedLongTy),
3355*67e74705SXin Li Context.getConstantArrayType(Context.UnsignedLongTy,
3356*67e74705SXin Li llvm::APInt(32, 5), ArrayType::Normal, 0)
3357*67e74705SXin Li };
3358*67e74705SXin Li
3359*67e74705SXin Li for (size_t i = 0; i < 4; ++i) {
3360*67e74705SXin Li FieldDecl *Field = FieldDecl::Create(Context,
3361*67e74705SXin Li D,
3362*67e74705SXin Li SourceLocation(),
3363*67e74705SXin Li SourceLocation(), nullptr,
3364*67e74705SXin Li FieldTypes[i], /*TInfo=*/nullptr,
3365*67e74705SXin Li /*BitWidth=*/nullptr,
3366*67e74705SXin Li /*Mutable=*/false,
3367*67e74705SXin Li ICIS_NoInit);
3368*67e74705SXin Li Field->setAccess(AS_public);
3369*67e74705SXin Li D->addDecl(Field);
3370*67e74705SXin Li }
3371*67e74705SXin Li
3372*67e74705SXin Li D->completeDefinition();
3373*67e74705SXin Li ObjCFastEnumerationStateType = Context.getTagDeclType(D);
3374*67e74705SXin Li }
3375*67e74705SXin Li
3376*67e74705SXin Li return ObjCFastEnumerationStateType;
3377*67e74705SXin Li }
3378*67e74705SXin Li
3379*67e74705SXin Li llvm::Constant *
GetConstantArrayFromStringLiteral(const StringLiteral * E)3380*67e74705SXin Li CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
3381*67e74705SXin Li assert(!E->getType()->isPointerType() && "Strings are always arrays");
3382*67e74705SXin Li
3383*67e74705SXin Li // Don't emit it as the address of the string, emit the string data itself
3384*67e74705SXin Li // as an inline array.
3385*67e74705SXin Li if (E->getCharByteWidth() == 1) {
3386*67e74705SXin Li SmallString<64> Str(E->getString());
3387*67e74705SXin Li
3388*67e74705SXin Li // Resize the string to the right size, which is indicated by its type.
3389*67e74705SXin Li const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
3390*67e74705SXin Li Str.resize(CAT->getSize().getZExtValue());
3391*67e74705SXin Li return llvm::ConstantDataArray::getString(VMContext, Str, false);
3392*67e74705SXin Li }
3393*67e74705SXin Li
3394*67e74705SXin Li auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
3395*67e74705SXin Li llvm::Type *ElemTy = AType->getElementType();
3396*67e74705SXin Li unsigned NumElements = AType->getNumElements();
3397*67e74705SXin Li
3398*67e74705SXin Li // Wide strings have either 2-byte or 4-byte elements.
3399*67e74705SXin Li if (ElemTy->getPrimitiveSizeInBits() == 16) {
3400*67e74705SXin Li SmallVector<uint16_t, 32> Elements;
3401*67e74705SXin Li Elements.reserve(NumElements);
3402*67e74705SXin Li
3403*67e74705SXin Li for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3404*67e74705SXin Li Elements.push_back(E->getCodeUnit(i));
3405*67e74705SXin Li Elements.resize(NumElements);
3406*67e74705SXin Li return llvm::ConstantDataArray::get(VMContext, Elements);
3407*67e74705SXin Li }
3408*67e74705SXin Li
3409*67e74705SXin Li assert(ElemTy->getPrimitiveSizeInBits() == 32);
3410*67e74705SXin Li SmallVector<uint32_t, 32> Elements;
3411*67e74705SXin Li Elements.reserve(NumElements);
3412*67e74705SXin Li
3413*67e74705SXin Li for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3414*67e74705SXin Li Elements.push_back(E->getCodeUnit(i));
3415*67e74705SXin Li Elements.resize(NumElements);
3416*67e74705SXin Li return llvm::ConstantDataArray::get(VMContext, Elements);
3417*67e74705SXin Li }
3418*67e74705SXin Li
3419*67e74705SXin Li static llvm::GlobalVariable *
GenerateStringLiteral(llvm::Constant * C,llvm::GlobalValue::LinkageTypes LT,CodeGenModule & CGM,StringRef GlobalName,CharUnits Alignment)3420*67e74705SXin Li GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
3421*67e74705SXin Li CodeGenModule &CGM, StringRef GlobalName,
3422*67e74705SXin Li CharUnits Alignment) {
3423*67e74705SXin Li // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
3424*67e74705SXin Li unsigned AddrSpace = 0;
3425*67e74705SXin Li if (CGM.getLangOpts().OpenCL)
3426*67e74705SXin Li AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
3427*67e74705SXin Li
3428*67e74705SXin Li llvm::Module &M = CGM.getModule();
3429*67e74705SXin Li // Create a global variable for this string
3430*67e74705SXin Li auto *GV = new llvm::GlobalVariable(
3431*67e74705SXin Li M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
3432*67e74705SXin Li nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
3433*67e74705SXin Li GV->setAlignment(Alignment.getQuantity());
3434*67e74705SXin Li GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3435*67e74705SXin Li if (GV->isWeakForLinker()) {
3436*67e74705SXin Li assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
3437*67e74705SXin Li GV->setComdat(M.getOrInsertComdat(GV->getName()));
3438*67e74705SXin Li }
3439*67e74705SXin Li
3440*67e74705SXin Li return GV;
3441*67e74705SXin Li }
3442*67e74705SXin Li
3443*67e74705SXin Li /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
3444*67e74705SXin Li /// constant array for the given string literal.
3445*67e74705SXin Li ConstantAddress
GetAddrOfConstantStringFromLiteral(const StringLiteral * S,StringRef Name)3446*67e74705SXin Li CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
3447*67e74705SXin Li StringRef Name) {
3448*67e74705SXin Li CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
3449*67e74705SXin Li
3450*67e74705SXin Li llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
3451*67e74705SXin Li llvm::GlobalVariable **Entry = nullptr;
3452*67e74705SXin Li if (!LangOpts.WritableStrings) {
3453*67e74705SXin Li Entry = &ConstantStringMap[C];
3454*67e74705SXin Li if (auto GV = *Entry) {
3455*67e74705SXin Li if (Alignment.getQuantity() > GV->getAlignment())
3456*67e74705SXin Li GV->setAlignment(Alignment.getQuantity());
3457*67e74705SXin Li return ConstantAddress(GV, Alignment);
3458*67e74705SXin Li }
3459*67e74705SXin Li }
3460*67e74705SXin Li
3461*67e74705SXin Li SmallString<256> MangledNameBuffer;
3462*67e74705SXin Li StringRef GlobalVariableName;
3463*67e74705SXin Li llvm::GlobalValue::LinkageTypes LT;
3464*67e74705SXin Li
3465*67e74705SXin Li // Mangle the string literal if the ABI allows for it. However, we cannot
3466*67e74705SXin Li // do this if we are compiling with ASan or -fwritable-strings because they
3467*67e74705SXin Li // rely on strings having normal linkage.
3468*67e74705SXin Li if (!LangOpts.WritableStrings &&
3469*67e74705SXin Li !LangOpts.Sanitize.has(SanitizerKind::Address) &&
3470*67e74705SXin Li getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
3471*67e74705SXin Li llvm::raw_svector_ostream Out(MangledNameBuffer);
3472*67e74705SXin Li getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
3473*67e74705SXin Li
3474*67e74705SXin Li LT = llvm::GlobalValue::LinkOnceODRLinkage;
3475*67e74705SXin Li GlobalVariableName = MangledNameBuffer;
3476*67e74705SXin Li } else {
3477*67e74705SXin Li LT = llvm::GlobalValue::PrivateLinkage;
3478*67e74705SXin Li GlobalVariableName = Name;
3479*67e74705SXin Li }
3480*67e74705SXin Li
3481*67e74705SXin Li auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
3482*67e74705SXin Li if (Entry)
3483*67e74705SXin Li *Entry = GV;
3484*67e74705SXin Li
3485*67e74705SXin Li SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
3486*67e74705SXin Li QualType());
3487*67e74705SXin Li return ConstantAddress(GV, Alignment);
3488*67e74705SXin Li }
3489*67e74705SXin Li
3490*67e74705SXin Li /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
3491*67e74705SXin Li /// array for the given ObjCEncodeExpr node.
3492*67e74705SXin Li ConstantAddress
GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr * E)3493*67e74705SXin Li CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
3494*67e74705SXin Li std::string Str;
3495*67e74705SXin Li getContext().getObjCEncodingForType(E->getEncodedType(), Str);
3496*67e74705SXin Li
3497*67e74705SXin Li return GetAddrOfConstantCString(Str);
3498*67e74705SXin Li }
3499*67e74705SXin Li
3500*67e74705SXin Li /// GetAddrOfConstantCString - Returns a pointer to a character array containing
3501*67e74705SXin Li /// the literal and a terminating '\0' character.
3502*67e74705SXin Li /// The result has pointer to array type.
GetAddrOfConstantCString(const std::string & Str,const char * GlobalName)3503*67e74705SXin Li ConstantAddress CodeGenModule::GetAddrOfConstantCString(
3504*67e74705SXin Li const std::string &Str, const char *GlobalName) {
3505*67e74705SXin Li StringRef StrWithNull(Str.c_str(), Str.size() + 1);
3506*67e74705SXin Li CharUnits Alignment =
3507*67e74705SXin Li getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
3508*67e74705SXin Li
3509*67e74705SXin Li llvm::Constant *C =
3510*67e74705SXin Li llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
3511*67e74705SXin Li
3512*67e74705SXin Li // Don't share any string literals if strings aren't constant.
3513*67e74705SXin Li llvm::GlobalVariable **Entry = nullptr;
3514*67e74705SXin Li if (!LangOpts.WritableStrings) {
3515*67e74705SXin Li Entry = &ConstantStringMap[C];
3516*67e74705SXin Li if (auto GV = *Entry) {
3517*67e74705SXin Li if (Alignment.getQuantity() > GV->getAlignment())
3518*67e74705SXin Li GV->setAlignment(Alignment.getQuantity());
3519*67e74705SXin Li return ConstantAddress(GV, Alignment);
3520*67e74705SXin Li }
3521*67e74705SXin Li }
3522*67e74705SXin Li
3523*67e74705SXin Li // Get the default prefix if a name wasn't specified.
3524*67e74705SXin Li if (!GlobalName)
3525*67e74705SXin Li GlobalName = ".str";
3526*67e74705SXin Li // Create a global variable for this.
3527*67e74705SXin Li auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
3528*67e74705SXin Li GlobalName, Alignment);
3529*67e74705SXin Li if (Entry)
3530*67e74705SXin Li *Entry = GV;
3531*67e74705SXin Li return ConstantAddress(GV, Alignment);
3532*67e74705SXin Li }
3533*67e74705SXin Li
GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr * E,const Expr * Init)3534*67e74705SXin Li ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
3535*67e74705SXin Li const MaterializeTemporaryExpr *E, const Expr *Init) {
3536*67e74705SXin Li assert((E->getStorageDuration() == SD_Static ||
3537*67e74705SXin Li E->getStorageDuration() == SD_Thread) && "not a global temporary");
3538*67e74705SXin Li const auto *VD = cast<VarDecl>(E->getExtendingDecl());
3539*67e74705SXin Li
3540*67e74705SXin Li // If we're not materializing a subobject of the temporary, keep the
3541*67e74705SXin Li // cv-qualifiers from the type of the MaterializeTemporaryExpr.
3542*67e74705SXin Li QualType MaterializedType = Init->getType();
3543*67e74705SXin Li if (Init == E->GetTemporaryExpr())
3544*67e74705SXin Li MaterializedType = E->getType();
3545*67e74705SXin Li
3546*67e74705SXin Li CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
3547*67e74705SXin Li
3548*67e74705SXin Li if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
3549*67e74705SXin Li return ConstantAddress(Slot, Align);
3550*67e74705SXin Li
3551*67e74705SXin Li // FIXME: If an externally-visible declaration extends multiple temporaries,
3552*67e74705SXin Li // we need to give each temporary the same name in every translation unit (and
3553*67e74705SXin Li // we also need to make the temporaries externally-visible).
3554*67e74705SXin Li SmallString<256> Name;
3555*67e74705SXin Li llvm::raw_svector_ostream Out(Name);
3556*67e74705SXin Li getCXXABI().getMangleContext().mangleReferenceTemporary(
3557*67e74705SXin Li VD, E->getManglingNumber(), Out);
3558*67e74705SXin Li
3559*67e74705SXin Li APValue *Value = nullptr;
3560*67e74705SXin Li if (E->getStorageDuration() == SD_Static) {
3561*67e74705SXin Li // We might have a cached constant initializer for this temporary. Note
3562*67e74705SXin Li // that this might have a different value from the value computed by
3563*67e74705SXin Li // evaluating the initializer if the surrounding constant expression
3564*67e74705SXin Li // modifies the temporary.
3565*67e74705SXin Li Value = getContext().getMaterializedTemporaryValue(E, false);
3566*67e74705SXin Li if (Value && Value->isUninit())
3567*67e74705SXin Li Value = nullptr;
3568*67e74705SXin Li }
3569*67e74705SXin Li
3570*67e74705SXin Li // Try evaluating it now, it might have a constant initializer.
3571*67e74705SXin Li Expr::EvalResult EvalResult;
3572*67e74705SXin Li if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
3573*67e74705SXin Li !EvalResult.hasSideEffects())
3574*67e74705SXin Li Value = &EvalResult.Val;
3575*67e74705SXin Li
3576*67e74705SXin Li llvm::Constant *InitialValue = nullptr;
3577*67e74705SXin Li bool Constant = false;
3578*67e74705SXin Li llvm::Type *Type;
3579*67e74705SXin Li if (Value) {
3580*67e74705SXin Li // The temporary has a constant initializer, use it.
3581*67e74705SXin Li InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr);
3582*67e74705SXin Li Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
3583*67e74705SXin Li Type = InitialValue->getType();
3584*67e74705SXin Li } else {
3585*67e74705SXin Li // No initializer, the initialization will be provided when we
3586*67e74705SXin Li // initialize the declaration which performed lifetime extension.
3587*67e74705SXin Li Type = getTypes().ConvertTypeForMem(MaterializedType);
3588*67e74705SXin Li }
3589*67e74705SXin Li
3590*67e74705SXin Li // Create a global variable for this lifetime-extended temporary.
3591*67e74705SXin Li llvm::GlobalValue::LinkageTypes Linkage =
3592*67e74705SXin Li getLLVMLinkageVarDefinition(VD, Constant);
3593*67e74705SXin Li if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
3594*67e74705SXin Li const VarDecl *InitVD;
3595*67e74705SXin Li if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
3596*67e74705SXin Li isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
3597*67e74705SXin Li // Temporaries defined inside a class get linkonce_odr linkage because the
3598*67e74705SXin Li // class can be defined in multipe translation units.
3599*67e74705SXin Li Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
3600*67e74705SXin Li } else {
3601*67e74705SXin Li // There is no need for this temporary to have external linkage if the
3602*67e74705SXin Li // VarDecl has external linkage.
3603*67e74705SXin Li Linkage = llvm::GlobalVariable::InternalLinkage;
3604*67e74705SXin Li }
3605*67e74705SXin Li }
3606*67e74705SXin Li unsigned AddrSpace = GetGlobalVarAddressSpace(
3607*67e74705SXin Li VD, getContext().getTargetAddressSpace(MaterializedType));
3608*67e74705SXin Li auto *GV = new llvm::GlobalVariable(
3609*67e74705SXin Li getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
3610*67e74705SXin Li /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3611*67e74705SXin Li AddrSpace);
3612*67e74705SXin Li setGlobalVisibility(GV, VD);
3613*67e74705SXin Li GV->setAlignment(Align.getQuantity());
3614*67e74705SXin Li if (supportsCOMDAT() && GV->isWeakForLinker())
3615*67e74705SXin Li GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3616*67e74705SXin Li if (VD->getTLSKind())
3617*67e74705SXin Li setTLSMode(GV, *VD);
3618*67e74705SXin Li MaterializedGlobalTemporaryMap[E] = GV;
3619*67e74705SXin Li return ConstantAddress(GV, Align);
3620*67e74705SXin Li }
3621*67e74705SXin Li
3622*67e74705SXin Li /// EmitObjCPropertyImplementations - Emit information for synthesized
3623*67e74705SXin Li /// properties for an implementation.
EmitObjCPropertyImplementations(const ObjCImplementationDecl * D)3624*67e74705SXin Li void CodeGenModule::EmitObjCPropertyImplementations(const
3625*67e74705SXin Li ObjCImplementationDecl *D) {
3626*67e74705SXin Li for (const auto *PID : D->property_impls()) {
3627*67e74705SXin Li // Dynamic is just for type-checking.
3628*67e74705SXin Li if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
3629*67e74705SXin Li ObjCPropertyDecl *PD = PID->getPropertyDecl();
3630*67e74705SXin Li
3631*67e74705SXin Li // Determine which methods need to be implemented, some may have
3632*67e74705SXin Li // been overridden. Note that ::isPropertyAccessor is not the method
3633*67e74705SXin Li // we want, that just indicates if the decl came from a
3634*67e74705SXin Li // property. What we want to know is if the method is defined in
3635*67e74705SXin Li // this implementation.
3636*67e74705SXin Li if (!D->getInstanceMethod(PD->getGetterName()))
3637*67e74705SXin Li CodeGenFunction(*this).GenerateObjCGetter(
3638*67e74705SXin Li const_cast<ObjCImplementationDecl *>(D), PID);
3639*67e74705SXin Li if (!PD->isReadOnly() &&
3640*67e74705SXin Li !D->getInstanceMethod(PD->getSetterName()))
3641*67e74705SXin Li CodeGenFunction(*this).GenerateObjCSetter(
3642*67e74705SXin Li const_cast<ObjCImplementationDecl *>(D), PID);
3643*67e74705SXin Li }
3644*67e74705SXin Li }
3645*67e74705SXin Li }
3646*67e74705SXin Li
needsDestructMethod(ObjCImplementationDecl * impl)3647*67e74705SXin Li static bool needsDestructMethod(ObjCImplementationDecl *impl) {
3648*67e74705SXin Li const ObjCInterfaceDecl *iface = impl->getClassInterface();
3649*67e74705SXin Li for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
3650*67e74705SXin Li ivar; ivar = ivar->getNextIvar())
3651*67e74705SXin Li if (ivar->getType().isDestructedType())
3652*67e74705SXin Li return true;
3653*67e74705SXin Li
3654*67e74705SXin Li return false;
3655*67e74705SXin Li }
3656*67e74705SXin Li
AllTrivialInitializers(CodeGenModule & CGM,ObjCImplementationDecl * D)3657*67e74705SXin Li static bool AllTrivialInitializers(CodeGenModule &CGM,
3658*67e74705SXin Li ObjCImplementationDecl *D) {
3659*67e74705SXin Li CodeGenFunction CGF(CGM);
3660*67e74705SXin Li for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
3661*67e74705SXin Li E = D->init_end(); B != E; ++B) {
3662*67e74705SXin Li CXXCtorInitializer *CtorInitExp = *B;
3663*67e74705SXin Li Expr *Init = CtorInitExp->getInit();
3664*67e74705SXin Li if (!CGF.isTrivialInitializer(Init))
3665*67e74705SXin Li return false;
3666*67e74705SXin Li }
3667*67e74705SXin Li return true;
3668*67e74705SXin Li }
3669*67e74705SXin Li
3670*67e74705SXin Li /// EmitObjCIvarInitializations - Emit information for ivar initialization
3671*67e74705SXin Li /// for an implementation.
EmitObjCIvarInitializations(ObjCImplementationDecl * D)3672*67e74705SXin Li void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
3673*67e74705SXin Li // We might need a .cxx_destruct even if we don't have any ivar initializers.
3674*67e74705SXin Li if (needsDestructMethod(D)) {
3675*67e74705SXin Li IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
3676*67e74705SXin Li Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3677*67e74705SXin Li ObjCMethodDecl *DTORMethod =
3678*67e74705SXin Li ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
3679*67e74705SXin Li cxxSelector, getContext().VoidTy, nullptr, D,
3680*67e74705SXin Li /*isInstance=*/true, /*isVariadic=*/false,
3681*67e74705SXin Li /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
3682*67e74705SXin Li /*isDefined=*/false, ObjCMethodDecl::Required);
3683*67e74705SXin Li D->addInstanceMethod(DTORMethod);
3684*67e74705SXin Li CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
3685*67e74705SXin Li D->setHasDestructors(true);
3686*67e74705SXin Li }
3687*67e74705SXin Li
3688*67e74705SXin Li // If the implementation doesn't have any ivar initializers, we don't need
3689*67e74705SXin Li // a .cxx_construct.
3690*67e74705SXin Li if (D->getNumIvarInitializers() == 0 ||
3691*67e74705SXin Li AllTrivialInitializers(*this, D))
3692*67e74705SXin Li return;
3693*67e74705SXin Li
3694*67e74705SXin Li IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
3695*67e74705SXin Li Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3696*67e74705SXin Li // The constructor returns 'self'.
3697*67e74705SXin Li ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
3698*67e74705SXin Li D->getLocation(),
3699*67e74705SXin Li D->getLocation(),
3700*67e74705SXin Li cxxSelector,
3701*67e74705SXin Li getContext().getObjCIdType(),
3702*67e74705SXin Li nullptr, D, /*isInstance=*/true,
3703*67e74705SXin Li /*isVariadic=*/false,
3704*67e74705SXin Li /*isPropertyAccessor=*/true,
3705*67e74705SXin Li /*isImplicitlyDeclared=*/true,
3706*67e74705SXin Li /*isDefined=*/false,
3707*67e74705SXin Li ObjCMethodDecl::Required);
3708*67e74705SXin Li D->addInstanceMethod(CTORMethod);
3709*67e74705SXin Li CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
3710*67e74705SXin Li D->setHasNonZeroConstructors(true);
3711*67e74705SXin Li }
3712*67e74705SXin Li
3713*67e74705SXin Li /// EmitNamespace - Emit all declarations in a namespace.
EmitNamespace(const NamespaceDecl * ND)3714*67e74705SXin Li void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
3715*67e74705SXin Li for (auto *I : ND->decls()) {
3716*67e74705SXin Li if (const auto *VD = dyn_cast<VarDecl>(I))
3717*67e74705SXin Li if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
3718*67e74705SXin Li VD->getTemplateSpecializationKind() != TSK_Undeclared)
3719*67e74705SXin Li continue;
3720*67e74705SXin Li EmitTopLevelDecl(I);
3721*67e74705SXin Li }
3722*67e74705SXin Li }
3723*67e74705SXin Li
3724*67e74705SXin Li // EmitLinkageSpec - Emit all declarations in a linkage spec.
EmitLinkageSpec(const LinkageSpecDecl * LSD)3725*67e74705SXin Li void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
3726*67e74705SXin Li if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
3727*67e74705SXin Li LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
3728*67e74705SXin Li ErrorUnsupported(LSD, "linkage spec");
3729*67e74705SXin Li return;
3730*67e74705SXin Li }
3731*67e74705SXin Li
3732*67e74705SXin Li for (auto *I : LSD->decls()) {
3733*67e74705SXin Li // Meta-data for ObjC class includes references to implemented methods.
3734*67e74705SXin Li // Generate class's method definitions first.
3735*67e74705SXin Li if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
3736*67e74705SXin Li for (auto *M : OID->methods())
3737*67e74705SXin Li EmitTopLevelDecl(M);
3738*67e74705SXin Li }
3739*67e74705SXin Li EmitTopLevelDecl(I);
3740*67e74705SXin Li }
3741*67e74705SXin Li }
3742*67e74705SXin Li
3743*67e74705SXin Li /// EmitTopLevelDecl - Emit code for a single top level declaration.
EmitTopLevelDecl(Decl * D)3744*67e74705SXin Li void CodeGenModule::EmitTopLevelDecl(Decl *D) {
3745*67e74705SXin Li // Ignore dependent declarations.
3746*67e74705SXin Li if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
3747*67e74705SXin Li return;
3748*67e74705SXin Li
3749*67e74705SXin Li switch (D->getKind()) {
3750*67e74705SXin Li case Decl::CXXConversion:
3751*67e74705SXin Li case Decl::CXXMethod:
3752*67e74705SXin Li case Decl::Function:
3753*67e74705SXin Li // Skip function templates
3754*67e74705SXin Li if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3755*67e74705SXin Li cast<FunctionDecl>(D)->isLateTemplateParsed())
3756*67e74705SXin Li return;
3757*67e74705SXin Li
3758*67e74705SXin Li EmitGlobal(cast<FunctionDecl>(D));
3759*67e74705SXin Li // Always provide some coverage mapping
3760*67e74705SXin Li // even for the functions that aren't emitted.
3761*67e74705SXin Li AddDeferredUnusedCoverageMapping(D);
3762*67e74705SXin Li break;
3763*67e74705SXin Li
3764*67e74705SXin Li case Decl::Var:
3765*67e74705SXin Li // Skip variable templates
3766*67e74705SXin Li if (cast<VarDecl>(D)->getDescribedVarTemplate())
3767*67e74705SXin Li return;
3768*67e74705SXin Li case Decl::VarTemplateSpecialization:
3769*67e74705SXin Li EmitGlobal(cast<VarDecl>(D));
3770*67e74705SXin Li break;
3771*67e74705SXin Li
3772*67e74705SXin Li // Indirect fields from global anonymous structs and unions can be
3773*67e74705SXin Li // ignored; only the actual variable requires IR gen support.
3774*67e74705SXin Li case Decl::IndirectField:
3775*67e74705SXin Li break;
3776*67e74705SXin Li
3777*67e74705SXin Li // C++ Decls
3778*67e74705SXin Li case Decl::Namespace:
3779*67e74705SXin Li EmitNamespace(cast<NamespaceDecl>(D));
3780*67e74705SXin Li break;
3781*67e74705SXin Li case Decl::CXXRecord:
3782*67e74705SXin Li // Emit any static data members, they may be definitions.
3783*67e74705SXin Li for (auto *I : cast<CXXRecordDecl>(D)->decls())
3784*67e74705SXin Li if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
3785*67e74705SXin Li EmitTopLevelDecl(I);
3786*67e74705SXin Li break;
3787*67e74705SXin Li // No code generation needed.
3788*67e74705SXin Li case Decl::UsingShadow:
3789*67e74705SXin Li case Decl::ClassTemplate:
3790*67e74705SXin Li case Decl::VarTemplate:
3791*67e74705SXin Li case Decl::VarTemplatePartialSpecialization:
3792*67e74705SXin Li case Decl::FunctionTemplate:
3793*67e74705SXin Li case Decl::TypeAliasTemplate:
3794*67e74705SXin Li case Decl::Block:
3795*67e74705SXin Li case Decl::Empty:
3796*67e74705SXin Li break;
3797*67e74705SXin Li case Decl::Using: // using X; [C++]
3798*67e74705SXin Li if (CGDebugInfo *DI = getModuleDebugInfo())
3799*67e74705SXin Li DI->EmitUsingDecl(cast<UsingDecl>(*D));
3800*67e74705SXin Li return;
3801*67e74705SXin Li case Decl::NamespaceAlias:
3802*67e74705SXin Li if (CGDebugInfo *DI = getModuleDebugInfo())
3803*67e74705SXin Li DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
3804*67e74705SXin Li return;
3805*67e74705SXin Li case Decl::UsingDirective: // using namespace X; [C++]
3806*67e74705SXin Li if (CGDebugInfo *DI = getModuleDebugInfo())
3807*67e74705SXin Li DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
3808*67e74705SXin Li return;
3809*67e74705SXin Li case Decl::CXXConstructor:
3810*67e74705SXin Li // Skip function templates
3811*67e74705SXin Li if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3812*67e74705SXin Li cast<FunctionDecl>(D)->isLateTemplateParsed())
3813*67e74705SXin Li return;
3814*67e74705SXin Li
3815*67e74705SXin Li getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
3816*67e74705SXin Li break;
3817*67e74705SXin Li case Decl::CXXDestructor:
3818*67e74705SXin Li if (cast<FunctionDecl>(D)->isLateTemplateParsed())
3819*67e74705SXin Li return;
3820*67e74705SXin Li getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
3821*67e74705SXin Li break;
3822*67e74705SXin Li
3823*67e74705SXin Li case Decl::StaticAssert:
3824*67e74705SXin Li // Nothing to do.
3825*67e74705SXin Li break;
3826*67e74705SXin Li
3827*67e74705SXin Li // Objective-C Decls
3828*67e74705SXin Li
3829*67e74705SXin Li // Forward declarations, no (immediate) code generation.
3830*67e74705SXin Li case Decl::ObjCInterface:
3831*67e74705SXin Li case Decl::ObjCCategory:
3832*67e74705SXin Li break;
3833*67e74705SXin Li
3834*67e74705SXin Li case Decl::ObjCProtocol: {
3835*67e74705SXin Li auto *Proto = cast<ObjCProtocolDecl>(D);
3836*67e74705SXin Li if (Proto->isThisDeclarationADefinition())
3837*67e74705SXin Li ObjCRuntime->GenerateProtocol(Proto);
3838*67e74705SXin Li break;
3839*67e74705SXin Li }
3840*67e74705SXin Li
3841*67e74705SXin Li case Decl::ObjCCategoryImpl:
3842*67e74705SXin Li // Categories have properties but don't support synthesize so we
3843*67e74705SXin Li // can ignore them here.
3844*67e74705SXin Li ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
3845*67e74705SXin Li break;
3846*67e74705SXin Li
3847*67e74705SXin Li case Decl::ObjCImplementation: {
3848*67e74705SXin Li auto *OMD = cast<ObjCImplementationDecl>(D);
3849*67e74705SXin Li EmitObjCPropertyImplementations(OMD);
3850*67e74705SXin Li EmitObjCIvarInitializations(OMD);
3851*67e74705SXin Li ObjCRuntime->GenerateClass(OMD);
3852*67e74705SXin Li // Emit global variable debug information.
3853*67e74705SXin Li if (CGDebugInfo *DI = getModuleDebugInfo())
3854*67e74705SXin Li if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
3855*67e74705SXin Li DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
3856*67e74705SXin Li OMD->getClassInterface()), OMD->getLocation());
3857*67e74705SXin Li break;
3858*67e74705SXin Li }
3859*67e74705SXin Li case Decl::ObjCMethod: {
3860*67e74705SXin Li auto *OMD = cast<ObjCMethodDecl>(D);
3861*67e74705SXin Li // If this is not a prototype, emit the body.
3862*67e74705SXin Li if (OMD->getBody())
3863*67e74705SXin Li CodeGenFunction(*this).GenerateObjCMethod(OMD);
3864*67e74705SXin Li break;
3865*67e74705SXin Li }
3866*67e74705SXin Li case Decl::ObjCCompatibleAlias:
3867*67e74705SXin Li ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
3868*67e74705SXin Li break;
3869*67e74705SXin Li
3870*67e74705SXin Li case Decl::PragmaComment: {
3871*67e74705SXin Li const auto *PCD = cast<PragmaCommentDecl>(D);
3872*67e74705SXin Li switch (PCD->getCommentKind()) {
3873*67e74705SXin Li case PCK_Unknown:
3874*67e74705SXin Li llvm_unreachable("unexpected pragma comment kind");
3875*67e74705SXin Li case PCK_Linker:
3876*67e74705SXin Li AppendLinkerOptions(PCD->getArg());
3877*67e74705SXin Li break;
3878*67e74705SXin Li case PCK_Lib:
3879*67e74705SXin Li AddDependentLib(PCD->getArg());
3880*67e74705SXin Li break;
3881*67e74705SXin Li case PCK_Compiler:
3882*67e74705SXin Li case PCK_ExeStr:
3883*67e74705SXin Li case PCK_User:
3884*67e74705SXin Li break; // We ignore all of these.
3885*67e74705SXin Li }
3886*67e74705SXin Li break;
3887*67e74705SXin Li }
3888*67e74705SXin Li
3889*67e74705SXin Li case Decl::PragmaDetectMismatch: {
3890*67e74705SXin Li const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
3891*67e74705SXin Li AddDetectMismatch(PDMD->getName(), PDMD->getValue());
3892*67e74705SXin Li break;
3893*67e74705SXin Li }
3894*67e74705SXin Li
3895*67e74705SXin Li case Decl::LinkageSpec:
3896*67e74705SXin Li EmitLinkageSpec(cast<LinkageSpecDecl>(D));
3897*67e74705SXin Li break;
3898*67e74705SXin Li
3899*67e74705SXin Li case Decl::FileScopeAsm: {
3900*67e74705SXin Li // File-scope asm is ignored during device-side CUDA compilation.
3901*67e74705SXin Li if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
3902*67e74705SXin Li break;
3903*67e74705SXin Li // File-scope asm is ignored during device-side OpenMP compilation.
3904*67e74705SXin Li if (LangOpts.OpenMPIsDevice)
3905*67e74705SXin Li break;
3906*67e74705SXin Li auto *AD = cast<FileScopeAsmDecl>(D);
3907*67e74705SXin Li getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
3908*67e74705SXin Li break;
3909*67e74705SXin Li }
3910*67e74705SXin Li
3911*67e74705SXin Li case Decl::Import: {
3912*67e74705SXin Li auto *Import = cast<ImportDecl>(D);
3913*67e74705SXin Li
3914*67e74705SXin Li // Ignore import declarations that come from imported modules.
3915*67e74705SXin Li if (Import->getImportedOwningModule())
3916*67e74705SXin Li break;
3917*67e74705SXin Li if (CGDebugInfo *DI = getModuleDebugInfo())
3918*67e74705SXin Li DI->EmitImportDecl(*Import);
3919*67e74705SXin Li
3920*67e74705SXin Li ImportedModules.insert(Import->getImportedModule());
3921*67e74705SXin Li break;
3922*67e74705SXin Li }
3923*67e74705SXin Li
3924*67e74705SXin Li case Decl::OMPThreadPrivate:
3925*67e74705SXin Li EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
3926*67e74705SXin Li break;
3927*67e74705SXin Li
3928*67e74705SXin Li case Decl::ClassTemplateSpecialization: {
3929*67e74705SXin Li const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
3930*67e74705SXin Li if (DebugInfo &&
3931*67e74705SXin Li Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
3932*67e74705SXin Li Spec->hasDefinition())
3933*67e74705SXin Li DebugInfo->completeTemplateDefinition(*Spec);
3934*67e74705SXin Li break;
3935*67e74705SXin Li }
3936*67e74705SXin Li
3937*67e74705SXin Li case Decl::OMPDeclareReduction:
3938*67e74705SXin Li EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
3939*67e74705SXin Li break;
3940*67e74705SXin Li
3941*67e74705SXin Li default:
3942*67e74705SXin Li // Make sure we handled everything we should, every other kind is a
3943*67e74705SXin Li // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
3944*67e74705SXin Li // function. Need to recode Decl::Kind to do that easily.
3945*67e74705SXin Li assert(isa<TypeDecl>(D) && "Unsupported decl kind");
3946*67e74705SXin Li break;
3947*67e74705SXin Li }
3948*67e74705SXin Li }
3949*67e74705SXin Li
AddDeferredUnusedCoverageMapping(Decl * D)3950*67e74705SXin Li void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
3951*67e74705SXin Li // Do we need to generate coverage mapping?
3952*67e74705SXin Li if (!CodeGenOpts.CoverageMapping)
3953*67e74705SXin Li return;
3954*67e74705SXin Li switch (D->getKind()) {
3955*67e74705SXin Li case Decl::CXXConversion:
3956*67e74705SXin Li case Decl::CXXMethod:
3957*67e74705SXin Li case Decl::Function:
3958*67e74705SXin Li case Decl::ObjCMethod:
3959*67e74705SXin Li case Decl::CXXConstructor:
3960*67e74705SXin Li case Decl::CXXDestructor: {
3961*67e74705SXin Li if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
3962*67e74705SXin Li return;
3963*67e74705SXin Li auto I = DeferredEmptyCoverageMappingDecls.find(D);
3964*67e74705SXin Li if (I == DeferredEmptyCoverageMappingDecls.end())
3965*67e74705SXin Li DeferredEmptyCoverageMappingDecls[D] = true;
3966*67e74705SXin Li break;
3967*67e74705SXin Li }
3968*67e74705SXin Li default:
3969*67e74705SXin Li break;
3970*67e74705SXin Li };
3971*67e74705SXin Li }
3972*67e74705SXin Li
ClearUnusedCoverageMapping(const Decl * D)3973*67e74705SXin Li void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
3974*67e74705SXin Li // Do we need to generate coverage mapping?
3975*67e74705SXin Li if (!CodeGenOpts.CoverageMapping)
3976*67e74705SXin Li return;
3977*67e74705SXin Li if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
3978*67e74705SXin Li if (Fn->isTemplateInstantiation())
3979*67e74705SXin Li ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
3980*67e74705SXin Li }
3981*67e74705SXin Li auto I = DeferredEmptyCoverageMappingDecls.find(D);
3982*67e74705SXin Li if (I == DeferredEmptyCoverageMappingDecls.end())
3983*67e74705SXin Li DeferredEmptyCoverageMappingDecls[D] = false;
3984*67e74705SXin Li else
3985*67e74705SXin Li I->second = false;
3986*67e74705SXin Li }
3987*67e74705SXin Li
EmitDeferredUnusedCoverageMappings()3988*67e74705SXin Li void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
3989*67e74705SXin Li std::vector<const Decl *> DeferredDecls;
3990*67e74705SXin Li for (const auto &I : DeferredEmptyCoverageMappingDecls) {
3991*67e74705SXin Li if (!I.second)
3992*67e74705SXin Li continue;
3993*67e74705SXin Li DeferredDecls.push_back(I.first);
3994*67e74705SXin Li }
3995*67e74705SXin Li // Sort the declarations by their location to make sure that the tests get a
3996*67e74705SXin Li // predictable order for the coverage mapping for the unused declarations.
3997*67e74705SXin Li if (CodeGenOpts.DumpCoverageMapping)
3998*67e74705SXin Li std::sort(DeferredDecls.begin(), DeferredDecls.end(),
3999*67e74705SXin Li [] (const Decl *LHS, const Decl *RHS) {
4000*67e74705SXin Li return LHS->getLocStart() < RHS->getLocStart();
4001*67e74705SXin Li });
4002*67e74705SXin Li for (const auto *D : DeferredDecls) {
4003*67e74705SXin Li switch (D->getKind()) {
4004*67e74705SXin Li case Decl::CXXConversion:
4005*67e74705SXin Li case Decl::CXXMethod:
4006*67e74705SXin Li case Decl::Function:
4007*67e74705SXin Li case Decl::ObjCMethod: {
4008*67e74705SXin Li CodeGenPGO PGO(*this);
4009*67e74705SXin Li GlobalDecl GD(cast<FunctionDecl>(D));
4010*67e74705SXin Li PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4011*67e74705SXin Li getFunctionLinkage(GD));
4012*67e74705SXin Li break;
4013*67e74705SXin Li }
4014*67e74705SXin Li case Decl::CXXConstructor: {
4015*67e74705SXin Li CodeGenPGO PGO(*this);
4016*67e74705SXin Li GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
4017*67e74705SXin Li PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4018*67e74705SXin Li getFunctionLinkage(GD));
4019*67e74705SXin Li break;
4020*67e74705SXin Li }
4021*67e74705SXin Li case Decl::CXXDestructor: {
4022*67e74705SXin Li CodeGenPGO PGO(*this);
4023*67e74705SXin Li GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
4024*67e74705SXin Li PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4025*67e74705SXin Li getFunctionLinkage(GD));
4026*67e74705SXin Li break;
4027*67e74705SXin Li }
4028*67e74705SXin Li default:
4029*67e74705SXin Li break;
4030*67e74705SXin Li };
4031*67e74705SXin Li }
4032*67e74705SXin Li }
4033*67e74705SXin Li
4034*67e74705SXin Li /// Turns the given pointer into a constant.
GetPointerConstant(llvm::LLVMContext & Context,const void * Ptr)4035*67e74705SXin Li static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
4036*67e74705SXin Li const void *Ptr) {
4037*67e74705SXin Li uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
4038*67e74705SXin Li llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
4039*67e74705SXin Li return llvm::ConstantInt::get(i64, PtrInt);
4040*67e74705SXin Li }
4041*67e74705SXin Li
EmitGlobalDeclMetadata(CodeGenModule & CGM,llvm::NamedMDNode * & GlobalMetadata,GlobalDecl D,llvm::GlobalValue * Addr)4042*67e74705SXin Li static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
4043*67e74705SXin Li llvm::NamedMDNode *&GlobalMetadata,
4044*67e74705SXin Li GlobalDecl D,
4045*67e74705SXin Li llvm::GlobalValue *Addr) {
4046*67e74705SXin Li if (!GlobalMetadata)
4047*67e74705SXin Li GlobalMetadata =
4048*67e74705SXin Li CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
4049*67e74705SXin Li
4050*67e74705SXin Li // TODO: should we report variant information for ctors/dtors?
4051*67e74705SXin Li llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
4052*67e74705SXin Li llvm::ConstantAsMetadata::get(GetPointerConstant(
4053*67e74705SXin Li CGM.getLLVMContext(), D.getDecl()))};
4054*67e74705SXin Li GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
4055*67e74705SXin Li }
4056*67e74705SXin Li
4057*67e74705SXin Li /// For each function which is declared within an extern "C" region and marked
4058*67e74705SXin Li /// as 'used', but has internal linkage, create an alias from the unmangled
4059*67e74705SXin Li /// name to the mangled name if possible. People expect to be able to refer
4060*67e74705SXin Li /// to such functions with an unmangled name from inline assembly within the
4061*67e74705SXin Li /// same translation unit.
EmitStaticExternCAliases()4062*67e74705SXin Li void CodeGenModule::EmitStaticExternCAliases() {
4063*67e74705SXin Li // Don't do anything if we're generating CUDA device code -- the NVPTX
4064*67e74705SXin Li // assembly target doesn't support aliases.
4065*67e74705SXin Li if (Context.getTargetInfo().getTriple().isNVPTX())
4066*67e74705SXin Li return;
4067*67e74705SXin Li for (auto &I : StaticExternCValues) {
4068*67e74705SXin Li IdentifierInfo *Name = I.first;
4069*67e74705SXin Li llvm::GlobalValue *Val = I.second;
4070*67e74705SXin Li if (Val && !getModule().getNamedValue(Name->getName()))
4071*67e74705SXin Li addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
4072*67e74705SXin Li }
4073*67e74705SXin Li }
4074*67e74705SXin Li
lookupRepresentativeDecl(StringRef MangledName,GlobalDecl & Result) const4075*67e74705SXin Li bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
4076*67e74705SXin Li GlobalDecl &Result) const {
4077*67e74705SXin Li auto Res = Manglings.find(MangledName);
4078*67e74705SXin Li if (Res == Manglings.end())
4079*67e74705SXin Li return false;
4080*67e74705SXin Li Result = Res->getValue();
4081*67e74705SXin Li return true;
4082*67e74705SXin Li }
4083*67e74705SXin Li
4084*67e74705SXin Li /// Emits metadata nodes associating all the global values in the
4085*67e74705SXin Li /// current module with the Decls they came from. This is useful for
4086*67e74705SXin Li /// projects using IR gen as a subroutine.
4087*67e74705SXin Li ///
4088*67e74705SXin Li /// Since there's currently no way to associate an MDNode directly
4089*67e74705SXin Li /// with an llvm::GlobalValue, we create a global named metadata
4090*67e74705SXin Li /// with the name 'clang.global.decl.ptrs'.
EmitDeclMetadata()4091*67e74705SXin Li void CodeGenModule::EmitDeclMetadata() {
4092*67e74705SXin Li llvm::NamedMDNode *GlobalMetadata = nullptr;
4093*67e74705SXin Li
4094*67e74705SXin Li for (auto &I : MangledDeclNames) {
4095*67e74705SXin Li llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
4096*67e74705SXin Li // Some mangled names don't necessarily have an associated GlobalValue
4097*67e74705SXin Li // in this module, e.g. if we mangled it for DebugInfo.
4098*67e74705SXin Li if (Addr)
4099*67e74705SXin Li EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
4100*67e74705SXin Li }
4101*67e74705SXin Li }
4102*67e74705SXin Li
4103*67e74705SXin Li /// Emits metadata nodes for all the local variables in the current
4104*67e74705SXin Li /// function.
EmitDeclMetadata()4105*67e74705SXin Li void CodeGenFunction::EmitDeclMetadata() {
4106*67e74705SXin Li if (LocalDeclMap.empty()) return;
4107*67e74705SXin Li
4108*67e74705SXin Li llvm::LLVMContext &Context = getLLVMContext();
4109*67e74705SXin Li
4110*67e74705SXin Li // Find the unique metadata ID for this name.
4111*67e74705SXin Li unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
4112*67e74705SXin Li
4113*67e74705SXin Li llvm::NamedMDNode *GlobalMetadata = nullptr;
4114*67e74705SXin Li
4115*67e74705SXin Li for (auto &I : LocalDeclMap) {
4116*67e74705SXin Li const Decl *D = I.first;
4117*67e74705SXin Li llvm::Value *Addr = I.second.getPointer();
4118*67e74705SXin Li if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
4119*67e74705SXin Li llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
4120*67e74705SXin Li Alloca->setMetadata(
4121*67e74705SXin Li DeclPtrKind, llvm::MDNode::get(
4122*67e74705SXin Li Context, llvm::ValueAsMetadata::getConstant(DAddr)));
4123*67e74705SXin Li } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
4124*67e74705SXin Li GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
4125*67e74705SXin Li EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
4126*67e74705SXin Li }
4127*67e74705SXin Li }
4128*67e74705SXin Li }
4129*67e74705SXin Li
EmitVersionIdentMetadata()4130*67e74705SXin Li void CodeGenModule::EmitVersionIdentMetadata() {
4131*67e74705SXin Li llvm::NamedMDNode *IdentMetadata =
4132*67e74705SXin Li TheModule.getOrInsertNamedMetadata("llvm.ident");
4133*67e74705SXin Li std::string Version = getClangFullVersion();
4134*67e74705SXin Li llvm::LLVMContext &Ctx = TheModule.getContext();
4135*67e74705SXin Li
4136*67e74705SXin Li llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
4137*67e74705SXin Li IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
4138*67e74705SXin Li }
4139*67e74705SXin Li
EmitTargetMetadata()4140*67e74705SXin Li void CodeGenModule::EmitTargetMetadata() {
4141*67e74705SXin Li // Warning, new MangledDeclNames may be appended within this loop.
4142*67e74705SXin Li // We rely on MapVector insertions adding new elements to the end
4143*67e74705SXin Li // of the container.
4144*67e74705SXin Li // FIXME: Move this loop into the one target that needs it, and only
4145*67e74705SXin Li // loop over those declarations for which we couldn't emit the target
4146*67e74705SXin Li // metadata when we emitted the declaration.
4147*67e74705SXin Li for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
4148*67e74705SXin Li auto Val = *(MangledDeclNames.begin() + I);
4149*67e74705SXin Li const Decl *D = Val.first.getDecl()->getMostRecentDecl();
4150*67e74705SXin Li llvm::GlobalValue *GV = GetGlobalValue(Val.second);
4151*67e74705SXin Li getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
4152*67e74705SXin Li }
4153*67e74705SXin Li }
4154*67e74705SXin Li
EmitCoverageFile()4155*67e74705SXin Li void CodeGenModule::EmitCoverageFile() {
4156*67e74705SXin Li if (!getCodeGenOpts().CoverageFile.empty()) {
4157*67e74705SXin Li if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
4158*67e74705SXin Li llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
4159*67e74705SXin Li llvm::LLVMContext &Ctx = TheModule.getContext();
4160*67e74705SXin Li llvm::MDString *CoverageFile =
4161*67e74705SXin Li llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
4162*67e74705SXin Li for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
4163*67e74705SXin Li llvm::MDNode *CU = CUNode->getOperand(i);
4164*67e74705SXin Li llvm::Metadata *Elts[] = {CoverageFile, CU};
4165*67e74705SXin Li GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
4166*67e74705SXin Li }
4167*67e74705SXin Li }
4168*67e74705SXin Li }
4169*67e74705SXin Li }
4170*67e74705SXin Li
EmitUuidofInitializer(StringRef Uuid)4171*67e74705SXin Li llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
4172*67e74705SXin Li // Sema has checked that all uuid strings are of the form
4173*67e74705SXin Li // "12345678-1234-1234-1234-1234567890ab".
4174*67e74705SXin Li assert(Uuid.size() == 36);
4175*67e74705SXin Li for (unsigned i = 0; i < 36; ++i) {
4176*67e74705SXin Li if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
4177*67e74705SXin Li else assert(isHexDigit(Uuid[i]));
4178*67e74705SXin Li }
4179*67e74705SXin Li
4180*67e74705SXin Li // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
4181*67e74705SXin Li const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
4182*67e74705SXin Li
4183*67e74705SXin Li llvm::Constant *Field3[8];
4184*67e74705SXin Li for (unsigned Idx = 0; Idx < 8; ++Idx)
4185*67e74705SXin Li Field3[Idx] = llvm::ConstantInt::get(
4186*67e74705SXin Li Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
4187*67e74705SXin Li
4188*67e74705SXin Li llvm::Constant *Fields[4] = {
4189*67e74705SXin Li llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
4190*67e74705SXin Li llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
4191*67e74705SXin Li llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
4192*67e74705SXin Li llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
4193*67e74705SXin Li };
4194*67e74705SXin Li
4195*67e74705SXin Li return llvm::ConstantStruct::getAnon(Fields);
4196*67e74705SXin Li }
4197*67e74705SXin Li
GetAddrOfRTTIDescriptor(QualType Ty,bool ForEH)4198*67e74705SXin Li llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
4199*67e74705SXin Li bool ForEH) {
4200*67e74705SXin Li // Return a bogus pointer if RTTI is disabled, unless it's for EH.
4201*67e74705SXin Li // FIXME: should we even be calling this method if RTTI is disabled
4202*67e74705SXin Li // and it's not for EH?
4203*67e74705SXin Li if (!ForEH && !getLangOpts().RTTI)
4204*67e74705SXin Li return llvm::Constant::getNullValue(Int8PtrTy);
4205*67e74705SXin Li
4206*67e74705SXin Li if (ForEH && Ty->isObjCObjectPointerType() &&
4207*67e74705SXin Li LangOpts.ObjCRuntime.isGNUFamily())
4208*67e74705SXin Li return ObjCRuntime->GetEHType(Ty);
4209*67e74705SXin Li
4210*67e74705SXin Li return getCXXABI().getAddrOfRTTIDescriptor(Ty);
4211*67e74705SXin Li }
4212*67e74705SXin Li
EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl * D)4213*67e74705SXin Li void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
4214*67e74705SXin Li for (auto RefExpr : D->varlists()) {
4215*67e74705SXin Li auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
4216*67e74705SXin Li bool PerformInit =
4217*67e74705SXin Li VD->getAnyInitializer() &&
4218*67e74705SXin Li !VD->getAnyInitializer()->isConstantInitializer(getContext(),
4219*67e74705SXin Li /*ForRef=*/false);
4220*67e74705SXin Li
4221*67e74705SXin Li Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
4222*67e74705SXin Li if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
4223*67e74705SXin Li VD, Addr, RefExpr->getLocStart(), PerformInit))
4224*67e74705SXin Li CXXGlobalInits.push_back(InitFunction);
4225*67e74705SXin Li }
4226*67e74705SXin Li }
4227*67e74705SXin Li
CreateMetadataIdentifierForType(QualType T)4228*67e74705SXin Li llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
4229*67e74705SXin Li llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()];
4230*67e74705SXin Li if (InternalId)
4231*67e74705SXin Li return InternalId;
4232*67e74705SXin Li
4233*67e74705SXin Li if (isExternallyVisible(T->getLinkage())) {
4234*67e74705SXin Li std::string OutName;
4235*67e74705SXin Li llvm::raw_string_ostream Out(OutName);
4236*67e74705SXin Li getCXXABI().getMangleContext().mangleTypeName(T, Out);
4237*67e74705SXin Li
4238*67e74705SXin Li InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
4239*67e74705SXin Li } else {
4240*67e74705SXin Li InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
4241*67e74705SXin Li llvm::ArrayRef<llvm::Metadata *>());
4242*67e74705SXin Li }
4243*67e74705SXin Li
4244*67e74705SXin Li return InternalId;
4245*67e74705SXin Li }
4246*67e74705SXin Li
4247*67e74705SXin Li /// Returns whether this module needs the "all-vtables" type identifier.
NeedAllVtablesTypeId() const4248*67e74705SXin Li bool CodeGenModule::NeedAllVtablesTypeId() const {
4249*67e74705SXin Li // Returns true if at least one of vtable-based CFI checkers is enabled and
4250*67e74705SXin Li // is not in the trapping mode.
4251*67e74705SXin Li return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
4252*67e74705SXin Li !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
4253*67e74705SXin Li (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
4254*67e74705SXin Li !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
4255*67e74705SXin Li (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
4256*67e74705SXin Li !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
4257*67e74705SXin Li (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
4258*67e74705SXin Li !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
4259*67e74705SXin Li }
4260*67e74705SXin Li
AddVTableTypeMetadata(llvm::GlobalVariable * VTable,CharUnits Offset,const CXXRecordDecl * RD)4261*67e74705SXin Li void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
4262*67e74705SXin Li CharUnits Offset,
4263*67e74705SXin Li const CXXRecordDecl *RD) {
4264*67e74705SXin Li llvm::Metadata *MD =
4265*67e74705SXin Li CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
4266*67e74705SXin Li VTable->addTypeMetadata(Offset.getQuantity(), MD);
4267*67e74705SXin Li
4268*67e74705SXin Li if (CodeGenOpts.SanitizeCfiCrossDso)
4269*67e74705SXin Li if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
4270*67e74705SXin Li VTable->addTypeMetadata(Offset.getQuantity(),
4271*67e74705SXin Li llvm::ConstantAsMetadata::get(CrossDsoTypeId));
4272*67e74705SXin Li
4273*67e74705SXin Li if (NeedAllVtablesTypeId()) {
4274*67e74705SXin Li llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
4275*67e74705SXin Li VTable->addTypeMetadata(Offset.getQuantity(), MD);
4276*67e74705SXin Li }
4277*67e74705SXin Li }
4278*67e74705SXin Li
4279*67e74705SXin Li // Fills in the supplied string map with the set of target features for the
4280*67e74705SXin Li // passed in function.
getFunctionFeatureMap(llvm::StringMap<bool> & FeatureMap,const FunctionDecl * FD)4281*67e74705SXin Li void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
4282*67e74705SXin Li const FunctionDecl *FD) {
4283*67e74705SXin Li StringRef TargetCPU = Target.getTargetOpts().CPU;
4284*67e74705SXin Li if (const auto *TD = FD->getAttr<TargetAttr>()) {
4285*67e74705SXin Li // If we have a TargetAttr build up the feature map based on that.
4286*67e74705SXin Li TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
4287*67e74705SXin Li
4288*67e74705SXin Li // Make a copy of the features as passed on the command line into the
4289*67e74705SXin Li // beginning of the additional features from the function to override.
4290*67e74705SXin Li ParsedAttr.first.insert(ParsedAttr.first.begin(),
4291*67e74705SXin Li Target.getTargetOpts().FeaturesAsWritten.begin(),
4292*67e74705SXin Li Target.getTargetOpts().FeaturesAsWritten.end());
4293*67e74705SXin Li
4294*67e74705SXin Li if (ParsedAttr.second != "")
4295*67e74705SXin Li TargetCPU = ParsedAttr.second;
4296*67e74705SXin Li
4297*67e74705SXin Li // Now populate the feature map, first with the TargetCPU which is either
4298*67e74705SXin Li // the default or a new one from the target attribute string. Then we'll use
4299*67e74705SXin Li // the passed in features (FeaturesAsWritten) along with the new ones from
4300*67e74705SXin Li // the attribute.
4301*67e74705SXin Li Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, ParsedAttr.first);
4302*67e74705SXin Li } else {
4303*67e74705SXin Li Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
4304*67e74705SXin Li Target.getTargetOpts().Features);
4305*67e74705SXin Li }
4306*67e74705SXin Li }
4307*67e74705SXin Li
getSanStats()4308*67e74705SXin Li llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
4309*67e74705SXin Li if (!SanStats)
4310*67e74705SXin Li SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
4311*67e74705SXin Li
4312*67e74705SXin Li return *SanStats;
4313*67e74705SXin Li }
4314