Bug Summary

File:tools/clang/lib/CodeGen/CodeGenModule.cpp
Warning:line 2705, column 27
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CodeGenModule.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-8/lib/clang/8.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-8~svn345461/tools/clang/include -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/include -I /build/llvm-toolchain-snapshot-8~svn345461/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/include/clang/8.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-8/lib/clang/8.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/tools/clang/lib/CodeGen -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-10-27-211344-32123-1 -x c++ /build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp -faddrsig

/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp

1//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenModule.h"
15#include "CGBlocks.h"
16#include "CGCUDARuntime.h"
17#include "CGCXXABI.h"
18#include "CGCall.h"
19#include "CGDebugInfo.h"
20#include "CGObjCRuntime.h"
21#include "CGOpenCLRuntime.h"
22#include "CGOpenMPRuntime.h"
23#include "CGOpenMPRuntimeNVPTX.h"
24#include "CodeGenFunction.h"
25#include "CodeGenPGO.h"
26#include "ConstantEmitter.h"
27#include "CoverageMappingGen.h"
28#include "TargetInfo.h"
29#include "clang/AST/ASTContext.h"
30#include "clang/AST/CharUnits.h"
31#include "clang/AST/DeclCXX.h"
32#include "clang/AST/DeclObjC.h"
33#include "clang/AST/DeclTemplate.h"
34#include "clang/AST/Mangle.h"
35#include "clang/AST/RecordLayout.h"
36#include "clang/AST/RecursiveASTVisitor.h"
37#include "clang/Basic/Builtins.h"
38#include "clang/Basic/CharInfo.h"
39#include "clang/Basic/Diagnostic.h"
40#include "clang/Basic/Module.h"
41#include "clang/Basic/SourceManager.h"
42#include "clang/Basic/TargetInfo.h"
43#include "clang/Basic/Version.h"
44#include "clang/CodeGen/ConstantInitBuilder.h"
45#include "clang/Frontend/CodeGenOptions.h"
46#include "clang/Sema/SemaDiagnostic.h"
47#include "llvm/ADT/StringSwitch.h"
48#include "llvm/ADT/Triple.h"
49#include "llvm/Analysis/TargetLibraryInfo.h"
50#include "llvm/IR/CallSite.h"
51#include "llvm/IR/CallingConv.h"
52#include "llvm/IR/DataLayout.h"
53#include "llvm/IR/Intrinsics.h"
54#include "llvm/IR/LLVMContext.h"
55#include "llvm/IR/Module.h"
56#include "llvm/ProfileData/InstrProfReader.h"
57#include "llvm/Support/CodeGen.h"
58#include "llvm/Support/ConvertUTF.h"
59#include "llvm/Support/ErrorHandling.h"
60#include "llvm/Support/MD5.h"
61
62using namespace clang;
63using namespace CodeGen;
64
65static llvm::cl::opt<bool> LimitedCoverage(
66 "limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden,
67 llvm::cl::desc("Emit limited coverage mapping information (experimental)"),
68 llvm::cl::init(false));
69
70static const char AnnotationSection[] = "llvm.metadata";
71
72static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
73 switch (CGM.getTarget().getCXXABI().getKind()) {
74 case TargetCXXABI::GenericAArch64:
75 case TargetCXXABI::GenericARM:
76 case TargetCXXABI::iOS:
77 case TargetCXXABI::iOS64:
78 case TargetCXXABI::WatchOS:
79 case TargetCXXABI::GenericMIPS:
80 case TargetCXXABI::GenericItanium:
81 case TargetCXXABI::WebAssembly:
82 return CreateItaniumCXXABI(CGM);
83 case TargetCXXABI::Microsoft:
84 return CreateMicrosoftCXXABI(CGM);
85 }
86
87 llvm_unreachable("invalid C++ ABI kind")::llvm::llvm_unreachable_internal("invalid C++ ABI kind", "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 87)
;
88}
89
90CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
91 const PreprocessorOptions &PPO,
92 const CodeGenOptions &CGO, llvm::Module &M,
93 DiagnosticsEngine &diags,
94 CoverageSourceInfo *CoverageInfo)
95 : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
96 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
97 Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
98 VMContext(M.getContext()), Types(*this), VTables(*this),
99 SanitizerMD(new SanitizerMetadata(*this)) {
100
101 // Initialize the type cache.
102 llvm::LLVMContext &LLVMContext = M.getContext();
103 VoidTy = llvm::Type::getVoidTy(LLVMContext);
104 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
105 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
106 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
107 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
108 HalfTy = llvm::Type::getHalfTy(LLVMContext);
109 FloatTy = llvm::Type::getFloatTy(LLVMContext);
110 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
111 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
112 PointerAlignInBytes =
113 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
114 SizeSizeInBytes =
115 C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
116 IntAlignInBytes =
117 C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
118 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
119 IntPtrTy = llvm::IntegerType::get(LLVMContext,
120 C.getTargetInfo().getMaxPointerWidth());
121 Int8PtrTy = Int8Ty->getPointerTo(0);
122 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
123 AllocaInt8PtrTy = Int8Ty->getPointerTo(
124 M.getDataLayout().getAllocaAddrSpace());
125 ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
126
127 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
128
129 if (LangOpts.ObjC1)
130 createObjCRuntime();
131 if (LangOpts.OpenCL)
132 createOpenCLRuntime();
133 if (LangOpts.OpenMP)
134 createOpenMPRuntime();
135 if (LangOpts.CUDA)
136 createCUDARuntime();
137
138 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
139 if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
140 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
141 TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(),
142 getCXXABI().getMangleContext()));
143
144 // If debug info or coverage generation is enabled, create the CGDebugInfo
145 // object.
146 if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
147 CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
148 DebugInfo.reset(new CGDebugInfo(*this));
149
150 Block.GlobalUniqueCount = 0;
151
152 if (C.getLangOpts().ObjC1)
153 ObjCData.reset(new ObjCEntrypoints());
154
155 if (CodeGenOpts.hasProfileClangUse()) {
156 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
157 CodeGenOpts.ProfileInstrumentUsePath, CodeGenOpts.ProfileRemappingFile);
158 if (auto E = ReaderOrErr.takeError()) {
159 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
160 "Could not read profile %0: %1");
161 llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
162 getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
163 << EI.message();
164 });
165 } else
166 PGOReader = std::move(ReaderOrErr.get());
167 }
168
169 // If coverage mapping generation is enabled, create the
170 // CoverageMappingModuleGen object.
171 if (CodeGenOpts.CoverageMapping)
172 CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
173}
174
175CodeGenModule::~CodeGenModule() {}
176
177void CodeGenModule::createObjCRuntime() {
178 // This is just isGNUFamily(), but we want to force implementors of
179 // new ABIs to decide how best to do this.
180 switch (LangOpts.ObjCRuntime.getKind()) {
181 case ObjCRuntime::GNUstep:
182 case ObjCRuntime::GCC:
183 case ObjCRuntime::ObjFW:
184 ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
185 return;
186
187 case ObjCRuntime::FragileMacOSX:
188 case ObjCRuntime::MacOSX:
189 case ObjCRuntime::iOS:
190 case ObjCRuntime::WatchOS:
191 ObjCRuntime.reset(CreateMacObjCRuntime(*this));
192 return;
193 }
194 llvm_unreachable("bad runtime kind")::llvm::llvm_unreachable_internal("bad runtime kind", "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 194)
;
195}
196
197void CodeGenModule::createOpenCLRuntime() {
198 OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
199}
200
201void CodeGenModule::createOpenMPRuntime() {
202 // Select a specialized code generation class based on the target, if any.
203 // If it does not exist use the default implementation.
204 switch (getTriple().getArch()) {
205 case llvm::Triple::nvptx:
206 case llvm::Triple::nvptx64:
207 assert(getLangOpts().OpenMPIsDevice &&((getLangOpts().OpenMPIsDevice && "OpenMP NVPTX is only prepared to deal with device code."
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().OpenMPIsDevice && \"OpenMP NVPTX is only prepared to deal with device code.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 208, __PRETTY_FUNCTION__))
208 "OpenMP NVPTX is only prepared to deal with device code.")((getLangOpts().OpenMPIsDevice && "OpenMP NVPTX is only prepared to deal with device code."
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().OpenMPIsDevice && \"OpenMP NVPTX is only prepared to deal with device code.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 208, __PRETTY_FUNCTION__))
;
209 OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
210 break;
211 default:
212 if (LangOpts.OpenMPSimd)
213 OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this));
214 else
215 OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
216 break;
217 }
218}
219
220void CodeGenModule::createCUDARuntime() {
221 CUDARuntime.reset(CreateNVCUDARuntime(*this));
222}
223
224void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
225 Replacements[Name] = C;
226}
227
228void CodeGenModule::applyReplacements() {
229 for (auto &I : Replacements) {
230 StringRef MangledName = I.first();
231 llvm::Constant *Replacement = I.second;
232 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
233 if (!Entry)
234 continue;
235 auto *OldF = cast<llvm::Function>(Entry);
236 auto *NewF = dyn_cast<llvm::Function>(Replacement);
237 if (!NewF) {
238 if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
239 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
240 } else {
241 auto *CE = cast<llvm::ConstantExpr>(Replacement);
242 assert(CE->getOpcode() == llvm::Instruction::BitCast ||((CE->getOpcode() == llvm::Instruction::BitCast || CE->
getOpcode() == llvm::Instruction::GetElementPtr) ? static_cast
<void> (0) : __assert_fail ("CE->getOpcode() == llvm::Instruction::BitCast || CE->getOpcode() == llvm::Instruction::GetElementPtr"
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 243, __PRETTY_FUNCTION__))
243 CE->getOpcode() == llvm::Instruction::GetElementPtr)((CE->getOpcode() == llvm::Instruction::BitCast || CE->
getOpcode() == llvm::Instruction::GetElementPtr) ? static_cast
<void> (0) : __assert_fail ("CE->getOpcode() == llvm::Instruction::BitCast || CE->getOpcode() == llvm::Instruction::GetElementPtr"
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 243, __PRETTY_FUNCTION__))
;
244 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
245 }
246 }
247
248 // Replace old with new, but keep the old order.
249 OldF->replaceAllUsesWith(Replacement);
250 if (NewF) {
251 NewF->removeFromParent();
252 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
253 NewF);
254 }
255 OldF->eraseFromParent();
256 }
257}
258
259void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
260 GlobalValReplacements.push_back(std::make_pair(GV, C));
261}
262
263void CodeGenModule::applyGlobalValReplacements() {
264 for (auto &I : GlobalValReplacements) {
265 llvm::GlobalValue *GV = I.first;
266 llvm::Constant *C = I.second;
267
268 GV->replaceAllUsesWith(C);
269 GV->eraseFromParent();
270 }
271}
272
273// This is only used in aliases that we created and we know they have a
274// linear structure.
275static const llvm::GlobalObject *getAliasedGlobal(
276 const llvm::GlobalIndirectSymbol &GIS) {
277 llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
278 const llvm::Constant *C = &GIS;
279 for (;;) {
280 C = C->stripPointerCasts();
281 if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
282 return GO;
283 // stripPointerCasts will not walk over weak aliases.
284 auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
285 if (!GIS2)
286 return nullptr;
287 if (!Visited.insert(GIS2).second)
288 return nullptr;
289 C = GIS2->getIndirectSymbol();
290 }
291}
292
293void CodeGenModule::checkAliases() {
294 // Check if the constructed aliases are well formed. It is really unfortunate
295 // that we have to do this in CodeGen, but we only construct mangled names
296 // and aliases during codegen.
297 bool Error = false;
298 DiagnosticsEngine &Diags = getDiags();
299 for (const GlobalDecl &GD : Aliases) {
300 const auto *D = cast<ValueDecl>(GD.getDecl());
301 SourceLocation Location;
302 bool IsIFunc = D->hasAttr<IFuncAttr>();
303 if (const Attr *A = D->getDefiningAttr())
304 Location = A->getLocation();
305 else
306 llvm_unreachable("Not an alias or ifunc?")::llvm::llvm_unreachable_internal("Not an alias or ifunc?", "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 306)
;
307 StringRef MangledName = getMangledName(GD);
308 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
309 auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry);
310 const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
311 if (!GV) {
312 Error = true;
313 Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
314 } else if (GV->isDeclaration()) {
315 Error = true;
316 Diags.Report(Location, diag::err_alias_to_undefined)
317 << IsIFunc << IsIFunc;
318 } else if (IsIFunc) {
319 // Check resolver function type.
320 llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
321 GV->getType()->getPointerElementType());
322 assert(FTy)((FTy) ? static_cast<void> (0) : __assert_fail ("FTy", "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 322, __PRETTY_FUNCTION__))
;
323 if (!FTy->getReturnType()->isPointerTy())
324 Diags.Report(Location, diag::err_ifunc_resolver_return);
325 }
326
327 llvm::Constant *Aliasee = Alias->getIndirectSymbol();
328 llvm::GlobalValue *AliaseeGV;
329 if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
330 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
331 else
332 AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
333
334 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
335 StringRef AliasSection = SA->getName();
336 if (AliasSection != AliaseeGV->getSection())
337 Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
338 << AliasSection << IsIFunc << IsIFunc;
339 }
340
341 // We have to handle alias to weak aliases in here. LLVM itself disallows
342 // this since the object semantics would not match the IL one. For
343 // compatibility with gcc we implement it by just pointing the alias
344 // to its aliasee's aliasee. We also warn, since the user is probably
345 // expecting the link to be weak.
346 if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
347 if (GA->isInterposable()) {
348 Diags.Report(Location, diag::warn_alias_to_weak_alias)
349 << GV->getName() << GA->getName() << IsIFunc;
350 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
351 GA->getIndirectSymbol(), Alias->getType());
352 Alias->setIndirectSymbol(Aliasee);
353 }
354 }
355 }
356 if (!Error)
357 return;
358
359 for (const GlobalDecl &GD : Aliases) {
360 StringRef MangledName = getMangledName(GD);
361 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
362 auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
363 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
364 Alias->eraseFromParent();
365 }
366}
367
368void CodeGenModule::clear() {
369 DeferredDeclsToEmit.clear();
370 if (OpenMPRuntime)
371 OpenMPRuntime->clear();
372}
373
374void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
375 StringRef MainFile) {
376 if (!hasDiagnostics())
377 return;
378 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
379 if (MainFile.empty())
380 MainFile = "<stdin>";
381 Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
382 } else {
383 if (Mismatched > 0)
384 Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
385
386 if (Missing > 0)
387 Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
388 }
389}
390
391void CodeGenModule::Release() {
392 EmitDeferred();
393 EmitVTablesOpportunistically();
394 applyGlobalValReplacements();
395 applyReplacements();
396 checkAliases();
397 emitMultiVersionFunctions();
398 EmitCXXGlobalInitFunc();
399 EmitCXXGlobalDtorFunc();
400 registerGlobalDtorsWithAtExit();
401 EmitCXXThreadLocalInitFunc();
402 if (ObjCRuntime)
403 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
404 AddGlobalCtor(ObjCInitFunction);
405 if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
406 CUDARuntime) {
407 if (llvm::Function *CudaCtorFunction =
408 CUDARuntime->makeModuleCtorFunction())
409 AddGlobalCtor(CudaCtorFunction);
410 }
411 if (OpenMPRuntime) {
412 if (llvm::Function *OpenMPRegistrationFunction =
413 OpenMPRuntime->emitRegistrationFunction()) {
414 auto ComdatKey = OpenMPRegistrationFunction->hasComdat() ?
415 OpenMPRegistrationFunction : nullptr;
416 AddGlobalCtor(OpenMPRegistrationFunction, 0, ComdatKey);
417 }
418 OpenMPRuntime->clear();
419 }
420 if (PGOReader) {
421 getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext));
422 if (PGOStats.hasDiagnostics())
423 PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
424 }
425 EmitCtorList(GlobalCtors, "llvm.global_ctors");
426 EmitCtorList(GlobalDtors, "llvm.global_dtors");
427 EmitGlobalAnnotations();
428 EmitStaticExternCAliases();
429 EmitDeferredUnusedCoverageMappings();
430 if (CoverageMapping)
431 CoverageMapping->emit();
432 if (CodeGenOpts.SanitizeCfiCrossDso) {
433 CodeGenFunction(*this).EmitCfiCheckFail();
434 CodeGenFunction(*this).EmitCfiCheckStub();
435 }
436 emitAtAvailableLinkGuard();
437 emitLLVMUsed();
438 if (SanStats)
439 SanStats->finish();
440
441 if (CodeGenOpts.Autolink &&
442 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
443 EmitModuleLinkOptions();
444 }
445
446 // Record mregparm value now so it is visible through rest of codegen.
447 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
448 getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
449 CodeGenOpts.NumRegisterParameters);
450
451 if (CodeGenOpts.DwarfVersion) {
452 // We actually want the latest version when there are conflicts.
453 // We can change from Warning to Latest if such mode is supported.
454 getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
455 CodeGenOpts.DwarfVersion);
456 }
457 if (CodeGenOpts.EmitCodeView) {
458 // Indicate that we want CodeView in the metadata.
459 getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
460 }
461 if (CodeGenOpts.ControlFlowGuard) {
462 // We want function ID tables for Control Flow Guard.
463 getModule().addModuleFlag(llvm::Module::Warning, "cfguardtable", 1);
464 }
465 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
466 // We don't support LTO with 2 with different StrictVTablePointers
467 // FIXME: we could support it by stripping all the information introduced
468 // by StrictVTablePointers.
469
470 getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
471
472 llvm::Metadata *Ops[2] = {
473 llvm::MDString::get(VMContext, "StrictVTablePointers"),
474 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
475 llvm::Type::getInt32Ty(VMContext), 1))};
476
477 getModule().addModuleFlag(llvm::Module::Require,
478 "StrictVTablePointersRequirement",
479 llvm::MDNode::get(VMContext, Ops));
480 }
481 if (DebugInfo)
482 // We support a single version in the linked module. The LLVM
483 // parser will drop debug info with a different version number
484 // (and warn about it, too).
485 getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
486 llvm::DEBUG_METADATA_VERSION);
487
488 // We need to record the widths of enums and wchar_t, so that we can generate
489 // the correct build attributes in the ARM backend. wchar_size is also used by
490 // TargetLibraryInfo.
491 uint64_t WCharWidth =
492 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
493 getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
494
495 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
496 if ( Arch == llvm::Triple::arm
497 || Arch == llvm::Triple::armeb
498 || Arch == llvm::Triple::thumb
499 || Arch == llvm::Triple::thumbeb) {
500 // The minimum width of an enum in bytes
501 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
502 getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
503 }
504
505 if (CodeGenOpts.SanitizeCfiCrossDso) {
506 // Indicate that we want cross-DSO control flow integrity checks.
507 getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
508 }
509
510 if (CodeGenOpts.CFProtectionReturn &&
511 Target.checkCFProtectionReturnSupported(getDiags())) {
512 // Indicate that we want to instrument return control flow protection.
513 getModule().addModuleFlag(llvm::Module::Override, "cf-protection-return",
514 1);
515 }
516
517 if (CodeGenOpts.CFProtectionBranch &&
518 Target.checkCFProtectionBranchSupported(getDiags())) {
519 // Indicate that we want to instrument branch control flow protection.
520 getModule().addModuleFlag(llvm::Module::Override, "cf-protection-branch",
521 1);
522 }
523
524 if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
525 // Indicate whether __nvvm_reflect should be configured to flush denormal
526 // floating point values to 0. (This corresponds to its "__CUDA_FTZ"
527 // property.)
528 getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
529 CodeGenOpts.FlushDenorm ? 1 : 0);
530 }
531
532 // Emit OpenCL specific module metadata: OpenCL/SPIR version.
533 if (LangOpts.OpenCL) {
534 EmitOpenCLMetadata();
535 // Emit SPIR version.
536 if (getTriple().getArch() == llvm::Triple::spir ||
537 getTriple().getArch() == llvm::Triple::spir64) {
538 // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
539 // opencl.spir.version named metadata.
540 llvm::Metadata *SPIRVerElts[] = {
541 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
542 Int32Ty, LangOpts.OpenCLVersion / 100)),
543 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
544 Int32Ty, (LangOpts.OpenCLVersion / 100 > 1) ? 0 : 2))};
545 llvm::NamedMDNode *SPIRVerMD =
546 TheModule.getOrInsertNamedMetadata("opencl.spir.version");
547 llvm::LLVMContext &Ctx = TheModule.getContext();
548 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
549 }
550 }
551
552 if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
553 assert(PLevel < 3 && "Invalid PIC Level")((PLevel < 3 && "Invalid PIC Level") ? static_cast
<void> (0) : __assert_fail ("PLevel < 3 && \"Invalid PIC Level\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 553, __PRETTY_FUNCTION__))
;
554 getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
555 if (Context.getLangOpts().PIE)
556 getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
557 }
558
559 if (getCodeGenOpts().CodeModel.size() > 0) {
560 unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel)
561 .Case("tiny", llvm::CodeModel::Tiny)
562 .Case("small", llvm::CodeModel::Small)
563 .Case("kernel", llvm::CodeModel::Kernel)
564 .Case("medium", llvm::CodeModel::Medium)
565 .Case("large", llvm::CodeModel::Large)
566 .Default(~0u);
567 if (CM != ~0u) {
568 llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM);
569 getModule().setCodeModel(codeModel);
570 }
571 }
572
573 if (CodeGenOpts.NoPLT)
574 getModule().setRtLibUseGOT();
575
576 SimplifyPersonality();
577
578 if (getCodeGenOpts().EmitDeclMetadata)
579 EmitDeclMetadata();
580
581 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
582 EmitCoverageFile();
583
584 if (DebugInfo)
585 DebugInfo->finalize();
586
587 if (getCodeGenOpts().EmitVersionIdentMetadata)
588 EmitVersionIdentMetadata();
589
590 EmitTargetMetadata();
591}
592
593void CodeGenModule::EmitOpenCLMetadata() {
594 // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
595 // opencl.ocl.version named metadata node.
596 llvm::Metadata *OCLVerElts[] = {
597 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
598 Int32Ty, LangOpts.OpenCLVersion / 100)),
599 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
600 Int32Ty, (LangOpts.OpenCLVersion % 100) / 10))};
601 llvm::NamedMDNode *OCLVerMD =
602 TheModule.getOrInsertNamedMetadata("opencl.ocl.version");
603 llvm::LLVMContext &Ctx = TheModule.getContext();
604 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
605}
606
607void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
608 // Make sure that this type is translated.
609 Types.UpdateCompletedType(TD);
610}
611
612void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
613 // Make sure that this type is translated.
614 Types.RefreshTypeCacheForClass(RD);
615}
616
617llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) {
618 if (!TBAA)
619 return nullptr;
620 return TBAA->getTypeInfo(QTy);
621}
622
623TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) {
624 if (!TBAA)
625 return TBAAAccessInfo();
626 return TBAA->getAccessInfo(AccessType);
627}
628
629TBAAAccessInfo
630CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
631 if (!TBAA)
632 return TBAAAccessInfo();
633 return TBAA->getVTablePtrAccessInfo(VTablePtrType);
634}
635
636llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
637 if (!TBAA)
638 return nullptr;
639 return TBAA->getTBAAStructInfo(QTy);
640}
641
642llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) {
643 if (!TBAA)
644 return nullptr;
645 return TBAA->getBaseTypeInfo(QTy);
646}
647
648llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) {
649 if (!TBAA)
650 return nullptr;
651 return TBAA->getAccessTagInfo(Info);
652}
653
654TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
655 TBAAAccessInfo TargetInfo) {
656 if (!TBAA)
657 return TBAAAccessInfo();
658 return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
659}
660
661TBAAAccessInfo
662CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
663 TBAAAccessInfo InfoB) {
664 if (!TBAA)
665 return TBAAAccessInfo();
666 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
667}
668
669TBAAAccessInfo
670CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
671 TBAAAccessInfo SrcInfo) {
672 if (!TBAA)
673 return TBAAAccessInfo();
674 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
675}
676
677void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
678 TBAAAccessInfo TBAAInfo) {
679 if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
680 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
681}
682
683void CodeGenModule::DecorateInstructionWithInvariantGroup(
684 llvm::Instruction *I, const CXXRecordDecl *RD) {
685 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
686 llvm::MDNode::get(getLLVMContext(), {}));
687}
688
689void CodeGenModule::Error(SourceLocation loc, StringRef message) {
690 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
691 getDiags().Report(Context.getFullLoc(loc), diagID) << message;
692}
693
694/// ErrorUnsupported - Print out an error that codegen doesn't support the
695/// specified stmt yet.
696void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
697 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
698 "cannot compile this %0 yet");
699 std::string Msg = Type;
700 getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID)
701 << Msg << S->getSourceRange();
702}
703
704/// ErrorUnsupported - Print out an error that codegen doesn't support the
705/// specified decl yet.
706void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
707 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
708 "cannot compile this %0 yet");
709 std::string Msg = Type;
710 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
711}
712
713llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
714 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
715}
716
717void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
718 const NamedDecl *D) const {
719 if (GV->hasDLLImportStorageClass())
720 return;
721 // Internal definitions always have default visibility.
722 if (GV->hasLocalLinkage()) {
723 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
724 return;
725 }
726 if (!D)
727 return;
728 // Set visibility for definitions.
729 LinkageInfo LV = D->getLinkageAndVisibility();
730 if (LV.isVisibilityExplicit() || !GV->isDeclarationForLinker())
731 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
732}
733
734static bool shouldAssumeDSOLocal(const CodeGenModule &CGM,
735 llvm::GlobalValue *GV) {
736 if (GV->hasLocalLinkage())
737 return true;
738
739 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
740 return true;
741
742 // DLLImport explicitly marks the GV as external.
743 if (GV->hasDLLImportStorageClass())
744 return false;
745
746 const llvm::Triple &TT = CGM.getTriple();
747 if (TT.isWindowsGNUEnvironment()) {
748 // In MinGW, variables without DLLImport can still be automatically
749 // imported from a DLL by the linker; don't mark variables that
750 // potentially could come from another DLL as DSO local.
751 if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) &&
752 !GV->isThreadLocal())
753 return false;
754 }
755 // Every other GV is local on COFF.
756 // Make an exception for windows OS in the triple: Some firmware builds use
757 // *-win32-macho triples. This (accidentally?) produced windows relocations
758 // without GOT tables in older clang versions; Keep this behaviour.
759 // FIXME: even thread local variables?
760 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
761 return true;
762
763 // Only handle COFF and ELF for now.
764 if (!TT.isOSBinFormatELF())
765 return false;
766
767 // If this is not an executable, don't assume anything is local.
768 const auto &CGOpts = CGM.getCodeGenOpts();
769 llvm::Reloc::Model RM = CGOpts.RelocationModel;
770 const auto &LOpts = CGM.getLangOpts();
771 if (RM != llvm::Reloc::Static && !LOpts.PIE)
772 return false;
773
774 // A definition cannot be preempted from an executable.
775 if (!GV->isDeclarationForLinker())
776 return true;
777
778 // Most PIC code sequences that assume that a symbol is local cannot produce a
779 // 0 if it turns out the symbol is undefined. While this is ABI and relocation
780 // depended, it seems worth it to handle it here.
781 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
782 return false;
783
784 // PPC has no copy relocations and cannot use a plt entry as a symbol address.
785 llvm::Triple::ArchType Arch = TT.getArch();
786 if (Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
787 Arch == llvm::Triple::ppc64le)
788 return false;
789
790 // If we can use copy relocations we can assume it is local.
791 if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
792 if (!Var->isThreadLocal() &&
793 (RM == llvm::Reloc::Static || CGOpts.PIECopyRelocations))
794 return true;
795
796 // If we can use a plt entry as the symbol address we can assume it
797 // is local.
798 // FIXME: This should work for PIE, but the gold linker doesn't support it.
799 if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
800 return true;
801
802 // Otherwise don't assue it is local.
803 return false;
804}
805
806void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const {
807 GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV));
808}
809
810void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
811 GlobalDecl GD) const {
812 const auto *D = dyn_cast<NamedDecl>(GD.getDecl());
813 // C++ destructors have a few C++ ABI specific special cases.
814 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
815 getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType());
816 return;
817 }
818 setDLLImportDLLExport(GV, D);
819}
820
821void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
822 const NamedDecl *D) const {
823 if (D && D->isExternallyVisible()) {
824 if (D->hasAttr<DLLImportAttr>())
825 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
826 else if (D->hasAttr<DLLExportAttr>() && !GV->isDeclarationForLinker())
827 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
828 }
829}
830
831void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
832 GlobalDecl GD) const {
833 setDLLImportDLLExport(GV, GD);
834 setGlobalVisibilityAndLocal(GV, dyn_cast<NamedDecl>(GD.getDecl()));
835}
836
837void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
838 const NamedDecl *D) const {
839 setDLLImportDLLExport(GV, D);
840 setGlobalVisibilityAndLocal(GV, D);
841}
842
843void CodeGenModule::setGlobalVisibilityAndLocal(llvm::GlobalValue *GV,
844 const NamedDecl *D) const {
845 setGlobalVisibility(GV, D);
846 setDSOLocal(GV);
847}
848
849static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
850 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
851 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
852 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
853 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
854 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
855}
856
857static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
858 CodeGenOptions::TLSModel M) {
859 switch (M) {
860 case CodeGenOptions::GeneralDynamicTLSModel:
861 return llvm::GlobalVariable::GeneralDynamicTLSModel;
862 case CodeGenOptions::LocalDynamicTLSModel:
863 return llvm::GlobalVariable::LocalDynamicTLSModel;
864 case CodeGenOptions::InitialExecTLSModel:
865 return llvm::GlobalVariable::InitialExecTLSModel;
866 case CodeGenOptions::LocalExecTLSModel:
867 return llvm::GlobalVariable::LocalExecTLSModel;
868 }
869 llvm_unreachable("Invalid TLS model!")::llvm::llvm_unreachable_internal("Invalid TLS model!", "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 869)
;
870}
871
872void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
873 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!")((D.getTLSKind() && "setting TLS mode on non-TLS var!"
) ? static_cast<void> (0) : __assert_fail ("D.getTLSKind() && \"setting TLS mode on non-TLS var!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 873, __PRETTY_FUNCTION__))
;
874
875 llvm::GlobalValue::ThreadLocalMode TLM;
876 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
877
878 // Override the TLS model if it is explicitly specified.
879 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
880 TLM = GetLLVMTLSModel(Attr->getModel());
881 }
882
883 GV->setThreadLocalMode(TLM);
884}
885
886static std::string getCPUSpecificMangling(const CodeGenModule &CGM,
887 StringRef Name) {
888 const TargetInfo &Target = CGM.getTarget();
889 return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str();
890}
891
892static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM,
893 const CPUSpecificAttr *Attr,
894 raw_ostream &Out) {
895 // cpu_specific gets the current name, dispatch gets the resolver if IFunc is
896 // supported.
897 if (Attr)
898 Out << getCPUSpecificMangling(CGM, Attr->getCurCPUName()->getName());
899 else if (CGM.getTarget().supportsIFunc())
900 Out << ".resolver";
901}
902
903static void AppendTargetMangling(const CodeGenModule &CGM,
904 const TargetAttr *Attr, raw_ostream &Out) {
905 if (Attr->isDefaultVersion())
906 return;
907
908 Out << '.';
909 const TargetInfo &Target = CGM.getTarget();
910 TargetAttr::ParsedTargetAttr Info =
911 Attr->parse([&Target](StringRef LHS, StringRef RHS) {
912 // Multiversioning doesn't allow "no-${feature}", so we can
913 // only have "+" prefixes here.
914 assert(LHS.startswith("+") && RHS.startswith("+") &&((LHS.startswith("+") && RHS.startswith("+") &&
"Features should always have a prefix.") ? static_cast<void
> (0) : __assert_fail ("LHS.startswith(\"+\") && RHS.startswith(\"+\") && \"Features should always have a prefix.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 915, __PRETTY_FUNCTION__))
915 "Features should always have a prefix.")((LHS.startswith("+") && RHS.startswith("+") &&
"Features should always have a prefix.") ? static_cast<void
> (0) : __assert_fail ("LHS.startswith(\"+\") && RHS.startswith(\"+\") && \"Features should always have a prefix.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 915, __PRETTY_FUNCTION__))
;
916 return Target.multiVersionSortPriority(LHS.substr(1)) >
917 Target.multiVersionSortPriority(RHS.substr(1));
918 });
919
920 bool IsFirst = true;
921
922 if (!Info.Architecture.empty()) {
923 IsFirst = false;
924 Out << "arch_" << Info.Architecture;
925 }
926
927 for (StringRef Feat : Info.Features) {
928 if (!IsFirst)
929 Out << '_';
930 IsFirst = false;
931 Out << Feat.substr(1);
932 }
933}
934
935static std::string getMangledNameImpl(const CodeGenModule &CGM, GlobalDecl GD,
936 const NamedDecl *ND,
937 bool OmitMultiVersionMangling = false) {
938 SmallString<256> Buffer;
939 llvm::raw_svector_ostream Out(Buffer);
940 MangleContext &MC = CGM.getCXXABI().getMangleContext();
941 if (MC.shouldMangleDeclName(ND)) {
942 llvm::raw_svector_ostream Out(Buffer);
943 if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
944 MC.mangleCXXCtor(D, GD.getCtorType(), Out);
945 else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
946 MC.mangleCXXDtor(D, GD.getDtorType(), Out);
947 else
948 MC.mangleName(ND, Out);
949 } else {
950 IdentifierInfo *II = ND->getIdentifier();
951 assert(II && "Attempt to mangle unnamed decl.")((II && "Attempt to mangle unnamed decl.") ? static_cast
<void> (0) : __assert_fail ("II && \"Attempt to mangle unnamed decl.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 951, __PRETTY_FUNCTION__))
;
952 const auto *FD = dyn_cast<FunctionDecl>(ND);
953
954 if (FD &&
955 FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
956 llvm::raw_svector_ostream Out(Buffer);
957 Out << "__regcall3__" << II->getName();
958 } else {
959 Out << II->getName();
960 }
961 }
962
963 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
964 if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
965 if (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion())
966 AppendCPUSpecificCPUDispatchMangling(
967 CGM, FD->getAttr<CPUSpecificAttr>(), Out);
968 else
969 AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out);
970 }
971
972 return Out.str();
973}
974
975void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
976 const FunctionDecl *FD) {
977 if (!FD->isMultiVersion())
978 return;
979
980 // Get the name of what this would be without the 'target' attribute. This
981 // allows us to lookup the version that was emitted when this wasn't a
982 // multiversion function.
983 std::string NonTargetName =
984 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
985 GlobalDecl OtherGD;
986 if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
987 assert(OtherGD.getCanonicalDecl()((OtherGD.getCanonicalDecl() .getDecl() ->getAsFunction() ->
isMultiVersion() && "Other GD should now be a multiversioned function"
) ? static_cast<void> (0) : __assert_fail ("OtherGD.getCanonicalDecl() .getDecl() ->getAsFunction() ->isMultiVersion() && \"Other GD should now be a multiversioned function\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 991, __PRETTY_FUNCTION__))
988 .getDecl()((OtherGD.getCanonicalDecl() .getDecl() ->getAsFunction() ->
isMultiVersion() && "Other GD should now be a multiversioned function"
) ? static_cast<void> (0) : __assert_fail ("OtherGD.getCanonicalDecl() .getDecl() ->getAsFunction() ->isMultiVersion() && \"Other GD should now be a multiversioned function\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 991, __PRETTY_FUNCTION__))
989 ->getAsFunction()((OtherGD.getCanonicalDecl() .getDecl() ->getAsFunction() ->
isMultiVersion() && "Other GD should now be a multiversioned function"
) ? static_cast<void> (0) : __assert_fail ("OtherGD.getCanonicalDecl() .getDecl() ->getAsFunction() ->isMultiVersion() && \"Other GD should now be a multiversioned function\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 991, __PRETTY_FUNCTION__))
990 ->isMultiVersion() &&((OtherGD.getCanonicalDecl() .getDecl() ->getAsFunction() ->
isMultiVersion() && "Other GD should now be a multiversioned function"
) ? static_cast<void> (0) : __assert_fail ("OtherGD.getCanonicalDecl() .getDecl() ->getAsFunction() ->isMultiVersion() && \"Other GD should now be a multiversioned function\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 991, __PRETTY_FUNCTION__))
991 "Other GD should now be a multiversioned function")((OtherGD.getCanonicalDecl() .getDecl() ->getAsFunction() ->
isMultiVersion() && "Other GD should now be a multiversioned function"
) ? static_cast<void> (0) : __assert_fail ("OtherGD.getCanonicalDecl() .getDecl() ->getAsFunction() ->isMultiVersion() && \"Other GD should now be a multiversioned function\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 991, __PRETTY_FUNCTION__))
;
992 // OtherFD is the version of this function that was mangled BEFORE
993 // becoming a MultiVersion function. It potentially needs to be updated.
994 const FunctionDecl *OtherFD =
995 OtherGD.getCanonicalDecl().getDecl()->getAsFunction();
996 std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
997 // This is so that if the initial version was already the 'default'
998 // version, we don't try to update it.
999 if (OtherName != NonTargetName) {
1000 // Remove instead of erase, since others may have stored the StringRef
1001 // to this.
1002 const auto ExistingRecord = Manglings.find(NonTargetName);
1003 if (ExistingRecord != std::end(Manglings))
1004 Manglings.remove(&(*ExistingRecord));
1005 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
1006 MangledDeclNames[OtherGD.getCanonicalDecl()] = Result.first->first();
1007 if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
1008 Entry->setName(OtherName);
1009 }
1010 }
1011}
1012
1013StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
1014 GlobalDecl CanonicalGD = GD.getCanonicalDecl();
1015
1016 // Some ABIs don't have constructor variants. Make sure that base and
1017 // complete constructors get mangled the same.
1018 if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
1019 if (!getTarget().getCXXABI().hasConstructorVariants()) {
1020 CXXCtorType OrigCtorType = GD.getCtorType();
1021 assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete)((OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete)
? static_cast<void> (0) : __assert_fail ("OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete"
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 1021, __PRETTY_FUNCTION__))
;
1022 if (OrigCtorType == Ctor_Base)
1023 CanonicalGD = GlobalDecl(CD, Ctor_Complete);
1024 }
1025 }
1026
1027 const auto *FD = dyn_cast<FunctionDecl>(GD.getDecl());
1028 // Since CPUSpecific can require multiple emits per decl, store the manglings
1029 // separately.
1030 if (FD &&
1031 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion())) {
1032 const auto *SD = FD->getAttr<CPUSpecificAttr>();
1033
1034 std::pair<GlobalDecl, unsigned> SpecCanonicalGD{
1035 CanonicalGD,
1036 SD ? SD->ActiveArgIndex : std::numeric_limits<unsigned>::max()};
1037
1038 auto FoundName = CPUSpecificMangledDeclNames.find(SpecCanonicalGD);
1039 if (FoundName != CPUSpecificMangledDeclNames.end())
1040 return FoundName->second;
1041
1042 auto Result = CPUSpecificManglings.insert(
1043 std::make_pair(getMangledNameImpl(*this, GD, FD), SpecCanonicalGD));
1044 return CPUSpecificMangledDeclNames[SpecCanonicalGD] = Result.first->first();
1045 }
1046
1047 auto FoundName = MangledDeclNames.find(CanonicalGD);
1048 if (FoundName != MangledDeclNames.end())
1049 return FoundName->second;
1050
1051 // Keep the first result in the case of a mangling collision.
1052 const auto *ND = cast<NamedDecl>(GD.getDecl());
1053 auto Result =
1054 Manglings.insert(std::make_pair(getMangledNameImpl(*this, GD, ND), GD));
1055 return MangledDeclNames[CanonicalGD] = Result.first->first();
1056}
1057
1058StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
1059 const BlockDecl *BD) {
1060 MangleContext &MangleCtx = getCXXABI().getMangleContext();
1061 const Decl *D = GD.getDecl();
1062
1063 SmallString<256> Buffer;
1064 llvm::raw_svector_ostream Out(Buffer);
1065 if (!D)
1066 MangleCtx.mangleGlobalBlock(BD,
1067 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
1068 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
1069 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
1070 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
1071 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
1072 else
1073 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
1074
1075 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
1076 return Result.first->first();
1077}
1078
1079llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
1080 return getModule().getNamedValue(Name);
1081}
1082
1083/// AddGlobalCtor - Add a function to the list that will be called before
1084/// main() runs.
1085void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
1086 llvm::Constant *AssociatedData) {
1087 // FIXME: Type coercion of void()* types.
1088 GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
1089}
1090
1091/// AddGlobalDtor - Add a function to the list that will be called
1092/// when the module is unloaded.
1093void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
1094 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit) {
1095 DtorsUsingAtExit[Priority].push_back(Dtor);
1096 return;
1097 }
1098
1099 // FIXME: Type coercion of void()* types.
1100 GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
1101}
1102
1103void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
1104 if (Fns.empty()) return;
1105
1106 // Ctor function type is void()*.
1107 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
1108 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
1109
1110 // Get the type of a ctor entry, { i32, void ()*, i8* }.
1111 llvm::StructType *CtorStructTy = llvm::StructType::get(
1112 Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy);
1113
1114 // Construct the constructor and destructor arrays.
1115 ConstantInitBuilder builder(*this);
1116 auto ctors = builder.beginArray(CtorStructTy);
1117 for (const auto &I : Fns) {
1118 auto ctor = ctors.beginStruct(CtorStructTy);
1119 ctor.addInt(Int32Ty, I.Priority);
1120 ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
1121 if (I.AssociatedData)
1122 ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
1123 else
1124 ctor.addNullPointer(VoidPtrTy);
1125 ctor.finishAndAddTo(ctors);
1126 }
1127
1128 auto list =
1129 ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
1130 /*constant*/ false,
1131 llvm::GlobalValue::AppendingLinkage);
1132
1133 // The LTO linker doesn't seem to like it when we set an alignment
1134 // on appending variables. Take it off as a workaround.
1135 list->setAlignment(0);
1136
1137 Fns.clear();
1138}
1139
1140llvm::GlobalValue::LinkageTypes
1141CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
1142 const auto *D = cast<FunctionDecl>(GD.getDecl());
1143
1144 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
1145
1146 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
1147 return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType());
1148
1149 if (isa<CXXConstructorDecl>(D) &&
1150 cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
1151 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1152 // Our approach to inheriting constructors is fundamentally different from
1153 // that used by the MS ABI, so keep our inheriting constructor thunks
1154 // internal rather than trying to pick an unambiguous mangling for them.
1155 return llvm::GlobalValue::InternalLinkage;
1156 }
1157
1158 return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
1159}
1160
1161llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
1162 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
1163 if (!MDS) return nullptr;
1164
1165 return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
1166}
1167
1168void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
1169 const CGFunctionInfo &Info,
1170 llvm::Function *F) {
1171 unsigned CallingConv;
1172 llvm::AttributeList PAL;
1173 ConstructAttributeList(F->getName(), Info, D, PAL, CallingConv, false);
1174 F->setAttributes(PAL);
1175 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
1176}
1177
1178/// Determines whether the language options require us to model
1179/// unwind exceptions. We treat -fexceptions as mandating this
1180/// except under the fragile ObjC ABI with only ObjC exceptions
1181/// enabled. This means, for example, that C with -fexceptions
1182/// enables this.
1183static bool hasUnwindExceptions(const LangOptions &LangOpts) {
1184 // If exceptions are completely disabled, obviously this is false.
1185 if (!LangOpts.Exceptions) return false;
1186
1187 // If C++ exceptions are enabled, this is true.
1188 if (LangOpts.CXXExceptions) return true;
1189
1190 // If ObjC exceptions are enabled, this depends on the ABI.
1191 if (LangOpts.ObjCExceptions) {
1192 return LangOpts.ObjCRuntime.hasUnwindExceptions();
1193 }
1194
1195 return true;
1196}
1197
1198static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM,
1199 const CXXMethodDecl *MD) {
1200 // Check that the type metadata can ever actually be used by a call.
1201 if (!CGM.getCodeGenOpts().LTOUnit ||
1202 !CGM.HasHiddenLTOVisibility(MD->getParent()))
1203 return false;
1204
1205 // Only functions whose address can be taken with a member function pointer
1206 // need this sort of type metadata.
1207 return !MD->isStatic() && !MD->isVirtual() && !isa<CXXConstructorDecl>(MD) &&
1208 !isa<CXXDestructorDecl>(MD);
1209}
1210
1211std::vector<const CXXRecordDecl *>
1212CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) {
1213 llvm::SetVector<const CXXRecordDecl *> MostBases;
1214
1215 std::function<void (const CXXRecordDecl *)> CollectMostBases;
1216 CollectMostBases = [&](const CXXRecordDecl *RD) {
1217 if (RD->getNumBases() == 0)
1218 MostBases.insert(RD);
1219 for (const CXXBaseSpecifier &B : RD->bases())
1220 CollectMostBases(B.getType()->getAsCXXRecordDecl());
1221 };
1222 CollectMostBases(RD);
1223 return MostBases.takeVector();
1224}
1225
1226void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
1227 llvm::Function *F) {
1228 llvm::AttrBuilder B;
1229
1230 if (CodeGenOpts.UnwindTables)
1231 B.addAttribute(llvm::Attribute::UWTable);
1232
1233 if (!hasUnwindExceptions(LangOpts))
1234 B.addAttribute(llvm::Attribute::NoUnwind);
1235
1236 if (!D || !D->hasAttr<NoStackProtectorAttr>()) {
1237 if (LangOpts.getStackProtector() == LangOptions::SSPOn)
1238 B.addAttribute(llvm::Attribute::StackProtect);
1239 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
1240 B.addAttribute(llvm::Attribute::StackProtectStrong);
1241 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
1242 B.addAttribute(llvm::Attribute::StackProtectReq);
1243 }
1244
1245 if (!D) {
1246 // If we don't have a declaration to control inlining, the function isn't
1247 // explicitly marked as alwaysinline for semantic reasons, and inlining is
1248 // disabled, mark the function as noinline.
1249 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
1250 CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
1251 B.addAttribute(llvm::Attribute::NoInline);
1252
1253 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
1254 return;
1255 }
1256
1257 // Track whether we need to add the optnone LLVM attribute,
1258 // starting with the default for this optimization level.
1259 bool ShouldAddOptNone =
1260 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
1261 // We can't add optnone in the following cases, it won't pass the verifier.
1262 ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
1263 ShouldAddOptNone &= !F->hasFnAttribute(llvm::Attribute::AlwaysInline);
1264 ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
1265
1266 if (ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) {
1267 B.addAttribute(llvm::Attribute::OptimizeNone);
1268
1269 // OptimizeNone implies noinline; we should not be inlining such functions.
1270 B.addAttribute(llvm::Attribute::NoInline);
1271 assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&((!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
"OptimizeNone and AlwaysInline on same function!") ? static_cast
<void> (0) : __assert_fail ("!F->hasFnAttribute(llvm::Attribute::AlwaysInline) && \"OptimizeNone and AlwaysInline on same function!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 1272, __PRETTY_FUNCTION__))
1272 "OptimizeNone and AlwaysInline on same function!")((!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
"OptimizeNone and AlwaysInline on same function!") ? static_cast
<void> (0) : __assert_fail ("!F->hasFnAttribute(llvm::Attribute::AlwaysInline) && \"OptimizeNone and AlwaysInline on same function!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 1272, __PRETTY_FUNCTION__))
;
1273
1274 // We still need to handle naked functions even though optnone subsumes
1275 // much of their semantics.
1276 if (D->hasAttr<NakedAttr>())
1277 B.addAttribute(llvm::Attribute::Naked);
1278
1279 // OptimizeNone wins over OptimizeForSize and MinSize.
1280 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
1281 F->removeFnAttr(llvm::Attribute::MinSize);
1282 } else if (D->hasAttr<NakedAttr>()) {
1283 // Naked implies noinline: we should not be inlining such functions.
1284 B.addAttribute(llvm::Attribute::Naked);
1285 B.addAttribute(llvm::Attribute::NoInline);
1286 } else if (D->hasAttr<NoDuplicateAttr>()) {
1287 B.addAttribute(llvm::Attribute::NoDuplicate);
1288 } else if (D->hasAttr<NoInlineAttr>()) {
1289 B.addAttribute(llvm::Attribute::NoInline);
1290 } else if (D->hasAttr<AlwaysInlineAttr>() &&
1291 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
1292 // (noinline wins over always_inline, and we can't specify both in IR)
1293 B.addAttribute(llvm::Attribute::AlwaysInline);
1294 } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
1295 // If we're not inlining, then force everything that isn't always_inline to
1296 // carry an explicit noinline attribute.
1297 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
1298 B.addAttribute(llvm::Attribute::NoInline);
1299 } else {
1300 // Otherwise, propagate the inline hint attribute and potentially use its
1301 // absence to mark things as noinline.
1302 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1303 // Search function and template pattern redeclarations for inline.
1304 auto CheckForInline = [](const FunctionDecl *FD) {
1305 auto CheckRedeclForInline = [](const FunctionDecl *Redecl) {
1306 return Redecl->isInlineSpecified();
1307 };
1308 if (any_of(FD->redecls(), CheckRedeclForInline))
1309 return true;
1310 const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
1311 if (!Pattern)
1312 return false;
1313 return any_of(Pattern->redecls(), CheckRedeclForInline);
1314 };
1315 if (CheckForInline(FD)) {
1316 B.addAttribute(llvm::Attribute::InlineHint);
1317 } else if (CodeGenOpts.getInlining() ==
1318 CodeGenOptions::OnlyHintInlining &&
1319 !FD->isInlined() &&
1320 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
1321 B.addAttribute(llvm::Attribute::NoInline);
1322 }
1323 }
1324 }
1325
1326 // Add other optimization related attributes if we are optimizing this
1327 // function.
1328 if (!D->hasAttr<OptimizeNoneAttr>()) {
1329 if (D->hasAttr<ColdAttr>()) {
1330 if (!ShouldAddOptNone)
1331 B.addAttribute(llvm::Attribute::OptimizeForSize);
1332 B.addAttribute(llvm::Attribute::Cold);
1333 }
1334
1335 if (D->hasAttr<MinSizeAttr>())
1336 B.addAttribute(llvm::Attribute::MinSize);
1337 }
1338
1339 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
1340
1341 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
1342 if (alignment)
1343 F->setAlignment(alignment);
1344
1345 if (!D->hasAttr<AlignedAttr>())
1346 if (LangOpts.FunctionAlignment)
1347 F->setAlignment(1 << LangOpts.FunctionAlignment);
1348
1349 // Some C++ ABIs require 2-byte alignment for member functions, in order to
1350 // reserve a bit for differentiating between virtual and non-virtual member
1351 // functions. If the current target's C++ ABI requires this and this is a
1352 // member function, set its alignment accordingly.
1353 if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
1354 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
1355 F->setAlignment(2);
1356 }
1357
1358 // In the cross-dso CFI mode, we want !type attributes on definitions only.
1359 if (CodeGenOpts.SanitizeCfiCrossDso)
1360 if (auto *FD = dyn_cast<FunctionDecl>(D))
1361 CreateFunctionTypeMetadataForIcall(FD, F);
1362
1363 // Emit type metadata on member functions for member function pointer checks.
1364 // These are only ever necessary on definitions; we're guaranteed that the
1365 // definition will be present in the LTO unit as a result of LTO visibility.
1366 auto *MD = dyn_cast<CXXMethodDecl>(D);
1367 if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) {
1368 for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) {
1369 llvm::Metadata *Id =
1370 CreateMetadataIdentifierForType(Context.getMemberPointerType(
1371 MD->getType(), Context.getRecordType(Base).getTypePtr()));
1372 F->addTypeMetadata(0, Id);
1373 }
1374 }
1375}
1376
1377void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
1378 const Decl *D = GD.getDecl();
1379 if (dyn_cast_or_null<NamedDecl>(D))
1380 setGVProperties(GV, GD);
1381 else
1382 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
1383
1384 if (D && D->hasAttr<UsedAttr>())
1385 addUsedGlobal(GV);
1386
1387 if (CodeGenOpts.KeepStaticConsts && D && isa<VarDecl>(D)) {
1388 const auto *VD = cast<VarDecl>(D);
1389 if (VD->getType().isConstQualified() &&
1390 VD->getStorageDuration() == SD_Static)
1391 addUsedGlobal(GV);
1392 }
1393}
1394
1395bool CodeGenModule::GetCPUAndFeaturesAttributes(const Decl *D,
1396 llvm::AttrBuilder &Attrs) {
1397 // Add target-cpu and target-features attributes to functions. If
1398 // we have a decl for the function and it has a target attribute then
1399 // parse that and add it to the feature set.
1400 StringRef TargetCPU = getTarget().getTargetOpts().CPU;
1401 std::vector<std::string> Features;
1402 const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
1403 FD = FD ? FD->getMostRecentDecl() : FD;
1404 const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
1405 const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr;
1406 bool AddedAttr = false;
1407 if (TD || SD) {
1408 llvm::StringMap<bool> FeatureMap;
1409 getFunctionFeatureMap(FeatureMap, FD);
1410
1411 // Produce the canonical string for this set of features.
1412 for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
1413 Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
1414
1415 // Now add the target-cpu and target-features to the function.
1416 // While we populated the feature map above, we still need to
1417 // get and parse the target attribute so we can get the cpu for
1418 // the function.
1419 if (TD) {
1420 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
1421 if (ParsedAttr.Architecture != "" &&
1422 getTarget().isValidCPUName(ParsedAttr.Architecture))
1423 TargetCPU = ParsedAttr.Architecture;
1424 }
1425 } else {
1426 // Otherwise just add the existing target cpu and target features to the
1427 // function.
1428 Features = getTarget().getTargetOpts().Features;
1429 }
1430
1431 if (TargetCPU != "") {
1432 Attrs.addAttribute("target-cpu", TargetCPU);
1433 AddedAttr = true;
1434 }
1435 if (!Features.empty()) {
1436 llvm::sort(Features);
1437 Attrs.addAttribute("target-features", llvm::join(Features, ","));
1438 AddedAttr = true;
1439 }
1440
1441 return AddedAttr;
1442}
1443
1444void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
1445 llvm::GlobalObject *GO) {
1446 const Decl *D = GD.getDecl();
1447 SetCommonAttributes(GD, GO);
1448
1449 if (D) {
1450 if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
1451 if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
1452 GV->addAttribute("bss-section", SA->getName());
1453 if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
1454 GV->addAttribute("data-section", SA->getName());
1455 if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
1456 GV->addAttribute("rodata-section", SA->getName());
1457 }
1458
1459 if (auto *F = dyn_cast<llvm::Function>(GO)) {
1460 if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
1461 if (!D->getAttr<SectionAttr>())
1462 F->addFnAttr("implicit-section-name", SA->getName());
1463
1464 llvm::AttrBuilder Attrs;
1465 if (GetCPUAndFeaturesAttributes(D, Attrs)) {
1466 // We know that GetCPUAndFeaturesAttributes will always have the
1467 // newest set, since it has the newest possible FunctionDecl, so the
1468 // new ones should replace the old.
1469 F->removeFnAttr("target-cpu");
1470 F->removeFnAttr("target-features");
1471 F->addAttributes(llvm::AttributeList::FunctionIndex, Attrs);
1472 }
1473 }
1474
1475 if (const auto *CSA = D->getAttr<CodeSegAttr>())
1476 GO->setSection(CSA->getName());
1477 else if (const auto *SA = D->getAttr<SectionAttr>())
1478 GO->setSection(SA->getName());
1479 }
1480
1481 getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
1482}
1483
1484void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD,
1485 llvm::Function *F,
1486 const CGFunctionInfo &FI) {
1487 const Decl *D = GD.getDecl();
1488 SetLLVMFunctionAttributes(D, FI, F);
1489 SetLLVMFunctionAttributesForDefinition(D, F);
1490
1491 F->setLinkage(llvm::Function::InternalLinkage);
1492
1493 setNonAliasAttributes(GD, F);
1494}
1495
1496static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
1497 // Set linkage and visibility in case we never see a definition.
1498 LinkageInfo LV = ND->getLinkageAndVisibility();
1499 // Don't set internal linkage on declarations.
1500 // "extern_weak" is overloaded in LLVM; we probably should have
1501 // separate linkage types for this.
1502 if (isExternallyVisible(LV.getLinkage()) &&
1503 (ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
1504 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1505}
1506
1507void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
1508 llvm::Function *F) {
1509 // Only if we are checking indirect calls.
1510 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
1511 return;
1512
1513 // Non-static class methods are handled via vtable or member function pointer
1514 // checks elsewhere.
1515 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
1516 return;
1517
1518 // Additionally, if building with cross-DSO support...
1519 if (CodeGenOpts.SanitizeCfiCrossDso) {
1520 // Skip available_externally functions. They won't be codegen'ed in the
1521 // current module anyway.
1522 if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
1523 return;
1524 }
1525
1526 llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
1527 F->addTypeMetadata(0, MD);
1528 F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
1529
1530 // Emit a hash-based bit set entry for cross-DSO calls.
1531 if (CodeGenOpts.SanitizeCfiCrossDso)
1532 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
1533 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
1534}
1535
1536void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1537 bool IsIncompleteFunction,
1538 bool IsThunk) {
1539
1540 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
1541 // If this is an intrinsic function, set the function's attributes
1542 // to the intrinsic's attributes.
1543 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
1544 return;
1545 }
1546
1547 const auto *FD = cast<FunctionDecl>(GD.getDecl());
1548
1549 if (!IsIncompleteFunction) {
1550 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
1551 // Setup target-specific attributes.
1552 if (F->isDeclaration())
1553 getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
1554 }
1555
1556 // Add the Returned attribute for "this", except for iOS 5 and earlier
1557 // where substantial code, including the libstdc++ dylib, was compiled with
1558 // GCC and does not actually return "this".
1559 if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
1560 !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
1561 assert(!F->arg_empty() &&((!F->arg_empty() && F->arg_begin()->getType
() ->canLosslesslyBitCastTo(F->getReturnType()) &&
"unexpected this return") ? static_cast<void> (0) : __assert_fail
("!F->arg_empty() && F->arg_begin()->getType() ->canLosslesslyBitCastTo(F->getReturnType()) && \"unexpected this return\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 1564, __PRETTY_FUNCTION__))
1562 F->arg_begin()->getType()((!F->arg_empty() && F->arg_begin()->getType
() ->canLosslesslyBitCastTo(F->getReturnType()) &&
"unexpected this return") ? static_cast<void> (0) : __assert_fail
("!F->arg_empty() && F->arg_begin()->getType() ->canLosslesslyBitCastTo(F->getReturnType()) && \"unexpected this return\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 1564, __PRETTY_FUNCTION__))
1563 ->canLosslesslyBitCastTo(F->getReturnType()) &&((!F->arg_empty() && F->arg_begin()->getType
() ->canLosslesslyBitCastTo(F->getReturnType()) &&
"unexpected this return") ? static_cast<void> (0) : __assert_fail
("!F->arg_empty() && F->arg_begin()->getType() ->canLosslesslyBitCastTo(F->getReturnType()) && \"unexpected this return\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 1564, __PRETTY_FUNCTION__))
1564 "unexpected this return")((!F->arg_empty() && F->arg_begin()->getType
() ->canLosslesslyBitCastTo(F->getReturnType()) &&
"unexpected this return") ? static_cast<void> (0) : __assert_fail
("!F->arg_empty() && F->arg_begin()->getType() ->canLosslesslyBitCastTo(F->getReturnType()) && \"unexpected this return\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 1564, __PRETTY_FUNCTION__))
;
1565 F->addAttribute(1, llvm::Attribute::Returned);
1566 }
1567
1568 // Only a few attributes are set on declarations; these may later be
1569 // overridden by a definition.
1570
1571 setLinkageForGV(F, FD);
1572 setGVProperties(F, FD);
1573
1574 if (const auto *CSA = FD->getAttr<CodeSegAttr>())
1575 F->setSection(CSA->getName());
1576 else if (const auto *SA = FD->getAttr<SectionAttr>())
1577 F->setSection(SA->getName());
1578
1579 if (FD->isReplaceableGlobalAllocationFunction()) {
1580 // A replaceable global allocation function does not act like a builtin by
1581 // default, only if it is invoked by a new-expression or delete-expression.
1582 F->addAttribute(llvm::AttributeList::FunctionIndex,
1583 llvm::Attribute::NoBuiltin);
1584
1585 // A sane operator new returns a non-aliasing pointer.
1586 // FIXME: Also add NonNull attribute to the return value
1587 // for the non-nothrow forms?
1588 auto Kind = FD->getDeclName().getCXXOverloadedOperator();
1589 if (getCodeGenOpts().AssumeSaneOperatorNew &&
1590 (Kind == OO_New || Kind == OO_Array_New))
1591 F->addAttribute(llvm::AttributeList::ReturnIndex,
1592 llvm::Attribute::NoAlias);
1593 }
1594
1595 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
1596 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1597 else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1598 if (MD->isVirtual())
1599 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1600
1601 // Don't emit entries for function declarations in the cross-DSO mode. This
1602 // is handled with better precision by the receiving DSO.
1603 if (!CodeGenOpts.SanitizeCfiCrossDso)
1604 CreateFunctionTypeMetadataForIcall(FD, F);
1605
1606 if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
1607 getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
1608}
1609
1610void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
1611 assert(!GV->isDeclaration() &&((!GV->isDeclaration() && "Only globals with definition can force usage."
) ? static_cast<void> (0) : __assert_fail ("!GV->isDeclaration() && \"Only globals with definition can force usage.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 1612, __PRETTY_FUNCTION__))
1612 "Only globals with definition can force usage.")((!GV->isDeclaration() && "Only globals with definition can force usage."
) ? static_cast<void> (0) : __assert_fail ("!GV->isDeclaration() && \"Only globals with definition can force usage.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 1612, __PRETTY_FUNCTION__))
;
1613 LLVMUsed.emplace_back(GV);
1614}
1615
1616void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
1617 assert(!GV->isDeclaration() &&((!GV->isDeclaration() && "Only globals with definition can force usage."
) ? static_cast<void> (0) : __assert_fail ("!GV->isDeclaration() && \"Only globals with definition can force usage.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 1618, __PRETTY_FUNCTION__))
1618 "Only globals with definition can force usage.")((!GV->isDeclaration() && "Only globals with definition can force usage."
) ? static_cast<void> (0) : __assert_fail ("!GV->isDeclaration() && \"Only globals with definition can force usage.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 1618, __PRETTY_FUNCTION__))
;
1619 LLVMCompilerUsed.emplace_back(GV);
1620}
1621
1622static void emitUsed(CodeGenModule &CGM, StringRef Name,
1623 std::vector<llvm::WeakTrackingVH> &List) {
1624 // Don't create llvm.used if there is no need.
1625 if (List.empty())
1626 return;
1627
1628 // Convert List to what ConstantArray needs.
1629 SmallVector<llvm::Constant*, 8> UsedArray;
1630 UsedArray.resize(List.size());
1631 for (unsigned i = 0, e = List.size(); i != e; ++i) {
1632 UsedArray[i] =
1633 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1634 cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
1635 }
1636
1637 if (UsedArray.empty())
1638 return;
1639 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
1640
1641 auto *GV = new llvm::GlobalVariable(
1642 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
1643 llvm::ConstantArray::get(ATy, UsedArray), Name);
1644
1645 GV->setSection("llvm.metadata");
1646}
1647
1648void CodeGenModule::emitLLVMUsed() {
1649 emitUsed(*this, "llvm.used", LLVMUsed);
1650 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
1651}
1652
1653void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
1654 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
1655 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1656}
1657
1658void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
1659 llvm::SmallString<32> Opt;
1660 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
1661 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1662 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1663}
1664
1665void CodeGenModule::AddELFLibDirective(StringRef Lib) {
1666 auto &C = getLLVMContext();
1667 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
1668 C, {llvm::MDString::get(C, "lib"), llvm::MDString::get(C, Lib)}));
1669}
1670
1671void CodeGenModule::AddDependentLib(StringRef Lib) {
1672 llvm::SmallString<24> Opt;
1673 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
1674 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1675 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1676}
1677
1678/// Add link options implied by the given module, including modules
1679/// it depends on, using a postorder walk.
1680static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
1681 SmallVectorImpl<llvm::MDNode *> &Metadata,
1682 llvm::SmallPtrSet<Module *, 16> &Visited) {
1683 // Import this module's parent.
1684 if (Mod->Parent && Visited.insert(Mod->Parent).second) {
1685 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
1686 }
1687
1688 // Import this module's dependencies.
1689 for (unsigned I = Mod->Imports.size(); I > 0; --I) {
1690 if (Visited.insert(Mod->Imports[I - 1]).second)
1691 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
1692 }
1693
1694 // Add linker options to link against the libraries/frameworks
1695 // described by this module.
1696 llvm::LLVMContext &Context = CGM.getLLVMContext();
1697
1698 // For modules that use export_as for linking, use that module
1699 // name instead.
1700 if (Mod->UseExportAsModuleLinkName)
1701 return;
1702
1703 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
1704 // Link against a framework. Frameworks are currently Darwin only, so we
1705 // don't to ask TargetCodeGenInfo for the spelling of the linker option.
1706 if (Mod->LinkLibraries[I-1].IsFramework) {
1707 llvm::Metadata *Args[2] = {
1708 llvm::MDString::get(Context, "-framework"),
1709 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
1710
1711 Metadata.push_back(llvm::MDNode::get(Context, Args));
1712 continue;
1713 }
1714
1715 // Link against a library.
1716 llvm::SmallString<24> Opt;
1717 CGM.getTargetCodeGenInfo().getDependentLibraryOption(
1718 Mod->LinkLibraries[I-1].Library, Opt);
1719 auto *OptString = llvm::MDString::get(Context, Opt);
1720 Metadata.push_back(llvm::MDNode::get(Context, OptString));
1721 }
1722}
1723
1724void CodeGenModule::EmitModuleLinkOptions() {
1725 // Collect the set of all of the modules we want to visit to emit link
1726 // options, which is essentially the imported modules and all of their
1727 // non-explicit child modules.
1728 llvm::SetVector<clang::Module *> LinkModules;
1729 llvm::SmallPtrSet<clang::Module *, 16> Visited;
1730 SmallVector<clang::Module *, 16> Stack;
1731
1732 // Seed the stack with imported modules.
1733 for (Module *M : ImportedModules) {
1734 // Do not add any link flags when an implementation TU of a module imports
1735 // a header of that same module.
1736 if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
1737 !getLangOpts().isCompilingModule())
1738 continue;
1739 if (Visited.insert(M).second)
1740 Stack.push_back(M);
1741 }
1742
1743 // Find all of the modules to import, making a little effort to prune
1744 // non-leaf modules.
1745 while (!Stack.empty()) {
1746 clang::Module *Mod = Stack.pop_back_val();
1747
1748 bool AnyChildren = false;
1749
1750 // Visit the submodules of this module.
1751 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
1752 SubEnd = Mod->submodule_end();
1753 Sub != SubEnd; ++Sub) {
1754 // Skip explicit children; they need to be explicitly imported to be
1755 // linked against.
1756 if ((*Sub)->IsExplicit)
1757 continue;
1758
1759 if (Visited.insert(*Sub).second) {
1760 Stack.push_back(*Sub);
1761 AnyChildren = true;
1762 }
1763 }
1764
1765 // We didn't find any children, so add this module to the list of
1766 // modules to link against.
1767 if (!AnyChildren) {
1768 LinkModules.insert(Mod);
1769 }
1770 }
1771
1772 // Add link options for all of the imported modules in reverse topological
1773 // order. We don't do anything to try to order import link flags with respect
1774 // to linker options inserted by things like #pragma comment().
1775 SmallVector<llvm::MDNode *, 16> MetadataArgs;
1776 Visited.clear();
1777 for (Module *M : LinkModules)
1778 if (Visited.insert(M).second)
1779 addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
1780 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
1781 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
1782
1783 // Add the linker options metadata flag.
1784 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
1785 for (auto *MD : LinkerOptionsMetadata)
1786 NMD->addOperand(MD);
1787}
1788
1789void CodeGenModule::EmitDeferred() {
1790 // Emit deferred declare target declarations.
1791 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
1792 getOpenMPRuntime().emitDeferredTargetDecls();
1793
1794 // Emit code for any potentially referenced deferred decls. Since a
1795 // previously unused static decl may become used during the generation of code
1796 // for a static function, iterate until no changes are made.
1797
1798 if (!DeferredVTables.empty()) {
1799 EmitDeferredVTables();
1800
1801 // Emitting a vtable doesn't directly cause more vtables to
1802 // become deferred, although it can cause functions to be
1803 // emitted that then need those vtables.
1804 assert(DeferredVTables.empty())((DeferredVTables.empty()) ? static_cast<void> (0) : __assert_fail
("DeferredVTables.empty()", "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 1804, __PRETTY_FUNCTION__))
;
1805 }
1806
1807 // Stop if we're out of both deferred vtables and deferred declarations.
1808 if (DeferredDeclsToEmit.empty())
1809 return;
1810
1811 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
1812 // work, it will not interfere with this.
1813 std::vector<GlobalDecl> CurDeclsToEmit;
1814 CurDeclsToEmit.swap(DeferredDeclsToEmit);
1815
1816 for (GlobalDecl &D : CurDeclsToEmit) {
1817 // We should call GetAddrOfGlobal with IsForDefinition set to true in order
1818 // to get GlobalValue with exactly the type we need, not something that
1819 // might had been created for another decl with the same mangled name but
1820 // different type.
1821 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
1822 GetAddrOfGlobal(D, ForDefinition));
1823
1824 // In case of different address spaces, we may still get a cast, even with
1825 // IsForDefinition equal to true. Query mangled names table to get
1826 // GlobalValue.
1827 if (!GV)
1828 GV = GetGlobalValue(getMangledName(D));
1829
1830 // Make sure GetGlobalValue returned non-null.
1831 assert(GV)((GV) ? static_cast<void> (0) : __assert_fail ("GV", "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 1831, __PRETTY_FUNCTION__))
;
1832
1833 // Check to see if we've already emitted this. This is necessary
1834 // for a couple of reasons: first, decls can end up in the
1835 // deferred-decls queue multiple times, and second, decls can end
1836 // up with definitions in unusual ways (e.g. by an extern inline
1837 // function acquiring a strong function redefinition). Just
1838 // ignore these cases.
1839 if (!GV->isDeclaration())
1840 continue;
1841
1842 // Otherwise, emit the definition and move on to the next one.
1843 EmitGlobalDefinition(D, GV);
1844
1845 // If we found out that we need to emit more decls, do that recursively.
1846 // This has the advantage that the decls are emitted in a DFS and related
1847 // ones are close together, which is convenient for testing.
1848 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
1849 EmitDeferred();
1850 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty())((DeferredVTables.empty() && DeferredDeclsToEmit.empty
()) ? static_cast<void> (0) : __assert_fail ("DeferredVTables.empty() && DeferredDeclsToEmit.empty()"
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 1850, __PRETTY_FUNCTION__))
;
1851 }
1852 }
1853}
1854
1855void CodeGenModule::EmitVTablesOpportunistically() {
1856 // Try to emit external vtables as available_externally if they have emitted
1857 // all inlined virtual functions. It runs after EmitDeferred() and therefore
1858 // is not allowed to create new references to things that need to be emitted
1859 // lazily. Note that it also uses fact that we eagerly emitting RTTI.
1860
1861 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())(((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables
()) && "Only emit opportunistic vtables with optimizations"
) ? static_cast<void> (0) : __assert_fail ("(OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables()) && \"Only emit opportunistic vtables with optimizations\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 1862, __PRETTY_FUNCTION__))
1862 && "Only emit opportunistic vtables with optimizations")(((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables
()) && "Only emit opportunistic vtables with optimizations"
) ? static_cast<void> (0) : __assert_fail ("(OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables()) && \"Only emit opportunistic vtables with optimizations\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 1862, __PRETTY_FUNCTION__))
;
1863
1864 for (const CXXRecordDecl *RD : OpportunisticVTables) {
1865 assert(getVTables().isVTableExternal(RD) &&((getVTables().isVTableExternal(RD) && "This queue should only contain external vtables"
) ? static_cast<void> (0) : __assert_fail ("getVTables().isVTableExternal(RD) && \"This queue should only contain external vtables\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 1866, __PRETTY_FUNCTION__))
1866 "This queue should only contain external vtables")((getVTables().isVTableExternal(RD) && "This queue should only contain external vtables"
) ? static_cast<void> (0) : __assert_fail ("getVTables().isVTableExternal(RD) && \"This queue should only contain external vtables\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 1866, __PRETTY_FUNCTION__))
;
1867 if (getCXXABI().canSpeculativelyEmitVTable(RD))
1868 VTables.GenerateClassData(RD);
1869 }
1870 OpportunisticVTables.clear();
1871}
1872
1873void CodeGenModule::EmitGlobalAnnotations() {
1874 if (Annotations.empty())
1875 return;
1876
1877 // Create a new global variable for the ConstantStruct in the Module.
1878 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1879 Annotations[0]->getType(), Annotations.size()), Annotations);
1880 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
1881 llvm::GlobalValue::AppendingLinkage,
1882 Array, "llvm.global.annotations");
1883 gv->setSection(AnnotationSection);
1884}
1885
1886llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
1887 llvm::Constant *&AStr = AnnotationStrings[Str];
1888 if (AStr)
1889 return AStr;
1890
1891 // Not found yet, create a new global.
1892 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
1893 auto *gv =
1894 new llvm::GlobalVariable(getModule(), s->getType(), true,
1895 llvm::GlobalValue::PrivateLinkage, s, ".str");
1896 gv->setSection(AnnotationSection);
1897 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1898 AStr = gv;
1899 return gv;
1900}
1901
1902llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
1903 SourceManager &SM = getContext().getSourceManager();
1904 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
1905 if (PLoc.isValid())
1906 return EmitAnnotationString(PLoc.getFilename());
1907 return EmitAnnotationString(SM.getBufferName(Loc));
1908}
1909
1910llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
1911 SourceManager &SM = getContext().getSourceManager();
1912 PresumedLoc PLoc = SM.getPresumedLoc(L);
1913 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
1914 SM.getExpansionLineNumber(L);
1915 return llvm::ConstantInt::get(Int32Ty, LineNo);
1916}
1917
1918llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
1919 const AnnotateAttr *AA,
1920 SourceLocation L) {
1921 // Get the globals for file name, annotation, and the line number.
1922 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
1923 *UnitGV = EmitAnnotationUnit(L),
1924 *LineNoCst = EmitAnnotationLineNo(L);
1925
1926 // Create the ConstantStruct for the global annotation.
1927 llvm::Constant *Fields[4] = {
1928 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
1929 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
1930 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
1931 LineNoCst
1932 };
1933 return llvm::ConstantStruct::getAnon(Fields);
1934}
1935
1936void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
1937 llvm::GlobalValue *GV) {
1938 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute")((D->hasAttr<AnnotateAttr>() && "no annotate attribute"
) ? static_cast<void> (0) : __assert_fail ("D->hasAttr<AnnotateAttr>() && \"no annotate attribute\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 1938, __PRETTY_FUNCTION__))
;
1939 // Get the struct elements for these annotations.
1940 for (const auto *I : D->specific_attrs<AnnotateAttr>())
1941 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
1942}
1943
1944bool CodeGenModule::isInSanitizerBlacklist(SanitizerMask Kind,
1945 llvm::Function *Fn,
1946 SourceLocation Loc) const {
1947 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1948 // Blacklist by function name.
1949 if (SanitizerBL.isBlacklistedFunction(Kind, Fn->getName()))
1950 return true;
1951 // Blacklist by location.
1952 if (Loc.isValid())
1953 return SanitizerBL.isBlacklistedLocation(Kind, Loc);
1954 // If location is unknown, this may be a compiler-generated function. Assume
1955 // it's located in the main file.
1956 auto &SM = Context.getSourceManager();
1957 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1958 return SanitizerBL.isBlacklistedFile(Kind, MainFile->getName());
1959 }
1960 return false;
1961}
1962
1963bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
1964 SourceLocation Loc, QualType Ty,
1965 StringRef Category) const {
1966 // For now globals can be blacklisted only in ASan and KASan.
1967 const SanitizerMask EnabledAsanMask = LangOpts.Sanitize.Mask &
1968 (SanitizerKind::Address | SanitizerKind::KernelAddress |
1969 SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress);
1970 if (!EnabledAsanMask)
1971 return false;
1972 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1973 if (SanitizerBL.isBlacklistedGlobal(EnabledAsanMask, GV->getName(), Category))
1974 return true;
1975 if (SanitizerBL.isBlacklistedLocation(EnabledAsanMask, Loc, Category))
1976 return true;
1977 // Check global type.
1978 if (!Ty.isNull()) {
1979 // Drill down the array types: if global variable of a fixed type is
1980 // blacklisted, we also don't instrument arrays of them.
1981 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
1982 Ty = AT->getElementType();
1983 Ty = Ty.getCanonicalType().getUnqualifiedType();
1984 // We allow to blacklist only record types (classes, structs etc.)
1985 if (Ty->isRecordType()) {
1986 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
1987 if (SanitizerBL.isBlacklistedType(EnabledAsanMask, TypeStr, Category))
1988 return true;
1989 }
1990 }
1991 return false;
1992}
1993
1994bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
1995 StringRef Category) const {
1996 const auto &XRayFilter = getContext().getXRayFilter();
1997 using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
1998 auto Attr = ImbueAttr::NONE;
1999 if (Loc.isValid())
2000 Attr = XRayFilter.shouldImbueLocation(Loc, Category);
2001 if (Attr == ImbueAttr::NONE)
2002 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
2003 switch (Attr) {
2004 case ImbueAttr::NONE:
2005 return false;
2006 case ImbueAttr::ALWAYS:
2007 Fn->addFnAttr("function-instrument", "xray-always");
2008 break;
2009 case ImbueAttr::ALWAYS_ARG1:
2010 Fn->addFnAttr("function-instrument", "xray-always");
2011 Fn->addFnAttr("xray-log-args", "1");
2012 break;
2013 case ImbueAttr::NEVER:
2014 Fn->addFnAttr("function-instrument", "xray-never");
2015 break;
2016 }
2017 return true;
2018}
2019
2020bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
2021 // Never defer when EmitAllDecls is specified.
2022 if (LangOpts.EmitAllDecls)
2023 return true;
2024
2025 if (CodeGenOpts.KeepStaticConsts) {
2026 const auto *VD = dyn_cast<VarDecl>(Global);
2027 if (VD && VD->getType().isConstQualified() &&
2028 VD->getStorageDuration() == SD_Static)
2029 return true;
2030 }
2031
2032 return getContext().DeclMustBeEmitted(Global);
2033}
2034
2035bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
2036 if (const auto *FD = dyn_cast<FunctionDecl>(Global))
2037 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
2038 // Implicit template instantiations may change linkage if they are later
2039 // explicitly instantiated, so they should not be emitted eagerly.
2040 return false;
2041 if (const auto *VD = dyn_cast<VarDecl>(Global))
2042 if (Context.getInlineVariableDefinitionKind(VD) ==
2043 ASTContext::InlineVariableDefinitionKind::WeakUnknown)
2044 // A definition of an inline constexpr static data member may change
2045 // linkage later if it's redeclared outside the class.
2046 return false;
2047 // If OpenMP is enabled and threadprivates must be generated like TLS, delay
2048 // codegen for global variables, because they may be marked as threadprivate.
2049 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
2050 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) &&
2051 !isTypeConstant(Global->getType(), false) &&
2052 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global))
2053 return false;
2054
2055 return true;
2056}
2057
2058ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
2059 const CXXUuidofExpr* E) {
2060 // Sema has verified that IIDSource has a __declspec(uuid()), and that its
2061 // well-formed.
2062 StringRef Uuid = E->getUuidStr();
2063 std::string Name = "_GUID_" + Uuid.lower();
2064 std::replace(Name.begin(), Name.end(), '-', '_');
2065
2066 // The UUID descriptor should be pointer aligned.
2067 CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
2068
2069 // Look for an existing global.
2070 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
2071 return ConstantAddress(GV, Alignment);
2072
2073 llvm::Constant *Init = EmitUuidofInitializer(Uuid);
2074 assert(Init && "failed to initialize as constant")((Init && "failed to initialize as constant") ? static_cast
<void> (0) : __assert_fail ("Init && \"failed to initialize as constant\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 2074, __PRETTY_FUNCTION__))
;
2075
2076 auto *GV = new llvm::GlobalVariable(
2077 getModule(), Init->getType(),
2078 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
2079 if (supportsCOMDAT())
2080 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2081 setDSOLocal(GV);
2082 return ConstantAddress(GV, Alignment);
2083}
2084
2085ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
2086 const AliasAttr *AA = VD->getAttr<AliasAttr>();
2087 assert(AA && "No alias?")((AA && "No alias?") ? static_cast<void> (0) : __assert_fail
("AA && \"No alias?\"", "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 2087, __PRETTY_FUNCTION__))
;
2088
2089 CharUnits Alignment = getContext().getDeclAlign(VD);
2090 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
2091
2092 // See if there is already something with the target's name in the module.
2093 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
2094 if (Entry) {
2095 unsigned AS = getContext().getTargetAddressSpace(VD->getType());
2096 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
2097 return ConstantAddress(Ptr, Alignment);
2098 }
2099
2100 llvm::Constant *Aliasee;
2101 if (isa<llvm::FunctionType>(DeclTy))
2102 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
2103 GlobalDecl(cast<FunctionDecl>(VD)),
2104 /*ForVTable=*/false);
2105 else
2106 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
2107 llvm::PointerType::getUnqual(DeclTy),
2108 nullptr);
2109
2110 auto *F = cast<llvm::GlobalValue>(Aliasee);
2111 F->setLinkage(llvm::Function::ExternalWeakLinkage);
2112 WeakRefReferences.insert(F);
2113
2114 return ConstantAddress(Aliasee, Alignment);
2115}
2116
2117void CodeGenModule::EmitGlobal(GlobalDecl GD) {
2118 const auto *Global = cast<ValueDecl>(GD.getDecl());
2119
2120 // Weak references don't produce any output by themselves.
2121 if (Global->hasAttr<WeakRefAttr>())
2122 return;
2123
2124 // If this is an alias definition (which otherwise looks like a declaration)
2125 // emit it now.
2126 if (Global->hasAttr<AliasAttr>())
2127 return EmitAliasDefinition(GD);
2128
2129 // IFunc like an alias whose value is resolved at runtime by calling resolver.
2130 if (Global->hasAttr<IFuncAttr>())
2131 return emitIFuncDefinition(GD);
2132
2133 // If this is a cpu_dispatch multiversion function, emit the resolver.
2134 if (Global->hasAttr<CPUDispatchAttr>())
2135 return emitCPUDispatchDefinition(GD);
2136
2137 // If this is CUDA, be selective about which declarations we emit.
2138 if (LangOpts.CUDA) {
2139 if (LangOpts.CUDAIsDevice) {
2140 if (!Global->hasAttr<CUDADeviceAttr>() &&
2141 !Global->hasAttr<CUDAGlobalAttr>() &&
2142 !Global->hasAttr<CUDAConstantAttr>() &&
2143 !Global->hasAttr<CUDASharedAttr>())
2144 return;
2145 } else {
2146 // We need to emit host-side 'shadows' for all global
2147 // device-side variables because the CUDA runtime needs their
2148 // size and host-side address in order to provide access to
2149 // their device-side incarnations.
2150
2151 // So device-only functions are the only things we skip.
2152 if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
2153 Global->hasAttr<CUDADeviceAttr>())
2154 return;
2155
2156 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&(((isa<FunctionDecl>(Global) || isa<VarDecl>(Global
)) && "Expected Variable or Function") ? static_cast<
void> (0) : __assert_fail ("(isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) && \"Expected Variable or Function\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 2157, __PRETTY_FUNCTION__))
2157 "Expected Variable or Function")(((isa<FunctionDecl>(Global) || isa<VarDecl>(Global
)) && "Expected Variable or Function") ? static_cast<
void> (0) : __assert_fail ("(isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) && \"Expected Variable or Function\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 2157, __PRETTY_FUNCTION__))
;
2158 }
2159 }
2160
2161 if (LangOpts.OpenMP) {
2162 // If this is OpenMP device, check if it is legal to emit this global
2163 // normally.
2164 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
2165 return;
2166 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
2167 if (MustBeEmitted(Global))
2168 EmitOMPDeclareReduction(DRD);
2169 return;
2170 }
2171 }
2172
2173 // Ignore declarations, they will be emitted on their first use.
2174 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
2175 // Forward declarations are emitted lazily on first use.
2176 if (!FD->doesThisDeclarationHaveABody()) {
2177 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
2178 return;
2179
2180 StringRef MangledName = getMangledName(GD);
2181
2182 // Compute the function info and LLVM type.
2183 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2184 llvm::Type *Ty = getTypes().GetFunctionType(FI);
2185
2186 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
2187 /*DontDefer=*/false);
2188 return;
2189 }
2190 } else {
2191 const auto *VD = cast<VarDecl>(Global);
2192 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.")((VD->isFileVarDecl() && "Cannot emit local var decl as global."
) ? static_cast<void> (0) : __assert_fail ("VD->isFileVarDecl() && \"Cannot emit local var decl as global.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 2192, __PRETTY_FUNCTION__))
;
2193 // We need to emit device-side global CUDA variables even if a
2194 // variable does not have a definition -- we still need to define
2195 // host-side shadow for it.
2196 bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
2197 !VD->hasDefinition() &&
2198 (VD->hasAttr<CUDAConstantAttr>() ||
2199 VD->hasAttr<CUDADeviceAttr>());
2200 if (!MustEmitForCuda &&
2201 VD->isThisDeclarationADefinition() != VarDecl::Definition &&
2202 !Context.isMSStaticDataMemberInlineDefinition(VD)) {
2203 if (LangOpts.OpenMP) {
2204 // Emit declaration of the must-be-emitted declare target variable.
2205 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2206 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
2207 if (*Res == OMPDeclareTargetDeclAttr::MT_To) {
2208 (void)GetAddrOfGlobalVar(VD);
2209 } else {
2210 assert(*Res == OMPDeclareTargetDeclAttr::MT_Link &&((*Res == OMPDeclareTargetDeclAttr::MT_Link && "link claue expected."
) ? static_cast<void> (0) : __assert_fail ("*Res == OMPDeclareTargetDeclAttr::MT_Link && \"link claue expected.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 2211, __PRETTY_FUNCTION__))
2211 "link claue expected.")((*Res == OMPDeclareTargetDeclAttr::MT_Link && "link claue expected."
) ? static_cast<void> (0) : __assert_fail ("*Res == OMPDeclareTargetDeclAttr::MT_Link && \"link claue expected.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 2211, __PRETTY_FUNCTION__))
;
2212 (void)getOpenMPRuntime().getAddrOfDeclareTargetLink(VD);
2213 }
2214 return;
2215 }
2216 }
2217 // If this declaration may have caused an inline variable definition to
2218 // change linkage, make sure that it's emitted.
2219 if (Context.getInlineVariableDefinitionKind(VD) ==
2220 ASTContext::InlineVariableDefinitionKind::Strong)
2221 GetAddrOfGlobalVar(VD);
2222 return;
2223 }
2224 }
2225
2226 // Defer code generation to first use when possible, e.g. if this is an inline
2227 // function. If the global must always be emitted, do it eagerly if possible
2228 // to benefit from cache locality.
2229 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
2230 // Emit the definition if it can't be deferred.
2231 EmitGlobalDefinition(GD);
2232 return;
2233 }
2234
2235 // If we're deferring emission of a C++ variable with an
2236 // initializer, remember the order in which it appeared in the file.
2237 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
2238 cast<VarDecl>(Global)->hasInit()) {
2239 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
2240 CXXGlobalInits.push_back(nullptr);
2241 }
2242
2243 StringRef MangledName = getMangledName(GD);
2244 if (GetGlobalValue(MangledName) != nullptr) {
2245 // The value has already been used and should therefore be emitted.
2246 addDeferredDeclToEmit(GD);
2247 } else if (MustBeEmitted(Global)) {
2248 // The value must be emitted, but cannot be emitted eagerly.
2249 assert(!MayBeEmittedEagerly(Global))((!MayBeEmittedEagerly(Global)) ? static_cast<void> (0)
: __assert_fail ("!MayBeEmittedEagerly(Global)", "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 2249, __PRETTY_FUNCTION__))
;
2250 addDeferredDeclToEmit(GD);
2251 } else {
2252 // Otherwise, remember that we saw a deferred decl with this name. The
2253 // first use of the mangled name will cause it to move into
2254 // DeferredDeclsToEmit.
2255 DeferredDecls[MangledName] = GD;
2256 }
2257}
2258
2259// Check if T is a class type with a destructor that's not dllimport.
2260static bool HasNonDllImportDtor(QualType T) {
2261 if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
2262 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2263 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
2264 return true;
2265
2266 return false;
2267}
2268
2269namespace {
2270 struct FunctionIsDirectlyRecursive :
2271 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
2272 const StringRef Name;
2273 const Builtin::Context &BI;
2274 bool Result;
2275 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
2276 Name(N), BI(C), Result(false) {
2277 }
2278 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
2279
2280 bool TraverseCallExpr(CallExpr *E) {
2281 const FunctionDecl *FD = E->getDirectCallee();
2282 if (!FD)
2283 return true;
2284 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
2285 if (Attr && Name == Attr->getLabel()) {
2286 Result = true;
2287 return false;
2288 }
2289 unsigned BuiltinID = FD->getBuiltinID();
2290 if (!BuiltinID || !BI.isLibFunction(BuiltinID))
2291 return true;
2292 StringRef BuiltinName = BI.getName(BuiltinID);
2293 if (BuiltinName.startswith("__builtin_") &&
2294 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
2295 Result = true;
2296 return false;
2297 }
2298 return true;
2299 }
2300 };
2301
2302 // Make sure we're not referencing non-imported vars or functions.
2303 struct DLLImportFunctionVisitor
2304 : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
2305 bool SafeToInline = true;
2306
2307 bool shouldVisitImplicitCode() const { return true; }
2308
2309 bool VisitVarDecl(VarDecl *VD) {
2310 if (VD->getTLSKind()) {
2311 // A thread-local variable cannot be imported.
2312 SafeToInline = false;
2313 return SafeToInline;
2314 }
2315
2316 // A variable definition might imply a destructor call.
2317 if (VD->isThisDeclarationADefinition())
2318 SafeToInline = !HasNonDllImportDtor(VD->getType());
2319
2320 return SafeToInline;
2321 }
2322
2323 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
2324 if (const auto *D = E->getTemporary()->getDestructor())
2325 SafeToInline = D->hasAttr<DLLImportAttr>();
2326 return SafeToInline;
2327 }
2328
2329 bool VisitDeclRefExpr(DeclRefExpr *E) {
2330 ValueDecl *VD = E->getDecl();
2331 if (isa<FunctionDecl>(VD))
2332 SafeToInline = VD->hasAttr<DLLImportAttr>();
2333 else if (VarDecl *V = dyn_cast<VarDecl>(VD))
2334 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
2335 return SafeToInline;
2336 }
2337
2338 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
2339 SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
2340 return SafeToInline;
2341 }
2342
2343 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2344 CXXMethodDecl *M = E->getMethodDecl();
2345 if (!M) {
2346 // Call through a pointer to member function. This is safe to inline.
2347 SafeToInline = true;
2348 } else {
2349 SafeToInline = M->hasAttr<DLLImportAttr>();
2350 }
2351 return SafeToInline;
2352 }
2353
2354 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
2355 SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
2356 return SafeToInline;
2357 }
2358
2359 bool VisitCXXNewExpr(CXXNewExpr *E) {
2360 SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
2361 return SafeToInline;
2362 }
2363 };
2364}
2365
2366// isTriviallyRecursive - Check if this function calls another
2367// decl that, because of the asm attribute or the other decl being a builtin,
2368// ends up pointing to itself.
2369bool
2370CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
2371 StringRef Name;
2372 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
2373 // asm labels are a special kind of mangling we have to support.
2374 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
2375 if (!Attr)
2376 return false;
2377 Name = Attr->getLabel();
2378 } else {
2379 Name = FD->getName();
2380 }
2381
2382 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
2383 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
2384 return Walker.Result;
2385}
2386
2387bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
2388 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
2389 return true;
2390 const auto *F = cast<FunctionDecl>(GD.getDecl());
2391 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
2392 return false;
2393
2394 if (F->hasAttr<DLLImportAttr>()) {
2395 // Check whether it would be safe to inline this dllimport function.
2396 DLLImportFunctionVisitor Visitor;
2397 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
2398 if (!Visitor.SafeToInline)
2399 return false;
2400
2401 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
2402 // Implicit destructor invocations aren't captured in the AST, so the
2403 // check above can't see them. Check for them manually here.
2404 for (const Decl *Member : Dtor->getParent()->decls())
2405 if (isa<FieldDecl>(Member))
2406 if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
2407 return false;
2408 for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
2409 if (HasNonDllImportDtor(B.getType()))
2410 return false;
2411 }
2412 }
2413
2414 // PR9614. Avoid cases where the source code is lying to us. An available
2415 // externally function should have an equivalent function somewhere else,
2416 // but a function that calls itself is clearly not equivalent to the real
2417 // implementation.
2418 // This happens in glibc's btowc and in some configure checks.
2419 return !isTriviallyRecursive(F);
2420}
2421
2422bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
2423 return CodeGenOpts.OptimizationLevel > 0;
2424}
2425
2426void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
2427 const auto *D = cast<ValueDecl>(GD.getDecl());
2428
2429 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
2430 Context.getSourceManager(),
2431 "Generating code for declaration");
2432
2433 if (isa<FunctionDecl>(D)) {
2434 // At -O0, don't generate IR for functions with available_externally
2435 // linkage.
2436 if (!shouldEmitFunction(GD))
2437 return;
2438
2439 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
2440 // Make sure to emit the definition(s) before we emit the thunks.
2441 // This is necessary for the generation of certain thunks.
2442 if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
2443 ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
2444 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
2445 ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
2446 else
2447 EmitGlobalFunctionDefinition(GD, GV);
2448
2449 if (Method->isVirtual())
2450 getVTables().EmitThunks(GD);
2451
2452 return;
2453 }
2454
2455 return EmitGlobalFunctionDefinition(GD, GV);
2456 }
2457
2458 if (const auto *VD = dyn_cast<VarDecl>(D))
2459 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
2460
2461 llvm_unreachable("Invalid argument to EmitGlobalDefinition()")::llvm::llvm_unreachable_internal("Invalid argument to EmitGlobalDefinition()"
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 2461)
;
2462}
2463
2464static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2465 llvm::Function *NewFn);
2466
2467static unsigned
2468TargetMVPriority(const TargetInfo &TI,
2469 const CodeGenFunction::MultiVersionResolverOption &RO) {
2470 unsigned Priority = 0;
2471 for (StringRef Feat : RO.Conditions.Features)
2472 Priority = std::max(Priority, TI.multiVersionSortPriority(Feat));
2473
2474 if (!RO.Conditions.Architecture.empty())
2475 Priority = std::max(
2476 Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture));
2477 return Priority;
2478}
2479
2480void CodeGenModule::emitMultiVersionFunctions() {
2481 for (GlobalDecl GD : MultiVersionFuncs) {
2482 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
2483 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
2484 getContext().forEachMultiversionedFunctionVersion(
2485 FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
2486 GlobalDecl CurGD{
2487 (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
1
Assuming the condition is false
2
'?' condition is false
2488 StringRef MangledName = getMangledName(CurGD);
2489 llvm::Constant *Func = GetGlobalValue(MangledName);
2490 if (!Func) {
3
Assuming 'Func' is null
4
Taking true branch
2491 if (CurFD->isDefined()) {
5
Assuming the condition is true
6
Taking true branch
2492 EmitGlobalFunctionDefinition(CurGD, nullptr);
7
Calling 'CodeGenModule::EmitGlobalFunctionDefinition'
2493 Func = GetGlobalValue(MangledName);
2494 } else {
2495 const CGFunctionInfo &FI =
2496 getTypes().arrangeGlobalDeclaration(GD);
2497 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2498 Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
2499 /*DontDefer=*/false, ForDefinition);
2500 }
2501 assert(Func && "This should have just been created")((Func && "This should have just been created") ? static_cast
<void> (0) : __assert_fail ("Func && \"This should have just been created\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 2501, __PRETTY_FUNCTION__))
;
2502 }
2503
2504 const auto *TA = CurFD->getAttr<TargetAttr>();
2505 llvm::SmallVector<StringRef, 8> Feats;
2506 TA->getAddedFeatures(Feats);
2507
2508 Options.emplace_back(cast<llvm::Function>(Func),
2509 TA->getArchitecture(), Feats);
2510 });
2511
2512 llvm::Function *ResolverFunc;
2513 const TargetInfo &TI = getTarget();
2514
2515 if (TI.supportsIFunc() || FD->isTargetMultiVersion())
2516 ResolverFunc = cast<llvm::Function>(
2517 GetGlobalValue((getMangledName(GD) + ".resolver").str()));
2518 else
2519 ResolverFunc = cast<llvm::Function>(GetGlobalValue(getMangledName(GD)));
2520
2521 if (supportsCOMDAT())
2522 ResolverFunc->setComdat(
2523 getModule().getOrInsertComdat(ResolverFunc->getName()));
2524
2525 std::stable_sort(
2526 Options.begin(), Options.end(),
2527 [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
2528 const CodeGenFunction::MultiVersionResolverOption &RHS) {
2529 return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
2530 });
2531 CodeGenFunction CGF(*this);
2532 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
2533 }
2534}
2535
2536void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
2537 const auto *FD = cast<FunctionDecl>(GD.getDecl());
2538 assert(FD && "Not a FunctionDecl?")((FD && "Not a FunctionDecl?") ? static_cast<void>
(0) : __assert_fail ("FD && \"Not a FunctionDecl?\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 2538, __PRETTY_FUNCTION__))
;
2539 const auto *DD = FD->getAttr<CPUDispatchAttr>();
2540 assert(DD && "Not a cpu_dispatch Function?")((DD && "Not a cpu_dispatch Function?") ? static_cast
<void> (0) : __assert_fail ("DD && \"Not a cpu_dispatch Function?\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 2540, __PRETTY_FUNCTION__))
;
2541 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(FD->getType());
2542
2543 StringRef ResolverName = getMangledName(GD);
2544
2545 llvm::Type *ResolverType;
2546 GlobalDecl ResolverGD;
2547 if (getTarget().supportsIFunc())
2548 ResolverType = llvm::FunctionType::get(
2549 llvm::PointerType::get(DeclTy,
2550 Context.getTargetAddressSpace(FD->getType())),
2551 false);
2552 else {
2553 ResolverType = DeclTy;
2554 ResolverGD = GD;
2555 }
2556
2557 auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
2558 ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false));
2559
2560 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
2561 const TargetInfo &Target = getTarget();
2562 for (const IdentifierInfo *II : DD->cpus()) {
2563 // Get the name of the target function so we can look it up/create it.
2564 std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
2565 getCPUSpecificMangling(*this, II->getName());
2566 llvm::Constant *Func = GetOrCreateLLVMFunction(
2567 MangledName, DeclTy, GD, /*ForVTable=*/false, /*DontDefer=*/false,
2568 /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
2569 llvm::SmallVector<StringRef, 32> Features;
2570 Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
2571 llvm::transform(Features, Features.begin(),
2572 [](StringRef Str) { return Str.substr(1); });
2573 Features.erase(std::remove_if(
2574 Features.begin(), Features.end(), [&Target](StringRef Feat) {
2575 return !Target.validateCpuSupports(Feat);
2576 }), Features.end());
2577 Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features);
2578 }
2579
2580 llvm::sort(
2581 Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS,
2582 const CodeGenFunction::MultiVersionResolverOption &RHS) {
2583 return CodeGenFunction::GetX86CpuSupportsMask(LHS.Conditions.Features) >
2584 CodeGenFunction::GetX86CpuSupportsMask(RHS.Conditions.Features);
2585 });
2586 CodeGenFunction CGF(*this);
2587 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
2588}
2589
2590/// If a dispatcher for the specified mangled name is not in the module, create
2591/// and return an llvm Function with the specified type.
2592llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(
2593 GlobalDecl GD, llvm::Type *DeclTy, const FunctionDecl *FD) {
2594 std::string MangledName =
2595 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
2596
2597 // Holds the name of the resolver, in ifunc mode this is the ifunc (which has
2598 // a separate resolver).
2599 std::string ResolverName = MangledName;
2600 if (getTarget().supportsIFunc())
2601 ResolverName += ".ifunc";
2602 else if (FD->isTargetMultiVersion())
2603 ResolverName += ".resolver";
2604
2605 // If this already exists, just return that one.
2606 if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName))
2607 return ResolverGV;
2608
2609 // Since this is the first time we've created this IFunc, make sure
2610 // that we put this multiversioned function into the list to be
2611 // replaced later if necessary (target multiversioning only).
2612 if (!FD->isCPUDispatchMultiVersion() && !FD->isCPUSpecificMultiVersion())
2613 MultiVersionFuncs.push_back(GD);
2614
2615 if (getTarget().supportsIFunc()) {
2616 llvm::Type *ResolverType = llvm::FunctionType::get(
2617 llvm::PointerType::get(
2618 DeclTy, getContext().getTargetAddressSpace(FD->getType())),
2619 false);
2620 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
2621 MangledName + ".resolver", ResolverType, GlobalDecl{},
2622 /*ForVTable=*/false);
2623 llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
2624 DeclTy, 0, llvm::Function::ExternalLinkage, "", Resolver, &getModule());
2625 GIF->setName(ResolverName);
2626 SetCommonAttributes(FD, GIF);
2627
2628 return GIF;
2629 }
2630
2631 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
2632 ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false);
2633 assert(isa<llvm::GlobalValue>(Resolver) &&((isa<llvm::GlobalValue>(Resolver) && "Resolver should be created for the first time"
) ? static_cast<void> (0) : __assert_fail ("isa<llvm::GlobalValue>(Resolver) && \"Resolver should be created for the first time\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 2634, __PRETTY_FUNCTION__))
2634 "Resolver should be created for the first time")((isa<llvm::GlobalValue>(Resolver) && "Resolver should be created for the first time"
) ? static_cast<void> (0) : __assert_fail ("isa<llvm::GlobalValue>(Resolver) && \"Resolver should be created for the first time\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 2634, __PRETTY_FUNCTION__))
;
2635 SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver));
2636 return Resolver;
2637}
2638
2639/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
2640/// module, create and return an llvm Function with the specified type. If there
2641/// is something in the module with the specified name, return it potentially
2642/// bitcasted to the right type.
2643///
2644/// If D is non-null, it specifies a decl that correspond to this. This is used
2645/// to set the attributes on the function when it is first created.
2646llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
2647 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
2648 bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
2649 ForDefinition_t IsForDefinition) {
2650 const Decl *D = GD.getDecl();
23
Calling 'GlobalDecl::getDecl'
40
Returning from 'GlobalDecl::getDecl'
41
'D' initialized here
2651
2652 // Any attempts to use a MultiVersion function should result in retrieving
2653 // the iFunc instead. Name Mangling will handle the rest of the changes.
2654 if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
42
Assuming 'FD' is null
43
Taking false branch
2655 // For the device mark the function as one that should be emitted.
2656 if (getLangOpts().OpenMPIsDevice && OpenMPRuntime &&
2657 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
2658 !DontDefer && !IsForDefinition) {
2659 if (const FunctionDecl *FDDef = FD->getDefinition()) {
2660 GlobalDecl GDDef;
2661 if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
2662 GDDef = GlobalDecl(CD, GD.getCtorType());
2663 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
2664 GDDef = GlobalDecl(DD, GD.getDtorType());
2665 else
2666 GDDef = GlobalDecl(FDDef);
2667 EmitGlobal(GDDef);
2668 }
2669 }
2670
2671 if (FD->isMultiVersion()) {
2672 const auto *TA = FD->getAttr<TargetAttr>();
2673 if (TA && TA->isDefaultVersion())
2674 UpdateMultiVersionNames(GD, FD);
2675 if (!IsForDefinition)
2676 return GetOrCreateMultiVersionResolver(GD, Ty, FD);
2677 }
2678 }
2679
2680 // Lookup the entry, lazily creating it if necessary.
2681 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2682 if (Entry) {
44
Assuming 'Entry' is non-null
45
Taking true branch
2683 if (WeakRefReferences.erase(Entry)) {
46
Assuming the condition is false
47
Taking false branch
2684 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
2685 if (FD && !FD->hasAttr<WeakAttr>())
2686 Entry->setLinkage(llvm::Function::ExternalLinkage);
2687 }
2688
2689 // Handle dropped DLL attributes.
2690 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) {
48
Assuming 'D' is null
49
Assuming pointer value is null
2691 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2692 setDSOLocal(Entry);
2693 }
2694
2695 // If there are two attempts to define the same mangled name, issue an
2696 // error.
2697 if (IsForDefinition && !Entry->isDeclaration()) {
50
Assuming the condition is true
51
Taking true branch
2698 GlobalDecl OtherGD;
2699 // Check that GD is not yet in DiagnosedConflictingDefinitions is required
2700 // to make sure that we issue an error only once.
2701 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
52
Assuming the condition is true
54
Assuming the condition is true
55
Taking true branch
2702 (GD.getCanonicalDecl().getDecl() !=
53
Assuming the condition is true
2703 OtherGD.getCanonicalDecl().getDecl()) &&
2704 DiagnosedConflictingDefinitions.insert(GD).second) {
2705 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
56
Called C++ object pointer is null
2706 << MangledName;
2707 getDiags().Report(OtherGD.getDecl()->getLocation(),
2708 diag::note_previous_definition);
2709 }
2710 }
2711
2712 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
2713 (Entry->getType()->getElementType() == Ty)) {
2714 return Entry;
2715 }
2716
2717 // Make sure the result is of the correct type.
2718 // (If function is requested for a definition, we always need to create a new
2719 // function, not just return a bitcast.)
2720 if (!IsForDefinition)
2721 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
2722 }
2723
2724 // This function doesn't have a complete type (for example, the return
2725 // type is an incomplete struct). Use a fake type instead, and make
2726 // sure not to try to set attributes.
2727 bool IsIncompleteFunction = false;
2728
2729 llvm::FunctionType *FTy;
2730 if (isa<llvm::FunctionType>(Ty)) {
2731 FTy = cast<llvm::FunctionType>(Ty);
2732 } else {
2733 FTy = llvm::FunctionType::get(VoidTy, false);
2734 IsIncompleteFunction = true;
2735 }
2736
2737 llvm::Function *F =
2738 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
2739 Entry ? StringRef() : MangledName, &getModule());
2740
2741 // If we already created a function with the same mangled name (but different
2742 // type) before, take its name and add it to the list of functions to be
2743 // replaced with F at the end of CodeGen.
2744 //
2745 // This happens if there is a prototype for a function (e.g. "int f()") and
2746 // then a definition of a different type (e.g. "int f(int x)").
2747 if (Entry) {
2748 F->takeName(Entry);
2749
2750 // This might be an implementation of a function without a prototype, in
2751 // which case, try to do special replacement of calls which match the new
2752 // prototype. The really key thing here is that we also potentially drop
2753 // arguments from the call site so as to make a direct call, which makes the
2754 // inliner happier and suppresses a number of optimizer warnings (!) about
2755 // dropping arguments.
2756 if (!Entry->use_empty()) {
2757 ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
2758 Entry->removeDeadConstantUsers();
2759 }
2760
2761 llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
2762 F, Entry->getType()->getElementType()->getPointerTo());
2763 addGlobalValReplacement(Entry, BC);
2764 }
2765
2766 assert(F->getName() == MangledName && "name was uniqued!")((F->getName() == MangledName && "name was uniqued!"
) ? static_cast<void> (0) : __assert_fail ("F->getName() == MangledName && \"name was uniqued!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 2766, __PRETTY_FUNCTION__))
;
2767 if (D)
2768 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
2769 if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
2770 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
2771 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
2772 }
2773
2774 if (!DontDefer) {
2775 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
2776 // each other bottoming out with the base dtor. Therefore we emit non-base
2777 // dtors on usage, even if there is no dtor definition in the TU.
2778 if (D && isa<CXXDestructorDecl>(D) &&
2779 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
2780 GD.getDtorType()))
2781 addDeferredDeclToEmit(GD);
2782
2783 // This is the first use or definition of a mangled name. If there is a
2784 // deferred decl with this name, remember that we need to emit it at the end
2785 // of the file.
2786 auto DDI = DeferredDecls.find(MangledName);
2787 if (DDI != DeferredDecls.end()) {
2788 // Move the potentially referenced deferred decl to the
2789 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
2790 // don't need it anymore).
2791 addDeferredDeclToEmit(DDI->second);
2792 DeferredDecls.erase(DDI);
2793
2794 // Otherwise, there are cases we have to worry about where we're
2795 // using a declaration for which we must emit a definition but where
2796 // we might not find a top-level definition:
2797 // - member functions defined inline in their classes
2798 // - friend functions defined inline in some class
2799 // - special member functions with implicit definitions
2800 // If we ever change our AST traversal to walk into class methods,
2801 // this will be unnecessary.
2802 //
2803 // We also don't emit a definition for a function if it's going to be an
2804 // entry in a vtable, unless it's already marked as used.
2805 } else if (getLangOpts().CPlusPlus && D) {
2806 // Look for a declaration that's lexically in a record.
2807 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
2808 FD = FD->getPreviousDecl()) {
2809 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
2810 if (FD->doesThisDeclarationHaveABody()) {
2811 addDeferredDeclToEmit(GD.getWithDecl(FD));
2812 break;
2813 }
2814 }
2815 }
2816 }
2817 }
2818
2819 // Make sure the result is of the requested type.
2820 if (!IsIncompleteFunction) {
2821 assert(F->getType()->getElementType() == Ty)((F->getType()->getElementType() == Ty) ? static_cast<
void> (0) : __assert_fail ("F->getType()->getElementType() == Ty"
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 2821, __PRETTY_FUNCTION__))
;
2822 return F;
2823 }
2824
2825 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2826 return llvm::ConstantExpr::getBitCast(F, PTy);
2827}
2828
2829/// GetAddrOfFunction - Return the address of the given function. If Ty is
2830/// non-null, then this function will use the specified type if it has to
2831/// create it (this occurs when we see a definition of the function).
2832llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
2833 llvm::Type *Ty,
2834 bool ForVTable,
2835 bool DontDefer,
2836 ForDefinition_t IsForDefinition) {
2837 // If there was no specific requested type, just convert it now.
2838 if (!Ty) {
19
Assuming 'Ty' is non-null
20
Taking false branch
2839 const auto *FD = cast<FunctionDecl>(GD.getDecl());
2840 auto CanonTy = Context.getCanonicalType(FD->getType());
2841 Ty = getTypes().ConvertFunctionType(CanonTy, FD);
2842 }
2843
2844 // Devirtualized destructor calls may come through here instead of via
2845 // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
2846 // of the complete destructor when necessary.
2847 if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
21
Taking false branch
2848 if (getTarget().getCXXABI().isMicrosoft() &&
2849 GD.getDtorType() == Dtor_Complete &&
2850 DD->getParent()->getNumVBases() == 0)
2851 GD = GlobalDecl(DD, Dtor_Base);
2852 }
2853
2854 StringRef MangledName = getMangledName(GD);
2855 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
22
Calling 'CodeGenModule::GetOrCreateLLVMFunction'
2856 /*IsThunk=*/false, llvm::AttributeList(),
2857 IsForDefinition);
2858}
2859
2860static const FunctionDecl *
2861GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
2862 TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
2863 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2864
2865 IdentifierInfo &CII = C.Idents.get(Name);
2866 for (const auto &Result : DC->lookup(&CII))
2867 if (const auto FD = dyn_cast<FunctionDecl>(Result))
2868 return FD;
2869
2870 if (!C.getLangOpts().CPlusPlus)
2871 return nullptr;
2872
2873 // Demangle the premangled name from getTerminateFn()
2874 IdentifierInfo &CXXII =
2875 (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
2876 ? C.Idents.get("terminate")
2877 : C.Idents.get(Name);
2878
2879 for (const auto &N : {"__cxxabiv1", "std"}) {
2880 IdentifierInfo &NS = C.Idents.get(N);
2881 for (const auto &Result : DC->lookup(&NS)) {
2882 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
2883 if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
2884 for (const auto &Result : LSD->lookup(&NS))
2885 if ((ND = dyn_cast<NamespaceDecl>(Result)))
2886 break;
2887
2888 if (ND)
2889 for (const auto &Result : ND->lookup(&CXXII))
2890 if (const auto *FD = dyn_cast<FunctionDecl>(Result))
2891 return FD;
2892 }
2893 }
2894
2895 return nullptr;
2896}
2897
2898/// CreateRuntimeFunction - Create a new runtime function with the specified
2899/// type and name.
2900llvm::Constant *
2901CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
2902 llvm::AttributeList ExtraAttrs,
2903 bool Local) {
2904 llvm::Constant *C =
2905 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
2906 /*DontDefer=*/false, /*IsThunk=*/false,
2907 ExtraAttrs);
2908
2909 if (auto *F = dyn_cast<llvm::Function>(C)) {
2910 if (F->empty()) {
2911 F->setCallingConv(getRuntimeCC());
2912
2913 if (!Local && getTriple().isOSBinFormatCOFF() &&
2914 !getCodeGenOpts().LTOVisibilityPublicStd &&
2915 !getTriple().isWindowsGNUEnvironment()) {
2916 const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
2917 if (!FD || FD->hasAttr<DLLImportAttr>()) {
2918 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2919 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
2920 }
2921 }
2922 setDSOLocal(F);
2923 }
2924 }
2925
2926 return C;
2927}
2928
2929/// CreateBuiltinFunction - Create a new builtin function with the specified
2930/// type and name.
2931llvm::Constant *
2932CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, StringRef Name,
2933 llvm::AttributeList ExtraAttrs) {
2934 return CreateRuntimeFunction(FTy, Name, ExtraAttrs, true);
2935}
2936
2937/// isTypeConstant - Determine whether an object of this type can be emitted
2938/// as a constant.
2939///
2940/// If ExcludeCtor is true, the duration when the object's constructor runs
2941/// will not be considered. The caller will need to verify that the object is
2942/// not written to during its construction.
2943bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
2944 if (!Ty.isConstant(Context) && !Ty->isReferenceType())
2945 return false;
2946
2947 if (Context.getLangOpts().CPlusPlus) {
2948 if (const CXXRecordDecl *Record
2949 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
2950 return ExcludeCtor && !Record->hasMutableFields() &&
2951 Record->hasTrivialDestructor();
2952 }
2953
2954 return true;
2955}
2956
2957/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
2958/// create and return an llvm GlobalVariable with the specified type. If there
2959/// is something in the module with the specified name, return it potentially
2960/// bitcasted to the right type.
2961///
2962/// If D is non-null, it specifies a decl that correspond to this. This is used
2963/// to set the attributes on the global when it is first created.
2964///
2965/// If IsForDefinition is true, it is guaranteed that an actual global with
2966/// type Ty will be returned, not conversion of a variable with the same
2967/// mangled name but some other type.
2968llvm::Constant *
2969CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
2970 llvm::PointerType *Ty,
2971 const VarDecl *D,
2972 ForDefinition_t IsForDefinition) {
2973 // Lookup the entry, lazily creating it if necessary.
2974 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2975 if (Entry) {
2976 if (WeakRefReferences.erase(Entry)) {
2977 if (D && !D->hasAttr<WeakAttr>())
2978 Entry->setLinkage(llvm::Function::ExternalLinkage);
2979 }
2980
2981 // Handle dropped DLL attributes.
2982 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
2983 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2984
2985 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
2986 getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
2987
2988 if (Entry->getType() == Ty)
2989 return Entry;
2990
2991 // If there are two attempts to define the same mangled name, issue an
2992 // error.
2993 if (IsForDefinition && !Entry->isDeclaration()) {
2994 GlobalDecl OtherGD;
2995 const VarDecl *OtherD;
2996
2997 // Check that D is not yet in DiagnosedConflictingDefinitions is required
2998 // to make sure that we issue an error only once.
2999 if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
3000 (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
3001 (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
3002 OtherD->hasInit() &&
3003 DiagnosedConflictingDefinitions.insert(D).second) {
3004 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
3005 << MangledName;
3006 getDiags().Report(OtherGD.getDecl()->getLocation(),
3007 diag::note_previous_definition);
3008 }
3009 }
3010
3011 // Make sure the result is of the correct type.
3012 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
3013 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
3014
3015 // (If global is requested for a definition, we always need to create a new
3016 // global, not just return a bitcast.)
3017 if (!IsForDefinition)
3018 return llvm::ConstantExpr::getBitCast(Entry, Ty);
3019 }
3020
3021 auto AddrSpace = GetGlobalVarAddressSpace(D);
3022 auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace);
3023
3024 auto *GV = new llvm::GlobalVariable(
3025 getModule(), Ty->getElementType(), false,
3026 llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
3027 llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace);
3028
3029 // If we already created a global with the same mangled name (but different
3030 // type) before, take its name and remove it from its parent.
3031 if (Entry) {
3032 GV->takeName(Entry);
3033
3034 if (!Entry->use_empty()) {
3035 llvm::Constant *NewPtrForOldDecl =
3036 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
3037 Entry->replaceAllUsesWith(NewPtrForOldDecl);
3038 }
3039
3040 Entry->eraseFromParent();
3041 }
3042
3043 // This is the first use or definition of a mangled name. If there is a
3044 // deferred decl with this name, remember that we need to emit it at the end
3045 // of the file.
3046 auto DDI = DeferredDecls.find(MangledName);
3047 if (DDI != DeferredDecls.end()) {
3048 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
3049 // list, and remove it from DeferredDecls (since we don't need it anymore).
3050 addDeferredDeclToEmit(DDI->second);
3051 DeferredDecls.erase(DDI);
3052 }
3053
3054 // Handle things which are present even on external declarations.
3055 if (D) {
3056 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
3057 getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
3058
3059 // FIXME: This code is overly simple and should be merged with other global
3060 // handling.
3061 GV->setConstant(isTypeConstant(D->getType(), false));
3062
3063 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
3064
3065 setLinkageForGV(GV, D);
3066
3067 if (D->getTLSKind()) {
3068 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
3069 CXXThreadLocals.push_back(D);
3070 setTLSMode(GV, *D);
3071 }
3072
3073 setGVProperties(GV, D);
3074
3075 // If required by the ABI, treat declarations of static data members with
3076 // inline initializers as definitions.
3077 if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
3078 EmitGlobalVarDefinition(D);
3079 }
3080
3081 // Emit section information for extern variables.
3082 if (D->hasExternalStorage()) {
3083 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
3084 GV->setSection(SA->getName());
3085 }
3086
3087 // Handle XCore specific ABI requirements.
3088 if (getTriple().getArch() == llvm::Triple::xcore &&
3089 D->getLanguageLinkage() == CLanguageLinkage &&
3090 D->getType().isConstant(Context) &&
3091 isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
3092 GV->setSection(".cp.rodata");
3093
3094 // Check if we a have a const declaration with an initializer, we may be
3095 // able to emit it as available_externally to expose it's value to the
3096 // optimizer.
3097 if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
3098 D->getType().isConstQualified() && !GV->hasInitializer() &&
3099 !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
3100 const auto *Record =
3101 Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
3102 bool HasMutableFields = Record && Record->hasMutableFields();
3103 if (!HasMutableFields) {
3104 const VarDecl *InitDecl;
3105 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
3106 if (InitExpr) {
3107 ConstantEmitter emitter(*this);
3108 llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
3109 if (Init) {
3110 auto *InitType = Init->getType();
3111 if (GV->getType()->getElementType() != InitType) {
3112 // The type of the initializer does not match the definition.
3113 // This happens when an initializer has a different type from
3114 // the type of the global (because of padding at the end of a
3115 // structure for instance).
3116 GV->setName(StringRef());
3117 // Make a new global with the correct type, this is now guaranteed
3118 // to work.
3119 auto *NewGV = cast<llvm::GlobalVariable>(
3120 GetAddrOfGlobalVar(D, InitType, IsForDefinition));
3121
3122 // Erase the old global, since it is no longer used.
3123 GV->eraseFromParent();
3124 GV = NewGV;
3125 } else {
3126 GV->setInitializer(Init);
3127 GV->setConstant(true);
3128 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
3129 }
3130 emitter.finalize(GV);
3131 }
3132 }
3133 }
3134 }
3135 }
3136
3137 LangAS ExpectedAS =
3138 D ? D->getType().getAddressSpace()
3139 : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
3140 assert(getContext().getTargetAddressSpace(ExpectedAS) ==((getContext().getTargetAddressSpace(ExpectedAS) == Ty->getPointerAddressSpace
()) ? static_cast<void> (0) : __assert_fail ("getContext().getTargetAddressSpace(ExpectedAS) == Ty->getPointerAddressSpace()"
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 3141, __PRETTY_FUNCTION__))
3141 Ty->getPointerAddressSpace())((getContext().getTargetAddressSpace(ExpectedAS) == Ty->getPointerAddressSpace
()) ? static_cast<void> (0) : __assert_fail ("getContext().getTargetAddressSpace(ExpectedAS) == Ty->getPointerAddressSpace()"
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 3141, __PRETTY_FUNCTION__))
;
3142 if (AddrSpace != ExpectedAS)
3143 return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace,
3144 ExpectedAS, Ty);
3145
3146 return GV;
3147}
3148
3149llvm::Constant *
3150CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
3151 ForDefinition_t IsForDefinition) {
3152 const Decl *D = GD.getDecl();
3153 if (isa<CXXConstructorDecl>(D))
3154 return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D),
3155 getFromCtorType(GD.getCtorType()),
3156 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
3157 /*DontDefer=*/false, IsForDefinition);
3158 else if (isa<CXXDestructorDecl>(D))
3159 return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D),
3160 getFromDtorType(GD.getDtorType()),
3161 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
3162 /*DontDefer=*/false, IsForDefinition);
3163 else if (isa<CXXMethodDecl>(D)) {
3164 auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
3165 cast<CXXMethodDecl>(D));
3166 auto Ty = getTypes().GetFunctionType(*FInfo);
3167 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
3168 IsForDefinition);
3169 } else if (isa<FunctionDecl>(D)) {
3170 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3171 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3172 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
3173 IsForDefinition);
3174 } else
3175 return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
3176 IsForDefinition);
3177}
3178
3179llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable(
3180 StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage,
3181 unsigned Alignment) {
3182 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
3183 llvm::GlobalVariable *OldGV = nullptr;
3184
3185 if (GV) {
3186 // Check if the variable has the right type.
3187 if (GV->getType()->getElementType() == Ty)
3188 return GV;
3189
3190 // Because C++ name mangling, the only way we can end up with an already
3191 // existing global with the same name is if it has been declared extern "C".
3192 assert(GV->isDeclaration() && "Declaration has wrong type!")((GV->isDeclaration() && "Declaration has wrong type!"
) ? static_cast<void> (0) : __assert_fail ("GV->isDeclaration() && \"Declaration has wrong type!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 3192, __PRETTY_FUNCTION__))
;
3193 OldGV = GV;
3194 }
3195
3196 // Create a new variable.
3197 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
3198 Linkage, nullptr, Name);
3199
3200 if (OldGV) {
3201 // Replace occurrences of the old variable if needed.
3202 GV->takeName(OldGV);
3203
3204 if (!OldGV->use_empty()) {
3205 llvm::Constant *NewPtrForOldDecl =
3206 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3207 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
3208 }
3209
3210 OldGV->eraseFromParent();
3211 }
3212
3213 if (supportsCOMDAT() && GV->isWeakForLinker() &&
3214 !GV->hasAvailableExternallyLinkage())
3215 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3216
3217 GV->setAlignment(Alignment);
3218
3219 return GV;
3220}
3221
3222/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
3223/// given global variable. If Ty is non-null and if the global doesn't exist,
3224/// then it will be created with the specified type instead of whatever the
3225/// normal requested type would be. If IsForDefinition is true, it is guaranteed
3226/// that an actual global with type Ty will be returned, not conversion of a
3227/// variable with the same mangled name but some other type.
3228llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
3229 llvm::Type *Ty,
3230 ForDefinition_t IsForDefinition) {
3231 assert(D->hasGlobalStorage() && "Not a global variable")((D->hasGlobalStorage() && "Not a global variable"
) ? static_cast<void> (0) : __assert_fail ("D->hasGlobalStorage() && \"Not a global variable\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 3231, __PRETTY_FUNCTION__))
;
3232 QualType ASTTy = D->getType();
3233 if (!Ty)
3234 Ty = getTypes().ConvertTypeForMem(ASTTy);
3235
3236 llvm::PointerType *PTy =
3237 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
3238
3239 StringRef MangledName = getMangledName(D);
3240 return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
3241}
3242
3243/// CreateRuntimeVariable - Create a new runtime global variable with the
3244/// specified type and name.
3245llvm::Constant *
3246CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
3247 StringRef Name) {
3248 auto *Ret =
3249 GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
3250 setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
3251 return Ret;
3252}
3253
3254void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
3255 assert(!D->getInit() && "Cannot emit definite definitions here!")((!D->getInit() && "Cannot emit definite definitions here!"
) ? static_cast<void> (0) : __assert_fail ("!D->getInit() && \"Cannot emit definite definitions here!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 3255, __PRETTY_FUNCTION__))
;
3256
3257 StringRef MangledName = getMangledName(D);
3258 llvm::GlobalValue *GV = GetGlobalValue(MangledName);
3259
3260 // We already have a definition, not declaration, with the same mangled name.
3261 // Emitting of declaration is not required (and actually overwrites emitted
3262 // definition).
3263 if (GV && !GV->isDeclaration())
3264 return;
3265
3266 // If we have not seen a reference to this variable yet, place it into the
3267 // deferred declarations table to be emitted if needed later.
3268 if (!MustBeEmitted(D) && !GV) {
3269 DeferredDecls[MangledName] = D;
3270 return;
3271 }
3272
3273 // The tentative definition is the only definition.
3274 EmitGlobalVarDefinition(D);
3275}
3276
3277CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
3278 return Context.toCharUnitsFromBits(
3279 getDataLayout().getTypeStoreSizeInBits(Ty));
3280}
3281
3282LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
3283 LangAS AddrSpace = LangAS::Default;
3284 if (LangOpts.OpenCL) {
3285 AddrSpace = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
3286 assert(AddrSpace == LangAS::opencl_global ||((AddrSpace == LangAS::opencl_global || AddrSpace == LangAS::
opencl_constant || AddrSpace == LangAS::opencl_local || AddrSpace
>= LangAS::FirstTargetAddressSpace) ? static_cast<void
> (0) : __assert_fail ("AddrSpace == LangAS::opencl_global || AddrSpace == LangAS::opencl_constant || AddrSpace == LangAS::opencl_local || AddrSpace >= LangAS::FirstTargetAddressSpace"
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 3289, __PRETTY_FUNCTION__))
3287 AddrSpace == LangAS::opencl_constant ||((AddrSpace == LangAS::opencl_global || AddrSpace == LangAS::
opencl_constant || AddrSpace == LangAS::opencl_local || AddrSpace
>= LangAS::FirstTargetAddressSpace) ? static_cast<void
> (0) : __assert_fail ("AddrSpace == LangAS::opencl_global || AddrSpace == LangAS::opencl_constant || AddrSpace == LangAS::opencl_local || AddrSpace >= LangAS::FirstTargetAddressSpace"
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 3289, __PRETTY_FUNCTION__))
3288 AddrSpace == LangAS::opencl_local ||((AddrSpace == LangAS::opencl_global || AddrSpace == LangAS::
opencl_constant || AddrSpace == LangAS::opencl_local || AddrSpace
>= LangAS::FirstTargetAddressSpace) ? static_cast<void
> (0) : __assert_fail ("AddrSpace == LangAS::opencl_global || AddrSpace == LangAS::opencl_constant || AddrSpace == LangAS::opencl_local || AddrSpace >= LangAS::FirstTargetAddressSpace"
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 3289, __PRETTY_FUNCTION__))
3289 AddrSpace >= LangAS::FirstTargetAddressSpace)((AddrSpace == LangAS::opencl_global || AddrSpace == LangAS::
opencl_constant || AddrSpace == LangAS::opencl_local || AddrSpace
>= LangAS::FirstTargetAddressSpace) ? static_cast<void
> (0) : __assert_fail ("AddrSpace == LangAS::opencl_global || AddrSpace == LangAS::opencl_constant || AddrSpace == LangAS::opencl_local || AddrSpace >= LangAS::FirstTargetAddressSpace"
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 3289, __PRETTY_FUNCTION__))
;
3290 return AddrSpace;
3291 }
3292
3293 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
3294 if (D && D->hasAttr<CUDAConstantAttr>())
3295 return LangAS::cuda_constant;
3296 else if (D && D->hasAttr<CUDASharedAttr>())
3297 return LangAS::cuda_shared;
3298 else if (D && D->hasAttr<CUDADeviceAttr>())
3299 return LangAS::cuda_device;
3300 else if (D && D->getType().isConstQualified())
3301 return LangAS::cuda_constant;
3302 else
3303 return LangAS::cuda_device;
3304 }
3305
3306 return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
3307}
3308
3309LangAS CodeGenModule::getStringLiteralAddressSpace() const {
3310 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
3311 if (LangOpts.OpenCL)
3312 return LangAS::opencl_constant;
3313 if (auto AS = getTarget().getConstantAddressSpace())
3314 return AS.getValue();
3315 return LangAS::Default;
3316}
3317
3318// In address space agnostic languages, string literals are in default address
3319// space in AST. However, certain targets (e.g. amdgcn) request them to be
3320// emitted in constant address space in LLVM IR. To be consistent with other
3321// parts of AST, string literal global variables in constant address space
3322// need to be casted to default address space before being put into address
3323// map and referenced by other part of CodeGen.
3324// In OpenCL, string literals are in constant address space in AST, therefore
3325// they should not be casted to default address space.
3326static llvm::Constant *
3327castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
3328 llvm::GlobalVariable *GV) {
3329 llvm::Constant *Cast = GV;
3330 if (!CGM.getLangOpts().OpenCL) {
3331 if (auto AS = CGM.getTarget().getConstantAddressSpace()) {
3332 if (AS != LangAS::Default)
3333 Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
3334 CGM, GV, AS.getValue(), LangAS::Default,
3335 GV->getValueType()->getPointerTo(
3336 CGM.getContext().getTargetAddressSpace(LangAS::Default)));
3337 }
3338 }
3339 return Cast;
3340}
3341
3342template<typename SomeDecl>
3343void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
3344 llvm::GlobalValue *GV) {
3345 if (!getLangOpts().CPlusPlus)
3346 return;
3347
3348 // Must have 'used' attribute, or else inline assembly can't rely on
3349 // the name existing.
3350 if (!D->template hasAttr<UsedAttr>())
3351 return;
3352
3353 // Must have internal linkage and an ordinary name.
3354 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
3355 return;
3356
3357 // Must be in an extern "C" context. Entities declared directly within
3358 // a record are not extern "C" even if the record is in such a context.
3359 const SomeDecl *First = D->getFirstDecl();
3360 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
3361 return;
3362
3363 // OK, this is an internal linkage entity inside an extern "C" linkage
3364 // specification. Make a note of that so we can give it the "expected"
3365 // mangled name if nothing else is using that name.
3366 std::pair<StaticExternCMap::iterator, bool> R =
3367 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
3368
3369 // If we have multiple internal linkage entities with the same name
3370 // in extern "C" regions, none of them gets that name.
3371 if (!R.second)
3372 R.first->second = nullptr;
3373}
3374
3375static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
3376 if (!CGM.supportsCOMDAT())
3377 return false;
3378
3379 if (D.hasAttr<SelectAnyAttr>())
3380 return true;
3381
3382 GVALinkage Linkage;
3383 if (auto *VD = dyn_cast<VarDecl>(&D))
3384 Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
3385 else
3386 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
3387
3388 switch (Linkage) {
3389 case GVA_Internal:
3390 case GVA_AvailableExternally:
3391 case GVA_StrongExternal:
3392 return false;
3393 case GVA_DiscardableODR:
3394 case GVA_StrongODR:
3395 return true;
3396 }
3397 llvm_unreachable("No such linkage")::llvm::llvm_unreachable_internal("No such linkage", "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 3397)
;
3398}
3399
3400void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
3401 llvm::GlobalObject &GO) {
3402 if (!shouldBeInCOMDAT(*this, D))
3403 return;
3404 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
3405}
3406
3407/// Pass IsTentative as true if you want to create a tentative definition.
3408void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
3409 bool IsTentative) {
3410 // OpenCL global variables of sampler type are translated to function calls,
3411 // therefore no need to be translated.
3412 QualType ASTTy = D->getType();
3413 if (getLangOpts().OpenCL && ASTTy->isSamplerT())
3414 return;
3415
3416 // If this is OpenMP device, check if it is legal to emit this global
3417 // normally.
3418 if (LangOpts.OpenMPIsDevice && OpenMPRuntime &&
3419 OpenMPRuntime->emitTargetGlobalVariable(D))
3420 return;
3421
3422 llvm::Constant *Init = nullptr;
3423 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3424 bool NeedsGlobalCtor = false;
3425 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
3426
3427 const VarDecl *InitDecl;
3428 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
3429
3430 Optional<ConstantEmitter> emitter;
3431
3432 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
3433 // as part of their declaration." Sema has already checked for
3434 // error cases, so we just need to set Init to UndefValue.
3435 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
3436 D->hasAttr<CUDASharedAttr>())
3437 Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
3438 else if (!InitExpr) {
3439 // This is a tentative definition; tentative definitions are
3440 // implicitly initialized with { 0 }.
3441 //
3442 // Note that tentative definitions are only emitted at the end of
3443 // a translation unit, so they should never have incomplete
3444 // type. In addition, EmitTentativeDefinition makes sure that we
3445 // never attempt to emit a tentative definition if a real one
3446 // exists. A use may still exists, however, so we still may need
3447 // to do a RAUW.
3448 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type")((!ASTTy->isIncompleteType() && "Unexpected incomplete type"
) ? static_cast<void> (0) : __assert_fail ("!ASTTy->isIncompleteType() && \"Unexpected incomplete type\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 3448, __PRETTY_FUNCTION__))
;
3449 Init = EmitNullConstant(D->getType());
3450 } else {
3451 initializedGlobalDecl = GlobalDecl(D);
3452 emitter.emplace(*this);
3453 Init = emitter->tryEmitForInitializer(*InitDecl);
3454
3455 if (!Init) {
3456 QualType T = InitExpr->getType();
3457 if (D->getType()->isReferenceType())
3458 T = D->getType();
3459
3460 if (getLangOpts().CPlusPlus) {
3461 Init = EmitNullConstant(T);
3462 NeedsGlobalCtor = true;
3463 } else {
3464 ErrorUnsupported(D, "static initializer");
3465 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
3466 }
3467 } else {
3468 // We don't need an initializer, so remove the entry for the delayed
3469 // initializer position (just in case this entry was delayed) if we
3470 // also don't need to register a destructor.
3471 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
3472 DelayedCXXInitPosition.erase(D);
3473 }
3474 }
3475
3476 llvm::Type* InitType = Init->getType();
3477 llvm::Constant *Entry =
3478 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
3479
3480 // Strip off a bitcast if we got one back.
3481 if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
3482 assert(CE->getOpcode() == llvm::Instruction::BitCast ||((CE->getOpcode() == llvm::Instruction::BitCast || CE->
getOpcode() == llvm::Instruction::AddrSpaceCast || CE->getOpcode
() == llvm::Instruction::GetElementPtr) ? static_cast<void
> (0) : __assert_fail ("CE->getOpcode() == llvm::Instruction::BitCast || CE->getOpcode() == llvm::Instruction::AddrSpaceCast || CE->getOpcode() == llvm::Instruction::GetElementPtr"
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 3485, __PRETTY_FUNCTION__))
3483 CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||((CE->getOpcode() == llvm::Instruction::BitCast || CE->
getOpcode() == llvm::Instruction::AddrSpaceCast || CE->getOpcode
() == llvm::Instruction::GetElementPtr) ? static_cast<void
> (0) : __assert_fail ("CE->getOpcode() == llvm::Instruction::BitCast || CE->getOpcode() == llvm::Instruction::AddrSpaceCast || CE->getOpcode() == llvm::Instruction::GetElementPtr"
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 3485, __PRETTY_FUNCTION__))
3484 // All zero index gep.((CE->getOpcode() == llvm::Instruction::BitCast || CE->
getOpcode() == llvm::Instruction::AddrSpaceCast || CE->getOpcode
() == llvm::Instruction::GetElementPtr) ? static_cast<void
> (0) : __assert_fail ("CE->getOpcode() == llvm::Instruction::BitCast || CE->getOpcode() == llvm::Instruction::AddrSpaceCast || CE->getOpcode() == llvm::Instruction::GetElementPtr"
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 3485, __PRETTY_FUNCTION__))
3485 CE->getOpcode() == llvm::Instruction::GetElementPtr)((CE->getOpcode() == llvm::Instruction::BitCast || CE->
getOpcode() == llvm::Instruction::AddrSpaceCast || CE->getOpcode
() == llvm::Instruction::GetElementPtr) ? static_cast<void
> (0) : __assert_fail ("CE->getOpcode() == llvm::Instruction::BitCast || CE->getOpcode() == llvm::Instruction::AddrSpaceCast || CE->getOpcode() == llvm::Instruction::GetElementPtr"
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 3485, __PRETTY_FUNCTION__))
;
3486 Entry = CE->getOperand(0);
3487 }
3488
3489 // Entry is now either a Function or GlobalVariable.
3490 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
3491
3492 // We have a definition after a declaration with the wrong type.
3493 // We must make a new GlobalVariable* and update everything that used OldGV
3494 // (a declaration or tentative definition) with the new GlobalVariable*
3495 // (which will be a definition).
3496 //
3497 // This happens if there is a prototype for a global (e.g.
3498 // "extern int x[];") and then a definition of a different type (e.g.
3499 // "int x[10];"). This also happens when an initializer has a different type
3500 // from the type of the global (this happens with unions).
3501 if (!GV || GV->getType()->getElementType() != InitType ||
3502 GV->getType()->getAddressSpace() !=
3503 getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
3504
3505 // Move the old entry aside so that we'll create a new one.
3506 Entry->setName(StringRef());
3507
3508 // Make a new global with the correct type, this is now guaranteed to work.
3509 GV = cast<llvm::GlobalVariable>(
3510 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
3511
3512 // Replace all uses of the old global with the new global
3513 llvm::Constant *NewPtrForOldDecl =
3514 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
3515 Entry->replaceAllUsesWith(NewPtrForOldDecl);
3516
3517 // Erase the old global, since it is no longer used.
3518 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
3519 }
3520
3521 MaybeHandleStaticInExternC(D, GV);
3522
3523 if (D->hasAttr<AnnotateAttr>())
3524 AddGlobalAnnotations(D, GV);
3525
3526 // Set the llvm linkage type as appropriate.
3527 llvm::GlobalValue::LinkageTypes Linkage =
3528 getLLVMLinkageVarDefinition(D, GV->isConstant());
3529
3530 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
3531 // the device. [...]"
3532 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
3533 // __device__, declares a variable that: [...]
3534 // Is accessible from all the threads within the grid and from the host
3535 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
3536 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
3537 if (GV && LangOpts.CUDA) {
3538 if (LangOpts.CUDAIsDevice) {
3539 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
3540 GV->setExternallyInitialized(true);
3541 } else {
3542 // Host-side shadows of external declarations of device-side
3543 // global variables become internal definitions. These have to
3544 // be internal in order to prevent name conflicts with global
3545 // host variables with the same name in a different TUs.
3546 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
3547 Linkage = llvm::GlobalValue::InternalLinkage;
3548
3549 // Shadow variables and their properties must be registered
3550 // with CUDA runtime.
3551 unsigned Flags = 0;
3552 if (!D->hasDefinition())
3553 Flags |= CGCUDARuntime::ExternDeviceVar;
3554 if (D->hasAttr<CUDAConstantAttr>())
3555 Flags |= CGCUDARuntime::ConstantDeviceVar;
3556 getCUDARuntime().registerDeviceVar(*GV, Flags);
3557 } else if (D->hasAttr<CUDASharedAttr>())
3558 // __shared__ variables are odd. Shadows do get created, but
3559 // they are not registered with the CUDA runtime, so they
3560 // can't really be used to access their device-side
3561 // counterparts. It's not clear yet whether it's nvcc's bug or
3562 // a feature, but we've got to do the same for compatibility.
3563 Linkage = llvm::GlobalValue::InternalLinkage;
3564 }
3565 }
3566
3567 GV->setInitializer(Init);
3568 if (emitter) emitter->finalize(GV);
3569
3570 // If it is safe to mark the global 'constant', do so now.
3571 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
3572 isTypeConstant(D->getType(), true));
3573
3574 // If it is in a read-only section, mark it 'constant'.
3575 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
3576 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
3577 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
3578 GV->setConstant(true);
3579 }
3580
3581 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
3582
3583
3584 // On Darwin, if the normal linkage of a C++ thread_local variable is
3585 // LinkOnce or Weak, we keep the normal linkage to prevent multiple
3586 // copies within a linkage unit; otherwise, the backing variable has
3587 // internal linkage and all accesses should just be calls to the
3588 // Itanium-specified entry point, which has the normal linkage of the
3589 // variable. This is to preserve the ability to change the implementation
3590 // behind the scenes.
3591 if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
3592 Context.getTargetInfo().getTriple().isOSDarwin() &&
3593 !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
3594 !llvm::GlobalVariable::isWeakLinkage(Linkage))
3595 Linkage = llvm::GlobalValue::InternalLinkage;
3596
3597 GV->setLinkage(Linkage);
3598 if (D->hasAttr<DLLImportAttr>())
3599 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
3600 else if (D->hasAttr<DLLExportAttr>())
3601 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
3602 else
3603 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
3604
3605 if (Linkage == llvm::GlobalVariable::CommonLinkage) {
3606 // common vars aren't constant even if declared const.
3607 GV->setConstant(false);
3608 // Tentative definition of global variables may be initialized with
3609 // non-zero null pointers. In this case they should have weak linkage
3610 // since common linkage must have zero initializer and must not have
3611 // explicit section therefore cannot have non-zero initial value.
3612 if (!GV->getInitializer()->isNullValue())
3613 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
3614 }
3615
3616 setNonAliasAttributes(D, GV);
3617
3618 if (D->getTLSKind() && !GV->isThreadLocal()) {
3619 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
3620 CXXThreadLocals.push_back(D);
3621 setTLSMode(GV, *D);
3622 }
3623
3624 maybeSetTrivialComdat(*D, *GV);
3625
3626 // Emit the initializer function if necessary.
3627 if (NeedsGlobalCtor || NeedsGlobalDtor)
3628 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
3629
3630 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
3631
3632 // Emit global variable debug information.
3633 if (CGDebugInfo *DI = getModuleDebugInfo())
3634 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
3635 DI->EmitGlobalVariable(GV, D);
3636}
3637
3638static bool isVarDeclStrongDefinition(const ASTContext &Context,
3639 CodeGenModule &CGM, const VarDecl *D,
3640 bool NoCommon) {
3641 // Don't give variables common linkage if -fno-common was specified unless it
3642 // was overridden by a NoCommon attribute.
3643 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
3644 return true;
3645
3646 // C11 6.9.2/2:
3647 // A declaration of an identifier for an object that has file scope without
3648 // an initializer, and without a storage-class specifier or with the
3649 // storage-class specifier static, constitutes a tentative definition.
3650 if (D->getInit() || D->hasExternalStorage())
3651 return true;
3652
3653 // A variable cannot be both common and exist in a section.
3654 if (D->hasAttr<SectionAttr>())
3655 return true;
3656
3657 // A variable cannot be both common and exist in a section.
3658 // We don't try to determine which is the right section in the front-end.
3659 // If no specialized section name is applicable, it will resort to default.
3660 if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
3661 D->hasAttr<PragmaClangDataSectionAttr>() ||
3662 D->hasAttr<PragmaClangRodataSectionAttr>())
3663 return true;
3664
3665 // Thread local vars aren't considered common linkage.
3666 if (D->getTLSKind())
3667 return true;
3668
3669 // Tentative definitions marked with WeakImportAttr are true definitions.
3670 if (D->hasAttr<WeakImportAttr>())
3671 return true;
3672
3673 // A variable cannot be both common and exist in a comdat.
3674 if (shouldBeInCOMDAT(CGM, *D))
3675 return true;
3676
3677 // Declarations with a required alignment do not have common linkage in MSVC
3678 // mode.
3679 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3680 if (D->hasAttr<AlignedAttr>())
3681 return true;
3682 QualType VarType = D->getType();
3683 if (Context.isAlignmentRequired(VarType))
3684 return true;
3685
3686 if (const auto *RT = VarType->getAs<RecordType>()) {
3687 const RecordDecl *RD = RT->getDecl();
3688 for (const FieldDecl *FD : RD->fields()) {
3689 if (FD->isBitField())
3690 continue;
3691 if (FD->hasAttr<AlignedAttr>())
3692 return true;
3693 if (Context.isAlignmentRequired(FD->getType()))
3694 return true;
3695 }
3696 }
3697 }
3698
3699 return false;
3700}
3701
3702llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
3703 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
3704 if (Linkage == GVA_Internal)
3705 return llvm::Function::InternalLinkage;
3706
3707 if (D->hasAttr<WeakAttr>()) {
3708 if (IsConstantVariable)
3709 return llvm::GlobalVariable::WeakODRLinkage;
3710 else
3711 return llvm::GlobalVariable::WeakAnyLinkage;
3712 }
3713
3714 if (const auto *FD = D->getAsFunction())
3715 if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
3716 return llvm::GlobalVariable::LinkOnceAnyLinkage;
3717
3718 // We are guaranteed to have a strong definition somewhere else,
3719 // so we can use available_externally linkage.
3720 if (Linkage == GVA_AvailableExternally)
3721 return llvm::GlobalValue::AvailableExternallyLinkage;
3722
3723 // Note that Apple's kernel linker doesn't support symbol
3724 // coalescing, so we need to avoid linkonce and weak linkages there.
3725 // Normally, this means we just map to internal, but for explicit
3726 // instantiations we'll map to external.
3727
3728 // In C++, the compiler has to emit a definition in every translation unit
3729 // that references the function. We should use linkonce_odr because
3730 // a) if all references in this translation unit are optimized away, we
3731 // don't need to codegen it. b) if the function persists, it needs to be
3732 // merged with other definitions. c) C++ has the ODR, so we know the
3733 // definition is dependable.
3734 if (Linkage == GVA_DiscardableODR)
3735 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
3736 : llvm::Function::InternalLinkage;
3737
3738 // An explicit instantiation of a template has weak linkage, since
3739 // explicit instantiations can occur in multiple translation units
3740 // and must all be equivalent. However, we are not allowed to
3741 // throw away these explicit instantiations.
3742 //
3743 // We don't currently support CUDA device code spread out across multiple TUs,
3744 // so say that CUDA templates are either external (for kernels) or internal.
3745 // This lets llvm perform aggressive inter-procedural optimizations.
3746 if (Linkage == GVA_StrongODR) {
3747 if (Context.getLangOpts().AppleKext)
3748 return llvm::Function::ExternalLinkage;
3749 if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
3750 return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
3751 : llvm::Function::InternalLinkage;
3752 return llvm::Function::WeakODRLinkage;
3753 }
3754
3755 // C++ doesn't have tentative definitions and thus cannot have common
3756 // linkage.
3757 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
3758 !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
3759 CodeGenOpts.NoCommon))
3760 return llvm::GlobalVariable::CommonLinkage;
3761
3762 // selectany symbols are externally visible, so use weak instead of
3763 // linkonce. MSVC optimizes away references to const selectany globals, so
3764 // all definitions should be the same and ODR linkage should be used.
3765 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
3766 if (D->hasAttr<SelectAnyAttr>())
3767 return llvm::GlobalVariable::WeakODRLinkage;
3768
3769 // Otherwise, we have strong external linkage.
3770 assert(Linkage == GVA_StrongExternal)((Linkage == GVA_StrongExternal) ? static_cast<void> (0
) : __assert_fail ("Linkage == GVA_StrongExternal", "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 3770, __PRETTY_FUNCTION__))
;
3771 return llvm::GlobalVariable::ExternalLinkage;
3772}
3773
3774llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
3775 const VarDecl *VD, bool IsConstant) {
3776 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
3777 return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
3778}
3779
3780/// Replace the uses of a function that was declared with a non-proto type.
3781/// We want to silently drop extra arguments from call sites
3782static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
3783 llvm::Function *newFn) {
3784 // Fast path.
3785 if (old->use_empty()) return;
3786
3787 llvm::Type *newRetTy = newFn->getReturnType();
3788 SmallVector<llvm::Value*, 4> newArgs;
3789 SmallVector<llvm::OperandBundleDef, 1> newBundles;
3790
3791 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
3792 ui != ue; ) {
3793 llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
3794 llvm::User *user = use->getUser();
3795
3796 // Recognize and replace uses of bitcasts. Most calls to
3797 // unprototyped functions will use bitcasts.
3798 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
3799 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
3800 replaceUsesOfNonProtoConstant(bitcast, newFn);
3801 continue;
3802 }
3803
3804 // Recognize calls to the function.
3805 llvm::CallSite callSite(user);
3806 if (!callSite) continue;
3807 if (!callSite.isCallee(&*use)) continue;
3808
3809 // If the return types don't match exactly, then we can't
3810 // transform this call unless it's dead.
3811 if (callSite->getType() != newRetTy && !callSite->use_empty())
3812 continue;
3813
3814 // Get the call site's attribute list.
3815 SmallVector<llvm::AttributeSet, 8> newArgAttrs;
3816 llvm::AttributeList oldAttrs = callSite.getAttributes();
3817
3818 // If the function was passed too few arguments, don't transform.
3819 unsigned newNumArgs = newFn->arg_size();
3820 if (callSite.arg_size() < newNumArgs) continue;
3821
3822 // If extra arguments were passed, we silently drop them.
3823 // If any of the types mismatch, we don't transform.
3824 unsigned argNo = 0;
3825 bool dontTransform = false;
3826 for (llvm::Argument &A : newFn->args()) {
3827 if (callSite.getArgument(argNo)->getType() != A.getType()) {
3828 dontTransform = true;
3829 break;
3830 }
3831
3832 // Add any parameter attributes.
3833 newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
3834 argNo++;
3835 }
3836 if (dontTransform)
3837 continue;
3838
3839 // Okay, we can transform this. Create the new call instruction and copy
3840 // over the required information.
3841 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
3842
3843 // Copy over any operand bundles.
3844 callSite.getOperandBundlesAsDefs(newBundles);
3845
3846 llvm::CallSite newCall;
3847 if (callSite.isCall()) {
3848 newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
3849 callSite.getInstruction());
3850 } else {
3851 auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
3852 newCall = llvm::InvokeInst::Create(newFn,
3853 oldInvoke->getNormalDest(),
3854 oldInvoke->getUnwindDest(),
3855 newArgs, newBundles, "",
3856 callSite.getInstruction());
3857 }
3858 newArgs.clear(); // for the next iteration
3859
3860 if (!newCall->getType()->isVoidTy())
3861 newCall->takeName(callSite.getInstruction());
3862 newCall.setAttributes(llvm::AttributeList::get(
3863 newFn->getContext(), oldAttrs.getFnAttributes(),
3864 oldAttrs.getRetAttributes(), newArgAttrs));
3865 newCall.setCallingConv(callSite.getCallingConv());
3866
3867 // Finally, remove the old call, replacing any uses with the new one.
3868 if (!callSite->use_empty())
3869 callSite->replaceAllUsesWith(newCall.getInstruction());
3870
3871 // Copy debug location attached to CI.
3872 if (callSite->getDebugLoc())
3873 newCall->setDebugLoc(callSite->getDebugLoc());
3874
3875 callSite->eraseFromParent();
3876 }
3877}
3878
3879/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
3880/// implement a function with no prototype, e.g. "int foo() {}". If there are
3881/// existing call uses of the old function in the module, this adjusts them to
3882/// call the new function directly.
3883///
3884/// This is not just a cleanup: the always_inline pass requires direct calls to
3885/// functions to be able to inline them. If there is a bitcast in the way, it
3886/// won't inline them. Instcombine normally deletes these calls, but it isn't
3887/// run at -O0.
3888static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
3889 llvm::Function *NewFn) {
3890 // If we're redefining a global as a function, don't transform it.
3891 if (!isa<llvm::Function>(Old)) return;
3892
3893 replaceUsesOfNonProtoConstant(Old, NewFn);
3894}
3895
3896void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
3897 auto DK = VD->isThisDeclarationADefinition();
3898 if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
3899 return;
3900
3901 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
3902 // If we have a definition, this might be a deferred decl. If the
3903 // instantiation is explicit, make sure we emit it at the end.
3904 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
3905 GetAddrOfGlobalVar(VD);
3906
3907 EmitTopLevelDecl(VD);
3908}
3909
3910void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
3911 llvm::GlobalValue *GV) {
3912 const auto *D = cast<FunctionDecl>(GD.getDecl());
3913
3914 // Compute the function info and LLVM type.
3915 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3916 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3917
3918 // Get or create the prototype for the function.
3919 if (!GV || (GV->getType()->getElementType() != Ty))
3920 GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
18
Calling 'CodeGenModule::GetAddrOfFunction'
3921 /*DontDefer=*/true,
3922 ForDefinition));
3923
3924 // Already emitted.
3925 if (!GV->isDeclaration())
8
Assuming the condition is false
9
Taking false branch
3926 return;
3927
3928 // We need to set linkage and visibility on the function before
3929 // generating code for it because various parts of IR generation
3930 // want to propagate this information down (e.g. to local static
3931 // declarations).
3932 auto *Fn = cast<llvm::Function>(GV);
3933 setFunctionLinkage(GD, Fn);
3934
3935 // FIXME: this is redundant with part of setFunctionDefinitionAttributes
3936 setGVProperties(Fn, GD);
3937
3938 MaybeHandleStaticInExternC(D, Fn);
3939
3940
3941 maybeSetTrivialComdat(*D, *Fn);
3942
3943 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
3944
3945 setNonAliasAttributes(GD, Fn);
3946 SetLLVMFunctionAttributesForDefinition(D, Fn);
3947
3948 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
10
Taking false branch
3949 AddGlobalCtor(Fn, CA->getPriority());
3950 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
11
Taking false branch
3951 AddGlobalDtor(Fn, DA->getPriority());
3952 if (D->hasAttr<AnnotateAttr>())
12
Taking false branch
3953 AddGlobalAnnotations(D, Fn);
3954
3955 if (D->isCPUSpecificMultiVersion()) {
13
Assuming the condition is true
14
Taking true branch
3956 auto *Spec = D->getAttr<CPUSpecificAttr>();
3957 // If there is another specific version we need to emit, do so here.
3958 if (Spec->ActiveArgIndex + 1 < Spec->cpus_size()) {
15
Assuming the condition is true
16
Taking true branch
3959 ++Spec->ActiveArgIndex;
3960 EmitGlobalFunctionDefinition(GD, nullptr);
17
Calling 'CodeGenModule::EmitGlobalFunctionDefinition'
3961 }
3962 }
3963}
3964
3965void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
3966 const auto *D = cast<ValueDecl>(GD.getDecl());
3967 const AliasAttr *AA = D->getAttr<AliasAttr>();
3968 assert(AA && "Not an alias?")((AA && "Not an alias?") ? static_cast<void> (0
) : __assert_fail ("AA && \"Not an alias?\"", "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 3968, __PRETTY_FUNCTION__))
;
3969
3970 StringRef MangledName = getMangledName(GD);
3971
3972 if (AA->getAliasee() == MangledName) {
3973 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
3974 return;
3975 }
3976
3977 // If there is a definition in the module, then it wins over the alias.
3978 // This is dubious, but allow it to be safe. Just ignore the alias.
3979 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3980 if (Entry && !Entry->isDeclaration())
3981 return;
3982
3983 Aliases.push_back(GD);
3984
3985 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3986
3987 // Create a reference to the named value. This ensures that it is emitted
3988 // if a deferred decl.
3989 llvm::Constant *Aliasee;
3990 if (isa<llvm::FunctionType>(DeclTy))
3991 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
3992 /*ForVTable=*/false);
3993 else
3994 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
3995 llvm::PointerType::getUnqual(DeclTy),
3996 /*D=*/nullptr);
3997
3998 // Create the new alias itself, but don't set a name yet.
3999 auto *GA = llvm::GlobalAlias::create(
4000 DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
4001
4002 if (Entry) {
4003 if (GA->getAliasee() == Entry) {
4004 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
4005 return;
4006 }
4007
4008 assert(Entry->isDeclaration())((Entry->isDeclaration()) ? static_cast<void> (0) : __assert_fail
("Entry->isDeclaration()", "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 4008, __PRETTY_FUNCTION__))
;
4009
4010 // If there is a declaration in the module, then we had an extern followed
4011 // by the alias, as in:
4012 // extern int test6();
4013 // ...
4014 // int test6() __attribute__((alias("test7")));
4015 //
4016 // Remove it and replace uses of it with the alias.
4017 GA->takeName(Entry);
4018
4019 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
4020 Entry->getType()));
4021 Entry->eraseFromParent();
4022 } else {
4023 GA->setName(MangledName);
4024 }
4025
4026 // Set attributes which are particular to an alias; this is a
4027 // specialization of the attributes which may be set on a global
4028 // variable/function.
4029 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
4030 D->isWeakImported()) {
4031 GA->setLinkage(llvm::Function::WeakAnyLinkage);
4032 }
4033
4034 if (const auto *VD = dyn_cast<VarDecl>(D))
4035 if (VD->getTLSKind())
4036 setTLSMode(GA, *VD);
4037
4038 SetCommonAttributes(GD, GA);
4039}
4040
4041void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
4042 const auto *D = cast<ValueDecl>(GD.getDecl());
4043 const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
4044 assert(IFA && "Not an ifunc?")((IFA && "Not an ifunc?") ? static_cast<void> (
0) : __assert_fail ("IFA && \"Not an ifunc?\"", "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 4044, __PRETTY_FUNCTION__))
;
4045
4046 StringRef MangledName = getMangledName(GD);
4047
4048 if (IFA->getResolver() == MangledName) {
4049 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
4050 return;
4051 }
4052
4053 // Report an error if some definition overrides ifunc.
4054 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4055 if (Entry && !Entry->isDeclaration()) {
4056 GlobalDecl OtherGD;
4057 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
4058 DiagnosedConflictingDefinitions.insert(GD).second) {
4059 Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
4060 << MangledName;
4061 Diags.Report(OtherGD.getDecl()->getLocation(),
4062 diag::note_previous_definition);
4063 }
4064 return;
4065 }
4066
4067 Aliases.push_back(GD);
4068
4069 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
4070 llvm::Constant *Resolver =
4071 GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
4072 /*ForVTable=*/false);
4073 llvm::GlobalIFunc *GIF =
4074 llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
4075 "", Resolver, &getModule());
4076 if (Entry) {
4077 if (GIF->getResolver() == Entry) {
4078 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
4079 return;
4080 }
4081 assert(Entry->isDeclaration())((Entry->isDeclaration()) ? static_cast<void> (0) : __assert_fail
("Entry->isDeclaration()", "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 4081, __PRETTY_FUNCTION__))
;
4082
4083 // If there is a declaration in the module, then we had an extern followed
4084 // by the ifunc, as in:
4085 // extern int test();
4086 // ...
4087 // int test() __attribute__((ifunc("resolver")));
4088 //
4089 // Remove it and replace uses of it with the ifunc.
4090 GIF->takeName(Entry);
4091
4092 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
4093 Entry->getType()));
4094 Entry->eraseFromParent();
4095 } else
4096 GIF->setName(MangledName);
4097
4098 SetCommonAttributes(GD, GIF);
4099}
4100
4101llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
4102 ArrayRef<llvm::Type*> Tys) {
4103 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
4104 Tys);
4105}
4106
4107static llvm::StringMapEntry<llvm::GlobalVariable *> &
4108GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
4109 const StringLiteral *Literal, bool TargetIsLSB,
4110 bool &IsUTF16, unsigned &StringLength) {
4111 StringRef String = Literal->getString();
4112 unsigned NumBytes = String.size();
4113
4114 // Check for simple case.
4115 if (!Literal->containsNonAsciiOrNull()) {
4116 StringLength = NumBytes;
4117 return *Map.insert(std::make_pair(String, nullptr)).first;
4118 }
4119
4120 // Otherwise, convert the UTF8 literals into a string of shorts.
4121 IsUTF16 = true;
4122
4123 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
4124 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
4125 llvm::UTF16 *ToPtr = &ToBuf[0];
4126
4127 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
4128 ToPtr + NumBytes, llvm::strictConversion);
4129
4130 // ConvertUTF8toUTF16 returns the length in ToPtr.
4131 StringLength = ToPtr - &ToBuf[0];
4132
4133 // Add an explicit null.
4134 *ToPtr = 0;
4135 return *Map.insert(std::make_pair(
4136 StringRef(reinterpret_cast<const char *>(ToBuf.data()),
4137 (StringLength + 1) * 2),
4138 nullptr)).first;
4139}
4140
4141ConstantAddress
4142CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
4143 unsigned StringLength = 0;
4144 bool isUTF16 = false;
4145 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
4146 GetConstantCFStringEntry(CFConstantStringMap, Literal,
4147 getDataLayout().isLittleEndian(), isUTF16,
4148 StringLength);
4149
4150 if (auto *C = Entry.second)
4151 return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
4152
4153 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
4154 llvm::Constant *Zeros[] = { Zero, Zero };
4155
4156 const ASTContext &Context = getContext();
4157 const llvm::Triple &Triple = getTriple();
4158
4159 const auto CFRuntime = getLangOpts().CFRuntime;
4160 const bool IsSwiftABI =
4161 static_cast<unsigned>(CFRuntime) >=
4162 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift);
4163 const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1;
4164
4165 // If we don't already have it, get __CFConstantStringClassReference.
4166 if (!CFConstantStringClassRef) {
4167 const char *CFConstantStringClassName = "__CFConstantStringClassReference";
4168 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
4169 Ty = llvm::ArrayType::get(Ty, 0);
4170
4171 switch (CFRuntime) {
4172 default: break;
4173 case LangOptions::CoreFoundationABI::Swift: LLVM_FALLTHROUGH[[clang::fallthrough]];
4174 case LangOptions::CoreFoundationABI::Swift5_0:
4175 CFConstantStringClassName =
4176 Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN"
4177 : "$s10Foundation19_NSCFConstantStringCN";
4178 Ty = IntPtrTy;
4179 break;
4180 case LangOptions::CoreFoundationABI::Swift4_2:
4181 CFConstantStringClassName =
4182 Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN"
4183 : "$S10Foundation19_NSCFConstantStringCN";
4184 Ty = IntPtrTy;
4185 break;
4186 case LangOptions::CoreFoundationABI::Swift4_1:
4187 CFConstantStringClassName =
4188 Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN"
4189 : "__T010Foundation19_NSCFConstantStringCN";
4190 Ty = IntPtrTy;
4191 break;
4192 }
4193
4194 llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName);
4195
4196 if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
4197 llvm::GlobalValue *GV = nullptr;
4198
4199 if ((GV = dyn_cast<llvm::GlobalValue>(C))) {
4200 IdentifierInfo &II = Context.Idents.get(GV->getName());
4201 TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl();
4202 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
4203
4204 const VarDecl *VD = nullptr;
4205 for (const auto &Result : DC->lookup(&II))
4206 if ((VD = dyn_cast<VarDecl>(Result)))
4207 break;
4208
4209 if (Triple.isOSBinFormatELF()) {
4210 if (!VD)
4211 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
4212 } else {
4213 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
4214 if (!VD || !VD->hasAttr<DLLExportAttr>())
4215 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
4216 else
4217 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
4218 }
4219
4220 setDSOLocal(GV);
4221 }
4222 }
4223
4224 // Decay array -> ptr
4225 CFConstantStringClassRef =
4226 IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty)
4227 : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros);
4228 }
4229
4230 QualType CFTy = Context.getCFConstantStringType();
4231
4232 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
4233
4234 ConstantInitBuilder Builder(*this);
4235 auto Fields = Builder.beginStruct(STy);
4236
4237 // Class pointer.
4238 Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
4239
4240 // Flags.
4241 if (IsSwiftABI) {
4242 Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
4243 Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
4244 } else {
4245 Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
4246 }
4247
4248 // String pointer.
4249 llvm::Constant *C = nullptr;
4250 if (isUTF16) {
4251 auto Arr = llvm::makeArrayRef(
4252 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
4253 Entry.first().size() / 2);
4254 C = llvm::ConstantDataArray::get(VMContext, Arr);
4255 } else {
4256 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
4257 }
4258
4259 // Note: -fwritable-strings doesn't make the backing store strings of
4260 // CFStrings writable. (See <rdar://problem/10657500>)
4261 auto *GV =
4262 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
4263 llvm::GlobalValue::PrivateLinkage, C, ".str");
4264 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4265 // Don't enforce the target's minimum global alignment, since the only use
4266 // of the string is via this class initializer.
4267 CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
4268 : Context.getTypeAlignInChars(Context.CharTy);
4269 GV->setAlignment(Align.getQuantity());
4270
4271 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
4272 // Without it LLVM can merge the string with a non unnamed_addr one during
4273 // LTO. Doing that changes the section it ends in, which surprises ld64.
4274 if (Triple.isOSBinFormatMachO())
4275 GV->setSection(isUTF16 ? "__TEXT,__ustring"
4276 : "__TEXT,__cstring,cstring_literals");
4277 // Make sure the literal ends up in .rodata to allow for safe ICF and for
4278 // the static linker to adjust permissions to read-only later on.
4279 else if (Triple.isOSBinFormatELF())
4280 GV->setSection(".rodata");
4281
4282 // String.
4283 llvm::Constant *Str =
4284 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
4285
4286 if (isUTF16)
4287 // Cast the UTF16 string to the correct type.
4288 Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
4289 Fields.add(Str);
4290
4291 // String length.
4292 llvm::IntegerType *LengthTy =
4293 llvm::IntegerType::get(getModule().getContext(),
4294 Context.getTargetInfo().getLongWidth());
4295 if (IsSwiftABI) {
4296 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
4297 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
4298 LengthTy = Int32Ty;
4299 else
4300 LengthTy = IntPtrTy;
4301 }
4302 Fields.addInt(LengthTy, StringLength);
4303
4304 CharUnits Alignment = getPointerAlign();
4305
4306 // The struct.
4307 GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
4308 /*isConstant=*/false,
4309 llvm::GlobalVariable::PrivateLinkage);
4310 switch (Triple.getObjectFormat()) {
4311 case llvm::Triple::UnknownObjectFormat:
4312 llvm_unreachable("unknown file format")::llvm::llvm_unreachable_internal("unknown file format", "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 4312)
;
4313 case llvm::Triple::COFF:
4314 case llvm::Triple::ELF:
4315 case llvm::Triple::Wasm:
4316 GV->setSection("cfstring");
4317 break;
4318 case llvm::Triple::MachO:
4319 GV->setSection("__DATA,__cfstring");
4320 break;
4321 }
4322 Entry.second = GV;
4323
4324 return ConstantAddress(GV, Alignment);
4325}
4326
4327bool CodeGenModule::getExpressionLocationsEnabled() const {
4328 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
4329}
4330
4331QualType CodeGenModule::getObjCFastEnumerationStateType() {
4332 if (ObjCFastEnumerationStateType.isNull()) {
4333 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
4334 D->startDefinition();
4335
4336 QualType FieldTypes[] = {
4337 Context.UnsignedLongTy,
4338 Context.getPointerType(Context.getObjCIdType()),
4339 Context.getPointerType(Context.UnsignedLongTy),
4340 Context.getConstantArrayType(Context.UnsignedLongTy,
4341 llvm::APInt(32, 5), ArrayType::Normal, 0)
4342 };
4343
4344 for (size_t i = 0; i < 4; ++i) {
4345 FieldDecl *Field = FieldDecl::Create(Context,
4346 D,
4347 SourceLocation(),
4348 SourceLocation(), nullptr,
4349 FieldTypes[i], /*TInfo=*/nullptr,
4350 /*BitWidth=*/nullptr,
4351 /*Mutable=*/false,
4352 ICIS_NoInit);
4353 Field->setAccess(AS_public);
4354 D->addDecl(Field);
4355 }
4356
4357 D->completeDefinition();
4358 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
4359 }
4360
4361 return ObjCFastEnumerationStateType;
4362}
4363
4364llvm::Constant *
4365CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
4366 assert(!E->getType()->isPointerType() && "Strings are always arrays")((!E->getType()->isPointerType() && "Strings are always arrays"
) ? static_cast<void> (0) : __assert_fail ("!E->getType()->isPointerType() && \"Strings are always arrays\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 4366, __PRETTY_FUNCTION__))
;
4367
4368 // Don't emit it as the address of the string, emit the string data itself
4369 // as an inline array.
4370 if (E->getCharByteWidth() == 1) {
4371 SmallString<64> Str(E->getString());
4372
4373 // Resize the string to the right size, which is indicated by its type.
4374 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
4375 Str.resize(CAT->getSize().getZExtValue());
4376 return llvm::ConstantDataArray::getString(VMContext, Str, false);
4377 }
4378
4379 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
4380 llvm::Type *ElemTy = AType->getElementType();
4381 unsigned NumElements = AType->getNumElements();
4382
4383 // Wide strings have either 2-byte or 4-byte elements.
4384 if (ElemTy->getPrimitiveSizeInBits() == 16) {
4385 SmallVector<uint16_t, 32> Elements;
4386 Elements.reserve(NumElements);
4387
4388 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
4389 Elements.push_back(E->getCodeUnit(i));
4390 Elements.resize(NumElements);
4391 return llvm::ConstantDataArray::get(VMContext, Elements);
4392 }
4393
4394 assert(ElemTy->getPrimitiveSizeInBits() == 32)((ElemTy->getPrimitiveSizeInBits() == 32) ? static_cast<
void> (0) : __assert_fail ("ElemTy->getPrimitiveSizeInBits() == 32"
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 4394, __PRETTY_FUNCTION__))
;
4395 SmallVector<uint32_t, 32> Elements;
4396 Elements.reserve(NumElements);
4397
4398 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
4399 Elements.push_back(E->getCodeUnit(i));
4400 Elements.resize(NumElements);
4401 return llvm::ConstantDataArray::get(VMContext, Elements);
4402}
4403
4404static llvm::GlobalVariable *
4405GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
4406 CodeGenModule &CGM, StringRef GlobalName,
4407 CharUnits Alignment) {
4408 unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
4409 CGM.getStringLiteralAddressSpace());
4410
4411 llvm::Module &M = CGM.getModule();
4412 // Create a global variable for this string
4413 auto *GV = new llvm::GlobalVariable(
4414 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
4415 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
4416 GV->setAlignment(Alignment.getQuantity());
4417 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4418 if (GV->isWeakForLinker()) {
4419 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals")((CGM.supportsCOMDAT() && "Only COFF uses weak string literals"
) ? static_cast<void> (0) : __assert_fail ("CGM.supportsCOMDAT() && \"Only COFF uses weak string literals\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 4419, __PRETTY_FUNCTION__))
;
4420 GV->setComdat(M.getOrInsertComdat(GV->getName()));
4421 }
4422 CGM.setDSOLocal(GV);
4423
4424 return GV;
4425}
4426
4427/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
4428/// constant array for the given string literal.
4429ConstantAddress
4430CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
4431 StringRef Name) {
4432 CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
4433
4434 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
4435 llvm::GlobalVariable **Entry = nullptr;
4436 if (!LangOpts.WritableStrings) {
4437 Entry = &ConstantStringMap[C];
4438 if (auto GV = *Entry) {
4439 if (Alignment.getQuantity() > GV->getAlignment())
4440 GV->setAlignment(Alignment.getQuantity());
4441 return ConstantAddress(GV, Alignment);
4442 }
4443 }
4444
4445 SmallString<256> MangledNameBuffer;
4446 StringRef GlobalVariableName;
4447 llvm::GlobalValue::LinkageTypes LT;
4448
4449 // Mangle the string literal if that's how the ABI merges duplicate strings.
4450 // Don't do it if they are writable, since we don't want writes in one TU to
4451 // affect strings in another.
4452 if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
4453 !LangOpts.WritableStrings) {
4454 llvm::raw_svector_ostream Out(MangledNameBuffer);
4455 getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
4456 LT = llvm::GlobalValue::LinkOnceODRLinkage;
4457 GlobalVariableName = MangledNameBuffer;
4458 } else {
4459 LT = llvm::GlobalValue::PrivateLinkage;
4460 GlobalVariableName = Name;
4461 }
4462
4463 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
4464 if (Entry)
4465 *Entry = GV;
4466
4467 SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
4468 QualType());
4469
4470 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
4471 Alignment);
4472}
4473
4474/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
4475/// array for the given ObjCEncodeExpr node.
4476ConstantAddress
4477CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
4478 std::string Str;
4479 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
4480
4481 return GetAddrOfConstantCString(Str);
4482}
4483
4484/// GetAddrOfConstantCString - Returns a pointer to a character array containing
4485/// the literal and a terminating '\0' character.
4486/// The result has pointer to array type.
4487ConstantAddress CodeGenModule::GetAddrOfConstantCString(
4488 const std::string &Str, const char *GlobalName) {
4489 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
4490 CharUnits Alignment =
4491 getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
4492
4493 llvm::Constant *C =
4494 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
4495
4496 // Don't share any string literals if strings aren't constant.
4497 llvm::GlobalVariable **Entry = nullptr;
4498 if (!LangOpts.WritableStrings) {
4499 Entry = &ConstantStringMap[C];
4500 if (auto GV = *Entry) {
4501 if (Alignment.getQuantity() > GV->getAlignment())
4502 GV->setAlignment(Alignment.getQuantity());
4503 return ConstantAddress(GV, Alignment);
4504 }
4505 }
4506
4507 // Get the default prefix if a name wasn't specified.
4508 if (!GlobalName)
4509 GlobalName = ".str";
4510 // Create a global variable for this.
4511 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
4512 GlobalName, Alignment);
4513 if (Entry)
4514 *Entry = GV;
4515
4516 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
4517 Alignment);
4518}
4519
4520ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
4521 const MaterializeTemporaryExpr *E, const Expr *Init) {
4522 assert((E->getStorageDuration() == SD_Static ||(((E->getStorageDuration() == SD_Static || E->getStorageDuration
() == SD_Thread) && "not a global temporary") ? static_cast
<void> (0) : __assert_fail ("(E->getStorageDuration() == SD_Static || E->getStorageDuration() == SD_Thread) && \"not a global temporary\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 4523, __PRETTY_FUNCTION__))
4523 E->getStorageDuration() == SD_Thread) && "not a global temporary")(((E->getStorageDuration() == SD_Static || E->getStorageDuration
() == SD_Thread) && "not a global temporary") ? static_cast
<void> (0) : __assert_fail ("(E->getStorageDuration() == SD_Static || E->getStorageDuration() == SD_Thread) && \"not a global temporary\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 4523, __PRETTY_FUNCTION__))
;
4524 const auto *VD = cast<VarDecl>(E->getExtendingDecl());
4525
4526 // If we're not materializing a subobject of the temporary, keep the
4527 // cv-qualifiers from the type of the MaterializeTemporaryExpr.
4528 QualType MaterializedType = Init->getType();
4529 if (Init == E->GetTemporaryExpr())
4530 MaterializedType = E->getType();
4531
4532 CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
4533
4534 if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
4535 return ConstantAddress(Slot, Align);
4536
4537 // FIXME: If an externally-visible declaration extends multiple temporaries,
4538 // we need to give each temporary the same name in every translation unit (and
4539 // we also need to make the temporaries externally-visible).
4540 SmallString<256> Name;
4541 llvm::raw_svector_ostream Out(Name);
4542 getCXXABI().getMangleContext().mangleReferenceTemporary(
4543 VD, E->getManglingNumber(), Out);
4544
4545 APValue *Value = nullptr;
4546 if (E->getStorageDuration() == SD_Static) {
4547 // We might have a cached constant initializer for this temporary. Note
4548 // that this might have a different value from the value computed by
4549 // evaluating the initializer if the surrounding constant expression
4550 // modifies the temporary.
4551 Value = getContext().getMaterializedTemporaryValue(E, false);
4552 if (Value && Value->isUninit())
4553 Value = nullptr;
4554 }
4555
4556 // Try evaluating it now, it might have a constant initializer.
4557 Expr::EvalResult EvalResult;
4558 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
4559 !EvalResult.hasSideEffects())
4560 Value = &EvalResult.Val;
4561
4562 LangAS AddrSpace =
4563 VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
4564
4565 Optional<ConstantEmitter> emitter;
4566 llvm::Constant *InitialValue = nullptr;
4567 bool Constant = false;
4568 llvm::Type *Type;
4569 if (Value) {
4570 // The temporary has a constant initializer, use it.
4571 emitter.emplace(*this);
4572 InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
4573 MaterializedType);
4574 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
4575 Type = InitialValue->getType();
4576 } else {
4577 // No initializer, the initialization will be provided when we
4578 // initialize the declaration which performed lifetime extension.
4579 Type = getTypes().ConvertTypeForMem(MaterializedType);
4580 }
4581
4582 // Create a global variable for this lifetime-extended temporary.
4583 llvm::GlobalValue::LinkageTypes Linkage =
4584 getLLVMLinkageVarDefinition(VD, Constant);
4585 if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
4586 const VarDecl *InitVD;
4587 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
4588 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
4589 // Temporaries defined inside a class get linkonce_odr linkage because the
4590 // class can be defined in multiple translation units.
4591 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
4592 } else {
4593 // There is no need for this temporary to have external linkage if the
4594 // VarDecl has external linkage.
4595 Linkage = llvm::GlobalVariable::InternalLinkage;
4596 }
4597 }
4598 auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
4599 auto *GV = new llvm::GlobalVariable(
4600 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
4601 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
4602 if (emitter) emitter->finalize(GV);
4603 setGVProperties(GV, VD);
4604 GV->setAlignment(Align.getQuantity());
4605 if (supportsCOMDAT() && GV->isWeakForLinker())
4606 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4607 if (VD->getTLSKind())
4608 setTLSMode(GV, *VD);
4609 llvm::Constant *CV = GV;
4610 if (AddrSpace != LangAS::Default)
4611 CV = getTargetCodeGenInfo().performAddrSpaceCast(
4612 *this, GV, AddrSpace, LangAS::Default,
4613 Type->getPointerTo(
4614 getContext().getTargetAddressSpace(LangAS::Default)));
4615 MaterializedGlobalTemporaryMap[E] = CV;
4616 return ConstantAddress(CV, Align);
4617}
4618
4619/// EmitObjCPropertyImplementations - Emit information for synthesized
4620/// properties for an implementation.
4621void CodeGenModule::EmitObjCPropertyImplementations(const
4622 ObjCImplementationDecl *D) {
4623 for (const auto *PID : D->property_impls()) {
4624 // Dynamic is just for type-checking.
4625 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
4626 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4627
4628 // Determine which methods need to be implemented, some may have
4629 // been overridden. Note that ::isPropertyAccessor is not the method
4630 // we want, that just indicates if the decl came from a
4631 // property. What we want to know is if the method is defined in
4632 // this implementation.
4633 if (!D->getInstanceMethod(PD->getGetterName()))
4634 CodeGenFunction(*this).GenerateObjCGetter(
4635 const_cast<ObjCImplementationDecl *>(D), PID);
4636 if (!PD->isReadOnly() &&
4637 !D->getInstanceMethod(PD->getSetterName()))
4638 CodeGenFunction(*this).GenerateObjCSetter(
4639 const_cast<ObjCImplementationDecl *>(D), PID);
4640 }
4641 }
4642}
4643
4644static bool needsDestructMethod(ObjCImplementationDecl *impl) {
4645 const ObjCInterfaceDecl *iface = impl->getClassInterface();
4646 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
4647 ivar; ivar = ivar->getNextIvar())
4648 if (ivar->getType().isDestructedType())
4649 return true;
4650
4651 return false;
4652}
4653
4654static bool AllTrivialInitializers(CodeGenModule &CGM,
4655 ObjCImplementationDecl *D) {
4656 CodeGenFunction CGF(CGM);
4657 for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
4658 E = D->init_end(); B != E; ++B) {
4659 CXXCtorInitializer *CtorInitExp = *B;
4660 Expr *Init = CtorInitExp->getInit();
4661 if (!CGF.isTrivialInitializer(Init))
4662 return false;
4663 }
4664 return true;
4665}
4666
4667/// EmitObjCIvarInitializations - Emit information for ivar initialization
4668/// for an implementation.
4669void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
4670 // We might need a .cxx_destruct even if we don't have any ivar initializers.
4671 if (needsDestructMethod(D)) {
4672 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
4673 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
4674 ObjCMethodDecl *DTORMethod =
4675 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
4676 cxxSelector, getContext().VoidTy, nullptr, D,
4677 /*isInstance=*/true, /*isVariadic=*/false,
4678 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
4679 /*isDefined=*/false, ObjCMethodDecl::Required);
4680 D->addInstanceMethod(DTORMethod);
4681 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
4682 D->setHasDestructors(true);
4683 }
4684
4685 // If the implementation doesn't have any ivar initializers, we don't need
4686 // a .cxx_construct.
4687 if (D->getNumIvarInitializers() == 0 ||
4688 AllTrivialInitializers(*this, D))
4689 return;
4690
4691 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
4692 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
4693 // The constructor returns 'self'.
4694 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
4695 D->getLocation(),
4696 D->getLocation(),
4697 cxxSelector,
4698 getContext().getObjCIdType(),
4699 nullptr, D, /*isInstance=*/true,
4700 /*isVariadic=*/false,
4701 /*isPropertyAccessor=*/true,
4702 /*isImplicitlyDeclared=*/true,
4703 /*isDefined=*/false,
4704 ObjCMethodDecl::Required);
4705 D->addInstanceMethod(CTORMethod);
4706 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
4707 D->setHasNonZeroConstructors(true);
4708}
4709
4710// EmitLinkageSpec - Emit all declarations in a linkage spec.
4711void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
4712 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
4713 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
4714 ErrorUnsupported(LSD, "linkage spec");
4715 return;
4716 }
4717
4718 EmitDeclContext(LSD);
4719}
4720
4721void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
4722 for (auto *I : DC->decls()) {
4723 // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
4724 // are themselves considered "top-level", so EmitTopLevelDecl on an
4725 // ObjCImplDecl does not recursively visit them. We need to do that in
4726 // case they're nested inside another construct (LinkageSpecDecl /
4727 // ExportDecl) that does stop them from being considered "top-level".
4728 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
4729 for (auto *M : OID->methods())
4730 EmitTopLevelDecl(M);
4731 }
4732
4733 EmitTopLevelDecl(I);
4734 }
4735}
4736
4737/// EmitTopLevelDecl - Emit code for a single top level declaration.
4738void CodeGenModule::EmitTopLevelDecl(Decl *D) {
4739 // Ignore dependent declarations.
4740 if (D->isTemplated())
4741 return;
4742
4743 switch (D->getKind()) {
4744 case Decl::CXXConversion:
4745 case Decl::CXXMethod:
4746 case Decl::Function:
4747 EmitGlobal(cast<FunctionDecl>(D));
4748 // Always provide some coverage mapping
4749 // even for the functions that aren't emitted.
4750 AddDeferredUnusedCoverageMapping(D);
4751 break;
4752
4753 case Decl::CXXDeductionGuide:
4754 // Function-like, but does not result in code emission.
4755 break;
4756
4757 case Decl::Var:
4758 case Decl::Decomposition:
4759 case Decl::VarTemplateSpecialization:
4760 EmitGlobal(cast<VarDecl>(D));
4761 if (auto *DD = dyn_cast<DecompositionDecl>(D))
4762 for (auto *B : DD->bindings())
4763 if (auto *HD = B->getHoldingVar())
4764 EmitGlobal(HD);
4765 break;
4766
4767 // Indirect fields from global anonymous structs and unions can be
4768 // ignored; only the actual variable requires IR gen support.
4769 case Decl::IndirectField:
4770 break;
4771
4772 // C++ Decls
4773 case Decl::Namespace:
4774 EmitDeclContext(cast<NamespaceDecl>(D));
4775 break;
4776 case Decl::ClassTemplateSpecialization: {
4777 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
4778 if (DebugInfo &&
4779 Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
4780 Spec->hasDefinition())
4781 DebugInfo->completeTemplateDefinition(*Spec);
4782 } LLVM_FALLTHROUGH[[clang::fallthrough]];
4783 case Decl::CXXRecord:
4784 if (DebugInfo) {
4785 if (auto *ES = D->getASTContext().getExternalSource())
4786 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
4787 DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
4788 }
4789 // Emit any static data members, they may be definitions.
4790 for (auto *I : cast<CXXRecordDecl>(D)->decls())
4791 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
4792 EmitTopLevelDecl(I);
4793 break;
4794 // No code generation needed.
4795 case Decl::UsingShadow:
4796 case Decl::ClassTemplate:
4797 case Decl::VarTemplate:
4798 case Decl::VarTemplatePartialSpecialization:
4799 case Decl::FunctionTemplate:
4800 case Decl::TypeAliasTemplate:
4801 case Decl::Block:
4802 case Decl::Empty:
4803 case Decl::Binding:
4804 break;
4805 case Decl::Using: // using X; [C++]
4806 if (CGDebugInfo *DI = getModuleDebugInfo())
4807 DI->EmitUsingDecl(cast<UsingDecl>(*D));
4808 return;
4809 case Decl::NamespaceAlias:
4810 if (CGDebugInfo *DI = getModuleDebugInfo())
4811 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
4812 return;
4813 case Decl::UsingDirective: // using namespace X; [C++]
4814 if (CGDebugInfo *DI = getModuleDebugInfo())
4815 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
4816 return;
4817 case Decl::CXXConstructor:
4818 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
4819 break;
4820 case Decl::CXXDestructor:
4821 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
4822 break;
4823
4824 case Decl::StaticAssert:
4825 // Nothing to do.
4826 break;
4827
4828 // Objective-C Decls
4829
4830 // Forward declarations, no (immediate) code generation.
4831 case Decl::ObjCInterface:
4832 case Decl::ObjCCategory:
4833 break;
4834
4835 case Decl::ObjCProtocol: {
4836 auto *Proto = cast<ObjCProtocolDecl>(D);
4837 if (Proto->isThisDeclarationADefinition())
4838 ObjCRuntime->GenerateProtocol(Proto);
4839 break;
4840 }
4841
4842 case Decl::ObjCCategoryImpl:
4843 // Categories have properties but don't support synthesize so we
4844 // can ignore them here.
4845 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
4846 break;
4847
4848 case Decl::ObjCImplementation: {
4849 auto *OMD = cast<ObjCImplementationDecl>(D);
4850 EmitObjCPropertyImplementations(OMD);
4851 EmitObjCIvarInitializations(OMD);
4852 ObjCRuntime->GenerateClass(OMD);
4853 // Emit global variable debug information.
4854 if (CGDebugInfo *DI = getModuleDebugInfo())
4855 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
4856 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
4857 OMD->getClassInterface()), OMD->getLocation());
4858 break;
4859 }
4860 case Decl::ObjCMethod: {
4861 auto *OMD = cast<ObjCMethodDecl>(D);
4862 // If this is not a prototype, emit the body.
4863 if (OMD->getBody())
4864 CodeGenFunction(*this).GenerateObjCMethod(OMD);
4865 break;
4866 }
4867 case Decl::ObjCCompatibleAlias:
4868 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
4869 break;
4870
4871 case Decl::PragmaComment: {
4872 const auto *PCD = cast<PragmaCommentDecl>(D);
4873 switch (PCD->getCommentKind()) {
4874 case PCK_Unknown:
4875 llvm_unreachable("unexpected pragma comment kind")::llvm::llvm_unreachable_internal("unexpected pragma comment kind"
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 4875)
;
4876 case PCK_Linker:
4877 AppendLinkerOptions(PCD->getArg());
4878 break;
4879 case PCK_Lib:
4880 if (getTarget().getTriple().isOSBinFormatELF() &&
4881 !getTarget().getTriple().isPS4())
4882 AddELFLibDirective(PCD->getArg());
4883 else
4884 AddDependentLib(PCD->getArg());
4885 break;
4886 case PCK_Compiler:
4887 case PCK_ExeStr:
4888 case PCK_User:
4889 break; // We ignore all of these.
4890 }
4891 break;
4892 }
4893
4894 case Decl::PragmaDetectMismatch: {
4895 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
4896 AddDetectMismatch(PDMD->getName(), PDMD->getValue());
4897 break;
4898 }
4899
4900 case Decl::LinkageSpec:
4901 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
4902 break;
4903
4904 case Decl::FileScopeAsm: {
4905 // File-scope asm is ignored during device-side CUDA compilation.
4906 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
4907 break;
4908 // File-scope asm is ignored during device-side OpenMP compilation.
4909 if (LangOpts.OpenMPIsDevice)
4910 break;
4911 auto *AD = cast<FileScopeAsmDecl>(D);
4912 getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
4913 break;
4914 }
4915
4916 case Decl::Import: {
4917 auto *Import = cast<ImportDecl>(D);
4918
4919 // If we've already imported this module, we're done.
4920 if (!ImportedModules.insert(Import->getImportedModule()))
4921 break;
4922
4923 // Emit debug information for direct imports.
4924 if (!Import->getImportedOwningModule()) {
4925 if (CGDebugInfo *DI = getModuleDebugInfo())
4926 DI->EmitImportDecl(*Import);
4927 }
4928
4929 // Find all of the submodules and emit the module initializers.
4930 llvm::SmallPtrSet<clang::Module *, 16> Visited;
4931 SmallVector<clang::Module *, 16> Stack;
4932 Visited.insert(Import->getImportedModule());
4933 Stack.push_back(Import->getImportedModule());
4934
4935 while (!Stack.empty()) {
4936 clang::Module *Mod = Stack.pop_back_val();
4937 if (!EmittedModuleInitializers.insert(Mod).second)
4938 continue;
4939
4940 for (auto *D : Context.getModuleInitializers(Mod))
4941 EmitTopLevelDecl(D);
4942
4943 // Visit the submodules of this module.
4944 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
4945 SubEnd = Mod->submodule_end();
4946 Sub != SubEnd; ++Sub) {
4947 // Skip explicit children; they need to be explicitly imported to emit
4948 // the initializers.
4949 if ((*Sub)->IsExplicit)
4950 continue;
4951
4952 if (Visited.insert(*Sub).second)
4953 Stack.push_back(*Sub);
4954 }
4955 }
4956 break;
4957 }
4958
4959 case Decl::Export:
4960 EmitDeclContext(cast<ExportDecl>(D));
4961 break;
4962
4963 case Decl::OMPThreadPrivate:
4964 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
4965 break;
4966
4967 case Decl::OMPDeclareReduction:
4968 EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
4969 break;
4970
4971 case Decl::OMPRequires:
4972 EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D));
4973 break;
4974
4975 default:
4976 // Make sure we handled everything we should, every other kind is a
4977 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
4978 // function. Need to recode Decl::Kind to do that easily.
4979 assert(isa<TypeDecl>(D) && "Unsupported decl kind")((isa<TypeDecl>(D) && "Unsupported decl kind") ?
static_cast<void> (0) : __assert_fail ("isa<TypeDecl>(D) && \"Unsupported decl kind\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 4979, __PRETTY_FUNCTION__))
;
4980 break;
4981 }
4982}
4983
4984void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
4985 // Do we need to generate coverage mapping?
4986 if (!CodeGenOpts.CoverageMapping)
4987 return;
4988 switch (D->getKind()) {
4989 case Decl::CXXConversion:
4990 case Decl::CXXMethod:
4991 case Decl::Function:
4992 case Decl::ObjCMethod:
4993 case Decl::CXXConstructor:
4994 case Decl::CXXDestructor: {
4995 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
4996 return;
4997 SourceManager &SM = getContext().getSourceManager();
4998 if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc()))
4999 return;
5000 auto I = DeferredEmptyCoverageMappingDecls.find(D);
5001 if (I == DeferredEmptyCoverageMappingDecls.end())
5002 DeferredEmptyCoverageMappingDecls[D] = true;
5003 break;
5004 }
5005 default:
5006 break;
5007 };
5008}
5009
5010void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
5011 // Do we need to generate coverage mapping?
5012 if (!CodeGenOpts.CoverageMapping)
5013 return;
5014 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
5015 if (Fn->isTemplateInstantiation())
5016 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
5017 }
5018 auto I = DeferredEmptyCoverageMappingDecls.find(D);
5019 if (I == DeferredEmptyCoverageMappingDecls.end())
5020 DeferredEmptyCoverageMappingDecls[D] = false;
5021 else
5022 I->second = false;
5023}
5024
5025void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
5026 // We call takeVector() here to avoid use-after-free.
5027 // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
5028 // we deserialize function bodies to emit coverage info for them, and that
5029 // deserializes more declarations. How should we handle that case?
5030 for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
5031 if (!Entry.second)
5032 continue;
5033 const Decl *D = Entry.first;
5034 switch (D->getKind()) {
5035 case Decl::CXXConversion:
5036 case Decl::CXXMethod:
5037 case Decl::Function:
5038 case Decl::ObjCMethod: {
5039 CodeGenPGO PGO(*this);
5040 GlobalDecl GD(cast<FunctionDecl>(D));
5041 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
5042 getFunctionLinkage(GD));
5043 break;
5044 }
5045 case Decl::CXXConstructor: {
5046 CodeGenPGO PGO(*this);
5047 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
5048 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
5049 getFunctionLinkage(GD));
5050 break;
5051 }
5052 case Decl::CXXDestructor: {
5053 CodeGenPGO PGO(*this);
5054 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
5055 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
5056 getFunctionLinkage(GD));
5057 break;
5058 }
5059 default:
5060 break;
5061 };
5062 }
5063}
5064
5065/// Turns the given pointer into a constant.
5066static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
5067 const void *Ptr) {
5068 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
5069 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
5070 return llvm::ConstantInt::get(i64, PtrInt);
5071}
5072
5073static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
5074 llvm::NamedMDNode *&GlobalMetadata,
5075 GlobalDecl D,
5076 llvm::GlobalValue *Addr) {
5077 if (!GlobalMetadata)
5078 GlobalMetadata =
5079 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
5080
5081 // TODO: should we report variant information for ctors/dtors?
5082 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
5083 llvm::ConstantAsMetadata::get(GetPointerConstant(
5084 CGM.getLLVMContext(), D.getDecl()))};
5085 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
5086}
5087
5088/// For each function which is declared within an extern "C" region and marked
5089/// as 'used', but has internal linkage, create an alias from the unmangled
5090/// name to the mangled name if possible. People expect to be able to refer
5091/// to such functions with an unmangled name from inline assembly within the
5092/// same translation unit.
5093void CodeGenModule::EmitStaticExternCAliases() {
5094 if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
5095 return;
5096 for (auto &I : StaticExternCValues) {
5097 IdentifierInfo *Name = I.first;
5098 llvm::GlobalValue *Val = I.second;
5099 if (Val && !getModule().getNamedValue(Name->getName()))
5100 addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
5101 }
5102}
5103
5104bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
5105 GlobalDecl &Result) const {
5106 auto Res = Manglings.find(MangledName);
5107 if (Res == Manglings.end())
5108 return false;
5109 Result = Res->getValue();
5110 return true;
5111}
5112
5113/// Emits metadata nodes associating all the global values in the
5114/// current module with the Decls they came from. This is useful for
5115/// projects using IR gen as a subroutine.
5116///
5117/// Since there's currently no way to associate an MDNode directly
5118/// with an llvm::GlobalValue, we create a global named metadata
5119/// with the name 'clang.global.decl.ptrs'.
5120void CodeGenModule::EmitDeclMetadata() {
5121 llvm::NamedMDNode *GlobalMetadata = nullptr;
5122
5123 for (auto &I : MangledDeclNames) {
5124 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
5125 // Some mangled names don't necessarily have an associated GlobalValue
5126 // in this module, e.g. if we mangled it for DebugInfo.
5127 if (Addr)
5128 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
5129 }
5130}
5131
5132/// Emits metadata nodes for all the local variables in the current
5133/// function.
5134void CodeGenFunction::EmitDeclMetadata() {
5135 if (LocalDeclMap.empty()) return;
5136
5137 llvm::LLVMContext &Context = getLLVMContext();
5138
5139 // Find the unique metadata ID for this name.
5140 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
5141
5142 llvm::NamedMDNode *GlobalMetadata = nullptr;
5143
5144 for (auto &I : LocalDeclMap) {
5145 const Decl *D = I.first;
5146 llvm::Value *Addr = I.second.getPointer();
5147 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
5148 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
5149 Alloca->setMetadata(
5150 DeclPtrKind, llvm::MDNode::get(
5151 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
5152 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
5153 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
5154 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
5155 }
5156 }
5157}
5158
5159void CodeGenModule::EmitVersionIdentMetadata() {
5160 llvm::NamedMDNode *IdentMetadata =
5161 TheModule.getOrInsertNamedMetadata("llvm.ident");
5162 std::string Version = getClangFullVersion();
5163 llvm::LLVMContext &Ctx = TheModule.getContext();
5164
5165 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
5166 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
5167}
5168
5169void CodeGenModule::EmitTargetMetadata() {
5170 // Warning, new MangledDeclNames may be appended within this loop.
5171 // We rely on MapVector insertions adding new elements to the end
5172 // of the container.
5173 // FIXME: Move this loop into the one target that needs it, and only
5174 // loop over those declarations for which we couldn't emit the target
5175 // metadata when we emitted the declaration.
5176 for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
5177 auto Val = *(MangledDeclNames.begin() + I);
5178 const Decl *D = Val.first.getDecl()->getMostRecentDecl();
5179 llvm::GlobalValue *GV = GetGlobalValue(Val.second);
5180 getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
5181 }
5182}
5183
5184void CodeGenModule::EmitCoverageFile() {
5185 if (getCodeGenOpts().CoverageDataFile.empty() &&
5186 getCodeGenOpts().CoverageNotesFile.empty())
5187 return;
5188
5189 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
5190 if (!CUNode)
5191 return;
5192
5193 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
5194 llvm::LLVMContext &Ctx = TheModule.getContext();
5195 auto *CoverageDataFile =
5196 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
5197 auto *CoverageNotesFile =
5198 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
5199 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
5200 llvm::MDNode *CU = CUNode->getOperand(i);
5201 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
5202 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
5203 }
5204}
5205
5206llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
5207 // Sema has checked that all uuid strings are of the form
5208 // "12345678-1234-1234-1234-1234567890ab".
5209 assert(Uuid.size() == 36)((Uuid.size() == 36) ? static_cast<void> (0) : __assert_fail
("Uuid.size() == 36", "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 5209, __PRETTY_FUNCTION__))
;
5210 for (unsigned i = 0; i < 36; ++i) {
5211 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-')((Uuid[i] == '-') ? static_cast<void> (0) : __assert_fail
("Uuid[i] == '-'", "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 5211, __PRETTY_FUNCTION__))
;
5212 else assert(isHexDigit(Uuid[i]))((isHexDigit(Uuid[i])) ? static_cast<void> (0) : __assert_fail
("isHexDigit(Uuid[i])", "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 5212, __PRETTY_FUNCTION__))
;
5213 }
5214
5215 // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
5216 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
5217
5218 llvm::Constant *Field3[8];
5219 for (unsigned Idx = 0; Idx < 8; ++Idx)
5220 Field3[Idx] = llvm::ConstantInt::get(
5221 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
5222
5223 llvm::Constant *Fields[4] = {
5224 llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
5225 llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
5226 llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
5227 llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
5228 };
5229
5230 return llvm::ConstantStruct::getAnon(Fields);
5231}
5232
5233llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
5234 bool ForEH) {
5235 // Return a bogus pointer if RTTI is disabled, unless it's for EH.
5236 // FIXME: should we even be calling this method if RTTI is disabled
5237 // and it's not for EH?
5238 if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice)
5239 return llvm::Constant::getNullValue(Int8PtrTy);
5240
5241 if (ForEH && Ty->isObjCObjectPointerType() &&
5242 LangOpts.ObjCRuntime.isGNUFamily())
5243 return ObjCRuntime->GetEHType(Ty);
5244
5245 return getCXXABI().getAddrOfRTTIDescriptor(Ty);
5246}
5247
5248void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
5249 // Do not emit threadprivates in simd-only mode.
5250 if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
5251 return;
5252 for (auto RefExpr : D->varlists()) {
5253 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
5254 bool PerformInit =
5255 VD->getAnyInitializer() &&
5256 !VD->getAnyInitializer()->isConstantInitializer(getContext(),
5257 /*ForRef=*/false);
5258
5259 Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
5260 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
5261 VD, Addr, RefExpr->getBeginLoc(), PerformInit))
5262 CXXGlobalInits.push_back(InitFunction);
5263 }
5264}
5265
5266llvm::Metadata *
5267CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
5268 StringRef Suffix) {
5269 llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
5270 if (InternalId)
5271 return InternalId;
5272
5273 if (isExternallyVisible(T->getLinkage())) {
5274 std::string OutName;
5275 llvm::raw_string_ostream Out(OutName);
5276 getCXXABI().getMangleContext().mangleTypeName(T, Out);
5277 Out << Suffix;
5278
5279 InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
5280 } else {
5281 InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
5282 llvm::ArrayRef<llvm::Metadata *>());
5283 }
5284
5285 return InternalId;
5286}
5287
5288llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
5289 return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
5290}
5291
5292llvm::Metadata *
5293CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) {
5294 return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
5295}
5296
5297// Generalize pointer types to a void pointer with the qualifiers of the
5298// originally pointed-to type, e.g. 'const char *' and 'char * const *'
5299// generalize to 'const void *' while 'char *' and 'const char **' generalize to
5300// 'void *'.
5301static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
5302 if (!Ty->isPointerType())
5303 return Ty;
5304
5305 return Ctx.getPointerType(
5306 QualType(Ctx.VoidTy).withCVRQualifiers(
5307 Ty->getPointeeType().getCVRQualifiers()));
5308}
5309
5310// Apply type generalization to a FunctionType's return and argument types
5311static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
5312 if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
5313 SmallVector<QualType, 8> GeneralizedParams;
5314 for (auto &Param : FnType->param_types())
5315 GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
5316
5317 return Ctx.getFunctionType(
5318 GeneralizeType(Ctx, FnType->getReturnType()),
5319 GeneralizedParams, FnType->getExtProtoInfo());
5320 }
5321
5322 if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
5323 return Ctx.getFunctionNoProtoType(
5324 GeneralizeType(Ctx, FnType->getReturnType()));
5325
5326 llvm_unreachable("Encountered unknown FunctionType")::llvm::llvm_unreachable_internal("Encountered unknown FunctionType"
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 5326)
;
5327}
5328
5329llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
5330 return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T),
5331 GeneralizedMetadataIdMap, ".generalized");
5332}
5333
5334/// Returns whether this module needs the "all-vtables" type identifier.
5335bool CodeGenModule::NeedAllVtablesTypeId() const {
5336 // Returns true if at least one of vtable-based CFI checkers is enabled and
5337 // is not in the trapping mode.
5338 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
5339 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
5340 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
5341 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
5342 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
5343 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
5344 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
5345 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
5346}
5347
5348void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
5349 CharUnits Offset,
5350 const CXXRecordDecl *RD) {
5351 llvm::Metadata *MD =
5352 CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
5353 VTable->addTypeMetadata(Offset.getQuantity(), MD);
5354
5355 if (CodeGenOpts.SanitizeCfiCrossDso)
5356 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
5357 VTable->addTypeMetadata(Offset.getQuantity(),
5358 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
5359
5360 if (NeedAllVtablesTypeId()) {
5361 llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
5362 VTable->addTypeMetadata(Offset.getQuantity(), MD);
5363 }
5364}
5365
5366TargetAttr::ParsedTargetAttr CodeGenModule::filterFunctionTargetAttrs(const TargetAttr *TD) {
5367 assert(TD != nullptr)((TD != nullptr) ? static_cast<void> (0) : __assert_fail
("TD != nullptr", "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CodeGenModule.cpp"
, 5367, __PRETTY_FUNCTION__))
;
5368 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
5369
5370 ParsedAttr.Features.erase(
5371 llvm::remove_if(ParsedAttr.Features,
5372 [&](const std::string &Feat) {
5373 return !Target.isValidFeatureName(
5374 StringRef{Feat}.substr(1));
5375 }),
5376 ParsedAttr.Features.end());
5377 return ParsedAttr;
5378}
5379
5380
5381// Fills in the supplied string map with the set of target features for the
5382// passed in function.
5383void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
5384 const FunctionDecl *FD) {
5385 StringRef TargetCPU = Target.getTargetOpts().CPU;
5386 if (const auto *TD = FD->getAttr<TargetAttr>()) {
5387 TargetAttr::ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD);
5388
5389 // Make a copy of the features as passed on the command line into the
5390 // beginning of the additional features from the function to override.
5391 ParsedAttr.Features.insert(ParsedAttr.Features.begin(),
5392 Target.getTargetOpts().FeaturesAsWritten.begin(),
5393 Target.getTargetOpts().FeaturesAsWritten.end());
5394
5395 if (ParsedAttr.Architecture != "" &&
5396 Target.isValidCPUName(ParsedAttr.Architecture))
5397 TargetCPU = ParsedAttr.Architecture;
5398
5399 // Now populate the feature map, first with the TargetCPU which is either
5400 // the default or a new one from the target attribute string. Then we'll use
5401 // the passed in features (FeaturesAsWritten) along with the new ones from
5402 // the attribute.
5403 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
5404 ParsedAttr.Features);
5405 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
5406 llvm::SmallVector<StringRef, 32> FeaturesTmp;
5407 Target.getCPUSpecificCPUDispatchFeatures(SD->getCurCPUName()->getName(),
5408 FeaturesTmp);
5409 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
5410 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, Features);
5411 } else {
5412 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
5413 Target.getTargetOpts().Features);
5414 }
5415}
5416
5417llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
5418 if (!SanStats)
5419 SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
5420
5421 return *SanStats;
5422}
5423llvm::Value *
5424CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
5425 CodeGenFunction &CGF) {
5426 llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
5427 auto SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
5428 auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
5429 return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
5430 "__translate_sampler_initializer"),
5431 {C});
5432}

