Bug Summary

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

Annotated Source Code

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

/build/llvm-toolchain-snapshot-6.0~svn318631/include/llvm/Support/Casting.h

1//===- llvm/Support/Casting.h - Allow flexible, checked, casts --*- 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 isa<X>(), cast<X>(), dyn_cast<X>(), cast_or_null<X>(),
11// and dyn_cast_or_null<X>() templates.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_SUPPORT_CASTING_H
16#define LLVM_SUPPORT_CASTING_H
17
18#include "llvm/Support/Compiler.h"
19#include "llvm/Support/type_traits.h"
20#include <cassert>
21#include <memory>
22#include <type_traits>
23
24namespace llvm {
25
26//===----------------------------------------------------------------------===//
27// isa<x> Support Templates
28//===----------------------------------------------------------------------===//
29
30// Define a template that can be specialized by smart pointers to reflect the
31// fact that they are automatically dereferenced, and are not involved with the
32// template selection process... the default implementation is a noop.
33//
34template<typename From> struct simplify_type {
35 using SimpleType = From; // The real type this represents...
36
37 // An accessor to get the real value...
38 static SimpleType &getSimplifiedValue(From &Val) { return Val; }
39};
40
41template<typename From> struct simplify_type<const From> {
42 using NonConstSimpleType = typename simplify_type<From>::SimpleType;
43 using SimpleType =
44 typename add_const_past_pointer<NonConstSimpleType>::type;
45 using RetType =
46 typename add_lvalue_reference_if_not_pointer<SimpleType>::type;
47
48 static RetType getSimplifiedValue(const From& Val) {
49 return simplify_type<From>::getSimplifiedValue(const_cast<From&>(Val));
5
Calling 'simplify_type::getSimplifiedValue'
6
Returning from 'simplify_type::getSimplifiedValue'
50 }
51};
52
53// The core of the implementation of isa<X> is here; To and From should be
54// the names of classes. This template can be specialized to customize the
55// implementation of isa<> without rewriting it from scratch.
56template <typename To, typename From, typename Enabler = void>
57struct isa_impl {
58 static inline bool doit(const From &Val) {
59 return To::classof(&Val);
12
Calling 'VarDecl::classof'
19
Returning from 'VarDecl::classof'
60 }
61};
62
63/// \brief Always allow upcasts, and perform no dynamic check for them.
64template <typename To, typename From>
65struct isa_impl<
66 To, From, typename std::enable_if<std::is_base_of<To, From>::value>::type> {
67 static inline bool doit(const From &) { return true; }
68};
69
70template <typename To, typename From> struct isa_impl_cl {
71 static inline bool doit(const From &Val) {
72 return isa_impl<To, From>::doit(Val);
73 }
74};
75
76template <typename To, typename From> struct isa_impl_cl<To, const From> {
77 static inline bool doit(const From &Val) {
78 return isa_impl<To, From>::doit(Val);
79 }
80};
81
82template <typename To, typename From>
83struct isa_impl_cl<To, const std::unique_ptr<From>> {
84 static inline bool doit(const std::unique_ptr<From> &Val) {
85 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-6.0~svn318631/include/llvm/Support/Casting.h"
, 85, __extension__ __PRETTY_FUNCTION__))
;
86 return isa_impl_cl<To, From>::doit(*Val);
87 }
88};
89
90template <typename To, typename From> struct isa_impl_cl<To, From*> {
91 static inline bool doit(const From *Val) {
92 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-6.0~svn318631/include/llvm/Support/Casting.h"
, 92, __extension__ __PRETTY_FUNCTION__))
;
93 return isa_impl<To, From>::doit(*Val);
94 }
95};
96
97template <typename To, typename From> struct isa_impl_cl<To, From*const> {
98 static inline bool doit(const From *Val) {
99 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-6.0~svn318631/include/llvm/Support/Casting.h"
, 99, __extension__ __PRETTY_FUNCTION__))
;
100 return isa_impl<To, From>::doit(*Val);
101 }
102};
103
104template <typename To, typename From> struct isa_impl_cl<To, const From*> {
105 static inline bool doit(const From *Val) {
106 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-6.0~svn318631/include/llvm/Support/Casting.h"
, 106, __extension__ __PRETTY_FUNCTION__))
;
10
Within the expansion of the macro 'assert':
a
Assuming 'Val' is non-null
107 return isa_impl<To, From>::doit(*Val);
11
Calling 'isa_impl::doit'
20
Returning from 'isa_impl::doit'
108 }
109};
110
111template <typename To, typename From> struct isa_impl_cl<To, const From*const> {
112 static inline bool doit(const From *Val) {
113 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-6.0~svn318631/include/llvm/Support/Casting.h"
, 113, __extension__ __PRETTY_FUNCTION__))
;
114 return isa_impl<To, From>::doit(*Val);
115 }
116};
117
118template<typename To, typename From, typename SimpleFrom>
119struct isa_impl_wrap {
120 // When From != SimplifiedType, we can simplify the type some more by using
121 // the simplify_type template.
122 static bool doit(const From &Val) {
123 return isa_impl_wrap<To, SimpleFrom,
8
Calling 'isa_impl_wrap::doit'
22
Returning from 'isa_impl_wrap::doit'
124 typename simplify_type<SimpleFrom>::SimpleType>::doit(
125 simplify_type<const From>::getSimplifiedValue(Val));
4
Calling 'simplify_type::getSimplifiedValue'
7
Returning from 'simplify_type::getSimplifiedValue'
126 }
127};
128
129template<typename To, typename FromTy>
130struct isa_impl_wrap<To, FromTy, FromTy> {
131 // When From == SimpleType, we are as simple as we are going to get.
132 static bool doit(const FromTy &Val) {
133 return isa_impl_cl<To,FromTy>::doit(Val);
9
Calling 'isa_impl_cl::doit'
21
Returning from 'isa_impl_cl::doit'
134 }
135};
136
137// isa<X> - Return true if the parameter to the template is an instance of the
138// template type argument. Used like this:
139//
140// if (isa<Type>(myVal)) { ... }
141//
142template <class X, class Y> LLVM_NODISCARD[[clang::warn_unused_result]] inline bool isa(const Y &Val) {
143 return isa_impl_wrap<X, const Y,
3
Calling 'isa_impl_wrap::doit'
23
Returning from 'isa_impl_wrap::doit'
144 typename simplify_type<const Y>::SimpleType>::doit(Val);
145}
146
147//===----------------------------------------------------------------------===//
148// cast<x> Support Templates
149//===----------------------------------------------------------------------===//
150
151template<class To, class From> struct cast_retty;
152
153// Calculate what type the 'cast' function should return, based on a requested
154// type of To and a source type of From.
155template<class To, class From> struct cast_retty_impl {
156 using ret_type = To &; // Normal case, return Ty&
157};
158template<class To, class From> struct cast_retty_impl<To, const From> {
159 using ret_type = const To &; // Normal case, return Ty&
160};
161
162template<class To, class From> struct cast_retty_impl<To, From*> {
163 using ret_type = To *; // Pointer arg case, return Ty*
164};
165
166template<class To, class From> struct cast_retty_impl<To, const From*> {
167 using ret_type = const To *; // Constant pointer arg case, return const Ty*
168};
169
170template<class To, class From> struct cast_retty_impl<To, const From*const> {
171 using ret_type = const To *; // Constant pointer arg case, return const Ty*
172};
173
174template <class To, class From>
175struct cast_retty_impl<To, std::unique_ptr<From>> {
176private:
177 using PointerType = typename cast_retty_impl<To, From *>::ret_type;
178 using ResultType = typename std::remove_pointer<PointerType>::type;
179
180public:
181 using ret_type = std::unique_ptr<ResultType>;
182};
183
184template<class To, class From, class SimpleFrom>
185struct cast_retty_wrap {
186 // When the simplified type and the from type are not the same, use the type
187 // simplifier to reduce the type, then reuse cast_retty_impl to get the
188 // resultant type.
189 using ret_type = typename cast_retty<To, SimpleFrom>::ret_type;
190};
191
192template<class To, class FromTy>
193struct cast_retty_wrap<To, FromTy, FromTy> {
194 // When the simplified type is equal to the from type, use it directly.
195 using ret_type = typename cast_retty_impl<To,FromTy>::ret_type;
196};
197
198template<class To, class From>
199struct cast_retty {
200 using ret_type = typename cast_retty_wrap<
201 To, From, typename simplify_type<From>::SimpleType>::ret_type;
202};
203
204// Ensure the non-simple values are converted using the simplify_type template
205// that may be specialized by smart pointers...
206//
207template<class To, class From, class SimpleFrom> struct cast_convert_val {
208 // This is not a simple type, use the template to simplify it...
209 static typename cast_retty<To, From>::ret_type doit(From &Val) {
210 return cast_convert_val<To, SimpleFrom,
211 typename simplify_type<SimpleFrom>::SimpleType>::doit(
212 simplify_type<From>::getSimplifiedValue(Val));
213 }
214};
215
216template<class To, class FromTy> struct cast_convert_val<To,FromTy,FromTy> {
217 // This _is_ a simple type, just cast it.
218 static typename cast_retty<To, FromTy>::ret_type doit(const FromTy &Val) {
219 typename cast_retty<To, FromTy>::ret_type Res2
220 = (typename cast_retty<To, FromTy>::ret_type)const_cast<FromTy&>(Val);
221 return Res2;
222 }
223};
224
225template <class X> struct is_simple_type {
226 static const bool value =
227 std::is_same<X, typename simplify_type<X>::SimpleType>::value;
228};
229
230// cast<X> - Return the argument parameter cast to the specified type. This
231// casting operator asserts that the type is correct, so it does not return null
232// on failure. It does not allow a null argument (use cast_or_null for that).
233// It is typically used like this:
234//
235// cast<Instruction>(myVal)->getParent()
236//
237template <class X, class Y>
238inline typename std::enable_if<!is_simple_type<Y>::value,
239 typename cast_retty<X, const Y>::ret_type>::type
240cast(const Y &Val) {
241 assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318631/include/llvm/Support/Casting.h"
, 241, __extension__ __PRETTY_FUNCTION__))
;
242 return cast_convert_val<
243 X, const Y, typename simplify_type<const Y>::SimpleType>::doit(Val);
244}
245
246template <class X, class Y>
247inline typename cast_retty<X, Y>::ret_type cast(Y &Val) {
248 assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318631/include/llvm/Support/Casting.h"
, 248, __extension__ __PRETTY_FUNCTION__))
;
249 return cast_convert_val<X, Y,
250 typename simplify_type<Y>::SimpleType>::doit(Val);
251}
252
253template <class X, class Y>
254inline typename cast_retty<X, Y *>::ret_type cast(Y *Val) {
255 assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318631/include/llvm/Support/Casting.h"
, 255, __extension__ __PRETTY_FUNCTION__))
;
2
Within the expansion of the macro 'assert':
a
Calling 'isa'
b
Returning from 'isa'
256 return cast_convert_val<X, Y*,
24
Calling 'cast_convert_val::doit'
25
Returning from 'cast_convert_val::doit'
257 typename simplify_type<Y*>::SimpleType>::doit(Val);
258}
259
260template <class X, class Y>
261inline typename cast_retty<X, std::unique_ptr<Y>>::ret_type
262cast(std::unique_ptr<Y> &&Val) {
263 assert(isa<X>(Val.get()) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val.get()) &&
"cast<Ty>() argument of incompatible type!") ? void (0
) : __assert_fail ("isa<X>(Val.get()) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318631/include/llvm/Support/Casting.h"
, 263, __extension__ __PRETTY_FUNCTION__))
;
264 using ret_type = typename cast_retty<X, std::unique_ptr<Y>>::ret_type;
265 return ret_type(
266 cast_convert_val<X, Y *, typename simplify_type<Y *>::SimpleType>::doit(
267 Val.release()));
268}
269
270// cast_or_null<X> - Functionally identical to cast, except that a null value is
271// accepted.
272//
273template <class X, class Y>
274LLVM_NODISCARD[[clang::warn_unused_result]] inline
275 typename std::enable_if<!is_simple_type<Y>::value,
276 typename cast_retty<X, const Y>::ret_type>::type
277 cast_or_null(const Y &Val) {
278 if (!Val)
279 return nullptr;
280 assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318631/include/llvm/Support/Casting.h"
, 280, __extension__ __PRETTY_FUNCTION__))
;
281 return cast<X>(Val);
282}
283
284template <class X, class Y>
285LLVM_NODISCARD[[clang::warn_unused_result]] inline
286 typename std::enable_if<!is_simple_type<Y>::value,
287 typename cast_retty<X, Y>::ret_type>::type
288 cast_or_null(Y &Val) {
289 if (!Val)
290 return nullptr;
291 assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318631/include/llvm/Support/Casting.h"
, 291, __extension__ __PRETTY_FUNCTION__))
;
292 return cast<X>(Val);
293}
294
295template <class X, class Y>
296LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type
297cast_or_null(Y *Val) {
298 if (!Val) return nullptr;
299 assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318631/include/llvm/Support/Casting.h"
, 299, __extension__ __PRETTY_FUNCTION__))
;
300 return cast<X>(Val);
301}
302
303template <class X, class Y>
304inline typename cast_retty<X, std::unique_ptr<Y>>::ret_type
305cast_or_null(std::unique_ptr<Y> &&Val) {
306 if (!Val)
307 return nullptr;
308 return cast<X>(std::move(Val));
309}
310
311// dyn_cast<X> - Return the argument parameter cast to the specified type. This
312// casting operator returns null if the argument is of the wrong type, so it can
313// be used to test for a type as well as cast if successful. This should be
314// used in the context of an if statement like this:
315//
316// if (const Instruction *I = dyn_cast<Instruction>(myVal)) { ... }
317//
318
319template <class X, class Y>
320LLVM_NODISCARD[[clang::warn_unused_result]] inline
321 typename std::enable_if<!is_simple_type<Y>::value,
322 typename cast_retty<X, const Y>::ret_type>::type
323 dyn_cast(const Y &Val) {
324 return isa<X>(Val) ? cast<X>(Val) : nullptr;
325}
326
327template <class X, class Y>
328LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y>::ret_type dyn_cast(Y &Val) {
329 return isa<X>(Val) ? cast<X>(Val) : nullptr;
330}
331
332template <class X, class Y>
333LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type dyn_cast(Y *Val) {
334 return isa<X>(Val) ? cast<X>(Val) : nullptr;
335}
336
337// dyn_cast_or_null<X> - Functionally identical to dyn_cast, except that a null
338// value is accepted.
339//
340template <class X, class Y>
341LLVM_NODISCARD[[clang::warn_unused_result]] inline
342 typename std::enable_if<!is_simple_type<Y>::value,
343 typename cast_retty<X, const Y>::ret_type>::type
344 dyn_cast_or_null(const Y &Val) {
345 return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr;
346}
347
348template <class X, class Y>
349LLVM_NODISCARD[[clang::warn_unused_result]] inline
350 typename std::enable_if<!is_simple_type<Y>::value,
351 typename cast_retty<X, Y>::ret_type>::type
352 dyn_cast_or_null(Y &Val) {
353 return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr;
354}
355
356template <class X, class Y>
357LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type
358dyn_cast_or_null(Y *Val) {
359 return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr;
360}
361
362// unique_dyn_cast<X> - Given a unique_ptr<Y>, try to return a unique_ptr<X>,
363// taking ownership of the input pointer iff isa<X>(Val) is true. If the
364// cast is successful, From refers to nullptr on exit and the casted value
365// is returned. If the cast is unsuccessful, the function returns nullptr
366// and From is unchanged.
367template <class X, class Y>
368LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast(std::unique_ptr<Y> &Val)
369 -> decltype(cast<X>(Val)) {
370 if (!isa<X>(Val))
371 return nullptr;
372 return cast<X>(std::move(Val));
373}
374
375template <class X, class Y>
376LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast(std::unique_ptr<Y> &&Val)
377 -> decltype(cast<X>(Val)) {
378 return unique_dyn_cast<X, Y>(Val);
379}
380
381// dyn_cast_or_null<X> - Functionally identical to unique_dyn_cast, except that
382// a null value is accepted.
383template <class X, class Y>
384LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast_or_null(std::unique_ptr<Y> &Val)
385 -> decltype(cast<X>(Val)) {
386 if (!Val)
387 return nullptr;
388 return unique_dyn_cast<X, Y>(Val);
389}
390
391template <class X, class Y>
392LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast_or_null(std::unique_ptr<Y> &&Val)
393 -> decltype(cast<X>(Val)) {
394 return unique_dyn_cast_or_null<X, Y>(Val);
395}
396
397} // end namespace llvm
398
399#endif // LLVM_SUPPORT_CASTING_H