/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/include/clang/AST/GlobalDecl.h

1//===- GlobalDecl.h - Global declaration holder -----------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// A GlobalDecl can hold either a regular variable/function or a C++ ctor/dtor
11// together with its type.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_AST_GLOBALDECL_H
16#define LLVM_CLANG_AST_GLOBALDECL_H
17
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/DeclOpenMP.h"
21#include "clang/Basic/ABI.h"
22#include "clang/Basic/LLVM.h"
23#include "llvm/ADT/DenseMapInfo.h"
24#include "llvm/ADT/PointerIntPair.h"
25#include "llvm/Support/Casting.h"
26#include "llvm/Support/type_traits.h"
27#include <cassert>
28
29namespace clang {
30
31/// GlobalDecl - represents a global declaration. This can either be a
32/// CXXConstructorDecl and the constructor type (Base, Complete).
33/// a CXXDestructorDecl and the destructor type (Base, Complete) or
34/// a VarDecl, a FunctionDecl or a BlockDecl.
35class GlobalDecl {
36 llvm::PointerIntPair<const Decl *, 2> Value;
37
38 void Init(const Decl *D) {
39 assert(!isa<CXXConstructorDecl>(D) && "Use other ctor with ctor decls!")((!isa<CXXConstructorDecl>(D) && "Use other ctor with ctor decls!"
) ? static_cast<void> (0) : __assert_fail ("!isa<CXXConstructorDecl>(D) && \"Use other ctor with ctor decls!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/include/clang/AST/GlobalDecl.h"
, 39, __PRETTY_FUNCTION__))
;
40 assert(!isa<CXXDestructorDecl>(D) && "Use other ctor with dtor decls!")((!isa<CXXDestructorDecl>(D) && "Use other ctor with dtor decls!"
) ? static_cast<void> (0) : __assert_fail ("!isa<CXXDestructorDecl>(D) && \"Use other ctor with dtor decls!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/include/clang/AST/GlobalDecl.h"
, 40, __PRETTY_FUNCTION__))
;
41
42 Value.setPointer(D);
43 }
44
45public:
46 GlobalDecl() = default;
47 GlobalDecl(const VarDecl *D) { Init(D);}
48 GlobalDecl(const FunctionDecl *D) { Init(D); }
49 GlobalDecl(const BlockDecl *D) { Init(D); }
50 GlobalDecl(const CapturedDecl *D) { Init(D); }
51 GlobalDecl(const ObjCMethodDecl *D) { Init(D); }
52 GlobalDecl(const OMPDeclareReductionDecl *D) { Init(D); }
53 GlobalDecl(const CXXConstructorDecl *D, CXXCtorType Type) : Value(D, Type) {}
54 GlobalDecl(const CXXDestructorDecl *D, CXXDtorType Type) : Value(D, Type) {}
55
56 GlobalDecl getCanonicalDecl() const {
57 GlobalDecl CanonGD;
58 CanonGD.Value.setPointer(Value.getPointer()->getCanonicalDecl());
59 CanonGD.Value.setInt(Value.getInt());
60
61 return CanonGD;
62 }
63
64 const Decl *getDecl() const { return Value.getPointer(); }
24
Calling 'PointerIntPair::getPointer'
38
Returning from 'PointerIntPair::getPointer'
39
Returning pointer
65
66 CXXCtorType getCtorType() const {
67 assert(isa<CXXConstructorDecl>(getDecl()) && "Decl is not a ctor!")((isa<CXXConstructorDecl>(getDecl()) && "Decl is not a ctor!"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXConstructorDecl>(getDecl()) && \"Decl is not a ctor!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/include/clang/AST/GlobalDecl.h"
, 67, __PRETTY_FUNCTION__))
;
68 return static_cast<CXXCtorType>(Value.getInt());
69 }
70
71 CXXDtorType getDtorType() const {
72 assert(isa<CXXDestructorDecl>(getDecl()) && "Decl is not a dtor!")((isa<CXXDestructorDecl>(getDecl()) && "Decl is not a dtor!"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXDestructorDecl>(getDecl()) && \"Decl is not a dtor!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/include/clang/AST/GlobalDecl.h"
, 72, __PRETTY_FUNCTION__))
;
73 return static_cast<CXXDtorType>(Value.getInt());
74 }
75
76 friend bool operator==(const GlobalDecl &LHS, const GlobalDecl &RHS) {
77 return LHS.Value == RHS.Value;
78 }
79
80 void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
81
82 static GlobalDecl getFromOpaquePtr(void *P) {
83 GlobalDecl GD;
84 GD.Value.setFromOpaqueValue(P);
85 return GD;
86 }
87
88 GlobalDecl getWithDecl(const Decl *D) {
89 GlobalDecl Result(*this);
90 Result.Value.setPointer(D);
91 return Result;
92 }
93};
94
95} // namespace clang
96
97namespace llvm {
98
99 template<> struct DenseMapInfo<clang::GlobalDecl> {
100 static inline clang::GlobalDecl getEmptyKey() {
101 return clang::GlobalDecl();
102 }
103
104 static inline clang::GlobalDecl getTombstoneKey() {
105 return clang::GlobalDecl::
106 getFromOpaquePtr(reinterpret_cast<void*>(-1));
107 }
108
109 static unsigned getHashValue(clang::GlobalDecl GD) {
110 return DenseMapInfo<void*>::getHashValue(GD.getAsOpaquePtr());
111 }
112
113 static bool isEqual(clang::GlobalDecl LHS,
114 clang::GlobalDecl RHS) {
115 return LHS == RHS;
116 }
117 };
118
119 // GlobalDecl isn't *technically* a POD type. However, its copy constructor,
120 // copy assignment operator, and destructor are all trivial.
121 template <>
122 struct isPodLike<clang::GlobalDecl> {
123 static const bool value = true;
124 };
125
126} // namespace llvm
127
128#endif // LLVM_CLANG_AST_GLOBALDECL_H

/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/ADT/PointerIntPair.h

1//===- llvm/ADT/PointerIntPair.h - Pair for pointer and int -----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the PointerIntPair class.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_ADT_POINTERINTPAIR_H
15#define LLVM_ADT_POINTERINTPAIR_H
16
17#include "llvm/Support/PointerLikeTypeTraits.h"
18#include <cassert>
19#include <cstdint>
20#include <limits>
21
22namespace llvm {
23
24template <typename T> struct DenseMapInfo;
25template <typename PointerT, unsigned IntBits, typename PtrTraits>
26struct PointerIntPairInfo;
27
28/// PointerIntPair - This class implements a pair of a pointer and small
29/// integer. It is designed to represent this in the space required by one
30/// pointer by bitmangling the integer into the low part of the pointer. This
31/// can only be done for small integers: typically up to 3 bits, but it depends
32/// on the number of bits available according to PointerLikeTypeTraits for the
33/// type.
34///
35/// Note that PointerIntPair always puts the IntVal part in the highest bits
36/// possible. For example, PointerIntPair<void*, 1, bool> will put the bit for
37/// the bool into bit #2, not bit #0, which allows the low two bits to be used
38/// for something else. For example, this allows:
39/// PointerIntPair<PointerIntPair<void*, 1, bool>, 1, bool>
40/// ... and the two bools will land in different bits.
41template <typename PointerTy, unsigned IntBits, typename IntType = unsigned,
42 typename PtrTraits = PointerLikeTypeTraits<PointerTy>,
43 typename Info = PointerIntPairInfo<PointerTy, IntBits, PtrTraits>>
44class PointerIntPair {
45 intptr_t Value = 0;
46
47public:
48 constexpr PointerIntPair() = default;
49
50 PointerIntPair(PointerTy PtrVal, IntType IntVal) {
51 setPointerAndInt(PtrVal, IntVal);
52 }
53
54 explicit PointerIntPair(PointerTy PtrVal) { initWithPointer(PtrVal); }
55
56 PointerTy getPointer() const { return Info::getPointer(Value); }
25
Calling 'PointerIntPairInfo::getPointer'
35
Returning from 'PointerIntPairInfo::getPointer'
36
Returning pointer
37
Assigning value
57
58 IntType getInt() const { return (IntType)Info::getInt(Value); }
59
60 void setPointer(PointerTy PtrVal) {
61 Value = Info::updatePointer(Value, PtrVal);
62 }
63
64 void setInt(IntType IntVal) {
65 Value = Info::updateInt(Value, static_cast<intptr_t>(IntVal));
66 }
67
68 void initWithPointer(PointerTy PtrVal) {
69 Value = Info::updatePointer(0, PtrVal);
70 }
71
72 void setPointerAndInt(PointerTy PtrVal, IntType IntVal) {
73 Value = Info::updateInt(Info::updatePointer(0, PtrVal),
74 static_cast<intptr_t>(IntVal));
75 }
76
77 PointerTy const *getAddrOfPointer() const {
78 return const_cast<PointerIntPair *>(this)->getAddrOfPointer();
79 }
80
81 PointerTy *getAddrOfPointer() {
82 assert(Value == reinterpret_cast<intptr_t>(getPointer()) &&((Value == reinterpret_cast<intptr_t>(getPointer()) &&
"Can only return the address if IntBits is cleared and " "PtrTraits doesn't change the pointer"
) ? static_cast<void> (0) : __assert_fail ("Value == reinterpret_cast<intptr_t>(getPointer()) && \"Can only return the address if IntBits is cleared and \" \"PtrTraits doesn't change the pointer\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/ADT/PointerIntPair.h"
, 84, __PRETTY_FUNCTION__))
83 "Can only return the address if IntBits is cleared and "((Value == reinterpret_cast<intptr_t>(getPointer()) &&
"Can only return the address if IntBits is cleared and " "PtrTraits doesn't change the pointer"
) ? static_cast<void> (0) : __assert_fail ("Value == reinterpret_cast<intptr_t>(getPointer()) && \"Can only return the address if IntBits is cleared and \" \"PtrTraits doesn't change the pointer\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/ADT/PointerIntPair.h"
, 84, __PRETTY_FUNCTION__))
84 "PtrTraits doesn't change the pointer")((Value == reinterpret_cast<intptr_t>(getPointer()) &&
"Can only return the address if IntBits is cleared and " "PtrTraits doesn't change the pointer"
) ? static_cast<void> (0) : __assert_fail ("Value == reinterpret_cast<intptr_t>(getPointer()) && \"Can only return the address if IntBits is cleared and \" \"PtrTraits doesn't change the pointer\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/ADT/PointerIntPair.h"
, 84, __PRETTY_FUNCTION__))
;
85 return reinterpret_cast<PointerTy *>(&Value);
86 }
87
88 void *getOpaqueValue() const { return reinterpret_cast<void *>(Value); }
89
90 void setFromOpaqueValue(void *Val) {
91 Value = reinterpret_cast<intptr_t>(Val);
92 }
93
94 static PointerIntPair getFromOpaqueValue(void *V) {
95 PointerIntPair P;
96 P.setFromOpaqueValue(V);
97 return P;
98 }
99
100 // Allow PointerIntPairs to be created from const void * if and only if the
101 // pointer type could be created from a const void *.
102 static PointerIntPair getFromOpaqueValue(const void *V) {
103 (void)PtrTraits::getFromVoidPointer(V);
104 return getFromOpaqueValue(const_cast<void *>(V));
105 }
106
107 bool operator==(const PointerIntPair &RHS) const {
108 return Value == RHS.Value;
109 }
110
111 bool operator!=(const PointerIntPair &RHS) const {
112 return Value != RHS.Value;
113 }
114
115 bool operator<(const PointerIntPair &RHS) const { return Value < RHS.Value; }
116 bool operator>(const PointerIntPair &RHS) const { return Value > RHS.Value; }
117
118 bool operator<=(const PointerIntPair &RHS) const {
119 return Value <= RHS.Value;
120 }
121
122 bool operator>=(const PointerIntPair &RHS) const {
123 return Value >= RHS.Value;
124 }
125};
126
127template <typename PointerT, unsigned IntBits, typename PtrTraits>
128struct PointerIntPairInfo {
129 static_assert(PtrTraits::NumLowBitsAvailable <
130 std::numeric_limits<uintptr_t>::digits,
131 "cannot use a pointer type that has all bits free");
132 static_assert(IntBits <= PtrTraits::NumLowBitsAvailable,
133 "PointerIntPair with integer size too large for pointer");
134 enum : uintptr_t {
135 /// PointerBitMask - The bits that come from the pointer.
136 PointerBitMask =
137 ~(uintptr_t)(((intptr_t)1 << PtrTraits::NumLowBitsAvailable) - 1),
138
139 /// IntShift - The number of low bits that we reserve for other uses, and
140 /// keep zero.
141 IntShift = (uintptr_t)PtrTraits::NumLowBitsAvailable - IntBits,
142
143 /// IntMask - This is the unshifted mask for valid bits of the int type.
144 IntMask = (uintptr_t)(((intptr_t)1 << IntBits) - 1),
145
146 // ShiftedIntMask - This is the bits for the integer shifted in place.
147 ShiftedIntMask = (uintptr_t)(IntMask << IntShift)
148 };
149
150 static PointerT getPointer(intptr_t Value) {
151 return PtrTraits::getFromVoidPointer(
26
Calling 'PointerLikeTypeTraits::getFromVoidPointer'
33
Returning from 'PointerLikeTypeTraits::getFromVoidPointer'
34
Returning pointer
152 reinterpret_cast<void *>(Value & PointerBitMask));
153 }
154
155 static intptr_t getInt(intptr_t Value) {
156 return (Value >> IntShift) & IntMask;
157 }
158
159 static intptr_t updatePointer(intptr_t OrigValue, PointerT Ptr) {
160 intptr_t PtrWord =
161 reinterpret_cast<intptr_t>(PtrTraits::getAsVoidPointer(Ptr));
162 assert((PtrWord & ~PointerBitMask) == 0 &&(((PtrWord & ~PointerBitMask) == 0 && "Pointer is not sufficiently aligned"
) ? static_cast<void> (0) : __assert_fail ("(PtrWord & ~PointerBitMask) == 0 && \"Pointer is not sufficiently aligned\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/ADT/PointerIntPair.h"
, 163, __PRETTY_FUNCTION__))
163 "Pointer is not sufficiently aligned")(((PtrWord & ~PointerBitMask) == 0 && "Pointer is not sufficiently aligned"
) ? static_cast<void> (0) : __assert_fail ("(PtrWord & ~PointerBitMask) == 0 && \"Pointer is not sufficiently aligned\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/ADT/PointerIntPair.h"
, 163, __PRETTY_FUNCTION__))
;
164 // Preserve all low bits, just update the pointer.
165 return PtrWord | (OrigValue & ~PointerBitMask);
166 }
167
168 static intptr_t updateInt(intptr_t OrigValue, intptr_t Int) {
169 intptr_t IntWord = static_cast<intptr_t>(Int);
170 assert((IntWord & ~IntMask) == 0 && "Integer too large for field")(((IntWord & ~IntMask) == 0 && "Integer too large for field"
) ? static_cast<void> (0) : __assert_fail ("(IntWord & ~IntMask) == 0 && \"Integer too large for field\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/ADT/PointerIntPair.h"
, 170, __PRETTY_FUNCTION__))
;
171
172 // Preserve all bits other than the ones we are updating.
173 return (OrigValue & ~ShiftedIntMask) | IntWord << IntShift;
174 }
175};
176
177template <typename T> struct isPodLike;
178template <typename PointerTy, unsigned IntBits, typename IntType>
179struct isPodLike<PointerIntPair<PointerTy, IntBits, IntType>> {
180 static const bool value = true;
181};
182
183// Provide specialization of DenseMapInfo for PointerIntPair.
184template <typename PointerTy, unsigned IntBits, typename IntType>
185struct DenseMapInfo<PointerIntPair<PointerTy, IntBits, IntType>> {
186 using Ty = PointerIntPair<PointerTy, IntBits, IntType>;
187
188 static Ty getEmptyKey() {
189 uintptr_t Val = static_cast<uintptr_t>(-1);
190 Val <<= PointerLikeTypeTraits<Ty>::NumLowBitsAvailable;
191 return Ty::getFromOpaqueValue(reinterpret_cast<void *>(Val));
192 }
193
194 static Ty getTombstoneKey() {
195 uintptr_t Val = static_cast<uintptr_t>(-2);
196 Val <<= PointerLikeTypeTraits<PointerTy>::NumLowBitsAvailable;
197 return Ty::getFromOpaqueValue(reinterpret_cast<void *>(Val));
198 }
199
200 static unsigned getHashValue(Ty V) {
201 uintptr_t IV = reinterpret_cast<uintptr_t>(V.getOpaqueValue());
202 return unsigned(IV) ^ unsigned(IV >> 9);
203 }
204
205 static bool isEqual(const Ty &LHS, const Ty &RHS) { return LHS == RHS; }
206};
207
208// Teach SmallPtrSet that PointerIntPair is "basically a pointer".
209template <typename PointerTy, unsigned IntBits, typename IntType,
210 typename PtrTraits>
211struct PointerLikeTypeTraits<
212 PointerIntPair<PointerTy, IntBits, IntType, PtrTraits>> {
213 static inline void *
214 getAsVoidPointer(const PointerIntPair<PointerTy, IntBits, IntType> &P) {
215 return P.getOpaqueValue();
216 }
217
218 static inline PointerIntPair<PointerTy, IntBits, IntType>
219 getFromVoidPointer(void *P) {
220 return PointerIntPair<PointerTy, IntBits, IntType>::getFromOpaqueValue(P);
221 }
222
223 static inline PointerIntPair<PointerTy, IntBits, IntType>
224 getFromVoidPointer(const void *P) {
225 return PointerIntPair<PointerTy, IntBits, IntType>::getFromOpaqueValue(P);
226 }
227
228 enum { NumLowBitsAvailable = PtrTraits::NumLowBitsAvailable - IntBits };
229};
230
231} // end namespace llvm
232
233#endif // LLVM_ADT_POINTERINTPAIR_H

/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/PointerLikeTypeTraits.h

1//===- llvm/Support/PointerLikeTypeTraits.h - Pointer Traits ----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the PointerLikeTypeTraits class. This allows data
11// structures to reason about pointers and other things that are pointer sized.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_SUPPORT_POINTERLIKETYPETRAITS_H
16#define LLVM_SUPPORT_POINTERLIKETYPETRAITS_H
17
18#include "llvm/Support/DataTypes.h"
19#include <assert.h>
20#include <type_traits>
21
22namespace llvm {
23
24/// A traits type that is used to handle pointer types and things that are just
25/// wrappers for pointers as a uniform entity.
26template <typename T> struct PointerLikeTypeTraits;
27
28namespace detail {
29/// A tiny meta function to compute the log2 of a compile time constant.
30template <size_t N>
31struct ConstantLog2
32 : std::integral_constant<size_t, ConstantLog2<N / 2>::value + 1> {};
33template <> struct ConstantLog2<1> : std::integral_constant<size_t, 0> {};
34
35// Provide a trait to check if T is pointer-like.
36template <typename T, typename U = void<