/build/llvm-toolchain-snapshot-6.0~svn318631/tools/clang/include/clang/AST/Decl.h

1//===- Decl.h - Classes for representing declarations -----------*- 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 Decl subclasses.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_AST_DECL_H
15#define LLVM_CLANG_AST_DECL_H
16
17#include "clang/AST/APValue.h"
18#include "clang/AST/DeclBase.h"
19#include "clang/AST/DeclarationName.h"
20#include "clang/AST/ExternalASTSource.h"
21#include "clang/AST/NestedNameSpecifier.h"
22#include "clang/AST/Redeclarable.h"
23#include "clang/AST/Type.h"
24#include "clang/Basic/AddressSpaces.h"
25#include "clang/Basic/Diagnostic.h"
26#include "clang/Basic/IdentifierTable.h"
27#include "clang/Basic/LLVM.h"
28#include "clang/Basic/Linkage.h"
29#include "clang/Basic/OperatorKinds.h"
30#include "clang/Basic/PartialDiagnostic.h"
31#include "clang/Basic/PragmaKinds.h"
32#include "clang/Basic/SourceLocation.h"
33#include "clang/Basic/Specifiers.h"
34#include "clang/Basic/Visibility.h"
35#include "llvm/ADT/APSInt.h"
36#include "llvm/ADT/ArrayRef.h"
37#include "llvm/ADT/Optional.h"
38#include "llvm/ADT/PointerIntPair.h"
39#include "llvm/ADT/PointerUnion.h"
40#include "llvm/ADT/StringRef.h"
41#include "llvm/ADT/iterator_range.h"
42#include "llvm/Support/Casting.h"
43#include "llvm/Support/Compiler.h"
44#include "llvm/Support/TrailingObjects.h"
45#include <cassert>
46#include <cstddef>
47#include <cstdint>
48#include <string>
49#include <utility>
50
51namespace clang {
52
53class ASTContext;
54struct ASTTemplateArgumentListInfo;
55class Attr;
56class CompoundStmt;
57class DependentFunctionTemplateSpecializationInfo;
58class EnumDecl;
59class Expr;
60class FunctionTemplateDecl;
61class FunctionTemplateSpecializationInfo;
62class LabelStmt;
63class MemberSpecializationInfo;
64class Module;
65class NamespaceDecl;
66class ParmVarDecl;
67class RecordDecl;
68class Stmt;
69class StringLiteral;
70class TagDecl;
71class TemplateArgumentList;
72class TemplateArgumentListInfo;
73class TemplateParameterList;
74class TypeAliasTemplateDecl;
75class TypeLoc;
76class UnresolvedSetImpl;
77class VarTemplateDecl;
78
79/// \brief A container of type source information.
80///
81/// A client can read the relevant info using TypeLoc wrappers, e.g:
82/// @code
83/// TypeLoc TL = TypeSourceInfo->getTypeLoc();
84/// TL.getStartLoc().print(OS, SrcMgr);
85/// @endcode
86class TypeSourceInfo {
87 // Contains a memory block after the class, used for type source information,
88 // allocated by ASTContext.
89 friend class ASTContext;
90
91 QualType Ty;
92
93 TypeSourceInfo(QualType ty) : Ty(ty) {}
94
95public:
96 /// \brief Return the type wrapped by this type source info.
97 QualType getType() const { return Ty; }
98
99 /// \brief Return the TypeLoc wrapper for the type source info.
100 TypeLoc getTypeLoc() const; // implemented in TypeLoc.h
101
102 /// \brief Override the type stored in this TypeSourceInfo. Use with caution!
103 void overrideType(QualType T) { Ty = T; }
104};
105
106/// TranslationUnitDecl - The top declaration context.
107class TranslationUnitDecl : public Decl, public DeclContext {
108 ASTContext &Ctx;
109
110 /// The (most recently entered) anonymous namespace for this
111 /// translation unit, if one has been created.
112 NamespaceDecl *AnonymousNamespace = nullptr;
113
114 explicit TranslationUnitDecl(ASTContext &ctx);
115
116 virtual void anchor();
117
118public:
119 ASTContext &getASTContext() const { return Ctx; }
120
121 NamespaceDecl *getAnonymousNamespace() const { return AnonymousNamespace; }
122 void setAnonymousNamespace(NamespaceDecl *D) { AnonymousNamespace = D; }
123
124 static TranslationUnitDecl *Create(ASTContext &C);
125
126 // Implement isa/cast/dyncast/etc.
127 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
128 static bool classofKind(Kind K) { return K == TranslationUnit; }
129 static DeclContext *castToDeclContext(const TranslationUnitDecl *D) {
130 return static_cast<DeclContext *>(const_cast<TranslationUnitDecl*>(D));
131 }
132 static TranslationUnitDecl *castFromDeclContext(const DeclContext *DC) {
133 return static_cast<TranslationUnitDecl *>(const_cast<DeclContext*>(DC));
134 }
135};
136
137/// \brief Represents a `#pragma comment` line. Always a child of
138/// TranslationUnitDecl.
139class PragmaCommentDecl final
140 : public Decl,
141 private llvm::TrailingObjects<PragmaCommentDecl, char> {
142 friend class ASTDeclReader;
143 friend class ASTDeclWriter;
144 friend TrailingObjects;
145
146 PragmaMSCommentKind CommentKind;
147
148 PragmaCommentDecl(TranslationUnitDecl *TU, SourceLocation CommentLoc,
149 PragmaMSCommentKind CommentKind)
150 : Decl(PragmaComment, TU, CommentLoc), CommentKind(CommentKind) {}
151
152 virtual void anchor();
153
154public:
155 static PragmaCommentDecl *Create(const ASTContext &C, TranslationUnitDecl *DC,
156 SourceLocation CommentLoc,
157 PragmaMSCommentKind CommentKind,
158 StringRef Arg);
159 static PragmaCommentDecl *CreateDeserialized(ASTContext &C, unsigned ID,
160 unsigned ArgSize);
161
162 PragmaMSCommentKind getCommentKind() const { return CommentKind; }
163
164 StringRef getArg() const { return getTrailingObjects<char>(); }
165
166 // Implement isa/cast/dyncast/etc.
167 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
168 static bool classofKind(Kind K) { return K == PragmaComment; }
169};
170
171/// \brief Represents a `#pragma detect_mismatch` line. Always a child of
172/// TranslationUnitDecl.
173class PragmaDetectMismatchDecl final
174 : public Decl,
175 private llvm::TrailingObjects<PragmaDetectMismatchDecl, char> {
176 friend class ASTDeclReader;
177 friend class ASTDeclWriter;
178 friend TrailingObjects;
179
180 size_t ValueStart;
181
182 PragmaDetectMismatchDecl(TranslationUnitDecl *TU, SourceLocation Loc,
183 size_t ValueStart)
184 : Decl(PragmaDetectMismatch, TU, Loc), ValueStart(ValueStart) {}
185
186 virtual void anchor();
187
188public:
189 static PragmaDetectMismatchDecl *Create(const ASTContext &C,
190 TranslationUnitDecl *DC,
191 SourceLocation Loc, StringRef Name,
192 StringRef Value);
193 static PragmaDetectMismatchDecl *
194 CreateDeserialized(ASTContext &C, unsigned ID, unsigned NameValueSize);
195
196 StringRef getName() const { return getTrailingObjects<char>(); }
197 StringRef getValue() const { return getTrailingObjects<char>() + ValueStart; }
198
199 // Implement isa/cast/dyncast/etc.
200 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
201 static bool classofKind(Kind K) { return K == PragmaDetectMismatch; }
202};
203
204/// \brief Declaration context for names declared as extern "C" in C++. This
205/// is neither the semantic nor lexical context for such declarations, but is
206/// used to check for conflicts with other extern "C" declarations. Example:
207///
208/// \code
209/// namespace N { extern "C" void f(); } // #1
210/// void N::f() {} // #2
211/// namespace M { extern "C" void f(); } // #3
212/// \endcode
213///
214/// The semantic context of #1 is namespace N and its lexical context is the
215/// LinkageSpecDecl; the semantic context of #2 is namespace N and its lexical
216/// context is the TU. However, both declarations are also visible in the
217/// extern "C" context.
218///
219/// The declaration at #3 finds it is a redeclaration of \c N::f through
220/// lookup in the extern "C" context.
221class ExternCContextDecl : public Decl, public DeclContext {
222 explicit ExternCContextDecl(TranslationUnitDecl *TU)
223 : Decl(ExternCContext, TU, SourceLocation()),
224 DeclContext(ExternCContext) {}
225
226 virtual void anchor();
227
228public:
229 static ExternCContextDecl *Create(const ASTContext &C,
230 TranslationUnitDecl *TU);
231
232 // Implement isa/cast/dyncast/etc.
233 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
234 static bool classofKind(Kind K) { return K == ExternCContext; }
235 static DeclContext *castToDeclContext(const ExternCContextDecl *D) {
236 return static_cast<DeclContext *>(const_cast<ExternCContextDecl*>(D));
237 }
238 static ExternCContextDecl *castFromDeclContext(const DeclContext *DC) {
239 return static_cast<ExternCContextDecl *>(const_cast<DeclContext*>(DC));
240 }
241};
242
243/// NamedDecl - This represents a decl with a name. Many decls have names such
244/// as ObjCMethodDecl, but not \@class, etc.
245class NamedDecl : public Decl {
246 /// Name - The name of this declaration, which is typically a normal
247 /// identifier but may also be a special kind of name (C++
248 /// constructor, Objective-C selector, etc.)
249 DeclarationName Name;
250
251 virtual void anchor();
252
253private:
254 NamedDecl *getUnderlyingDeclImpl() LLVM_READONLY__attribute__((__pure__));
255
256protected:
257 NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N)
258 : Decl(DK, DC, L), Name(N) {}
259
260public:
261 /// getIdentifier - Get the identifier that names this declaration,
262 /// if there is one. This will return NULL if this declaration has
263 /// no name (e.g., for an unnamed class) or if the name is a special
264 /// name (C++ constructor, Objective-C selector, etc.).
265 IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); }
266
267 /// getName - Get the name of identifier for this declaration as a StringRef.
268 /// This requires that the declaration have a name and that it be a simple
269 /// identifier.
270 StringRef getName() const {
271 assert(Name.isIdentifier() && "Name is not a simple identifier")(static_cast <bool> (Name.isIdentifier() && "Name is not a simple identifier"
) ? void (0) : __assert_fail ("Name.isIdentifier() && \"Name is not a simple identifier\""
, "/build/llvm-toolchain-snapshot-6.0~svn318631/tools/clang/include/clang/AST/Decl.h"
, 271, __extension__ __PRETTY_FUNCTION__))
;
272 return getIdentifier() ? getIdentifier()->getName() : "";
273 }
274
275 /// getNameAsString - Get a human-readable name for the declaration, even if
276 /// it is one of the special kinds of names (C++ constructor, Objective-C
277 /// selector, etc). Creating this name requires expensive string
278 /// manipulation, so it should be called only when performance doesn't matter.
279 /// For simple declarations, getNameAsCString() should suffice.
280 //
281 // FIXME: This function should be renamed to indicate that it is not just an
282 // alternate form of getName(), and clients should move as appropriate.
283 //
284 // FIXME: Deprecated, move clients to getName().
285 std::string getNameAsString() const { return Name.getAsString(); }
286
287 virtual void printName(raw_ostream &os) const;
288
289 /// getDeclName - Get the actual, stored name of the declaration,
290 /// which may be a special name.
291 DeclarationName getDeclName() const { return Name; }
292
293 /// \brief Set the name of this declaration.
294 void setDeclName(DeclarationName N) { Name = N; }
295
296 /// printQualifiedName - Returns human-readable qualified name for
297 /// declaration, like A::B::i, for i being member of namespace A::B.
298 /// If declaration is not member of context which can be named (record,
299 /// namespace), it will return same result as printName().
300 /// Creating this name is expensive, so it should be called only when
301 /// performance doesn't matter.
302 void printQualifiedName(raw_ostream &OS) const;
303 void printQualifiedName(raw_ostream &OS, const PrintingPolicy &Policy) const;
304
305 // FIXME: Remove string version.
306 std::string getQualifiedNameAsString() const;
307
308 /// getNameForDiagnostic - Appends a human-readable name for this
309 /// declaration into the given stream.
310 ///
311 /// This is the method invoked by Sema when displaying a NamedDecl
312 /// in a diagnostic. It does not necessarily produce the same
313 /// result as printName(); for example, class template
314 /// specializations are printed with their template arguments.
315 virtual void getNameForDiagnostic(raw_ostream &OS,
316 const PrintingPolicy &Policy,
317 bool Qualified) const;
318
319 /// \brief Determine whether this declaration, if
320 /// known to be well-formed within its context, will replace the
321 /// declaration OldD if introduced into scope. A declaration will
322 /// replace another declaration if, for example, it is a
323 /// redeclaration of the same variable or function, but not if it is
324 /// a declaration of a different kind (function vs. class) or an
325 /// overloaded function.
326 ///
327 /// \param IsKnownNewer \c true if this declaration is known to be newer
328 /// than \p OldD (for instance, if this declaration is newly-created).
329 bool declarationReplaces(NamedDecl *OldD, bool IsKnownNewer = true) const;
330
331 /// \brief Determine whether this declaration has linkage.
332 bool hasLinkage() const;
333
334 using Decl::isModulePrivate;
335 using Decl::setModulePrivate;
336
337 /// \brief Determine whether this declaration is a C++ class member.
338 bool isCXXClassMember() const {
339 const DeclContext *DC = getDeclContext();
340
341 // C++0x [class.mem]p1:
342 // The enumerators of an unscoped enumeration defined in
343 // the class are members of the class.
344 if (isa<EnumDecl>(DC))
345 DC = DC->getRedeclContext();
346
347 return DC->isRecord();
348 }
349
350 /// \brief Determine whether the given declaration is an instance member of
351 /// a C++ class.
352 bool isCXXInstanceMember() const;
353
354 /// \brief Determine what kind of linkage this entity has.
355 /// This is not the linkage as defined by the standard or the codegen notion
356 /// of linkage. It is just an implementation detail that is used to compute
357 /// those.
358 Linkage getLinkageInternal() const;
359
360 /// \brief Get the linkage from a semantic point of view. Entities in
361 /// anonymous namespaces are external (in c++98).
362 Linkage getFormalLinkage() const {
363 return clang::getFormalLinkage(getLinkageInternal());
364 }
365
366 /// \brief True if this decl has external linkage.
367 bool hasExternalFormalLinkage() const {
368 return isExternalFormalLinkage(getLinkageInternal());
369 }
370
371 bool isExternallyVisible() const {
372 return clang::isExternallyVisible(getLinkageInternal());
373 }
374
375 /// Determine whether this declaration can be redeclared in a
376 /// different translation unit.
377 bool isExternallyDeclarable() const {
378 return isExternallyVisible() && !getOwningModuleForLinkage();
379 }
380
381 /// \brief Determines the visibility of this entity.
382 Visibility getVisibility() const {
383 return getLinkageAndVisibility().getVisibility();
384 }
385
386 /// \brief Determines the linkage and visibility of this entity.
387 LinkageInfo getLinkageAndVisibility() const;
388
389 /// Kinds of explicit visibility.
390 enum ExplicitVisibilityKind {
391 /// Do an LV computation for, ultimately, a type.
392 /// Visibility may be restricted by type visibility settings and
393 /// the visibility of template arguments.
394 VisibilityForType,
395
396 /// Do an LV computation for, ultimately, a non-type declaration.
397 /// Visibility may be restricted by value visibility settings and
398 /// the visibility of template arguments.
399 VisibilityForValue
400 };
401
402 /// \brief If visibility was explicitly specified for this
403 /// declaration, return that visibility.
404 Optional<Visibility>
405 getExplicitVisibility(ExplicitVisibilityKind kind) const;
406
407 /// \brief True if the computed linkage is valid. Used for consistency
408 /// checking. Should always return true.
409 bool isLinkageValid() const;
410
411 /// \brief True if something has required us to compute the linkage
412 /// of this declaration.
413 ///
414 /// Language features which can retroactively change linkage (like a
415 /// typedef name for linkage purposes) may need to consider this,
416 /// but hopefully only in transitory ways during parsing.
417 bool hasLinkageBeenComputed() const {
418 return hasCachedLinkage();
419 }
420
421 /// \brief Looks through UsingDecls and ObjCCompatibleAliasDecls for
422 /// the underlying named decl.
423 NamedDecl *getUnderlyingDecl() {
424 // Fast-path the common case.
425 if (this->getKind() != UsingShadow &&
426 this->getKind() != ConstructorUsingShadow &&
427 this->getKind() != ObjCCompatibleAlias &&
428 this->getKind() != NamespaceAlias)
429 return this;
430
431 return getUnderlyingDeclImpl();
432 }
433 const NamedDecl *getUnderlyingDecl() const {
434 return const_cast<NamedDecl*>(this)->getUnderlyingDecl();
435 }
436
437 NamedDecl *getMostRecentDecl() {
438 return cast<NamedDecl>(static_cast<Decl *>(this)->getMostRecentDecl());
439 }
440 const NamedDecl *getMostRecentDecl() const {
441 return const_cast<NamedDecl*>(this)->getMostRecentDecl();
442 }
443
444 ObjCStringFormatFamily getObjCFStringFormattingFamily() const;
445
446 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
447 static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; }
448};
449
450inline raw_ostream &operator<<(raw_ostream &OS, const NamedDecl &ND) {
451 ND.printName(OS);
452 return OS;
453}
454
455/// LabelDecl - Represents the declaration of a label. Labels also have a
456/// corresponding LabelStmt, which indicates the position that the label was
457/// defined at. For normal labels, the location of the decl is the same as the
458/// location of the statement. For GNU local labels (__label__), the decl
459/// location is where the __label__ is.
460class LabelDecl : public NamedDecl {
461 LabelStmt *TheStmt;
462 StringRef MSAsmName;
463 bool MSAsmNameResolved = false;
464
465 /// LocStart - For normal labels, this is the same as the main declaration
466 /// label, i.e., the location of the identifier; for GNU local labels,
467 /// this is the location of the __label__ keyword.
468 SourceLocation LocStart;
469
470 LabelDecl(DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II,
471 LabelStmt *S, SourceLocation StartL)
472 : NamedDecl(Label, DC, IdentL, II), TheStmt(S), LocStart(StartL) {}
473
474 void anchor() override;
475
476public:
477 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
478 SourceLocation IdentL, IdentifierInfo *II);
479 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
480 SourceLocation IdentL, IdentifierInfo *II,
481 SourceLocation GnuLabelL);
482 static LabelDecl *CreateDeserialized(ASTContext &C, unsigned ID);
483
484 LabelStmt *getStmt() const { return TheStmt; }
485 void setStmt(LabelStmt *T) { TheStmt = T; }
486
487 bool isGnuLocal() const { return LocStart != getLocation(); }
488 void setLocStart(SourceLocation L) { LocStart = L; }
489
490 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
491 return SourceRange(LocStart, getLocation());
492 }
493
494 bool isMSAsmLabel() const { return !MSAsmName.empty(); }
495 bool isResolvedMSAsmLabel() const { return isMSAsmLabel() && MSAsmNameResolved; }
496 void setMSAsmLabel(StringRef Name);
497 StringRef getMSAsmLabel() const { return MSAsmName; }
498 void setMSAsmLabelResolved() { MSAsmNameResolved = true; }
499
500 // Implement isa/cast/dyncast/etc.
501 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
502 static bool classofKind(Kind K) { return K == Label; }
503};
504
505/// NamespaceDecl - Represent a C++ namespace.
506class NamespaceDecl : public NamedDecl, public DeclContext,
507 public Redeclarable<NamespaceDecl>
508{
509 /// LocStart - The starting location of the source range, pointing
510 /// to either the namespace or the inline keyword.
511 SourceLocation LocStart;
512
513 /// RBraceLoc - The ending location of the source range.
514 SourceLocation RBraceLoc;
515
516 /// \brief A pointer to either the anonymous namespace that lives just inside
517 /// this namespace or to the first namespace in the chain (the latter case
518 /// only when this is not the first in the chain), along with a
519 /// boolean value indicating whether this is an inline namespace.
520 llvm::PointerIntPair<NamespaceDecl *, 1, bool> AnonOrFirstNamespaceAndInline;
521
522 NamespaceDecl(ASTContext &C, DeclContext *DC, bool Inline,
523 SourceLocation StartLoc, SourceLocation IdLoc,
524 IdentifierInfo *Id, NamespaceDecl *PrevDecl);
525
526 using redeclarable_base = Redeclarable<NamespaceDecl>;
527
528 NamespaceDecl *getNextRedeclarationImpl() override;
529 NamespaceDecl *getPreviousDeclImpl() override;
530 NamespaceDecl *getMostRecentDeclImpl() override;
531
532public:
533 friend class ASTDeclReader;
534 friend class ASTDeclWriter;
535
536 static NamespaceDecl *Create(ASTContext &C, DeclContext *DC,
537 bool Inline, SourceLocation StartLoc,
538 SourceLocation IdLoc, IdentifierInfo *Id,
539 NamespaceDecl *PrevDecl);
540
541 static NamespaceDecl *CreateDeserialized(ASTContext &C, unsigned ID);
542
543 using redecl_range = redeclarable_base::redecl_range;
544 using redecl_iterator = redeclarable_base::redecl_iterator;
545
546 using redeclarable_base::redecls_begin;
547 using redeclarable_base::redecls_end;
548 using redeclarable_base::redecls;
549 using redeclarable_base::getPreviousDecl;
550 using redeclarable_base::getMostRecentDecl;
551 using redeclarable_base::isFirstDecl;
552
553 /// \brief Returns true if this is an anonymous namespace declaration.
554 ///
555 /// For example:
556 /// \code
557 /// namespace {
558 /// ...
559 /// };
560 /// \endcode
561 /// q.v. C++ [namespace.unnamed]
562 bool isAnonymousNamespace() const {
563 return !getIdentifier();
564 }
565
566 /// \brief Returns true if this is an inline namespace declaration.
567 bool isInline() const {
568 return AnonOrFirstNamespaceAndInline.getInt();
569 }
570
571 /// \brief Set whether this is an inline namespace declaration.
572 void setInline(bool Inline) {
573 AnonOrFirstNamespaceAndInline.setInt(Inline);
574 }
575
576 /// \brief Get the original (first) namespace declaration.
577 NamespaceDecl *getOriginalNamespace();
578
579 /// \brief Get the original (first) namespace declaration.
580 const NamespaceDecl *getOriginalNamespace() const;
581
582 /// \brief Return true if this declaration is an original (first) declaration
583 /// of the namespace. This is false for non-original (subsequent) namespace
584 /// declarations and anonymous namespaces.
585 bool isOriginalNamespace() const;
586
587 /// \brief Retrieve the anonymous namespace nested inside this namespace,
588 /// if any.
589 NamespaceDecl *getAnonymousNamespace() const {
590 return getOriginalNamespace()->AnonOrFirstNamespaceAndInline.getPointer();
591 }
592
593 void setAnonymousNamespace(NamespaceDecl *D) {
594 getOriginalNamespace()->AnonOrFirstNamespaceAndInline.setPointer(D);
595 }
596
597 /// Retrieves the canonical declaration of this namespace.
598 NamespaceDecl *getCanonicalDecl() override {
599 return getOriginalNamespace();
600 }
601 const NamespaceDecl *getCanonicalDecl() const {
602 return getOriginalNamespace();
603 }
604
605 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
606 return SourceRange(LocStart, RBraceLoc);
607 }
608
609 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return LocStart; }
610 SourceLocation getRBraceLoc() const { return RBraceLoc; }
611 void setLocStart(SourceLocation L) { LocStart = L; }
612 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
613
614 // Implement isa/cast/dyncast/etc.
615 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
616 static bool classofKind(Kind K) { return K == Namespace; }
617 static DeclContext *castToDeclContext(const NamespaceDecl *D) {
618 return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D));
619 }
620 static NamespaceDecl *castFromDeclContext(const DeclContext *DC) {
621 return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC));
622 }
623};
624
625/// ValueDecl - Represent the declaration of a variable (in which case it is
626/// an lvalue) a function (in which case it is a function designator) or
627/// an enum constant.
628class ValueDecl : public NamedDecl {
629 QualType DeclType;
630
631 void anchor() override;
632
633protected:
634 ValueDecl(Kind DK, DeclContext *DC, SourceLocation L,
635 DeclarationName N, QualType T)
636 : NamedDecl(DK, DC, L, N), DeclType(T) {}
637
638public:
639 QualType getType() const { return DeclType; }
640 void setType(QualType newType) { DeclType = newType; }
641
642 /// \brief Determine whether this symbol is weakly-imported,
643 /// or declared with the weak or weak-ref attr.
644 bool isWeak() const;
645
646 // Implement isa/cast/dyncast/etc.
647 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
648 static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; }
649};
650
651/// QualifierInfo - A struct with extended info about a syntactic
652/// name qualifier, to be used for the case of out-of-line declarations.
653struct QualifierInfo {
654 NestedNameSpecifierLoc QualifierLoc;
655
656 /// NumTemplParamLists - The number of "outer" template parameter lists.
657 /// The count includes all of the template parameter lists that were matched
658 /// against the template-ids occurring into the NNS and possibly (in the
659 /// case of an explicit specialization) a final "template <>".
660 unsigned NumTemplParamLists = 0;
661
662 /// TemplParamLists - A new-allocated array of size NumTemplParamLists,
663 /// containing pointers to the "outer" template parameter lists.
664 /// It includes all of the template parameter lists that were matched
665 /// against the template-ids occurring into the NNS and possibly (in the
666 /// case of an explicit specialization) a final "template <>".
667 TemplateParameterList** TemplParamLists = nullptr;
668
669 QualifierInfo() = default;
670 QualifierInfo(const QualifierInfo &) = delete;
671 QualifierInfo& operator=(const QualifierInfo &) = delete;
672
673 /// setTemplateParameterListsInfo - Sets info about "outer" template
674 /// parameter lists.
675 void setTemplateParameterListsInfo(ASTContext &Context,
676 ArrayRef<TemplateParameterList *> TPLists);
677};
678
679/// \brief Represents a ValueDecl that came out of a declarator.
680/// Contains type source information through TypeSourceInfo.
681class DeclaratorDecl : public ValueDecl {
682 // A struct representing both a TInfo and a syntactic qualifier,
683 // to be used for the (uncommon) case of out-of-line declarations.
684 struct ExtInfo : public QualifierInfo {
685 TypeSourceInfo *TInfo;
686 };
687
688 llvm::PointerUnion<TypeSourceInfo *, ExtInfo *> DeclInfo;
689
690 /// InnerLocStart - The start of the source range for this declaration,
691 /// ignoring outer template declarations.
692 SourceLocation InnerLocStart;
693
694 bool hasExtInfo() const { return DeclInfo.is<ExtInfo*>(); }
695 ExtInfo *getExtInfo() { return DeclInfo.get<ExtInfo*>(); }
696 const ExtInfo *getExtInfo() const { return DeclInfo.get<ExtInfo*>(); }
697
698protected:
699 DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L,
700 DeclarationName N, QualType T, TypeSourceInfo *TInfo,
701 SourceLocation StartL)
702 : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo), InnerLocStart(StartL) {}
703
704public:
705 friend class ASTDeclReader;
706 friend class ASTDeclWriter;
707
708 TypeSourceInfo *getTypeSourceInfo() const {
709 return hasExtInfo()
710 ? getExtInfo()->TInfo
711 : DeclInfo.get<TypeSourceInfo*>();
712 }
713
714 void setTypeSourceInfo(TypeSourceInfo *TI) {
715 if (hasExtInfo())
716 getExtInfo()->TInfo = TI;
717 else
718 DeclInfo = TI;
719 }
720
721 /// getInnerLocStart - Return SourceLocation representing start of source
722 /// range ignoring outer template declarations.
723 SourceLocation getInnerLocStart() const { return InnerLocStart; }
724 void setInnerLocStart(SourceLocation L) { InnerLocStart = L; }
725
726 /// getOuterLocStart - Return SourceLocation representing start of source
727 /// range taking into account any outer template declarations.
728 SourceLocation getOuterLocStart() const;
729
730 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
731
732 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) {
733 return getOuterLocStart();
734 }
735
736 /// \brief Retrieve the nested-name-specifier that qualifies the name of this
737 /// declaration, if it was present in the source.
738 NestedNameSpecifier *getQualifier() const {
739 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
740 : nullptr;
741 }
742
743 /// \brief Retrieve the nested-name-specifier (with source-location
744 /// information) that qualifies the name of this declaration, if it was
745 /// present in the source.
746 NestedNameSpecifierLoc getQualifierLoc() const {
747 return hasExtInfo() ? getExtInfo()->QualifierLoc
748 : NestedNameSpecifierLoc();
749 }
750
751 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
752
753 unsigned getNumTemplateParameterLists() const {
754 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
755 }
756
757 TemplateParameterList *getTemplateParameterList(unsigned index) const {
758 assert(index < getNumTemplateParameterLists())(static_cast <bool> (index < getNumTemplateParameterLists
()) ? void (0) : __assert_fail ("index < getNumTemplateParameterLists()"
, "/build/llvm-toolchain-snapshot-6.0~svn318631/tools/clang/include/clang/AST/Decl.h"
, 758, __extension__ __PRETTY_FUNCTION__))
;
759 return getExtInfo()->TemplParamLists[index];
760 }
761
762 void setTemplateParameterListsInfo(ASTContext &Context,
763 ArrayRef<TemplateParameterList *> TPLists);
764
765 SourceLocation getTypeSpecStartLoc() const;
766
767 // Implement isa/cast/dyncast/etc.
768 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
769 static bool classofKind(Kind K) {
770 return K >= firstDeclarator && K <= lastDeclarator;
771 }
772};
773
774/// \brief Structure used to store a statement, the constant value to
775/// which it was evaluated (if any), and whether or not the statement
776/// is an integral constant expression (if known).
777struct EvaluatedStmt {
778 /// \brief Whether this statement was already evaluated.
779 bool WasEvaluated : 1;
780
781 /// \brief Whether this statement is being evaluated.
782 bool IsEvaluating : 1;
783
784 /// \brief Whether we already checked whether this statement was an
785 /// integral constant expression.
786 bool CheckedICE : 1;
787
788 /// \brief Whether we are checking whether this statement is an
789 /// integral constant expression.
790 bool CheckingICE : 1;
791
792 /// \brief Whether this statement is an integral constant expression,
793 /// or in C++11, whether the statement is a constant expression. Only
794 /// valid if CheckedICE is true.
795 bool IsICE : 1;
796
797 Stmt *Value;
798 APValue Evaluated;
799
800 EvaluatedStmt() : WasEvaluated(false), IsEvaluating(false), CheckedICE(false),
801 CheckingICE(false), IsICE(false) {}
802
803};
804
805/// VarDecl - An instance of this class is created to represent a variable
806/// declaration or definition.
807class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> {
808public:
809 /// \brief Initialization styles.
810 enum InitializationStyle {
811 /// C-style initialization with assignment
812 CInit,
813
814 /// Call-style initialization (C++98)
815 CallInit,
816
817 /// Direct list-initialization (C++11)
818 ListInit
819 };
820
821 /// \brief Kinds of thread-local storage.
822 enum TLSKind {
823 /// Not a TLS variable.
824 TLS_None,
825
826 /// TLS with a known-constant initializer.
827 TLS_Static,
828
829 /// TLS with a dynamic initializer.
830 TLS_Dynamic
831 };
832
833 /// getStorageClassSpecifierString - Return the string used to
834 /// specify the storage class \p SC.
835 ///
836 /// It is illegal to call this function with SC == None.
837 static const char *getStorageClassSpecifierString(StorageClass SC);
838
839protected:
840 // A pointer union of Stmt * and EvaluatedStmt *. When an EvaluatedStmt, we
841 // have allocated the auxiliary struct of information there.
842 //
843 // TODO: It is a bit unfortunate to use a PointerUnion inside the VarDecl for
844 // this as *many* VarDecls are ParmVarDecls that don't have default
845 // arguments. We could save some space by moving this pointer union to be
846 // allocated in trailing space when necessary.
847 using InitType = llvm::PointerUnion<Stmt *, EvaluatedStmt *>;
848
849 /// \brief The initializer for this variable or, for a ParmVarDecl, the
850 /// C++ default argument.
851 mutable InitType Init;
852
853private:
854 friend class ASTDeclReader;
855 friend class ASTNodeImporter;
856 friend class StmtIteratorBase;
857
858 class VarDeclBitfields {
859 friend class ASTDeclReader;
860 friend class VarDecl;
861
862 unsigned SClass : 3;
863 unsigned TSCSpec : 2;
864 unsigned InitStyle : 2;
865 };
866 enum { NumVarDeclBits = 7 };
867
868protected:
869 enum { NumParameterIndexBits = 8 };
870
871 enum DefaultArgKind {
872 DAK_None,
873 DAK_Unparsed,
874 DAK_Uninstantiated,
875 DAK_Normal
876 };
877
878 class ParmVarDeclBitfields {
879 friend class ASTDeclReader;
880 friend class ParmVarDecl;
881
882 unsigned : NumVarDeclBits;
883
884 /// Whether this parameter inherits a default argument from a
885 /// prior declaration.
886 unsigned HasInheritedDefaultArg : 1;
887
888 /// Describes the kind of default argument for this parameter. By default
889 /// this is none. If this is normal, then the default argument is stored in
890 /// the \c VarDecl initializer expression unless we were unable to parse
891 /// (even an invalid) expression for the default argument.
892 unsigned DefaultArgKind : 2;
893
894 /// Whether this parameter undergoes K&R argument promotion.
895 unsigned IsKNRPromoted : 1;
896
897 /// Whether this parameter is an ObjC method parameter or not.
898 unsigned IsObjCMethodParam : 1;
899
900 /// If IsObjCMethodParam, a Decl::ObjCDeclQualifier.
901 /// Otherwise, the number of function parameter scopes enclosing
902 /// the function parameter scope in which this parameter was
903 /// declared.
904 unsigned ScopeDepthOrObjCQuals : 7;
905
906 /// The number of parameters preceding this parameter in the
907 /// function parameter scope in which it was declared.
908 unsigned ParameterIndex : NumParameterIndexBits;
909 };
910
911 class NonParmVarDeclBitfields {
912 friend class ASTDeclReader;
913 friend class ImplicitParamDecl;
914 friend class VarDecl;
915
916 unsigned : NumVarDeclBits;
917
918 // FIXME: We need something similar to CXXRecordDecl::DefinitionData.
919 /// \brief Whether this variable is a definition which was demoted due to
920 /// module merge.
921 unsigned IsThisDeclarationADemotedDefinition : 1;
922
923 /// \brief Whether this variable is the exception variable in a C++ catch
924 /// or an Objective-C @catch statement.
925 unsigned ExceptionVar : 1;
926
927 /// \brief Whether this local variable could be allocated in the return
928 /// slot of its function, enabling the named return value optimization
929 /// (NRVO).
930 unsigned NRVOVariable : 1;
931
932 /// \brief Whether this variable is the for-range-declaration in a C++0x
933 /// for-range statement.
934 unsigned CXXForRangeDecl : 1;
935
936 /// \brief Whether this variable is an ARC pseudo-__strong
937 /// variable; see isARCPseudoStrong() for details.
938 unsigned ARCPseudoStrong : 1;
939
940 /// \brief Whether this variable is (C++1z) inline.
941 unsigned IsInline : 1;
942
943 /// \brief Whether this variable has (C++1z) inline explicitly specified.
944 unsigned IsInlineSpecified : 1;
945
946 /// \brief Whether this variable is (C++0x) constexpr.
947 unsigned IsConstexpr : 1;
948
949 /// \brief Whether this variable is the implicit variable for a lambda
950 /// init-capture.
951 unsigned IsInitCapture : 1;
952
953 /// \brief Whether this local extern variable's previous declaration was
954 /// declared in the same block scope. This controls whether we should merge
955 /// the type of this declaration with its previous declaration.
956 unsigned PreviousDeclInSameBlockScope : 1;
957
958 /// Defines kind of the ImplicitParamDecl: 'this', 'self', 'vtt', '_cmd' or
959 /// something else.
960 unsigned ImplicitParamKind : 3;
961 };
962
963 union {
964 unsigned AllBits;
965 VarDeclBitfields VarDeclBits;
966 ParmVarDeclBitfields ParmVarDeclBits;
967 NonParmVarDeclBitfields NonParmVarDeclBits;
968 };
969
970 VarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
971 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
972 TypeSourceInfo *TInfo, StorageClass SC);
973
974 using redeclarable_base = Redeclarable<VarDecl>;
975
976 VarDecl *getNextRedeclarationImpl() override {
977 return getNextRedeclaration();
978 }
979
980 VarDecl *getPreviousDeclImpl() override {
981 return getPreviousDecl();
982 }
983
984 VarDecl *getMostRecentDeclImpl() override {
985 return getMostRecentDecl();
986 }
987
988public:
989 using redecl_range = redeclarable_base::redecl_range;
990 using redecl_iterator = redeclarable_base::redecl_iterator;
991
992 using redeclarable_base::redecls_begin;
993 using redeclarable_base::redecls_end;
994 using redeclarable_base::redecls;
995 using redeclarable_base::getPreviousDecl;
996 using redeclarable_base::getMostRecentDecl;
997 using redeclarable_base::isFirstDecl;
998
999 static VarDecl *Create(ASTContext &C, DeclContext *DC,
1000 SourceLocation StartLoc, SourceLocation IdLoc,
1001 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1002 StorageClass S);
1003
1004 static VarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1005
1006 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1007
1008 /// \brief Returns the storage class as written in the source. For the
1009 /// computed linkage of symbol, see getLinkage.
1010 StorageClass getStorageClass() const {
1011 return (StorageClass) VarDeclBits.SClass;
1012 }
1013 void setStorageClass(StorageClass SC);
1014
1015 void setTSCSpec(ThreadStorageClassSpecifier TSC) {
1016 VarDeclBits.TSCSpec = TSC;
1017 assert(VarDeclBits.TSCSpec == TSC && "truncation")(static_cast <bool> (VarDeclBits.TSCSpec == TSC &&
"truncation") ? void (0) : __assert_fail ("VarDeclBits.TSCSpec == TSC && \"truncation\""
, "/build/llvm-toolchain-snapshot-6.0~svn318631/tools/clang/include/clang/AST/Decl.h"
, 1017, __extension__ __PRETTY_FUNCTION__))
;
1018 }
1019 ThreadStorageClassSpecifier getTSCSpec() const {
1020 return static_cast<ThreadStorageClassSpecifier>(VarDeclBits.TSCSpec);
1021 }
1022 TLSKind getTLSKind() const;
1023
1024 /// hasLocalStorage - Returns true if a variable with function scope
1025 /// is a non-static local variable.
1026 bool hasLocalStorage() const {
1027 if (getStorageClass() == SC_None) {
1028 // OpenCL v1.2 s6.5.3: The __constant or constant address space name is
1029 // used to describe variables allocated in global memory and which are
1030 // accessed inside a kernel(s) as read-only variables. As such, variables
1031 // in constant address space cannot have local storage.
1032 if (getType().getAddressSpace() == LangAS::opencl_constant)
1033 return false;
1034 // Second check is for C++11 [dcl.stc]p4.
1035 return !isFileVarDecl() && getTSCSpec() == TSCS_unspecified;
1036 }
1037
1038 // Global Named Register (GNU extension)
1039 if (getStorageClass() == SC_Register && !isLocalVarDeclOrParm())
1040 return false;
1041
1042 // Return true for: Auto, Register.
1043 // Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal.
1044
1045 return getStorageClass() >= SC_Auto;
1046 }
1047
1048 /// isStaticLocal - Returns true if a variable with function scope is a
1049 /// static local variable.
1050 bool isStaticLocal() const {
1051 return (getStorageClass() == SC_Static ||
1052 // C++11 [dcl.stc]p4
1053 (getStorageClass() == SC_None && getTSCSpec() == TSCS_thread_local))
1054 && !isFileVarDecl();
1055 }
1056
1057 /// \brief Returns true if a variable has extern or __private_extern__
1058 /// storage.
1059 bool hasExternalStorage() const {
1060 return getStorageClass() == SC_Extern ||
1061 getStorageClass() == SC_PrivateExtern;
1062 }
1063
1064 /// \brief Returns true for all variables that do not have local storage.
1065 ///
1066 /// This includes all global variables as well as static variables declared
1067 /// within a function.
1068 bool hasGlobalStorage() const { return !hasLocalStorage(); }
1069
1070 /// \brief Get the storage duration of this variable, per C++ [basic.stc].
1071 StorageDuration getStorageDuration() const {
1072 return hasLocalStorage() ? SD_Automatic :
1073 getTSCSpec() ? SD_Thread : SD_Static;
1074 }
1075
1076 /// \brief Compute the language linkage.
1077 LanguageLinkage getLanguageLinkage() const;
1078
1079 /// \brief Determines whether this variable is a variable with
1080 /// external, C linkage.
1081 bool isExternC() const;
1082
1083 /// \brief Determines whether this variable's context is, or is nested within,
1084 /// a C++ extern "C" linkage spec.
1085 bool isInExternCContext() const;
1086
1087 /// \brief Determines whether this variable's context is, or is nested within,
1088 /// a C++ extern "C++" linkage spec.
1089 bool isInExternCXXContext() const;
1090
1091 /// isLocalVarDecl - Returns true for local variable declarations
1092 /// other than parameters. Note that this includes static variables
1093 /// inside of functions. It also includes variables inside blocks.
1094 ///
1095 /// void foo() { int x; static int y; extern int z; }
1096 bool isLocalVarDecl() const {
1097 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1098 return false;
1099 if (const DeclContext *DC = getLexicalDeclContext())
1100 return DC->getRedeclContext()->isFunctionOrMethod();
1101 return false;
1102 }
1103
1104 /// \brief Similar to isLocalVarDecl but also includes parameters.
1105 bool isLocalVarDeclOrParm() const {
1106 return isLocalVarDecl() || getKind() == Decl::ParmVar;
1107 }
1108
1109 /// isFunctionOrMethodVarDecl - Similar to isLocalVarDecl, but
1110 /// excludes variables declared in blocks.
1111 bool isFunctionOrMethodVarDecl() const {
1112 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1113 return false;
1114 const DeclContext *DC = getLexicalDeclContext()->getRedeclContext();
1115 return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block;
1116 }
1117
1118 /// \brief Determines whether this is a static data member.
1119 ///
1120 /// This will only be true in C++, and applies to, e.g., the
1121 /// variable 'x' in:
1122 /// \code
1123 /// struct S {
1124 /// static int x;
1125 /// };
1126 /// \endcode
1127 bool isStaticDataMember() const {
1128 // If it wasn't static, it would be a FieldDecl.
1129 return getKind() != Decl::ParmVar && getDeclContext()->isRecord();
1130 }
1131
1132 VarDecl *getCanonicalDecl() override;
1133 const VarDecl *getCanonicalDecl() const {
1134 return const_cast<VarDecl*>(this)->getCanonicalDecl();
1135 }
1136
1137 enum DefinitionKind {
1138 /// This declaration is only a declaration.
1139 DeclarationOnly,
1140
1141 /// This declaration is a tentative definition.
1142 TentativeDefinition,
1143
1144 /// This declaration is definitely a definition.
1145 Definition
1146 };
1147
1148 /// \brief Check whether this declaration is a definition. If this could be
1149 /// a tentative definition (in C), don't check whether there's an overriding
1150 /// definition.
1151 DefinitionKind isThisDeclarationADefinition(ASTContext &) const;
1152 DefinitionKind isThisDeclarationADefinition() const {
1153 return isThisDeclarationADefinition(getASTContext());
1154 }
1155
1156 /// \brief Check whether this variable is defined in this
1157 /// translation unit.
1158 DefinitionKind hasDefinition(ASTContext &) const;
1159 DefinitionKind hasDefinition() const {
1160 return hasDefinition(getASTContext());
1161 }
1162
1163 /// \brief Get the tentative definition that acts as the real definition in
1164 /// a TU. Returns null if there is a proper definition available.
1165 VarDecl *getActingDefinition();
1166 const VarDecl *getActingDefinition() const {
1167 return const_cast<VarDecl*>(this)->getActingDefinition();
1168 }
1169
1170 /// \brief Get the real (not just tentative) definition for this declaration.
1171 VarDecl *getDefinition(ASTContext &);
1172 const VarDecl *getDefinition(ASTContext &C) const {
1173 return const_cast<VarDecl*>(this)->getDefinition(C);
1174 }
1175 VarDecl *getDefinition() {
1176 return getDefinition(getASTContext());
1177 }
1178 const VarDecl *getDefinition() const {
1179 return const_cast<VarDecl*>(this)->getDefinition();
1180 }
1181
1182 /// \brief Determine whether this is or was instantiated from an out-of-line
1183 /// definition of a static data member.
1184 bool isOutOfLine() const override;
1185
1186 /// isFileVarDecl - Returns true for file scoped variable declaration.
1187 bool isFileVarDecl() const {
1188 Kind K = getKind();
1189 if (K == ParmVar || K == ImplicitParam)
1190 return false;
1191
1192 if (getLexicalDeclContext()->getRedeclContext()->isFileContext())
1193 return true;
1194
1195 if (isStaticDataMember())
1196 return true;
1197
1198 return false;
1199 }
1200
1201 /// getAnyInitializer - Get the initializer for this variable, no matter which
1202 /// declaration it is attached to.
1203 const Expr *getAnyInitializer() const {
1204 const VarDecl *D;
1205 return getAnyInitializer(D);
1206 }
1207
1208 /// getAnyInitializer - Get the initializer for this variable, no matter which
1209 /// declaration it is attached to. Also get that declaration.
1210 const Expr *getAnyInitializer(const VarDecl *&D) const;
1211
1212 bool hasInit() const;
1213 const Expr *getInit() const {
1214 return const_cast<VarDecl *>(this)->getInit();
1215 }
1216 Expr *getInit();
1217
1218 /// \brief Retrieve the address of the initializer expression.
1219 Stmt **getInitAddress();
1220
1221 void setInit(Expr *I);
1222
1223 /// \brief Determine whether this variable's value can be used in a
1224 /// constant expression, according to the relevant language standard.
1225 /// This only checks properties of the declaration, and does not check
1226 /// whether the initializer is in fact a constant expression.
1227 bool isUsableInConstantExpressions(ASTContext &C) const;
1228
1229 EvaluatedStmt *ensureEvaluatedStmt() const;
1230
1231 /// \brief Attempt to evaluate the value of the initializer attached to this
1232 /// declaration, and produce notes explaining why it cannot be evaluated or is
1233 /// not a constant expression. Returns a pointer to the value if evaluation
1234 /// succeeded, 0 otherwise.
1235 APValue *evaluateValue() const;
1236 APValue *evaluateValue(SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
1237
1238 /// \brief Return the already-evaluated value of this variable's
1239 /// initializer, or NULL if the value is not yet known. Returns pointer
1240 /// to untyped APValue if the value could not be evaluated.
1241 APValue *getEvaluatedValue() const;
1242
1243 /// \brief Determines whether it is already known whether the
1244 /// initializer is an integral constant expression or not.
1245 bool isInitKnownICE() const;
1246
1247 /// \brief Determines whether the initializer is an integral constant
1248 /// expression, or in C++11, whether the initializer is a constant
1249 /// expression.
1250 ///
1251 /// \pre isInitKnownICE()
1252 bool isInitICE() const;
1253
1254 /// \brief Determine whether the value of the initializer attached to this
1255 /// declaration is an integral constant expression.
1256 bool checkInitIsICE() const;
1257
1258 void setInitStyle(InitializationStyle Style) {
1259 VarDeclBits.InitStyle = Style;
1260 }
1261
1262 /// \brief The style of initialization for this declaration.
1263 ///
1264 /// C-style initialization is "int x = 1;". Call-style initialization is
1265 /// a C++98 direct-initializer, e.g. "int x(1);". The Init expression will be
1266 /// the expression inside the parens or a "ClassType(a,b,c)" class constructor
1267 /// expression for class types. List-style initialization is C++11 syntax,
1268 /// e.g. "int x{1};". Clients can distinguish between different forms of
1269 /// initialization by checking this value. In particular, "int x = {1};" is
1270 /// C-style, "int x({1})" is call-style, and "int x{1};" is list-style; the
1271 /// Init expression in all three cases is an InitListExpr.
1272 InitializationStyle getInitStyle() const {
1273 return static_cast<InitializationStyle>(VarDeclBits.InitStyle);
1274 }
1275
1276 /// \brief Whether the initializer is a direct-initializer (list or call).
1277 bool isDirectInit() const {
1278 return getInitStyle() != CInit;
1279 }
1280
1281 /// \brief If this definition should pretend to be a declaration.
1282 bool isThisDeclarationADemotedDefinition() const {
1283 return isa<ParmVarDecl>(this) ? false :
1284 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition;
1285 }
1286
1287 /// \brief This is a definition which should be demoted to a declaration.
1288 ///
1289 /// In some cases (mostly module merging) we can end up with two visible
1290 /// definitions one of which needs to be demoted to a declaration to keep
1291 /// the AST invariants.
1292 void demoteThisDefinitionToDeclaration() {
1293 assert(isThisDeclarationADefinition() && "Not a definition!")(static_cast <bool> (isThisDeclarationADefinition() &&
"Not a definition!") ? void (0) : __assert_fail ("isThisDeclarationADefinition() && \"Not a definition!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318631/tools/clang/include/clang/AST/Decl.h"
, 1293, __extension__ __PRETTY_FUNCTION__))
;
1294 assert(!isa<ParmVarDecl>(this) && "Cannot demote ParmVarDecls!")(static_cast <bool> (!isa<ParmVarDecl>(this) &&
"Cannot demote ParmVarDecls!") ? void (0) : __assert_fail ("!isa<ParmVarDecl>(this) && \"Cannot demote ParmVarDecls!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318631/tools/clang/include/clang/AST/Decl.h"
, 1294, __extension__ __PRETTY_FUNCTION__))
;
1295 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition = 1;
1296 }
1297
1298 /// \brief Determine whether this variable is the exception variable in a
1299 /// C++ catch statememt or an Objective-C \@catch statement.
1300 bool isExceptionVariable() const {
1301 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ExceptionVar;
1302 }
1303 void setExceptionVariable(bool EV) {
1304 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-6.0~svn318631/tools/clang/include/clang/AST/Decl.h"
, 1304, __extension__ __PRETTY_FUNCTION__))
;
1305 NonParmVarDeclBits.ExceptionVar = EV;
1306 }
1307
1308 /// \brief Determine whether this local variable can be used with the named
1309 /// return value optimization (NRVO).
1310 ///
1311 /// The named return value optimization (NRVO) works by marking certain
1312 /// non-volatile local variables of class type as NRVO objects. These
1313 /// locals can be allocated within the return slot of their containing
1314 /// function, in which case there is no need to copy the object to the
1315 /// return slot when returning from the function. Within the function body,
1316 /// each return that returns the NRVO object will have this variable as its
1317 /// NRVO candidate.
1318 bool isNRVOVariable() const {
1319 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.NRVOVariable;
1320 }
1321 void setNRVOVariable(bool NRVO) {
1322 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-6.0~svn318631/tools/clang/include/clang/AST/Decl.h"
, 1322, __extension__ __PRETTY_FUNCTION__))
;
1323 NonParmVarDeclBits.NRVOVariable = NRVO;
1324 }
1325
1326 /// \brief Determine whether this variable is the for-range-declaration in
1327 /// a C++0x for-range statement.
1328 bool isCXXForRangeDecl() const {
1329 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.CXXForRangeDecl;
1330 }
1331 void setCXXForRangeDecl(bool FRD) {
1332 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-6.0~svn318631/tools/clang/include/clang/AST/Decl.h"
, 1332, __extension__ __PRETTY_FUNCTION__))
;
1333 NonParmVarDeclBits.CXXForRangeDecl = FRD;
1334 }
1335
1336 /// \brief Determine whether this variable is an ARC pseudo-__strong
1337 /// variable. A pseudo-__strong variable has a __strong-qualified
1338 /// type but does not actually retain the object written into it.
1339 /// Generally such variables are also 'const' for safety.
1340 bool isARCPseudoStrong() const {
1341 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ARCPseudoStrong;
1342 }
1343 void setARCPseudoStrong(bool ps) {
1344 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-6.0~svn318631/tools/clang/include/clang/AST/Decl.h"
, 1344, __extension__ __PRETTY_FUNCTION__))
;
1345 NonParmVarDeclBits.ARCPseudoStrong = ps;
1346 }
1347
1348 /// Whether this variable is (C++1z) inline.
1349 bool isInline() const {
1350 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInline;
1351 }
1352 bool isInlineSpecified() const {
1353 return isa<ParmVarDecl>(this) ? false
1354 : NonParmVarDeclBits.IsInlineSpecified;
1355 }
1356 void setInlineSpecified() {
1357 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-6.0~svn318631/tools/clang/include/clang/AST/Decl.h"
, 1357, __extension__ __PRETTY_FUNCTION__))
;
1358 NonParmVarDeclBits.IsInline = true;
1359 NonParmVarDeclBits.IsInlineSpecified = true;
1360 }
1361 void setImplicitlyInline() {
1362 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-6.0~svn318631/tools/clang/include/clang/AST/Decl.h"
, 1362, __extension__ __PRETTY_FUNCTION__))
;
1363 NonParmVarDeclBits.IsInline = true;
1364 }
1365
1366 /// Whether this variable is (C++11) constexpr.
1367 bool isConstexpr() const {
1368 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsConstexpr;
1369 }
1370 void setConstexpr(bool IC) {
1371 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-6.0~svn318631/tools/clang/include/clang/AST/Decl.h"
, 1371, __extension__ __PRETTY_FUNCTION__))
;
1372 NonParmVarDeclBits.IsConstexpr = IC;
1373 }
1374
1375 /// Whether this variable is the implicit variable for a lambda init-capture.
1376 bool isInitCapture() const {
1377 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInitCapture;
1378 }
1379 void setInitCapture(bool IC) {
1380 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-6.0~svn318631/tools/clang/include/clang/AST/Decl.h"
, 1380, __extension__ __PRETTY_FUNCTION__))
;
1381 NonParmVarDeclBits.IsInitCapture = IC;
1382 }
1383
1384 /// Whether this local extern variable declaration's previous declaration
1385 /// was declared in the same block scope. Only correct in C++.
1386 bool isPreviousDeclInSameBlockScope() const {
1387 return isa<ParmVarDecl>(this)
1388 ? false
1389 : NonParmVarDeclBits.PreviousDeclInSameBlockScope;
1390 }
1391 void setPreviousDeclInSameBlockScope(bool Same) {
1392 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-6.0~svn318631/tools/clang/include/clang/AST/Decl.h"
, 1392, __extension__ __PRETTY_FUNCTION__))
;
1393 NonParmVarDeclBits.PreviousDeclInSameBlockScope = Same;
1394 }
1395
1396 /// \brief Retrieve the variable declaration from which this variable could
1397 /// be instantiated, if it is an instantiation (rather than a non-template).
1398 VarDecl *getTemplateInstantiationPattern() const;
1399
1400 /// \brief If this variable is an instantiated static data member of a
1401 /// class template specialization, returns the templated static data member
1402 /// from which it was instantiated.
1403 VarDecl *getInstantiatedFromStaticDataMember() const;
1404
1405 /// \brief If this variable is an instantiation of a variable template or a
1406 /// static data member of a class template, determine what kind of
1407 /// template specialization or instantiation this is.
1408 TemplateSpecializationKind getTemplateSpecializationKind() const;
1409
1410 /// \brief If this variable is an instantiation of a variable template or a
1411 /// static data member of a class template, determine its point of
1412 /// instantiation.
1413 SourceLocation getPointOfInstantiation() const;
1414
1415 /// \brief If this variable is an instantiation of a static data member of a
1416 /// class template specialization, retrieves the member specialization
1417 /// information.
1418 MemberSpecializationInfo *getMemberSpecializationInfo() const;
1419
1420 /// \brief For a static data member that was instantiated from a static
1421 /// data member of a class template, set the template specialiation kind.
1422 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1423 SourceLocation PointOfInstantiation = SourceLocation());
1424
1425 /// \brief Specify that this variable is an instantiation of the
1426 /// static data member VD.
1427 void setInstantiationOfStaticDataMember(VarDecl *VD,
1428 TemplateSpecializationKind TSK);
1429
1430 /// \brief Retrieves the variable template that is described by this
1431 /// variable declaration.
1432 ///
1433 /// Every variable template is represented as a VarTemplateDecl and a
1434 /// VarDecl. The former contains template properties (such as
1435 /// the template parameter lists) while the latter contains the
1436 /// actual description of the template's
1437 /// contents. VarTemplateDecl::getTemplatedDecl() retrieves the
1438 /// VarDecl that from a VarTemplateDecl, while
1439 /// getDescribedVarTemplate() retrieves the VarTemplateDecl from
1440 /// a VarDecl.
1441 VarTemplateDecl *getDescribedVarTemplate() const;
1442
1443 void setDescribedVarTemplate(VarTemplateDecl *Template);
1444
1445 // Implement isa/cast/dyncast/etc.
1446 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
13
Calling 'Decl::getKind'
14
Returning from 'Decl::getKind'
15
Calling 'VarDecl::classofKind'
18
Returning from 'VarDecl::classofKind'
1447 static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; }
16
Assuming 'K' is >= firstVar
17
Assuming 'K' is <= lastVar
1448};
1449
1450class ImplicitParamDecl : public VarDecl {
1451 void anchor() override;
1452
1453public:
1454 /// Defines the kind of the implicit parameter: is this an implicit parameter
1455 /// with pointer to 'this', 'self', '_cmd', virtual table pointers, captured
1456 /// context or something else.
1457 enum ImplicitParamKind : unsigned {
1458 /// Parameter for Objective-C 'self' argument
1459 ObjCSelf,
1460
1461 /// Parameter for Objective-C '_cmd' argument
1462 ObjCCmd,
1463
1464 /// Parameter for C++ 'this' argument
1465 CXXThis,
1466
1467 /// Parameter for C++ virtual table pointers
1468 CXXVTT,
1469
1470 /// Parameter for captured context
1471 CapturedContext,
1472
1473 /// Other implicit parameter
1474 Other,
1475 };
1476
1477 /// Create implicit parameter.
1478 static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC,
1479 SourceLocation IdLoc, IdentifierInfo *Id,
1480 QualType T, ImplicitParamKind ParamKind);
1481 static ImplicitParamDecl *Create(ASTContext &C, QualType T,
1482 ImplicitParamKind ParamKind);
1483
1484 static ImplicitParamDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1485
1486 ImplicitParamDecl(ASTContext &C, DeclContext *DC, SourceLocation IdLoc,
1487 IdentifierInfo *Id, QualType Type,
1488 ImplicitParamKind ParamKind)
1489 : VarDecl(ImplicitParam, C, DC, IdLoc, IdLoc, Id, Type,
1490 /*TInfo=*/nullptr, SC_None) {
1491 NonParmVarDeclBits.ImplicitParamKind = ParamKind;
1492 setImplicit();
1493 }
1494
1495 ImplicitParamDecl(ASTContext &C, QualType Type, ImplicitParamKind ParamKind)
1496 : VarDecl(ImplicitParam, C, /*DC=*/nullptr, SourceLocation(),
1497 SourceLocation(), /*Id=*/nullptr, Type,
1498 /*TInfo=*/nullptr, SC_None) {
1499 NonParmVarDeclBits.ImplicitParamKind = ParamKind;
1500 setImplicit();
1501 }
1502
1503 /// Returns the implicit parameter kind.
1504 ImplicitParamKind getParameterKind() const {
1505 return static_cast<ImplicitParamKind>(NonParmVarDeclBits.ImplicitParamKind);
1506 }
1507
1508 // Implement isa/cast/dyncast/etc.
1509 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1510 static bool classofKind(Kind K) { return K == ImplicitParam; }
1511};
1512
1513/// ParmVarDecl - Represents a parameter to a function.
1514class ParmVarDecl : public VarDecl {
1515public:
1516 enum { MaxFunctionScopeDepth = 255 };
1517 enum { MaxFunctionScopeIndex = 255 };
1518
1519protected:
1520 ParmVarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1521 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
1522 TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
1523 : VarDecl(DK, C, DC, StartLoc, IdLoc, Id, T, TInfo, S) {
1524 assert(ParmVarDeclBits.HasInheritedDefaultArg == false)(static_cast <bool> (ParmVarDeclBits.HasInheritedDefaultArg
== false) ? void (0) : __assert_fail ("ParmVarDeclBits.HasInheritedDefaultArg == false"
, "/build/llvm-toolchain-snapshot-6.0~svn318631/tools/clang/include/clang/AST/Decl.h"
, 1524, __extension__ __PRETTY_FUNCTION__))
;
1525 assert(ParmVarDeclBits.DefaultArgKind == DAK_None)(static_cast <bool> (ParmVarDeclBits.DefaultArgKind == DAK_None
) ? void (0) : __assert_fail ("ParmVarDeclBits.DefaultArgKind == DAK_None"
, "/build/llvm-toolchain-snapshot-6.0~svn318631/tools/clang/include/clang/AST/Decl.h"
, 1525, __extension__ __PRETTY_FUNCTION__))
;
1526 assert(ParmVarDeclBits.IsKNRPromoted == false)(static_cast <bool> (ParmVarDeclBits.IsKNRPromoted == false
) ? void (0) : __assert_fail ("ParmVarDeclBits.IsKNRPromoted == false"
, "/build/llvm-toolchain-snapshot-6.0~svn318631/tools/clang/include/clang/AST/Decl.h"
, 1526, __extension__ __PRETTY_FUNCTION__))
;
1527 assert(ParmVarDeclBits.IsObjCMethodParam == false)(static_cast <bool> (ParmVarDeclBits.IsObjCMethodParam ==
false) ? void (0) : __assert_fail ("ParmVarDeclBits.IsObjCMethodParam == false"
, "/build/llvm-toolchain-snapshot-6.0~svn318631/tools/clang/include/clang/AST/Decl.h"
, 1527, __extension__ __PRETTY_FUNCTION__))
;
1528 setDefaultArg(DefArg);
1529 }
1530
1531public:
1532 static ParmVarDecl *Create(ASTContext &C, DeclContext *DC,
1533 SourceLocation StartLoc,
1534 SourceLocation IdLoc, IdentifierInfo *Id,
1535 QualType T, TypeSourceInfo *TInfo,
1536 StorageClass S, Expr *DefArg);
1537
1538 static ParmVarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1539
1540 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1541
1542 void setObjCMethodScopeInfo(unsigned parameterIndex) {
1543 ParmVarDeclBits.IsObjCMethodParam = true;
1544 setParameterIndex(parameterIndex);
1545 }
1546
1547 void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex) {
1548 assert(!ParmVarDeclBits.IsObjCMethodParam)(static_cast <bool> (!ParmVarDeclBits.IsObjCMethodParam
) ? void (0) : __assert_fail ("!ParmVarDeclBits.IsObjCMethodParam"
, "/build/llvm-toolchain-snapshot-6.0~svn318631/tools/clang/include/clang/AST/Decl.h"
, 1548, __extension__ __PRETTY_FUNCTION__))
;
1549
1550 ParmVarDeclBits.ScopeDepthOrObjCQuals = scopeDepth;
1551 assert(ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth(static_cast <bool> (ParmVarDeclBits.ScopeDepthOrObjCQuals
== scopeDepth && "truncation!") ? void (0) : __assert_fail
("ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && \"truncation!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318631/tools/clang/include/clang/AST/Decl.h"
, 1552, __extension__ __PRETTY_FUNCTION__))
1552 && "truncation!")(static_cast <bool> (ParmVarDeclBits.ScopeDepthOrObjCQuals
== scopeDepth && "truncation!") ? void (0) : __assert_fail
("ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && \"truncation!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318631/tools/clang/include/clang/AST/Decl.h"
, 1552, __extension__ __PRETTY_FUNCTION__))
;
1553
1554 setParameterIndex(parameterIndex);
1555 }
1556
1557 bool isObjCMethodParameter() const {
1558 return ParmVarDeclBits.IsObjCMethodParam;
1559 }
1560
1561 unsigned getFunctionScopeDepth() const {
1562 if (ParmVarDeclBits.IsObjCMethodParam) return 0;
1563 return ParmVarDeclBits.ScopeDepthOrObjCQuals;
1564 }
1565
1566 /// Returns the index of this parameter in its prototype or method scope.
1567 unsigned getFunctionScopeIndex() const {
1568 return getParameterIndex();
1569 }
1570
1571 ObjCDeclQualifier getObjCDeclQualifier() const {
1572 if (!ParmVarDeclBits.IsObjCMethodParam) return OBJC_TQ_None;
1573 return ObjCDeclQualifier(ParmVarDeclBits.ScopeDepthOrObjCQuals);
1574 }
1575 void setObjCDeclQualifier(ObjCDeclQualifier QTVal) {
1576 assert(ParmVarDeclBits.IsObjCMethodParam)(static_cast <bool> (ParmVarDeclBits.IsObjCMethodParam)
? void (0) : __assert_fail ("ParmVarDeclBits.IsObjCMethodParam"
, "/build/llvm-toolchain-snapshot-6.0~svn318631/tools/clang/include/clang/AST/Decl.h"
, 1576, __extension__ __PRETTY_FUNCTION__))
;
1577 ParmVarDeclBits.ScopeDepthOrObjCQuals = QTVal;
1578 }
1579
1580 /// True if the value passed to this parameter must undergo
1581 /// K&R-style default argument promotion:
1582 ///
1583 /// C99 6.5.2.2.
1584 /// If the expression that denotes the called function has a type
1585 /// that does not include a prototype, the integer promotions are
1586 /// performed on each argument, and arguments that have type float
1587 /// are promoted to double.
1588 bool isKNRPromoted() const {
1589 return ParmVarDeclBits.IsKNRPromoted;
1590 }
1591 void setKNRPromoted(bool promoted) {
1592 ParmVarDeclBits.IsKNRPromoted = promoted;
1593 }
1594
1595 Expr *getDefaultArg();
1596 const Expr *getDefaultArg() const {
1597 return const_cast<ParmVarDecl *>(this)->getDefaultArg();
1598 }
1599
1600 void setDefaultArg(Expr *defarg);
1601
1602 /// \brief Retrieve the source range that covers the entire default
1603 /// argument.
1604 SourceRange getDefaultArgRange() const;
1605 void setUninstantiatedDefaultArg(Expr *arg);
1606 Expr *getUninstantiatedDefaultArg();
1607 const Expr *getUninstantiatedDefaultArg() const {
1608 return const_cast<ParmVarDecl *>(this)->getUninstantiatedDefaultArg();
1609 }
1610
1611 /// hasDefaultArg - Determines whether this parameter has a default argument,
1612 /// either parsed or not.
1613 bool hasDefaultArg() const;
1614
1615 /// hasUnparsedDefaultArg - Determines whether this parameter has a
1616 /// default argument that has not yet been parsed. This will occur
1617 /// during the processing of a C++ class whose member functions have
1618 /// default arguments, e.g.,
1619 /// @code
1620 /// class X {
1621 /// public:
1622 /// void f(int x = 17); // x has an unparsed default argument now
1623 /// }; // x has a regular default argument now
1624 /// @endcode
1625 bool hasUnparsedDefaultArg() const {
1626 return ParmVarDeclBits.DefaultArgKind == DAK_Unparsed;
1627 }
1628
1629 bool hasUninstantiatedDefaultArg() const {
1630 return ParmVarDeclBits.DefaultArgKind == DAK_Uninstantiated;
1631 }
1632
1633 /// setUnparsedDefaultArg - Specify that this parameter has an
1634 /// unparsed default argument. The argument will be replaced with a
1635 /// real default argument via setDefaultArg when the class
1636 /// definition enclosing the function declaration that owns this
1637 /// default argument is completed.
1638 void setUnparsedDefaultArg() {
1639 ParmVarDeclBits.DefaultArgKind = DAK_Unparsed;
1640 }
1641
1642 bool hasInheritedDefaultArg() const {
1643 return ParmVarDeclBits.HasInheritedDefaultArg;
1644 }
1645
1646 void setHasInheritedDefaultArg(bool I = true) {
1647 ParmVarDeclBits.HasInheritedDefaultArg = I;
1648 }
1649
1650 QualType getOriginalType() const;
1651
1652 /// \brief Determine whether this parameter is actually a function
1653 /// parameter pack.
1654 bool isParameterPack() const;
1655
1656 /// setOwningFunction - Sets the function declaration that owns this
1657 /// ParmVarDecl. Since ParmVarDecls are often created before the
1658 /// FunctionDecls that own them, this routine is required to update
1659 /// the DeclContext appropriately.
1660 void setOwningFunction(DeclContext *FD) { setDeclContext(FD); }
1661
1662 // Implement isa/cast/dyncast/etc.
1663 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1664 static bool classofKind(Kind K) { return K == ParmVar; }
1665
1666private:
1667 enum { ParameterIndexSentinel = (1 << NumParameterIndexBits) - 1 };
1668
1669 void setParameterIndex(unsigned parameterIndex) {
1670 if (parameterIndex >= ParameterIndexSentinel) {
1671 setParameterIndexLarge(parameterIndex);
1672 return;
1673 }
1674
1675 ParmVarDeclBits.ParameterIndex = parameterIndex;
1676 assert(ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!")(static_cast <bool> (ParmVarDeclBits.ParameterIndex == parameterIndex
&& "truncation!") ? void (0) : __assert_fail ("ParmVarDeclBits.ParameterIndex == parameterIndex && \"truncation!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318631/tools/clang/include/clang/AST/Decl.h"
, 1676, __extension__ __PRETTY_FUNCTION__))
;
1677 }
1678 unsigned getParameterIndex() const {
1679 unsigned d = ParmVarDeclBits.ParameterIndex;
1680 return d == ParameterIndexSentinel ? getParameterIndexLarge() : d;
1681 }
1682
1683 void setParameterIndexLarge(unsigned parameterIndex);
1684 unsigned getParameterIndexLarge() const;
1685};
1686
1687/// FunctionDecl - An instance of this class is created to represent a
1688/// function declaration or definition.
1689///
1690/// Since a given function can be declared several times in a program,
1691/// there may be several FunctionDecls that correspond to that
1692/// function. Only one of those FunctionDecls will be found when
1693/// traversing the list of declarations in the context of the
1694/// FunctionDecl (e.g., the translation unit); this FunctionDecl
1695/// contains all of the information known about the function. Other,
1696/// previous declarations of the function are available via the
1697/// getPreviousDecl() chain.
1698class FunctionDecl : public DeclaratorDecl, public DeclContext,
1699 public Redeclarable<FunctionDecl> {
1700public:
1701 /// \brief The kind of templated function a FunctionDecl can be.
1702 enum TemplatedKind {
1703 TK_NonTemplate,
1704 TK_FunctionTemplate,
1705 TK_MemberSpecialization,
1706 TK_FunctionTemplateSpecialization,
1707 TK_DependentFunctionTemplateSpecialization
1708 };
1709
1710private:
1711 /// ParamInfo - new[]'d array of pointers to VarDecls for the formal
1712 /// parameters of this function. This is null if a prototype or if there are
1713 /// no formals.
1714 ParmVarDecl **ParamInfo = nullptr;
1715
1716 LazyDeclStmtPtr Body;
1717
1718 // FIXME: This can be packed into the bitfields in DeclContext.
1719 // NOTE: VC++ packs bitfields poorly if the types differ.
1720 unsigned SClass : 3;
1721 unsigned IsInline : 1;
1722 unsigned IsInlineSpecified : 1;
1723
1724protected:
1725 // This is shared by CXXConstructorDecl, CXXConversionDecl, and
1726 // CXXDeductionGuideDecl.
1727 unsigned IsExplicitSpecified : 1;
1728
1729private:
1730 unsigned IsVirtualAsWritten : 1;
1731 unsigned IsPure : 1;
1732 unsigned HasInheritedPrototype : 1;
1733 unsigned HasWrittenPrototype : 1;
1734 unsigned IsDeleted : 1;
1735 unsigned IsTrivial : 1; // sunk from CXXMethodDecl
1736 unsigned IsDefaulted : 1; // sunk from CXXMethoDecl
1737 unsigned IsExplicitlyDefaulted : 1; //sunk from CXXMethodDecl
1738 unsigned HasImplicitReturnZero : 1;
1739 unsigned IsLateTemplateParsed : 1;
1740 unsigned IsConstexpr : 1;
1741 unsigned InstantiationIsPending : 1;
1742
1743 /// \brief Indicates if the function uses __try.
1744 unsigned UsesSEHTry : 1;
1745
1746 /// \brief Indicates if the function was a definition but its body was
1747 /// skipped.
1748 unsigned HasSkippedBody : 1;
1749
1750 /// Indicates if the function declaration will have a body, once we're done
1751 /// parsing it.
1752 unsigned WillHaveBody : 1;
1753
1754protected:
1755 /// [C++17] Only used by CXXDeductionGuideDecl. Declared here to avoid
1756 /// increasing the size of CXXDeductionGuideDecl by the size of an unsigned
1757 /// int as opposed to adding a single bit to FunctionDecl.
1758 /// Indicates that the Deduction Guide is the implicitly generated 'copy
1759 /// deduction candidate' (is used during overload resolution).
1760 unsigned IsCopyDeductionCandidate : 1;
1761
1762private:
1763 /// \brief End part of this FunctionDecl's source range.
1764 ///
1765 /// We could compute the full range in getSourceRange(). However, when we're
1766 /// dealing with a function definition deserialized from a PCH/AST file,
1767 /// we can only compute the full range once the function body has been
1768 /// de-serialized, so it's far better to have the (sometimes-redundant)
1769 /// EndRangeLoc.
1770 SourceLocation EndRangeLoc;
1771
1772 /// \brief The template or declaration that this declaration
1773 /// describes or was instantiated from, respectively.
1774 ///
1775 /// For non-templates, this value will be NULL. For function
1776 /// declarations that describe a function template, this will be a
1777 /// pointer to a FunctionTemplateDecl. For member functions
1778 /// of class template specializations, this will be a MemberSpecializationInfo
1779 /// pointer containing information about the specialization.
1780 /// For function template specializations, this will be a
1781 /// FunctionTemplateSpecializationInfo, which contains information about
1782 /// the template being specialized and the template arguments involved in
1783 /// that specialization.
1784 llvm::PointerUnion4<FunctionTemplateDecl *,
1785 MemberSpecializationInfo *,
1786 FunctionTemplateSpecializationInfo *,
1787 DependentFunctionTemplateSpecializationInfo *>
1788 TemplateOrSpecialization;
1789
1790 /// DNLoc - Provides source/type location info for the
1791 /// declaration name embedded in the DeclaratorDecl base class.
1792 DeclarationNameLoc DNLoc;
1793
1794 /// \brief Specify that this function declaration is actually a function
1795 /// template specialization.
1796 ///
1797 /// \param C the ASTContext.
1798 ///
1799 /// \param Template the function template that this function template
1800 /// specialization specializes.
1801 ///
1802 /// \param TemplateArgs the template arguments that produced this
1803 /// function template specialization from the template.
1804 ///
1805 /// \param InsertPos If non-NULL, the position in the function template
1806 /// specialization set where the function template specialization data will
1807 /// be inserted.
1808 ///
1809 /// \param TSK the kind of template specialization this is.
1810 ///
1811 /// \param TemplateArgsAsWritten location info of template arguments.
1812 ///
1813 /// \param PointOfInstantiation point at which the function template
1814 /// specialization was first instantiated.
1815 void setFunctionTemplateSpecialization(ASTContext &C,
1816 FunctionTemplateDecl *Template,
1817 const TemplateArgumentList *TemplateArgs,
1818 void *InsertPos,
1819 TemplateSpecializationKind TSK,
1820 const TemplateArgumentListInfo *TemplateArgsAsWritten,
1821 SourceLocation PointOfInstantiation);
1822
1823 /// \brief Specify that this record is an instantiation of the
1824 /// member function FD.
1825 void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD,
1826 TemplateSpecializationKind TSK);
1827
1828 void setParams(ASTContext &C, ArrayRef<ParmVarDecl *> NewParamInfo);
1829
1830protected:
1831 FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1832 const DeclarationNameInfo &NameInfo, QualType T,
1833 TypeSourceInfo *TInfo, StorageClass S, bool isInlineSpecified,
1834 bool isConstexprSpecified)
1835 : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
1836 StartLoc),
1837 DeclContext(DK), redeclarable_base(C), SClass(S),
1838 IsInline(isInlineSpecified), IsInlineSpecified(isInlineSpecified),
1839 IsExplicitSpecified(false), IsVirtualAsWritten(false), IsPure(false),
1840 HasInheritedPrototype(false), HasWrittenPrototype(true),
1841 IsDeleted(false), IsTrivial(false), IsDefaulted(false),
1842 IsExplicitlyDefaulted(false), HasImplicitReturnZero(false),
1843 IsLateTemplateParsed(false), IsConstexpr(isConstexprSpecified),
1844 InstantiationIsPending(false), UsesSEHTry(false), HasSkippedBody(false),
1845 WillHaveBody(false), IsCopyDeductionCandidate(false),
1846 EndRangeLoc(NameInfo.getEndLoc()), DNLoc(NameInfo.getInfo()) {}
1847
1848 using redeclarable_base = Redeclarable<FunctionDecl>;
1849
1850 FunctionDecl *getNextRedeclarationImpl() override {
1851 return getNextRedeclaration();
1852 }
1853
1854 FunctionDecl *getPreviousDeclImpl() override {
1855 return getPreviousDecl();
1856 }
1857
1858 FunctionDecl *getMostRecentDeclImpl() override {
1859 return getMostRecentDecl();
1860 }
1861
1862public:
1863 friend class ASTDeclReader;
1864 friend class ASTDeclWriter;
1865
1866 using redecl_range = redeclarable_base::redecl_range;
1867 using redecl_iterator = redeclarable_base::redecl_iterator;
1868
1869 using redeclarable_base::redecls_begin;
1870 using redeclarable_base::redecls_end;
1871 using redeclarable_base::redecls;
1872 using redeclarable_base::getPreviousDecl;
1873 using redeclarable_base::getMostRecentDecl;
1874 using redeclarable_base::isFirstDecl;
1875
1876 static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1877 SourceLocation StartLoc, SourceLocation NLoc,
1878 DeclarationName N, QualType T,
1879 TypeSourceInfo *TInfo,
1880 StorageClass SC,
1881 bool isInlineSpecified = false,
1882 bool hasWrittenPrototype = true,
1883 bool isConstexprSpecified = false) {
1884 DeclarationNameInfo NameInfo(N, NLoc);
1885 return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo,
1886 SC,
1887 isInlineSpecified, hasWrittenPrototype,
1888 isConstexprSpecified);
1889 }
1890
1891 static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1892 SourceLocation StartLoc,
1893 const DeclarationNameInfo &NameInfo,
1894 QualType T, TypeSourceInfo *TInfo,
1895 StorageClass SC,
1896 bool isInlineSpecified,
1897 bool hasWrittenPrototype,
1898 bool isConstexprSpecified = false);
1899
1900 static FunctionDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1901
1902 DeclarationNameInfo getNameInfo() const {
1903 return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
1904 }
1905
1906 void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
1907 bool Qualified) const override;
1908
1909 void setRangeEnd(SourceLocation E) { EndRangeLoc = E; }
1910
1911 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1912
1913 /// \brief Returns true if the function has a body (definition). The
1914 /// function body might be in any of the (re-)declarations of this
1915 /// function. The variant that accepts a FunctionDecl pointer will
1916 /// set that function declaration to the actual declaration
1917 /// containing the body (if there is one).
1918 bool hasBody(const FunctionDecl *&Definition) const;
1919
1920 bool hasBody() const override {
1921 const FunctionDecl* Definition;
1922 return hasBody(Definition);
1923 }
1924
1925 /// hasTrivialBody - Returns whether the function has a trivial body that does
1926 /// not require any specific codegen.
1927 bool hasTrivialBody() const;
1928
1929 /// isDefined - Returns true if the function is defined at all, including
1930 /// a deleted definition. Except for the behavior when the function is
1931 /// deleted, behaves like hasBody.
1932 bool isDefined(const FunctionDecl *&Definition) const;
1933
1934 virtual bool isDefined() const {
1935 const FunctionDecl* Definition;
1936 return isDefined(Definition);
1937 }
1938
1939 /// \brief Get the definition for this declaration.
1940 FunctionDecl *getDefinition() {
1941 const FunctionDecl *Definition;
1942 if (isDefined(Definition))
1943 return const_cast<FunctionDecl *>(Definition);
1944 return nullptr;
1945 }
1946 const FunctionDecl *getDefinition() const {
1947 return const_cast<FunctionDecl *>(this)->getDefinition();
1948 }
1949
1950 /// getBody - Retrieve the body (definition) of the function. The
1951 /// function body might be in any of the (re-)declarations of this
1952 /// function. The variant that accepts a FunctionDecl pointer will
1953 /// set that function declaration to the actual declaration
1954 /// containing the body (if there is one).
1955 /// NOTE: For checking if there is a body, use hasBody() instead, to avoid
1956 /// unnecessary AST de-serialization of the body.
1957 Stmt *getBody(const FunctionDecl *&Definition) const;
1958
1959 Stmt *getBody() const override {
1960 const FunctionDecl* Definition;
1961 return getBody(Definition);
1962 }
1963
1964 /// Returns whether this specific declaration of the function is also a
1965 /// definition that does not contain uninstantiated body.
1966 ///
1967 /// This does not determine whether the function has been defined (e.g., in a
1968 /// previous definition); for that information, use isDefined.
1969 bool isThisDeclarationADefinition() const {
1970 return IsDeleted || IsDefaulted || Body || IsLateTemplateParsed ||
1971 WillHaveBody || hasDefiningAttr();
1972 }
1973
1974 /// doesThisDeclarationHaveABody - Returns whether this specific
1975 /// declaration of the function has a body - that is, if it is a non-
1976 /// deleted definition.
1977 bool doesThisDeclarationHaveABody() const {
1978 return Body || IsLateTemplateParsed;
1979 }
1980
1981 void setBody(Stmt *B);
1982 void setLazyBody(uint64_t Offset) { Body = Offset; }
1983
1984 /// Whether this function is variadic.
1985 bool isVariadic() const;
1986
1987 /// Whether this function is marked as virtual explicitly.
1988 bool isVirtualAsWritten() const { return IsVirtualAsWritten; }
1989 void setVirtualAsWritten(bool V) { IsVirtualAsWritten = V; }
1990
1991 /// Whether this virtual function is pure, i.e. makes the containing class
1992 /// abstract.
1993 bool isPure() const { return IsPure; }
1994 void setPure(bool P = true);
1995
1996 /// Whether this templated function will be late parsed.
1997 bool isLateTemplateParsed() const { return IsLateTemplateParsed; }
1998 void setLateTemplateParsed(bool ILT = true) { IsLateTemplateParsed = ILT; }
1999
2000 /// Whether this function is "trivial" in some specialized C++ senses.
2001 /// Can only be true for default constructors, copy constructors,
2002 /// copy assignment operators, and destructors. Not meaningful until
2003 /// the class has been fully built by Sema.
2004 bool isTrivial() const { return IsTrivial; }
2005 void setTrivial(bool IT) { IsTrivial = IT; }
2006
2007 /// Whether this function is defaulted per C++0x. Only valid for
2008 /// special member functions.
2009 bool isDefaulted() const { return IsDefaulted; }
2010 void setDefaulted(bool D = true) { IsDefaulted = D; }
2011
2012 /// Whether this function is explicitly defaulted per C++0x. Only valid
2013 /// for special member functions.
2014 bool isExplicitlyDefaulted() const { return IsExplicitlyDefaulted; }
2015 void setExplicitlyDefaulted(bool ED = true) { IsExplicitlyDefaulted = ED; }
2016
2017 /// Whether falling off this function implicitly returns null/zero.
2018 /// If a more specific implicit return value is required, front-ends
2019 /// should synthesize the appropriate return statements.
2020 bool hasImplicitReturnZero() const { return HasImplicitReturnZero; }
2021 void setHasImplicitReturnZero(bool IRZ) { HasImplicitReturnZero = IRZ; }
2022
2023 /// \brief Whether this function has a prototype, either because one
2024 /// was explicitly written or because it was "inherited" by merging
2025 /// a declaration without a prototype with a declaration that has a
2026 /// prototype.
2027 bool hasPrototype() const {
2028 return HasWrittenPrototype || HasInheritedPrototype;
2029 }
2030
2031 bool hasWrittenPrototype() const { return HasWrittenPrototype; }
2032
2033 /// \brief Whether this function inherited its prototype from a
2034 /// previous declaration.
2035 bool hasInheritedPrototype() const { return HasInheritedPrototype; }
2036 void setHasInheritedPrototype(bool P = true) { HasInheritedPrototype = P; }
2037
2038 /// Whether this is a (C++11) constexpr function or constexpr constructor.
2039 bool isConstexpr() const { return IsConstexpr; }
2040 void setConstexpr(bool IC) { IsConstexpr = IC; }
2041
2042 /// \brief Whether the instantiation of this function is pending.
2043 /// This bit is set when the decision to instantiate this function is made
2044 /// and unset if and when the function body is created. That leaves out
2045 /// cases where instantiation did not happen because the template definition
2046 /// was not seen in this TU. This bit remains set in those cases, under the
2047 /// assumption that the instantiation will happen in some other TU.
2048 bool instantiationIsPending() const { return InstantiationIsPending; }
2049 void setInstantiationIsPending(bool IC) { InstantiationIsPending = IC; }
2050
2051 /// \brief Indicates the function uses __try.
2052 bool usesSEHTry() const { return UsesSEHTry; }
2053 void setUsesSEHTry(bool UST) { UsesSEHTry = UST; }
2054
2055 /// \brief Whether this function has been deleted.
2056 ///
2057 /// A function that is "deleted" (via the C++0x "= delete" syntax)
2058 /// acts like a normal function, except that it cannot actually be
2059 /// called or have its address taken. Deleted functions are
2060 /// typically used in C++ overload resolution to attract arguments
2061 /// whose type or lvalue/rvalue-ness would permit the use of a
2062 /// different overload that would behave incorrectly. For example,
2063 /// one might use deleted functions to ban implicit conversion from
2064 /// a floating-point number to an Integer type:
2065 ///
2066 /// @code
2067 /// struct Integer {
2068 /// Integer(long); // construct from a long
2069 /// Integer(double) = delete; // no construction from float or double
2070 /// Integer(long double) = delete; // no construction from long double
2071 /// };
2072 /// @endcode
2073 // If a function is deleted, its first declaration must be.
2074 bool isDeleted() const { return getCanonicalDecl()->IsDeleted; }
2075 bool isDeletedAsWritten() const { return IsDeleted && !IsDefaulted; }
2076 void setDeletedAsWritten(bool D = true) { IsDeleted = D; }
2077
2078 /// \brief Determines whether this function is "main", which is the
2079 /// entry point into an executable program.
2080 bool isMain() const;
2081
2082 /// \brief Determines whether this function is a MSVCRT user defined entry
2083 /// point.
2084 bool isMSVCRTEntryPoint() const;
2085
2086 /// \brief Determines whether this operator new or delete is one
2087 /// of the reserved global placement operators:
2088 /// void *operator new(size_t, void *);
2089 /// void *operator new[](size_t, void *);
2090 /// void operator delete(void *, void *);
2091 /// void operator delete[](void *, void *);
2092 /// These functions have special behavior under [new.delete.placement]:
2093 /// These functions are reserved, a C++ program may not define
2094 /// functions that displace the versions in the Standard C++ library.
2095 /// The provisions of [basic.stc.dynamic] do not apply to these
2096 /// reserved placement forms of operator new and operator delete.
2097 ///
2098 /// This function must be an allocation or deallocation function.
2099 bool isReservedGlobalPlacementOperator() const;
2100
2101 /// \brief Determines whether this function is one of the replaceable
2102 /// global allocation functions:
2103 /// void *operator new(size_t);
2104 /// void *operator new(size_t, const std::nothrow_t &) noexcept;
2105 /// void *operator new[](size_t);
2106 /// void *operator new[](size_t, const std::nothrow_t &) noexcept;
2107 /// void operator delete(void *) noexcept;
2108 /// void operator delete(void *, std::size_t) noexcept; [C++1y]
2109 /// void operator delete(void *, const std::nothrow_t &) noexcept;
2110 /// void operator delete[](void *) noexcept;
2111 /// void operator delete[](void *, std::size_t) noexcept; [C++1y]
2112 /// void operator delete[](void *, const std::nothrow_t &) noexcept;
2113 /// These functions have special behavior under C++1y [expr.new]:
2114 /// An implementation is allowed to omit a call to a replaceable global
2115 /// allocation function. [...]
2116 ///
2117 /// If this function is an aligned allocation/deallocation function, return
2118 /// true through IsAligned.
2119 bool isReplaceableGlobalAllocationFunction(bool *IsAligned = nullptr) const;
2120
2121 /// \brief Determine whether this is a destroying operator delete.
2122 bool isDestroyingOperatorDelete() const;
2123
2124 /// Compute the language linkage.
2125 LanguageLinkage getLanguageLinkage() const;
2126
2127 /// \brief Determines whether this function is a function with
2128 /// external, C linkage.
2129 bool isExternC() const;
2130
2131 /// \brief Determines whether this function's context is, or is nested within,
2132 /// a C++ extern "C" linkage spec.
2133 bool isInExternCContext() const;
2134
2135 /// \brief Determines whether this function's context is, or is nested within,
2136 /// a C++ extern "C++" linkage spec.
2137 bool isInExternCXXContext() const;
2138
2139 /// \brief Determines whether this is a global function.
2140 bool isGlobal() const;
2141
2142 /// \brief Determines whether this function is known to be 'noreturn', through
2143 /// an attribute on its declaration or its type.
2144 bool isNoReturn() const;
2145
2146 /// \brief True if the function was a definition but its body was skipped.
2147 bool hasSkippedBody() const { return HasSkippedBody; }
2148 void setHasSkippedBody(bool Skipped = true) { HasSkippedBody = Skipped; }
2149
2150 /// True if this function will eventually have a body, once it's fully parsed.
2151 bool willHaveBody() const { return WillHaveBody; }
2152 void setWillHaveBody(bool V = true) { WillHaveBody = V; }
2153
2154 void setPreviousDeclaration(FunctionDecl * PrevDecl);
2155
2156 FunctionDecl *getCanonicalDecl() override;
2157 const FunctionDecl *getCanonicalDecl() const {
2158 return const_cast<FunctionDecl*>(this)->getCanonicalDecl();
2159 }
2160
2161 unsigned getBuiltinID() const;
2162
2163 // ArrayRef interface to parameters.
2164 ArrayRef<ParmVarDecl *> parameters() const {
2165 return {ParamInfo, getNumParams()};
2166 }
2167 MutableArrayRef<ParmVarDecl *> parameters() {
2168 return {ParamInfo, getNumParams()};
2169 }
2170
2171 // Iterator access to formal parameters.
2172 using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator;
2173 using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator;
2174
2175 bool param_empty() const { return parameters().empty(); }
2176 param_iterator param_begin() { return parameters().begin(); }
2177 param_iterator param_end() { return parameters().end(); }
2178 param_const_iterator param_begin() const { return parameters().begin(); }
2179 param_const_iterator param_end() const { return parameters().end(); }
2180 size_t param_size() const { return parameters().size(); }
2181
2182 /// getNumParams - Return the number of parameters this function must have
2183 /// based on its FunctionType. This is the length of the ParamInfo array
2184 /// after it has been created.
2185 unsigned getNumParams() const;
2186
2187 const ParmVarDecl *getParamDecl(unsigned i) const {
2188 assert(i < getNumParams() && "Illegal param #")(static_cast <bool> (i < getNumParams() && "Illegal param #"
) ? void (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-6.0~svn318631/tools/clang/include/clang/AST/Decl.h"
, 2188, __extension__ __PRETTY_FUNCTION__))
;
2189 return ParamInfo[i];
2190 }
2191 ParmVarDecl *getParamDecl(unsigned i) {
2192 assert(i < getNumParams() && "Illegal param #")(static_cast <bool> (i < getNumParams() && "Illegal param #"
) ? void (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-6.0~svn318631/tools/clang/include/clang/AST/Decl.h"
, 2192, __extension__ __PRETTY_FUNCTION__))
;
2193 return ParamInfo[i];
2194 }
2195 void setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
2196 setParams(getASTContext(), NewParamInfo);
2197 }
2198
2199 /// getMinRequiredArguments - Returns the minimum number of arguments
2200 /// needed to call this function. This may be fewer than the number of
2201 /// function parameters, if some of the parameters have default
2202 /// arguments (in C++).
2203 unsigned getMinRequiredArguments() const;
2204
2205 QualType getReturnType() const {
2206 assert(getType()->getAs<FunctionType>() && "Expected a FunctionType!")(static_cast <bool> (getType()->getAs<FunctionType
>() && "Expected a FunctionType!") ? void (0) : __assert_fail
("getType()->getAs<FunctionType>() && \"Expected a FunctionType!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318631/tools/clang/include/clang/AST/Decl.h"
, 2206, __extension__ __PRETTY_FUNCTION__))
;
2207 return getType()->getAs<FunctionType>()->getReturnType();
2208 }
2209
2210 /// \brief Attempt to compute an informative source range covering the
2211 /// function return type. This may omit qualifiers and other information with
2212 /// limited representation in the AST.
2213 SourceRange getReturnTypeSourceRange() const;
2214
2215 /// \brief Attempt to compute an informative source range covering the
2216 /// function exception specification, if any.
2217 SourceRange getExceptionSpecSourceRange() const;
2218
2219 /// \brief Determine the type of an expression that calls this function.
2220 QualType getCallResultType() const {
2221 assert(getType()->getAs<FunctionType>() && "Expected a FunctionType!")(static_cast <bool> (getType()->getAs<FunctionType
>() && "Expected a FunctionType!") ? void (0) : __assert_fail
("getType()->getAs<FunctionType>() && \"Expected a FunctionType!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318631/tools/clang/include/clang/AST/Decl.h"
, 2221, __extension__ __PRETTY_FUNCTION__))
;
2222 return getType()->getAs<FunctionType>()->getCallResultType(getASTContext());
2223 }
2224
2225 /// \brief Returns the WarnUnusedResultAttr that is either declared on this
2226 /// function, or its return type declaration.
2227 const Attr *getUnusedResultAttr() const;
2228
2229 /// \brief Returns true if this function or its return type has the
2230 /// warn_unused_result attribute.
2231 bool hasUnusedResultAttr() const { return getUnusedResultAttr() != nullptr; }
2232
2233 /// \brief Returns the storage class as written in the source. For the
2234 /// computed linkage of symbol, see getLinkage.
2235 StorageClass getStorageClass() const { return StorageClass(SClass); }
2236
2237 /// \brief Determine whether the "inline" keyword was specified for this
2238 /// function.
2239 bool isInlineSpecified() const { return IsInlineSpecified; }
2240
2241 /// Set whether the "inline" keyword was specified for this function.
2242 void setInlineSpecified(bool I) {
2243 IsInlineSpecified = I;
2244 IsInline = I;
2245 }
2246
2247 /// Flag that this function is implicitly inline.
2248 void setImplicitlyInline() {
2249 IsInline = true;
2250 }
2251
2252 /// \brief Determine whether this function should be inlined, because it is
2253 /// either marked "inline" or "constexpr" or is a member function of a class
2254 /// that was defined in the class body.
2255 bool isInlined() const { return IsInline; }
2256
2257 bool isInlineDefinitionExternallyVisible() const;
2258
2259 bool isMSExternInline() const;
2260
2261 bool doesDeclarationForceExternallyVisibleDefinition() const;
2262
2263 /// isOverloadedOperator - Whether this function declaration
2264 /// represents an C++ overloaded operator, e.g., "operator+".
2265 bool isOverloadedOperator() const {
2266 return getOverloadedOperator() != OO_None;
2267 }
2268
2269 OverloadedOperatorKind getOverloadedOperator() const;
2270
2271 const IdentifierInfo *getLiteralIdentifier() const;
2272
2273 /// \brief If this function is an instantiation of a member function
2274 /// of a class template specialization, retrieves the function from
2275 /// which it was instantiated.
2276 ///
2277 /// This routine will return non-NULL for (non-templated) member
2278 /// functions of class templates and for instantiations of function
2279 /// templates. For example, given:
2280 ///
2281 /// \code
2282 /// template<typename T>
2283 /// struct X {
2284 /// void f(T);
2285 /// };
2286 /// \endcode
2287 ///
2288 /// The declaration for X<int>::f is a (non-templated) FunctionDecl
2289 /// whose parent is the class template specialization X<int>. For
2290 /// this declaration, getInstantiatedFromFunction() will return
2291 /// the FunctionDecl X<T>::A. When a complete definition of
2292 /// X<int>::A is required, it will be instantiated from the
2293 /// declaration returned by getInstantiatedFromMemberFunction().
2294 FunctionDecl *getInstantiatedFromMemberFunction() const;
2295
2296 /// \brief What kind of templated function this is.
2297 TemplatedKind getTemplatedKind() const;
2298
2299 /// \brief If this function is an instantiation of a member function of a
2300 /// class template specialization, retrieves the member specialization
2301 /// information.
2302 MemberSpecializationInfo *getMemberSpecializationInfo() const;
2303
2304 /// \brief Specify that this record is an instantiation of the
2305 /// member function FD.
2306 void setInstantiationOfMemberFunction(FunctionDecl *FD,
2307 TemplateSpecializationKind TSK) {
2308 setInstantiationOfMemberFunction(getASTContext(), FD, TSK);
2309 }
2310
2311 /// \brief Retrieves the function template that is described by this
2312 /// function declaration.
2313 ///
2314 /// Every function template is represented as a FunctionTemplateDecl
2315 /// and a FunctionDecl (or something derived from FunctionDecl). The
2316 /// former contains template properties (such as the template
2317 /// parameter lists) while the latter contains the actual
2318 /// description of the template's
2319 /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the
2320 /// FunctionDecl that describes the function template,
2321 /// getDescribedFunctionTemplate() retrieves the
2322 /// FunctionTemplateDecl from a FunctionDecl.
2323 FunctionTemplateDecl *getDescribedFunctionTemplate() const;
2324
2325 void setDescribedFunctionTemplate(FunctionTemplateDecl *Template);
2326
2327 /// \brief Determine whether this function is a function template
2328 /// specialization.
2329 bool isFunctionTemplateSpecialization() const {
2330 return getPrimaryTemplate() != nullptr;
2331 }
2332
2333 /// \brief Retrieve the class scope template pattern that this function
2334 /// template specialization is instantiated from.
2335 FunctionDecl *getClassScopeSpecializationPattern() const;
2336
2337 /// \brief If this function is actually a function template specialization,
2338 /// retrieve information about this function template specialization.
2339 /// Otherwise, returns NULL.
2340 FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const;
2341
2342 /// \brief Determines whether this function is a function template
2343 /// specialization or a member of a class template specialization that can
2344 /// be implicitly instantiated.
2345 bool isImplicitlyInstantiable() const;
2346
2347 /// \brief Determines if the given function was instantiated from a
2348 /// function template.
2349 bool isTemplateInstantiation() const;
2350
2351 /// \brief Retrieve the function declaration from which this function could
2352 /// be instantiated, if it is an instantiation (rather than a non-template
2353 /// or a specialization, for example).
2354 FunctionDecl *getTemplateInstantiationPattern() const;
2355
2356 /// \brief Retrieve the primary template that this function template
2357 /// specialization either specializes or was instantiated from.
2358 ///
2359 /// If this function declaration is not a function template specialization,
2360 /// returns NULL.
2361 FunctionTemplateDecl *getPrimaryTemplate() const;
2362
2363 /// \brief Retrieve the template arguments used to produce this function
2364 /// template specialization from the primary template.
2365 ///
2366 /// If this function declaration is not a function template specialization,
2367 /// returns NULL.
2368 const TemplateArgumentList *getTemplateSpecializationArgs() const;
2369
2370 /// \brief Retrieve the template argument list as written in the sources,
2371 /// if any.
2372 ///
2373 /// If this function declaration is not a function template specialization
2374 /// or if it had no explicit template argument list, returns NULL.
2375 /// Note that it an explicit template argument list may be written empty,
2376 /// e.g., template<> void foo<>(char* s);
2377 const ASTTemplateArgumentListInfo*
2378 getTemplateSpecializationArgsAsWritten() const;
2379
2380 /// \brief Specify that this function declaration is actually a function
2381 /// template specialization.
2382 ///
2383 /// \param Template the function template that this function template
2384 /// specialization specializes.
2385 ///
2386 /// \param TemplateArgs the template arguments that produced this
2387 /// function template specialization from the template.
2388 ///
2389 /// \param InsertPos If non-NULL, the position in the function template
2390 /// specialization set where the function template specialization data will
2391 /// be inserted.
2392 ///
2393 /// \param TSK the kind of template specialization this is.
2394 ///
2395 /// \param TemplateArgsAsWritten location info of template arguments.
2396 ///
2397 /// \param PointOfInstantiation point at which the function template
2398 /// specialization was first instantiated.
2399 void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template,
2400 const TemplateArgumentList *TemplateArgs,
2401 void *InsertPos,
2402 TemplateSpecializationKind TSK = TSK_ImplicitInstantiation,
2403 const TemplateArgumentListInfo *TemplateArgsAsWritten = nullptr,
2404 SourceLocation PointOfInstantiation = SourceLocation()) {
2405 setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs,
2406 InsertPos, TSK, TemplateArgsAsWritten,
2407 PointOfInstantiation);
2408 }
2409
2410 /// \brief Specifies that this function declaration is actually a
2411 /// dependent function template specialization.
2412 void setDependentTemplateSpecialization(ASTContext &Context,
2413 const UnresolvedSetImpl &Templates,
2414 const TemplateArgumentListInfo &TemplateArgs);
2415
2416 DependentFunctionTemplateSpecializationInfo *
2417 getDependentSpecializationInfo() const;
2418
2419 /// \brief Determine what kind of template instantiation this function
2420 /// represents.
2421 TemplateSpecializationKind getTemplateSpecializationKind() const;
2422
2423 /// \brief Determine what kind of template instantiation this function
2424 /// represents.
2425 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2426 SourceLocation PointOfInstantiation = SourceLocation());
2427
2428 /// \brief Retrieve the (first) point of instantiation of a function template
2429 /// specialization or a member of a class template specialization.
2430 ///
2431 /// \returns the first point of instantiation, if this function was
2432 /// instantiated from a template; otherwise, returns an invalid source
2433 /// location.
2434 SourceLocation getPointOfInstantiation() const;
2435
2436 /// \brief Determine whether this is or was instantiated from an out-of-line
2437 /// definition of a member function.
2438 bool isOutOfLine() const override;
2439
2440 /// \brief Identify a memory copying or setting function.
2441 /// If the given function is a memory copy or setting function, returns
2442 /// the corresponding Builtin ID. If the function is not a memory function,
2443 /// returns 0.
2444 unsigned getMemoryFunctionKind() const;
2445
2446 // Implement isa/cast/dyncast/etc.
2447 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2448 static bool classofKind(Kind K) {
2449 return K >= firstFunction && K <= lastFunction;
2450 }
2451 static DeclContext *castToDeclContext(const FunctionDecl *D) {
2452 return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D));
2453 }
2454 static FunctionDecl *castFromDeclContext(const DeclContext *DC) {
2455 return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC));
2456 }
2457};
2458
2459/// FieldDecl - An instance of this class is created by Sema::ActOnField to
2460/// represent a member of a struct/union/class.
2461class FieldDecl : public DeclaratorDecl, public Mergeable<FieldDecl> {
2462 unsigned BitField : 1;
2463 unsigned Mutable : 1;
2464 mutable unsigned CachedFieldIndex : 30;
2465
2466 /// The kinds of value we can store in InitializerOrBitWidth.
2467 ///
2468 /// Note that this is compatible with InClassInitStyle except for
2469 /// ISK_CapturedVLAType.
2470 enum InitStorageKind {
2471 /// If the pointer is null, there's nothing special. Otherwise,
2472 /// this is a bitfield and the pointer is the Expr* storing the
2473 /// bit-width.
2474 ISK_NoInit = (unsigned) ICIS_NoInit,
2475
2476 /// The pointer is an (optional due to delayed parsing) Expr*
2477 /// holding the copy-initializer.
2478 ISK_InClassCopyInit = (unsigned) ICIS_CopyInit,
2479
2480 /// The pointer is an (optional due to delayed parsing) Expr*
2481 /// holding the list-initializer.
2482 ISK_InClassListInit = (unsigned) ICIS_ListInit,
2483
2484 /// The pointer is a VariableArrayType* that's been captured;
2485 /// the enclosing context is a lambda or captured statement.
2486 ISK_CapturedVLAType,
2487 };
2488
2489 /// If this is a bitfield with a default member initializer, this
2490 /// structure is used to represent the two expressions.
2491 struct InitAndBitWidth {
2492 Expr *Init;
2493 Expr *BitWidth;
2494 };
2495
2496 /// \brief Storage for either the bit-width, the in-class initializer, or
2497 /// both (via InitAndBitWidth), or the captured variable length array bound.
2498 ///
2499 /// If the storage kind is ISK_InClassCopyInit or
2500 /// ISK_InClassListInit, but the initializer is null, then this
2501 /// field has an in-class initializer that has not yet been parsed
2502 /// and attached.
2503 // FIXME: Tail-allocate this to reduce the size of FieldDecl in the
2504 // overwhelmingly common case that we have none of these things.
2505 llvm::PointerIntPair<void *, 2, InitStorageKind> InitStorage;
2506
2507protected:
2508 FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
2509 SourceLocation IdLoc, IdentifierInfo *Id,
2510 QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2511 InClassInitStyle InitStyle)
2512 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
2513 BitField(false), Mutable(Mutable), CachedFieldIndex(0),
2514 InitStorage(nullptr, (InitStorageKind) InitStyle) {
2515 if (BW)
2516 setBitWidth(BW);
2517 }
2518
2519public:
2520 friend class ASTDeclReader;
2521 friend class ASTDeclWriter;
2522
2523 static FieldDecl *Create(const ASTContext &C, DeclContext *DC,
2524 SourceLocation StartLoc, SourceLocation IdLoc,
2525 IdentifierInfo *Id, QualType T,
2526 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2527 InClassInitStyle InitStyle);
2528
2529 static FieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2530
2531 /// getFieldIndex - Returns the index of this field within its record,
2532 /// as appropriate for passing to ASTRecordLayout::getFieldOffset.
2533 unsigned getFieldIndex() const;
2534
2535 /// isMutable - Determines whether this field is mutable (C++ only).
2536 bool isMutable() const { return Mutable; }
2537