Bug Summary

File:tools/clang/lib/Sema/SemaCUDA.cpp
Warning:line 837, column 51
Potential leak of memory pointed to by field 'DiagStorage'

Annotated Source Code

Press '?' to see keyboard shortcuts

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

/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/lib/Sema/SemaCUDA.cpp

1//===--- SemaCUDA.cpp - Semantic Analysis for CUDA constructs -------------===//
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/// \file
10/// \brief This file implements semantic analysis for CUDA constructs.
11///
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/Decl.h"
16#include "clang/AST/ExprCXX.h"
17#include "clang/Lex/Preprocessor.h"
18#include "clang/Sema/Lookup.h"
19#include "clang/Sema/Sema.h"
20#include "clang/Sema/SemaDiagnostic.h"
21#include "clang/Sema/SemaInternal.h"
22#include "clang/Sema/Template.h"
23#include "llvm/ADT/Optional.h"
24#include "llvm/ADT/SmallVector.h"
25using namespace clang;
26
27void Sema::PushForceCUDAHostDevice() {
28 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation")(static_cast <bool> (getLangOpts().CUDA && "Should only be called during CUDA compilation"
) ? void (0) : __assert_fail ("getLangOpts().CUDA && \"Should only be called during CUDA compilation\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/lib/Sema/SemaCUDA.cpp"
, 28, __extension__ __PRETTY_FUNCTION__))
;
29 ForceCUDAHostDeviceDepth++;
30}
31
32bool Sema::PopForceCUDAHostDevice() {
33 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation")(static_cast <bool> (getLangOpts().CUDA && "Should only be called during CUDA compilation"
) ? void (0) : __assert_fail ("getLangOpts().CUDA && \"Should only be called during CUDA compilation\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/lib/Sema/SemaCUDA.cpp"
, 33, __extension__ __PRETTY_FUNCTION__))
;
34 if (ForceCUDAHostDeviceDepth == 0)
35 return false;
36 ForceCUDAHostDeviceDepth--;
37 return true;
38}
39
40ExprResult Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
41 MultiExprArg ExecConfig,
42 SourceLocation GGGLoc) {
43 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
44 if (!ConfigDecl)
45 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
46 << "cudaConfigureCall");
47 QualType ConfigQTy = ConfigDecl->getType();
48
49 DeclRefExpr *ConfigDR = new (Context)
50 DeclRefExpr(ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
51 MarkFunctionReferenced(LLLLoc, ConfigDecl);
52
53 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, nullptr,
54 /*IsExecConfig=*/true);
55}
56
57Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const AttributeList *Attr) {
58 bool HasHostAttr = false;
59 bool HasDeviceAttr = false;
60 bool HasGlobalAttr = false;
61 bool HasInvalidTargetAttr = false;
62 while (Attr) {
63 switch(Attr->getKind()){
64 case AttributeList::AT_CUDAGlobal:
65 HasGlobalAttr = true;
66 break;
67 case AttributeList::AT_CUDAHost:
68 HasHostAttr = true;
69 break;
70 case AttributeList::AT_CUDADevice:
71 HasDeviceAttr = true;
72 break;
73 case AttributeList::AT_CUDAInvalidTarget:
74 HasInvalidTargetAttr = true;
75 break;
76 default:
77 break;
78 }
79 Attr = Attr->getNext();
80 }
81 if (HasInvalidTargetAttr)
82 return CFT_InvalidTarget;
83
84 if (HasGlobalAttr)
85 return CFT_Global;
86
87 if (HasHostAttr && HasDeviceAttr)
88 return CFT_HostDevice;
89
90 if (HasDeviceAttr)
91 return CFT_Device;
92
93 return CFT_Host;
94}
95
96template <typename A>
97static bool hasAttr(const FunctionDecl *D, bool IgnoreImplicitAttr) {
98 return D->hasAttrs() && llvm::any_of(D->getAttrs(), [&](Attr *Attribute) {
99 return isa<A>(Attribute) &&
100 !(IgnoreImplicitAttr && Attribute->isImplicit());
101 });
102}
103
104/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
105Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D,
106 bool IgnoreImplicitHDAttr) {
107 // Code that lives outside a function is run on the host.
108 if (D == nullptr)
109 return CFT_Host;
110
111 if (D->hasAttr<CUDAInvalidTargetAttr>())
112 return CFT_InvalidTarget;
113
114 if (D->hasAttr<CUDAGlobalAttr>())
115 return CFT_Global;
116
117 if (hasAttr<CUDADeviceAttr>(D, IgnoreImplicitHDAttr)) {
118 if (hasAttr<CUDAHostAttr>(D, IgnoreImplicitHDAttr))
119 return CFT_HostDevice;
120 return CFT_Device;
121 } else if (hasAttr<CUDAHostAttr>(D, IgnoreImplicitHDAttr)) {
122 return CFT_Host;
123 } else if (D->isImplicit() && !IgnoreImplicitHDAttr) {
124 // Some implicit declarations (like intrinsic functions) are not marked.
125 // Set the most lenient target on them for maximal flexibility.
126 return CFT_HostDevice;
127 }
128
129 return CFT_Host;
130}
131
132// * CUDA Call preference table
133//
134// F - from,
135// T - to
136// Ph - preference in host mode
137// Pd - preference in device mode
138// H - handled in (x)
139// Preferences: N:native, SS:same side, HD:host-device, WS:wrong side, --:never.
140//
141// | F | T | Ph | Pd | H |
142// |----+----+-----+-----+-----+
143// | d | d | N | N | (c) |
144// | d | g | -- | -- | (a) |
145// | d | h | -- | -- | (e) |
146// | d | hd | HD | HD | (b) |
147// | g | d | N | N | (c) |
148// | g | g | -- | -- | (a) |
149// | g | h | -- | -- | (e) |
150// | g | hd | HD | HD | (b) |
151// | h | d | -- | -- | (e) |
152// | h | g | N | N | (c) |
153// | h | h | N | N | (c) |
154// | h | hd | HD | HD | (b) |
155// | hd | d | WS | SS | (d) |
156// | hd | g | SS | -- |(d/a)|
157// | hd | h | SS | WS | (d) |
158// | hd | hd | HD | HD | (b) |
159
160Sema::CUDAFunctionPreference
161Sema::IdentifyCUDAPreference(const FunctionDecl *Caller,
162 const FunctionDecl *Callee) {
163 assert(Callee && "Callee must be valid.")(static_cast <bool> (Callee && "Callee must be valid."
) ? void (0) : __assert_fail ("Callee && \"Callee must be valid.\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/lib/Sema/SemaCUDA.cpp"
, 163, __extension__ __PRETTY_FUNCTION__))
;
164 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller);
165 CUDAFunctionTarget CalleeTarget = IdentifyCUDATarget(Callee);
166
167 // If one of the targets is invalid, the check always fails, no matter what
168 // the other target is.
169 if (CallerTarget == CFT_InvalidTarget || CalleeTarget == CFT_InvalidTarget)
170 return CFP_Never;
171
172 // (a) Can't call global from some contexts until we support CUDA's
173 // dynamic parallelism.
174 if (CalleeTarget == CFT_Global &&
175 (CallerTarget == CFT_Global || CallerTarget == CFT_Device))
176 return CFP_Never;
177
178 // (b) Calling HostDevice is OK for everyone.
179 if (CalleeTarget == CFT_HostDevice)
180 return CFP_HostDevice;
181
182 // (c) Best case scenarios
183 if (CalleeTarget == CallerTarget ||
184 (CallerTarget == CFT_Host && CalleeTarget == CFT_Global) ||
185 (CallerTarget == CFT_Global && CalleeTarget == CFT_Device))
186 return CFP_Native;
187
188 // (d) HostDevice behavior depends on compilation mode.
189 if (CallerTarget == CFT_HostDevice) {
190 // It's OK to call a compilation-mode matching function from an HD one.
191 if ((getLangOpts().CUDAIsDevice && CalleeTarget == CFT_Device) ||
192 (!getLangOpts().CUDAIsDevice &&
193 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global)))
194 return CFP_SameSide;
195
196 // Calls from HD to non-mode-matching functions (i.e., to host functions
197 // when compiling in device mode or to device functions when compiling in
198 // host mode) are allowed at the sema level, but eventually rejected if
199 // they're ever codegened. TODO: Reject said calls earlier.
200 return CFP_WrongSide;
201 }
202
203 // (e) Calling across device/host boundary is not something you should do.
204 if ((CallerTarget == CFT_Host && CalleeTarget == CFT_Device) ||
205 (CallerTarget == CFT_Device && CalleeTarget == CFT_Host) ||
206 (CallerTarget == CFT_Global && CalleeTarget == CFT_Host))
207 return CFP_Never;
208
209 llvm_unreachable("All cases should've been handled by now.")::llvm::llvm_unreachable_internal("All cases should've been handled by now."
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/lib/Sema/SemaCUDA.cpp"
, 209)
;
210}
211
212void Sema::EraseUnwantedCUDAMatches(
213 const FunctionDecl *Caller,
214 SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches) {
215 if (Matches.size() <= 1)
216 return;
217
218 using Pair = std::pair<DeclAccessPair, FunctionDecl*>;
219
220 // Gets the CUDA function preference for a call from Caller to Match.
221 auto GetCFP = [&](const Pair &Match) {
222 return IdentifyCUDAPreference(Caller, Match.second);
223 };
224
225 // Find the best call preference among the functions in Matches.
226 CUDAFunctionPreference BestCFP = GetCFP(*std::max_element(
227 Matches.begin(), Matches.end(),
228 [&](const Pair &M1, const Pair &M2) { return GetCFP(M1) < GetCFP(M2); }));
229
230 // Erase all functions with lower priority.
231 llvm::erase_if(Matches,
232 [&](const Pair &Match) { return GetCFP(Match) < BestCFP; });
233}
234
235/// When an implicitly-declared special member has to invoke more than one
236/// base/field special member, conflicts may occur in the targets of these
237/// members. For example, if one base's member __host__ and another's is
238/// __device__, it's a conflict.
239/// This function figures out if the given targets \param Target1 and
240/// \param Target2 conflict, and if they do not it fills in
241/// \param ResolvedTarget with a target that resolves for both calls.
242/// \return true if there's a conflict, false otherwise.
243static bool
244resolveCalleeCUDATargetConflict(Sema::CUDAFunctionTarget Target1,
245 Sema::CUDAFunctionTarget Target2,
246 Sema::CUDAFunctionTarget *ResolvedTarget) {
247 // Only free functions and static member functions may be global.
248 assert(Target1 != Sema::CFT_Global)(static_cast <bool> (Target1 != Sema::CFT_Global) ? void
(0) : __assert_fail ("Target1 != Sema::CFT_Global", "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/lib/Sema/SemaCUDA.cpp"
, 248, __extension__ __PRETTY_FUNCTION__))
;
249 assert(Target2 != Sema::CFT_Global)(static_cast <bool> (Target2 != Sema::CFT_Global) ? void
(0) : __assert_fail ("Target2 != Sema::CFT_Global", "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/lib/Sema/SemaCUDA.cpp"
, 249, __extension__ __PRETTY_FUNCTION__))
;
250
251 if (Target1 == Sema::CFT_HostDevice) {
252 *ResolvedTarget = Target2;
253 } else if (Target2 == Sema::CFT_HostDevice) {
254 *ResolvedTarget = Target1;
255 } else if (Target1 != Target2) {
256 return true;
257 } else {
258 *ResolvedTarget = Target1;
259 }
260
261 return false;
262}
263
264bool Sema::inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
265 CXXSpecialMember CSM,
266 CXXMethodDecl *MemberDecl,
267 bool ConstRHS,
268 bool Diagnose) {
269 llvm::Optional<CUDAFunctionTarget> InferredTarget;
270
271 // We're going to invoke special member lookup; mark that these special
272 // members are called from this one, and not from its caller.
273 ContextRAII MethodContext(*this, MemberDecl);
274
275 // Look for special members in base classes that should be invoked from here.
276 // Infer the target of this member base on the ones it should call.
277 // Skip direct and indirect virtual bases for abstract classes.
278 llvm::SmallVector<const CXXBaseSpecifier *, 16> Bases;
279 for (const auto &B : ClassDecl->bases()) {
280 if (!B.isVirtual()) {
281 Bases.push_back(&B);
282 }
283 }
284
285 if (!ClassDecl->isAbstract()) {
286 for (const auto &VB : ClassDecl->vbases()) {
287 Bases.push_back(&VB);
288 }
289 }
290
291 for (const auto *B : Bases) {
292 const RecordType *BaseType = B->getType()->getAs<RecordType>();
293 if (!BaseType) {
294 continue;
295 }
296
297 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
298 Sema::SpecialMemberOverloadResult SMOR =
299 LookupSpecialMember(BaseClassDecl, CSM,
300 /* ConstArg */ ConstRHS,
301 /* VolatileArg */ false,
302 /* RValueThis */ false,
303 /* ConstThis */ false,
304 /* VolatileThis */ false);
305
306 if (!SMOR.getMethod())
307 continue;
308
309 CUDAFunctionTarget BaseMethodTarget = IdentifyCUDATarget(SMOR.getMethod());
310 if (!InferredTarget.hasValue()) {
311 InferredTarget = BaseMethodTarget;
312 } else {
313 bool ResolutionError = resolveCalleeCUDATargetConflict(
314 InferredTarget.getValue(), BaseMethodTarget,
315 InferredTarget.getPointer());
316 if (ResolutionError) {
317 if (Diagnose) {
318 Diag(ClassDecl->getLocation(),
319 diag::note_implicit_member_target_infer_collision)
320 << (unsigned)CSM << InferredTarget.getValue() << BaseMethodTarget;
321 }
322 MemberDecl->addAttr(CUDAInvalidTargetAttr::CreateImplicit(Context));
323 return true;
324 }
325 }
326 }
327
328 // Same as for bases, but now for special members of fields.
329 for (const auto *F : ClassDecl->fields()) {
330 if (F->isInvalidDecl()) {
331 continue;
332 }
333
334 const RecordType *FieldType =
335 Context.getBaseElementType(F->getType())->getAs<RecordType>();
336 if (!FieldType) {
337 continue;
338 }
339
340 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(FieldType->getDecl());
341 Sema::SpecialMemberOverloadResult SMOR =
342 LookupSpecialMember(FieldRecDecl, CSM,
343 /* ConstArg */ ConstRHS && !F->isMutable(),
344 /* VolatileArg */ false,
345 /* RValueThis */ false,
346 /* ConstThis */ false,
347 /* VolatileThis */ false);
348
349 if (!SMOR.getMethod())
350 continue;
351
352 CUDAFunctionTarget FieldMethodTarget =
353 IdentifyCUDATarget(SMOR.getMethod());
354 if (!InferredTarget.hasValue()) {
355 InferredTarget = FieldMethodTarget;
356 } else {
357 bool ResolutionError = resolveCalleeCUDATargetConflict(
358 InferredTarget.getValue(), FieldMethodTarget,
359 InferredTarget.getPointer());
360 if (ResolutionError) {
361 if (Diagnose) {
362 Diag(ClassDecl->getLocation(),
363 diag::note_implicit_member_target_infer_collision)
364 << (unsigned)CSM << InferredTarget.getValue()
365 << FieldMethodTarget;
366 }
367 MemberDecl->addAttr(CUDAInvalidTargetAttr::CreateImplicit(Context));
368 return true;
369 }
370 }
371 }
372
373 if (InferredTarget.hasValue()) {
374 if (InferredTarget.getValue() == CFT_Device) {
375 MemberDecl->addAttr(CUDADeviceAttr::CreateImplicit(Context));
376 } else if (InferredTarget.getValue() == CFT_Host) {
377 MemberDecl->addAttr(CUDAHostAttr::CreateImplicit(Context));
378 } else {
379 MemberDecl->addAttr(CUDADeviceAttr::CreateImplicit(Context));
380 MemberDecl->addAttr(CUDAHostAttr::CreateImplicit(Context));
381 }
382 } else {
383 // If no target was inferred, mark this member as __host__ __device__;
384 // it's the least restrictive option that can be invoked from any target.
385 MemberDecl->addAttr(CUDADeviceAttr::CreateImplicit(Context));
386 MemberDecl->addAttr(CUDAHostAttr::CreateImplicit(Context));
387 }
388
389 return false;
390}
391
392bool Sema::isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD) {
393 if (!CD->isDefined() && CD->isTemplateInstantiation())
394 InstantiateFunctionDefinition(Loc, CD->getFirstDecl());
395
396 // (E.2.3.1, CUDA 7.5) A constructor for a class type is considered
397 // empty at a point in the translation unit, if it is either a
398 // trivial constructor
399 if (CD->isTrivial())
400 return true;
401
402 // ... or it satisfies all of the following conditions:
403 // The constructor function has been defined.
404 // The constructor function has no parameters,
405 // and the function body is an empty compound statement.
406 if (!(CD->hasTrivialBody() && CD->getNumParams() == 0))
407 return false;
408
409 // Its class has no virtual functions and no virtual base classes.
410 if (CD->getParent()->isDynamicClass())
411 return false;
412
413 // The only form of initializer allowed is an empty constructor.
414 // This will recursively check all base classes and member initializers
415 if (!llvm::all_of(CD->inits(), [&](const CXXCtorInitializer *CI) {
416 if (const CXXConstructExpr *CE =
417 dyn_cast<CXXConstructExpr>(CI->getInit()))
418 return isEmptyCudaConstructor(Loc, CE->getConstructor());
419 return false;
420 }))
421 return false;
422
423 return true;
424}
425
426bool Sema::isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *DD) {
427 // No destructor -> no problem.
428 if (!DD)
429 return true;
430
431 if (!DD->isDefined() && DD->isTemplateInstantiation())
432 InstantiateFunctionDefinition(Loc, DD->getFirstDecl());
433
434 // (E.2.3.1, CUDA 7.5) A destructor for a class type is considered
435 // empty at a point in the translation unit, if it is either a
436 // trivial constructor
437 if (DD->isTrivial())
438 return true;
439
440 // ... or it satisfies all of the following conditions:
441 // The destructor function has been defined.
442 // and the function body is an empty compound statement.
443 if (!DD->hasTrivialBody())
444 return false;
445
446 const CXXRecordDecl *ClassDecl = DD->getParent();
447
448 // Its class has no virtual functions and no virtual base classes.
449 if (ClassDecl->isDynamicClass())
450 return false;
451
452 // Only empty destructors are allowed. This will recursively check
453 // destructors for all base classes...
454 if (!llvm::all_of(ClassDecl->bases(), [&](const CXXBaseSpecifier &BS) {
455 if (CXXRecordDecl *RD = BS.getType()->getAsCXXRecordDecl())
456 return isEmptyCudaDestructor(Loc, RD->getDestructor());
457 return true;
458 }))
459 return false;
460
461 // ... and member fields.
462 if (!llvm::all_of(ClassDecl->fields(), [&](const FieldDecl *Field) {
463 if (CXXRecordDecl *RD = Field->getType()
464 ->getBaseElementTypeUnsafe()
465 ->getAsCXXRecordDecl())
466 return isEmptyCudaDestructor(Loc, RD->getDestructor());
467 return true;
468 }))
469 return false;
470
471 return true;
472}
473
474// With -fcuda-host-device-constexpr, an unattributed constexpr function is
475// treated as implicitly __host__ __device__, unless:
476// * it is a variadic function (device-side variadic functions are not
477// allowed), or
478// * a __device__ function with this signature was already declared, in which
479// case in which case we output an error, unless the __device__ decl is in a
480// system header, in which case we leave the constexpr function unattributed.
481//
482// In addition, all function decls are treated as __host__ __device__ when
483// ForceCUDAHostDeviceDepth > 0 (corresponding to code within a
484// #pragma clang force_cuda_host_device_begin/end
485// pair).
486void Sema::maybeAddCUDAHostDeviceAttrs(FunctionDecl *NewD,
487 const LookupResult &Previous) {
488 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation")(static_cast <bool> (getLangOpts().CUDA && "Should only be called during CUDA compilation"
) ? void (0) : __assert_fail ("getLangOpts().CUDA && \"Should only be called during CUDA compilation\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/lib/Sema/SemaCUDA.cpp"
, 488, __extension__ __PRETTY_FUNCTION__))
;
489
490 if (ForceCUDAHostDeviceDepth > 0) {
491 if (!NewD->hasAttr<CUDAHostAttr>())
492 NewD->addAttr(CUDAHostAttr::CreateImplicit(Context));
493 if (!NewD->hasAttr<CUDADeviceAttr>())
494 NewD->addAttr(CUDADeviceAttr::CreateImplicit(Context));
495 return;
496 }
497
498 if (!getLangOpts().CUDAHostDeviceConstexpr || !NewD->isConstexpr() ||
499 NewD->isVariadic() || NewD->hasAttr<CUDAHostAttr>() ||
500 NewD->hasAttr<CUDADeviceAttr>() || NewD->hasAttr<CUDAGlobalAttr>())
501 return;
502
503 // Is D a __device__ function with the same signature as NewD, ignoring CUDA
504 // attributes?
505 auto IsMatchingDeviceFn = [&](NamedDecl *D) {
506 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(D))
507 D = Using->getTargetDecl();
508 FunctionDecl *OldD = D->getAsFunction();
509 return OldD && OldD->hasAttr<CUDADeviceAttr>() &&
510 !OldD->hasAttr<CUDAHostAttr>() &&
511 !IsOverload(NewD, OldD, /* UseMemberUsingDeclRules = */ false,
512 /* ConsiderCudaAttrs = */ false);
513 };
514 auto It = llvm::find_if(Previous, IsMatchingDeviceFn);
515 if (It != Previous.end()) {
516 // We found a __device__ function with the same name and signature as NewD
517 // (ignoring CUDA attrs). This is an error unless that function is defined
518 // in a system header, in which case we simply return without making NewD
519 // host+device.
520 NamedDecl *Match = *It;
521 if (!getSourceManager().isInSystemHeader(Match->getLocation())) {
522 Diag(NewD->getLocation(),
523 diag::err_cuda_unattributed_constexpr_cannot_overload_device)
524 << NewD->getName();
525 Diag(Match->getLocation(),
526 diag::note_cuda_conflicting_device_function_declared_here);
527 }
528 return;
529 }
530
531 NewD->addAttr(CUDAHostAttr::CreateImplicit(Context));
532 NewD->addAttr(CUDADeviceAttr::CreateImplicit(Context));
533}
534
535// In CUDA, there are some constructs which may appear in semantically-valid
536// code, but trigger errors if we ever generate code for the function in which
537// they appear. Essentially every construct you're not allowed to use on the
538// device falls into this category, because you are allowed to use these
539// constructs in a __host__ __device__ function, but only if that function is
540// never codegen'ed on the device.
541//
542// To handle semantic checking for these constructs, we keep track of the set of
543// functions we know will be emitted, either because we could tell a priori that
544// they would be emitted, or because they were transitively called by a
545// known-emitted function.
546//
547// We also keep a partial call graph of which not-known-emitted functions call
548// which other not-known-emitted functions.
549//
550// When we see something which is illegal if the current function is emitted
551// (usually by way of CUDADiagIfDeviceCode, CUDADiagIfHostCode, or
552// CheckCUDACall), we first check if the current function is known-emitted. If
553// so, we immediately output the diagnostic.
554//
555// Otherwise, we "defer" the diagnostic. It sits in Sema::CUDADeferredDiags
556// until we discover that the function is known-emitted, at which point we take
557// it out of this map and emit the diagnostic.
558
559Sema::CUDADiagBuilder::CUDADiagBuilder(Kind K, SourceLocation Loc,
560 unsigned DiagID, FunctionDecl *Fn,
561 Sema &S)
562 : S(S), Loc(Loc), DiagID(DiagID), Fn(Fn),
563 ShowCallStack(K == K_ImmediateWithCallStack || K == K_Deferred) {
564 switch (K) {
565 case K_Nop:
566 break;
567 case K_Immediate:
568 case K_ImmediateWithCallStack:
569 ImmediateDiag.emplace(S.Diag(Loc, DiagID));
570 break;
571 case K_Deferred:
572 assert(Fn && "Must have a function to attach the deferred diag to.")(static_cast <bool> (Fn && "Must have a function to attach the deferred diag to."
) ? void (0) : __assert_fail ("Fn && \"Must have a function to attach the deferred diag to.\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/lib/Sema/SemaCUDA.cpp"
, 572, __extension__ __PRETTY_FUNCTION__))
;
573 PartialDiag.emplace(S.PDiag(DiagID));
574 break;
575 }
576}
577
578// Print notes showing how we can reach FD starting from an a priori
579// known-callable function.
580static void EmitCallStackNotes(Sema &S, FunctionDecl *FD) {
581 auto FnIt = S.CUDAKnownEmittedFns.find(FD);
582 while (FnIt != S.CUDAKnownEmittedFns.end()) {
583 DiagnosticBuilder Builder(
584 S.Diags.Report(FnIt->second.Loc, diag::note_called_by));
585 Builder << FnIt->second.FD;
586 Builder.setForceEmit();
587
588 FnIt = S.CUDAKnownEmittedFns.find(FnIt->second.FD);
589 }
590}
591
592Sema::CUDADiagBuilder::~CUDADiagBuilder() {
593 if (ImmediateDiag) {
594 // Emit our diagnostic and, if it was a warning or error, output a callstack
595 // if Fn isn't a priori known-emitted.
596 bool IsWarningOrError = S.getDiagnostics().getDiagnosticLevel(
597 DiagID, Loc) >= DiagnosticsEngine::Warning;
598 ImmediateDiag.reset(); // Emit the immediate diag.
599 if (IsWarningOrError && ShowCallStack)
600 EmitCallStackNotes(S, Fn);
601 } else if (PartialDiag) {
602 assert(ShowCallStack && "Must always show call stack for deferred diags.")(static_cast <bool> (ShowCallStack && "Must always show call stack for deferred diags."
) ? void (0) : __assert_fail ("ShowCallStack && \"Must always show call stack for deferred diags.\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/lib/Sema/SemaCUDA.cpp"
, 602, __extension__ __PRETTY_FUNCTION__))
;
603 S.CUDADeferredDiags[Fn].push_back({Loc, std::move(*PartialDiag)});
604 }
605}
606
607// Do we know that we will eventually codegen the given function?
608static bool IsKnownEmitted(Sema &S, FunctionDecl *FD) {
609 // Templates are emitted when they're instantiated.
610 if (FD->isDependentContext())
611 return false;
612
613 // When compiling for device, host functions are never emitted. Similarly,
614 // when compiling for host, device and global functions are never emitted.
615 // (Technically, we do emit a host-side stub for global functions, but this
616 // doesn't count for our purposes here.)
617 Sema::CUDAFunctionTarget T = S.IdentifyCUDATarget(FD);
618 if (S.getLangOpts().CUDAIsDevice && T == Sema::CFT_Host)
619 return false;
620 if (!S.getLangOpts().CUDAIsDevice &&
621 (T == Sema::CFT_Device || T == Sema::CFT_Global))
622 return false;
623
624 // Check whether this function is externally visible -- if so, it's
625 // known-emitted.
626 //
627 // We have to check the GVA linkage of the function's *definition* -- if we
628 // only have a declaration, we don't know whether or not the function will be
629 // emitted, because (say) the definition could include "inline".
630 FunctionDecl *Def = FD->getDefinition();
631
632 if (Def &&
633 !isDiscardableGVALinkage(S.getASTContext().GetGVALinkageForFunction(Def)))
634 return true;
635
636 // Otherwise, the function is known-emitted if it's in our set of
637 // known-emitted functions.
638 return S.CUDAKnownEmittedFns.count(FD) > 0;
639}
640
641Sema::CUDADiagBuilder Sema::CUDADiagIfDeviceCode(SourceLocation Loc,
642 unsigned DiagID) {
643 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation")(static_cast <bool> (getLangOpts().CUDA && "Should only be called during CUDA compilation"
) ? void (0) : __assert_fail ("getLangOpts().CUDA && \"Should only be called during CUDA compilation\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/lib/Sema/SemaCUDA.cpp"
, 643, __extension__ __PRETTY_FUNCTION__))
;
644 CUDADiagBuilder::Kind DiagKind = [&] {
645 switch (CurrentCUDATarget()) {
646 case CFT_Global:
647 case CFT_Device:
648 return CUDADiagBuilder::K_Immediate;
649 case CFT_HostDevice:
650 // An HD function counts as host code if we're compiling for host, and
651 // device code if we're compiling for device. Defer any errors in device
652 // mode until the function is known-emitted.
653 if (getLangOpts().CUDAIsDevice) {
654 return IsKnownEmitted(*this, dyn_cast<FunctionDecl>(CurContext))
655 ? CUDADiagBuilder::K_ImmediateWithCallStack
656 : CUDADiagBuilder::K_Deferred;
657 }
658 return CUDADiagBuilder::K_Nop;
659
660 default:
661 return CUDADiagBuilder::K_Nop;
662 }
663 }();
664 return CUDADiagBuilder(DiagKind, Loc, DiagID,
665 dyn_cast<FunctionDecl>(CurContext), *this);
666}
667
668Sema::CUDADiagBuilder Sema::CUDADiagIfHostCode(SourceLocation Loc,
669 unsigned DiagID) {
670 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation")(static_cast <bool> (getLangOpts().CUDA && "Should only be called during CUDA compilation"
) ? void (0) : __assert_fail ("getLangOpts().CUDA && \"Should only be called during CUDA compilation\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/lib/Sema/SemaCUDA.cpp"
, 670, __extension__ __PRETTY_FUNCTION__))
;
671 CUDADiagBuilder::Kind DiagKind = [&] {
672 switch (CurrentCUDATarget()) {
673 case CFT_Host:
674 return CUDADiagBuilder::K_Immediate;
675 case CFT_HostDevice:
676 // An HD function counts as host code if we're compiling for host, and
677 // device code if we're compiling for device. Defer any errors in device
678 // mode until the function is known-emitted.
679 if (getLangOpts().CUDAIsDevice)
680 return CUDADiagBuilder::K_Nop;
681
682 return IsKnownEmitted(*this, dyn_cast<FunctionDecl>(CurContext))
683 ? CUDADiagBuilder::K_ImmediateWithCallStack
684 : CUDADiagBuilder::K_Deferred;
685 default:
686 return CUDADiagBuilder::K_Nop;
687 }
688 }();
689 return CUDADiagBuilder(DiagKind, Loc, DiagID,
690 dyn_cast<FunctionDecl>(CurContext), *this);
691}
692
693// Emit any deferred diagnostics for FD and erase them from the map in which
694// they're stored.
695static void EmitDeferredDiags(Sema &S, FunctionDecl *FD) {
696 auto It = S.CUDADeferredDiags.find(FD);
697 if (It == S.CUDADeferredDiags.end())
698 return;
699 bool HasWarningOrError = false;
700 for (PartialDiagnosticAt &PDAt : It->second) {
701 const SourceLocation &Loc = PDAt.first;
702 const PartialDiagnostic &PD = PDAt.second;
703 HasWarningOrError |= S.getDiagnostics().getDiagnosticLevel(
704 PD.getDiagID(), Loc) >= DiagnosticsEngine::Warning;
705 DiagnosticBuilder Builder(S.Diags.Report(Loc, PD.getDiagID()));
706 Builder.setForceEmit();
707 PD.Emit(Builder);
708 }
709 S.CUDADeferredDiags.erase(It);
710
711 // FIXME: Should this be called after every warning/error emitted in the loop
712 // above, instead of just once per function? That would be consistent with
713 // how we handle immediate errors, but it also seems like a bit much.
714 if (HasWarningOrError)
715 EmitCallStackNotes(S, FD);
716}
717
718// Indicate that this function (and thus everything it transtively calls) will
719// be codegen'ed, and emit any deferred diagnostics on this function and its
720// (transitive) callees.
721static void MarkKnownEmitted(Sema &S, FunctionDecl *OrigCaller,
722 FunctionDecl *OrigCallee, SourceLocation OrigLoc) {
723 // Nothing to do if we already know that FD is emitted.
724 if (IsKnownEmitted(S, OrigCallee)) {
725 assert(!S.CUDACallGraph.count(OrigCallee))(static_cast <bool> (!S.CUDACallGraph.count(OrigCallee)
) ? void (0) : __assert_fail ("!S.CUDACallGraph.count(OrigCallee)"
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/lib/Sema/SemaCUDA.cpp"
, 725, __extension__ __PRETTY_FUNCTION__))
;
726 return;
727 }
728
729 // We've just discovered that OrigCallee is known-emitted. Walk our call
730 // graph to see what else we can now discover also must be emitted.
731
732 struct CallInfo {
733 FunctionDecl *Caller;
734 FunctionDecl *Callee;
735 SourceLocation Loc;
736 };
737 llvm::SmallVector<CallInfo, 4> Worklist = {{OrigCaller, OrigCallee, OrigLoc}};
738 llvm::SmallSet<CanonicalDeclPtr<FunctionDecl>, 4> Seen;
739 Seen.insert(OrigCallee);
740 while (!Worklist.empty()) {
741 CallInfo C = Worklist.pop_back_val();
742 assert(!IsKnownEmitted(S, C.Callee) &&(static_cast <bool> (!IsKnownEmitted(S, C.Callee) &&
"Worklist should not contain known-emitted functions.") ? void
(0) : __assert_fail ("!IsKnownEmitted(S, C.Callee) && \"Worklist should not contain known-emitted functions.\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/lib/Sema/SemaCUDA.cpp"
, 743, __extension__ __PRETTY_FUNCTION__))
743 "Worklist should not contain known-emitted functions.")(static_cast <bool> (!IsKnownEmitted(S, C.Callee) &&
"Worklist should not contain known-emitted functions.") ? void
(0) : __assert_fail ("!IsKnownEmitted(S, C.Callee) && \"Worklist should not contain known-emitted functions.\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/lib/Sema/SemaCUDA.cpp"
, 743, __extension__ __PRETTY_FUNCTION__))
;
744 S.CUDAKnownEmittedFns[C.Callee] = {C.Caller, C.Loc};
745 EmitDeferredDiags(S, C.Callee);
746
747 // If this is a template instantiation, explore its callgraph as well:
748 // Non-dependent calls are part of the template's callgraph, while dependent
749 // calls are part of to the instantiation's call graph.
750 if (auto *Templ = C.Callee->getPrimaryTemplate()) {
751 FunctionDecl *TemplFD = Templ->getAsFunction();
752 if (!Seen.count(TemplFD) && !S.CUDAKnownEmittedFns.count(TemplFD)) {
753 Seen.insert(TemplFD);
754 Worklist.push_back(
755 {/* Caller = */ C.Caller, /* Callee = */ TemplFD, C.Loc});
756 }
757 }
758
759 // Add all functions called by Callee to our worklist.
760 auto CGIt = S.CUDACallGraph.find(C.Callee);
761 if (CGIt == S.CUDACallGraph.end())
762 continue;
763
764 for (std::pair<CanonicalDeclPtr<FunctionDecl>, SourceLocation> FDLoc :
765 CGIt->second) {
766 FunctionDecl *NewCallee = FDLoc.first;
767 SourceLocation CallLoc = FDLoc.second;
768 if (Seen.count(NewCallee) || IsKnownEmitted(S, NewCallee))
769 continue;
770 Seen.insert(NewCallee);
771 Worklist.push_back(
772 {/* Caller = */ C.Callee, /* Callee = */ NewCallee, CallLoc});
773 }
774
775 // C.Callee is now known-emitted, so we no longer need to maintain its list
776 // of callees in CUDACallGraph.
777 S.CUDACallGraph.erase(CGIt);
778 }
779}
780
781bool Sema::CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee) {
782 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation")(static_cast <bool> (getLangOpts().CUDA && "Should only be called during CUDA compilation"
) ? void (0) : __assert_fail ("getLangOpts().CUDA && \"Should only be called during CUDA compilation\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/lib/Sema/SemaCUDA.cpp"
, 782, __extension__ __PRETTY_FUNCTION__))
;
783 assert(Callee && "Callee may not be null.")(static_cast <bool> (Callee && "Callee may not be null."
) ? void (0) : __assert_fail ("Callee && \"Callee may not be null.\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/lib/Sema/SemaCUDA.cpp"
, 783, __extension__ __PRETTY_FUNCTION__))
;
784 // FIXME: Is bailing out early correct here? Should we instead assume that
785 // the caller is a global initializer?
786 FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext);
787 if (!Caller)
1
Assuming 'Caller' is non-null
2
Taking false branch
788 return true;
789
790 // If the caller is known-emitted, mark the callee as known-emitted.
791 // Otherwise, mark the call in our call graph so we can traverse it later.
792 bool CallerKnownEmitted = IsKnownEmitted(*this, Caller);
793 if (CallerKnownEmitted)
3
Taking false branch
794 MarkKnownEmitted(*this, Caller, Callee, Loc);
795 else {
796 // If we have
797 // host fn calls kernel fn calls host+device,
798 // the HD function does not get instantiated on the host. We model this by
799 // omitting at the call to the kernel from the callgraph. This ensures
800 // that, when compiling for host, only HD functions actually called from the
801 // host get marked as known-emitted.
802 if (getLangOpts().CUDAIsDevice || IdentifyCUDATarget(Callee) != CFT_Global)
4
Assuming the condition is false
5
Assuming the condition is false
6
Taking false branch
803 CUDACallGraph[Caller].insert({Callee, Loc});
804 }
805
806 CUDADiagBuilder::Kind DiagKind = [&] {
807 switch (IdentifyCUDAPreference(Caller, Callee)) {
808 case CFP_Never:
809 return CUDADiagBuilder::K_Immediate;
810 case CFP_WrongSide:
811 assert(Caller && "WrongSide calls require a non-null caller")(static_cast <bool> (Caller && "WrongSide calls require a non-null caller"
) ? void (0) : __assert_fail ("Caller && \"WrongSide calls require a non-null caller\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/lib/Sema/SemaCUDA.cpp"
, 811, __extension__ __PRETTY_FUNCTION__))
;
812 // If we know the caller will be emitted, we know this wrong-side call
813 // will be emitted, so it's an immediate error. Otherwise, defer the
814 // error until we know the caller is emitted.
815 return CallerKnownEmitted ? CUDADiagBuilder::K_ImmediateWithCallStack
816 : CUDADiagBuilder::K_Deferred;
817 default:
818 return CUDADiagBuilder::K_Nop;
819 }
820 }();
821
822 if (DiagKind == CUDADiagBuilder::K_Nop)
7
Taking false branch
823 return true;
824
825 // Avoid emitting this error twice for the same location. Using a hashtable
826 // like this is unfortunate, but because we must continue parsing as normal
827 // after encountering a deferred error, it's otherwise very tricky for us to
828 // ensure that we only emit this deferred error once.
829 if (!LocsWithCUDACallDiags.insert({Caller, Loc}).second)
8
Assuming the condition is false
9
Taking false branch
830 return true;
831
832 CUDADiagBuilder(DiagKind, Loc, diag::err_ref_bad_target, Caller, *this)
833 << IdentifyCUDATarget(Callee) << Callee << IdentifyCUDATarget(Caller);
834 CUDADiagBuilder(DiagKind, Callee->getLocation(), diag::note_previous_decl,
10
Calling 'operator<<'
27
Returned allocated memory
835 Caller, *this)
836 << Callee;
837 return DiagKind != CUDADiagBuilder::K_Immediate &&
28
Potential leak of memory pointed to by field 'DiagStorage'
838 DiagKind != CUDADiagBuilder::K_ImmediateWithCallStack;
839}
840
841void Sema::CUDASetLambdaAttrs(CXXMethodDecl *Method) {
842 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation")(static_cast <bool> (getLangOpts().CUDA && "Should only be called during CUDA compilation"
) ? void (0) : __assert_fail ("getLangOpts().CUDA && \"Should only be called during CUDA compilation\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/lib/Sema/SemaCUDA.cpp"
, 842, __extension__ __PRETTY_FUNCTION__))
;
843 if (Method->hasAttr<CUDAHostAttr>() || Method->hasAttr<CUDADeviceAttr>())
844 return;
845 FunctionDecl *CurFn = dyn_cast<FunctionDecl>(CurContext);
846 if (!CurFn)
847 return;
848 CUDAFunctionTarget Target = IdentifyCUDATarget(CurFn);
849 if (Target == CFT_Global || Target == CFT_Device) {
850 Method->addAttr(CUDADeviceAttr::CreateImplicit(Context));
851 } else if (Target == CFT_HostDevice) {
852 Method->addAttr(CUDADeviceAttr::CreateImplicit(Context));
853 Method->addAttr(CUDAHostAttr::CreateImplicit(Context));
854 }
855}
856
857void Sema::checkCUDATargetOverload(FunctionDecl *NewFD,
858 const LookupResult &Previous) {
859 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation")(static_cast <bool> (getLangOpts().CUDA && "Should only be called during CUDA compilation"
) ? void (0) : __assert_fail ("getLangOpts().CUDA && \"Should only be called during CUDA compilation\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/lib/Sema/SemaCUDA.cpp"
, 859, __extension__ __PRETTY_FUNCTION__))
;
860 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(NewFD);
861 for (NamedDecl *OldND : Previous) {
862 FunctionDecl *OldFD = OldND->getAsFunction();
863 if (!OldFD)
864 continue;
865
866 CUDAFunctionTarget OldTarget = IdentifyCUDATarget(OldFD);
867 // Don't allow HD and global functions to overload other functions with the
868 // same signature. We allow overloading based on CUDA attributes so that
869 // functions can have different implementations on the host and device, but
870 // HD/global functions "exist" in some sense on both the host and device, so
871 // should have the same implementation on both sides.
872 if (NewTarget != OldTarget &&
873 ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice) ||
874 (NewTarget == CFT_Global) || (OldTarget == CFT_Global)) &&
875 !IsOverload(NewFD, OldFD, /* UseMemberUsingDeclRules = */ false,
876 /* ConsiderCudaAttrs = */ false)) {
877 Diag(NewFD->getLocation(), diag::err_cuda_ovl_target)
878 << NewTarget << NewFD->getDeclName() << OldTarget << OldFD;
879 Diag(OldFD->getLocation(), diag::note_previous_declaration);
880 NewFD->setInvalidDecl();
881 break;
882 }
883 }
884}
885
886template <typename AttrTy>
887static void copyAttrIfPresent(Sema &S, FunctionDecl *FD,
888 const FunctionDecl &TemplateFD) {
889 if (AttrTy *Attribute = TemplateFD.getAttr<AttrTy>()) {
890 AttrTy *Clone = Attribute->clone(S.Context);
891 Clone->setInherited(true);
892 FD->addAttr(Clone);
893 }
894}
895
896void Sema::inheritCUDATargetAttrs(FunctionDecl *FD,
897 const FunctionTemplateDecl &TD) {
898 const FunctionDecl &TemplateFD = *TD.getTemplatedDecl();
899 copyAttrIfPresent<CUDAGlobalAttr>(*this, FD, TemplateFD);
900 copyAttrIfPresent<CUDAHostAttr>(*this, FD, TemplateFD);
901 copyAttrIfPresent<CUDADeviceAttr>(*this, FD, TemplateFD);
902}

/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/Sema/Sema.h

1//===--- Sema.h - Semantic Analysis & AST Building --------------*- 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 Sema class, which performs semantic analysis and
11// builds ASTs.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_SEMA_SEMA_H
16#define LLVM_CLANG_SEMA_SEMA_H
17
18#include "clang/AST/Attr.h"
19#include "clang/AST/Availability.h"
20#include "clang/AST/DeclarationName.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprObjC.h"
24#include "clang/AST/ExternalASTSource.h"
25#include "clang/AST/LocInfoType.h"
26#include "clang/AST/MangleNumberingContext.h"
27#include "clang/AST/NSAPI.h"
28#include "clang/AST/PrettyPrinter.h"
29#include "clang/AST/StmtCXX.h"
30#include "clang/AST/TypeLoc.h"
31#include "clang/AST/TypeOrdering.h"
32#include "clang/Basic/ExpressionTraits.h"
33#include "clang/Basic/LangOptions.h"
34#include "clang/Basic/Module.h"
35#include "clang/Basic/OpenMPKinds.h"
36#include "clang/Basic/PragmaKinds.h"
37#include "clang/Basic/Specifiers.h"
38#include "clang/Basic/TemplateKinds.h"
39#include "clang/Basic/TypeTraits.h"
40#include "clang/Sema/AnalysisBasedWarnings.h"
41#include "clang/Sema/CleanupInfo.h"
42#include "clang/Sema/DeclSpec.h"
43#include "clang/Sema/ExternalSemaSource.h"
44#include "clang/Sema/IdentifierResolver.h"
45#include "clang/Sema/ObjCMethodList.h"
46#include "clang/Sema/Ownership.h"
47#include "clang/Sema/Scope.h"
48#include "clang/Sema/ScopeInfo.h"
49#include "clang/Sema/TypoCorrection.h"
50#include "clang/Sema/Weak.h"
51#include "llvm/ADT/ArrayRef.h"
52#include "llvm/ADT/Optional.h"
53#include "llvm/ADT/SetVector.h"
54#include "llvm/ADT/SmallPtrSet.h"
55#include "llvm/ADT/SmallVector.h"
56#include "llvm/ADT/TinyPtrVector.h"
57#include <deque>
58#include <memory>
59#include <string>
60#include <vector>
61
62namespace llvm {
63 class APSInt;
64 template <typename ValueT> struct DenseMapInfo;
65 template <typename ValueT, typename ValueInfoT> class DenseSet;
66 class SmallBitVector;
67 struct InlineAsmIdentifierInfo;
68}
69
70namespace clang {
71 class ADLResult;
72 class ASTConsumer;
73 class ASTContext;
74 class ASTMutationListener;
75 class ASTReader;
76 class ASTWriter;
77 class ArrayType;
78 class AttributeList;
79 class BindingDecl;
80 class BlockDecl;
81 class CapturedDecl;
82 class CXXBasePath;
83 class CXXBasePaths;
84 class CXXBindTemporaryExpr;
85 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
86 class CXXConstructorDecl;
87 class CXXConversionDecl;
88 class CXXDeleteExpr;
89 class CXXDestructorDecl;
90 class CXXFieldCollector;
91 class CXXMemberCallExpr;
92 class CXXMethodDecl;
93 class CXXScopeSpec;
94 class CXXTemporary;
95 class CXXTryStmt;
96 class CallExpr;
97 class ClassTemplateDecl;
98 class ClassTemplatePartialSpecializationDecl;
99 class ClassTemplateSpecializationDecl;
100 class VarTemplatePartialSpecializationDecl;
101 class CodeCompleteConsumer;
102 class CodeCompletionAllocator;
103 class CodeCompletionTUInfo;
104 class CodeCompletionResult;
105 class CoroutineBodyStmt;
106 class Decl;
107 class DeclAccessPair;
108 class DeclContext;
109 class DeclRefExpr;
110 class DeclaratorDecl;
111 class DeducedTemplateArgument;
112 class DependentDiagnostic;
113 class DesignatedInitExpr;
114 class Designation;
115 class EnableIfAttr;
116 class EnumConstantDecl;
117 class Expr;
118 class ExtVectorType;
119 class FormatAttr;
120 class FriendDecl;
121 class FunctionDecl;
122 class FunctionProtoType;
123 class FunctionTemplateDecl;
124 class ImplicitConversionSequence;
125 typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
126 class InitListExpr;
127 class InitializationKind;
128 class InitializationSequence;
129 class InitializedEntity;
130 class IntegerLiteral;
131 class LabelStmt;
132 class LambdaExpr;
133 class LangOptions;
134 class LocalInstantiationScope;
135 class LookupResult;
136 class MacroInfo;
137 typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
138 class ModuleLoader;
139 class MultiLevelTemplateArgumentList;
140 class NamedDecl;
141 class ObjCCategoryDecl;
142 class ObjCCategoryImplDecl;
143 class ObjCCompatibleAliasDecl;
144 class ObjCContainerDecl;
145 class ObjCImplDecl;
146 class ObjCImplementationDecl;
147 class ObjCInterfaceDecl;
148 class ObjCIvarDecl;
149 template <class T> class ObjCList;
150 class ObjCMessageExpr;
151 class ObjCMethodDecl;
152 class ObjCPropertyDecl;
153 class ObjCProtocolDecl;
154 class OMPThreadPrivateDecl;
155 class OMPDeclareReductionDecl;
156 class OMPDeclareSimdDecl;
157 class OMPClause;
158 struct OverloadCandidate;
159 class OverloadCandidateSet;
160 class OverloadExpr;
161 class ParenListExpr;
162 class ParmVarDecl;
163 class Preprocessor;
164 class PseudoDestructorTypeStorage;
165 class PseudoObjectExpr;
166 class QualType;
167 class StandardConversionSequence;
168 class Stmt;
169 class StringLiteral;
170 class SwitchStmt;
171 class TemplateArgument;
172 class TemplateArgumentList;
173 class TemplateArgumentLoc;
174 class TemplateDecl;
175 class TemplateInstantiationCallback;
176 class TemplateParameterList;
177 class TemplatePartialOrderingContext;
178 class TemplateTemplateParmDecl;
179 class Token;
180 class TypeAliasDecl;
181 class TypedefDecl;
182 class TypedefNameDecl;
183 class TypeLoc;
184 class TypoCorrectionConsumer;
185 class UnqualifiedId;
186 class UnresolvedLookupExpr;
187 class UnresolvedMemberExpr;
188 class UnresolvedSetImpl;
189 class UnresolvedSetIterator;
190 class UsingDecl;
191 class UsingShadowDecl;
192 class ValueDecl;
193 class VarDecl;
194 class VarTemplateSpecializationDecl;
195 class VisibilityAttr;
196 class VisibleDeclConsumer;
197 class IndirectFieldDecl;
198 struct DeductionFailureInfo;
199 class TemplateSpecCandidateSet;
200
201namespace sema {
202 class AccessedEntity;
203 class BlockScopeInfo;
204 class CapturedRegionScopeInfo;
205 class CapturingScopeInfo;
206 class CompoundScopeInfo;
207 class DelayedDiagnostic;
208 class DelayedDiagnosticPool;
209 class FunctionScopeInfo;
210 class LambdaScopeInfo;
211 class PossiblyUnreachableDiag;
212 class SemaPPCallbacks;
213 class TemplateDeductionInfo;
214}
215
216namespace threadSafety {
217 class BeforeSet;
218 void threadSafetyCleanup(BeforeSet* Cache);
219}
220
221// FIXME: No way to easily map from TemplateTypeParmTypes to
222// TemplateTypeParmDecls, so we have this horrible PointerUnion.
223typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
224 SourceLocation> UnexpandedParameterPack;
225
226/// Describes whether we've seen any nullability information for the given
227/// file.
228struct FileNullability {
229 /// The first pointer declarator (of any pointer kind) in the file that does
230 /// not have a corresponding nullability annotation.
231 SourceLocation PointerLoc;
232
233 /// The end location for the first pointer declarator in the file. Used for
234 /// placing fix-its.
235 SourceLocation PointerEndLoc;
236
237 /// Which kind of pointer declarator we saw.
238 uint8_t PointerKind;
239
240 /// Whether we saw any type nullability annotations in the given file.
241 bool SawTypeNullability = false;
242};
243
244/// A mapping from file IDs to a record of whether we've seen nullability
245/// information in that file.
246class FileNullabilityMap {
247 /// A mapping from file IDs to the nullability information for each file ID.
248 llvm::DenseMap<FileID, FileNullability> Map;
249
250 /// A single-element cache based on the file ID.
251 struct {
252 FileID File;
253 FileNullability Nullability;
254 } Cache;
255
256public:
257 FileNullability &operator[](FileID file) {
258 // Check the single-element cache.
259 if (file == Cache.File)
260 return Cache.Nullability;
261
262 // It's not in the single-element cache; flush the cache if we have one.
263 if (!Cache.File.isInvalid()) {
264 Map[Cache.File] = Cache.Nullability;
265 }
266
267 // Pull this entry into the cache.
268 Cache.File = file;
269 Cache.Nullability = Map[file];
270 return Cache.Nullability;
271 }
272};
273
274/// Sema - This implements semantic analysis and AST building for C.
275class Sema {
276 Sema(const Sema &) = delete;
277 void operator=(const Sema &) = delete;
278
279 ///\brief Source of additional semantic information.
280 ExternalSemaSource *ExternalSource;
281
282 ///\brief Whether Sema has generated a multiplexer and has to delete it.
283 bool isMultiplexExternalSource;
284
285 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
286
287 bool isVisibleSlow(const NamedDecl *D);
288
289 /// Determine whether two declarations should be linked together, given that
290 /// the old declaration might not be visible and the new declaration might
291 /// not have external linkage.
292 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
293 const NamedDecl *New) {
294 if (isVisible(Old))
295 return true;
296 // See comment in below overload for why it's safe to compute the linkage
297 // of the new declaration here.
298 if (New->isExternallyDeclarable()) {
299 assert(Old->isExternallyDeclarable() &&(static_cast <bool> (Old->isExternallyDeclarable() &&
"should not have found a non-externally-declarable previous decl"
) ? void (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/Sema/Sema.h"
, 300, __extension__ __PRETTY_FUNCTION__))
300 "should not have found a non-externally-declarable previous decl")(static_cast <bool> (Old->isExternallyDeclarable() &&
"should not have found a non-externally-declarable previous decl"
) ? void (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/Sema/Sema.h"
, 300, __extension__ __PRETTY_FUNCTION__))
;
301 return true;
302 }
303 return false;
304 }
305 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
306
307public:
308 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
309 typedef OpaquePtr<TemplateName> TemplateTy;
310 typedef OpaquePtr<QualType> TypeTy;
311
312 OpenCLOptions OpenCLFeatures;
313 FPOptions FPFeatures;
314
315 const LangOptions &LangOpts;
316 Preprocessor &PP;
317 ASTContext &Context;
318 ASTConsumer &Consumer;
319 DiagnosticsEngine &Diags;
320 SourceManager &SourceMgr;
321
322 /// \brief Flag indicating whether or not to collect detailed statistics.
323 bool CollectStats;
324
325 /// \brief Code-completion consumer.
326 CodeCompleteConsumer *CodeCompleter;
327
328 /// CurContext - This is the current declaration context of parsing.
329 DeclContext *CurContext;
330
331 /// \brief Generally null except when we temporarily switch decl contexts,
332 /// like in \see ActOnObjCTemporaryExitContainerContext.
333 DeclContext *OriginalLexicalContext;
334
335 /// VAListTagName - The declaration name corresponding to __va_list_tag.
336 /// This is used as part of a hack to omit that class from ADL results.
337 DeclarationName VAListTagName;
338
339 bool MSStructPragmaOn; // True when \#pragma ms_struct on
340
341 /// \brief Controls member pointer representation format under the MS ABI.
342 LangOptions::PragmaMSPointersToMembersKind
343 MSPointerToMemberRepresentationMethod;
344
345 /// Stack of active SEH __finally scopes. Can be empty.
346 SmallVector<Scope*, 2> CurrentSEHFinally;
347
348 /// \brief Source location for newly created implicit MSInheritanceAttrs
349 SourceLocation ImplicitMSInheritanceAttrLoc;
350
351 /// \brief pragma clang section kind
352 enum PragmaClangSectionKind {
353 PCSK_Invalid = 0,
354 PCSK_BSS = 1,
355 PCSK_Data = 2,
356 PCSK_Rodata = 3,
357 PCSK_Text = 4
358 };
359
360 enum PragmaClangSectionAction {
361 PCSA_Set = 0,
362 PCSA_Clear = 1
363 };
364
365 struct PragmaClangSection {
366 std::string SectionName;
367 bool Valid = false;
368 SourceLocation PragmaLocation;
369
370 void Act(SourceLocation PragmaLocation,
371 PragmaClangSectionAction Action,
372 StringLiteral* Name);
373 };
374
375 PragmaClangSection PragmaClangBSSSection;
376 PragmaClangSection PragmaClangDataSection;
377 PragmaClangSection PragmaClangRodataSection;
378 PragmaClangSection PragmaClangTextSection;
379
380 enum PragmaMsStackAction {
381 PSK_Reset = 0x0, // #pragma ()
382 PSK_Set = 0x1, // #pragma (value)
383 PSK_Push = 0x2, // #pragma (push[, id])
384 PSK_Pop = 0x4, // #pragma (pop[, id])
385 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
386 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
387 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
388 };
389
390 template<typename ValueType>
391 struct PragmaStack {
392 struct Slot {
393 llvm::StringRef StackSlotLabel;
394 ValueType Value;
395 SourceLocation PragmaLocation;
396 SourceLocation PragmaPushLocation;
397 Slot(llvm::StringRef StackSlotLabel, ValueType Value,
398 SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
399 : StackSlotLabel(StackSlotLabel), Value(Value),
400 PragmaLocation(PragmaLocation),
401 PragmaPushLocation(PragmaPushLocation) {}
402 };
403 void Act(SourceLocation PragmaLocation,
404 PragmaMsStackAction Action,
405 llvm::StringRef StackSlotLabel,
406 ValueType Value);
407
408 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
409 // method body to restore the stacks on exit, so it works like this:
410 //
411 // struct S {
412 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
413 // void Method {}
414 // #pragma <name>(pop, InternalPragmaSlot)
415 // };
416 //
417 // It works even with #pragma vtordisp, although MSVC doesn't support
418 // #pragma vtordisp(push [, id], n)
419 // syntax.
420 //
421 // Push / pop a named sentinel slot.
422 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
423 assert((Action == PSK_Push || Action == PSK_Pop) &&(static_cast <bool> ((Action == PSK_Push || Action == PSK_Pop
) && "Can only push / pop #pragma stack sentinels!") ?
void (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/Sema/Sema.h"
, 424, __extension__ __PRETTY_FUNCTION__))
424 "Can only push / pop #pragma stack sentinels!")(static_cast <bool> ((Action == PSK_Push || Action == PSK_Pop
) && "Can only push / pop #pragma stack sentinels!") ?
void (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/Sema/Sema.h"
, 424, __extension__ __PRETTY_FUNCTION__))
;
425 Act(CurrentPragmaLocation, Action, Label, CurrentValue);
426 }
427
428 // Constructors.
429 explicit PragmaStack(const ValueType &Default)
430 : DefaultValue(Default), CurrentValue(Default) {}
431
432 bool hasValue() const { return CurrentValue != DefaultValue; }
433
434 SmallVector<Slot, 2> Stack;
435 ValueType DefaultValue; // Value used for PSK_Reset action.
436 ValueType CurrentValue;
437 SourceLocation CurrentPragmaLocation;
438 };
439 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
440 // we shouldn't do so if they're in a module).
441
442 /// \brief Whether to insert vtordisps prior to virtual bases in the Microsoft
443 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
444 ///
445 /// 0: Suppress all vtordisps
446 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
447 /// structors
448 /// 2: Always insert vtordisps to support RTTI on partially constructed
449 /// objects
450 PragmaStack<MSVtorDispAttr::Mode> VtorDispStack;
451 // #pragma pack.
452 // Sentinel to represent when the stack is set to mac68k alignment.
453 static const unsigned kMac68kAlignmentSentinel = ~0U;
454 PragmaStack<unsigned> PackStack;
455 // The current #pragma pack values and locations at each #include.
456 struct PackIncludeState {
457 unsigned CurrentValue;
458 SourceLocation CurrentPragmaLocation;
459 bool HasNonDefaultValue, ShouldWarnOnInclude;
460 };
461 SmallVector<PackIncludeState, 8> PackIncludeStack;
462 // Segment #pragmas.
463 PragmaStack<StringLiteral *> DataSegStack;
464 PragmaStack<StringLiteral *> BSSSegStack;
465 PragmaStack<StringLiteral *> ConstSegStack;
466 PragmaStack<StringLiteral *> CodeSegStack;
467
468 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
469 // Actions should be performed only if we enter / exit a C++ method body.
470 class PragmaStackSentinelRAII {
471 public:
472 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
473 ~PragmaStackSentinelRAII();
474
475 private:
476 Sema &S;
477 StringRef SlotLabel;
478 bool ShouldAct;
479 };
480
481 /// A mapping that describes the nullability we've seen in each header file.
482 FileNullabilityMap NullabilityMap;
483
484 /// Last section used with #pragma init_seg.
485 StringLiteral *CurInitSeg;
486 SourceLocation CurInitSegLoc;
487
488 /// VisContext - Manages the stack for \#pragma GCC visibility.
489 void *VisContext; // Really a "PragmaVisStack*"
490
491 /// \brief This represents the stack of attributes that were pushed by
492 /// \#pragma clang attribute.
493 struct PragmaAttributeEntry {
494 SourceLocation Loc;
495 AttributeList *Attribute;
496 SmallVector<attr::SubjectMatchRule, 4> MatchRules;
497 bool IsUsed;
498 };
499 SmallVector<PragmaAttributeEntry, 2> PragmaAttributeStack;
500
501 /// \brief The declaration that is currently receiving an attribute from the
502 /// #pragma attribute stack.
503 const Decl *PragmaAttributeCurrentTargetDecl;
504
505 /// \brief This represents the last location of a "#pragma clang optimize off"
506 /// directive if such a directive has not been closed by an "on" yet. If
507 /// optimizations are currently "on", this is set to an invalid location.
508 SourceLocation OptimizeOffPragmaLocation;
509
510 /// \brief Flag indicating if Sema is building a recovery call expression.
511 ///
512 /// This flag is used to avoid building recovery call expressions
513 /// if Sema is already doing so, which would cause infinite recursions.
514 bool IsBuildingRecoveryCallExpr;
515
516 /// Used to control the generation of ExprWithCleanups.
517 CleanupInfo Cleanup;
518
519 /// ExprCleanupObjects - This is the stack of objects requiring
520 /// cleanup that are created by the current full expression. The
521 /// element type here is ExprWithCleanups::Object.
522 SmallVector<BlockDecl*, 8> ExprCleanupObjects;
523
524 /// \brief Store a list of either DeclRefExprs or MemberExprs
525 /// that contain a reference to a variable (constant) that may or may not
526 /// be odr-used in this Expr, and we won't know until all lvalue-to-rvalue
527 /// and discarded value conversions have been applied to all subexpressions
528 /// of the enclosing full expression. This is cleared at the end of each
529 /// full expression.
530 llvm::SmallPtrSet<Expr*, 2> MaybeODRUseExprs;
531
532 /// \brief Stack containing information about each of the nested
533 /// function, block, and method scopes that are currently active.
534 ///
535 /// This array is never empty. Clients should ignore the first
536 /// element, which is used to cache a single FunctionScopeInfo
537 /// that's used to parse every top-level function.
538 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
539
540 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
541 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
542 ExtVectorDeclsType;
543
544 /// ExtVectorDecls - This is a list all the extended vector types. This allows
545 /// us to associate a raw vector type with one of the ext_vector type names.
546 /// This is only necessary for issuing pretty diagnostics.
547 ExtVectorDeclsType ExtVectorDecls;
548
549 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
550 std::unique_ptr<CXXFieldCollector> FieldCollector;
551
552 typedef llvm::SmallSetVector<const NamedDecl*, 16> NamedDeclSetType;
553
554 /// \brief Set containing all declared private fields that are not used.
555 NamedDeclSetType UnusedPrivateFields;
556
557 /// \brief Set containing all typedefs that are likely unused.
558 llvm::SmallSetVector<const TypedefNameDecl *, 4>
559 UnusedLocalTypedefNameCandidates;
560
561 /// \brief Delete-expressions to be analyzed at the end of translation unit
562 ///
563 /// This list contains class members, and locations of delete-expressions
564 /// that could not be proven as to whether they mismatch with new-expression
565 /// used in initializer of the field.
566 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
567 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
568 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
569
570 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
571
572 /// PureVirtualClassDiagSet - a set of class declarations which we have
573 /// emitted a list of pure virtual functions. Used to prevent emitting the
574 /// same list more than once.
575 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
576
577 /// ParsingInitForAutoVars - a set of declarations with auto types for which
578 /// we are currently parsing the initializer.
579 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
580
581 /// \brief Look for a locally scoped extern "C" declaration by the given name.
582 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
583
584 typedef LazyVector<VarDecl *, ExternalSemaSource,
585 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
586 TentativeDefinitionsType;
587
588 /// \brief All the tentative definitions encountered in the TU.
589 TentativeDefinitionsType TentativeDefinitions;
590
591 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
592 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
593 UnusedFileScopedDeclsType;
594
595 /// \brief The set of file scoped decls seen so far that have not been used
596 /// and must warn if not used. Only contains the first declaration.
597 UnusedFileScopedDeclsType UnusedFileScopedDecls;
598
599 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
600 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
601 DelegatingCtorDeclsType;
602
603 /// \brief All the delegating constructors seen so far in the file, used for
604 /// cycle detection at the end of the TU.
605 DelegatingCtorDeclsType DelegatingCtorDecls;
606
607 /// \brief All the overriding functions seen during a class definition
608 /// that had their exception spec checks delayed, plus the overridden
609 /// function.
610 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
611 DelayedExceptionSpecChecks;
612
613 /// \brief All the members seen during a class definition which were both
614 /// explicitly defaulted and had explicitly-specified exception
615 /// specifications, along with the function type containing their
616 /// user-specified exception specification. Those exception specifications
617 /// were overridden with the default specifications, but we still need to
618 /// check whether they are compatible with the default specification, and
619 /// we can't do that until the nesting set of class definitions is complete.
620 SmallVector<std::pair<CXXMethodDecl*, const FunctionProtoType*>, 2>
621 DelayedDefaultedMemberExceptionSpecs;
622
623 typedef llvm::MapVector<const FunctionDecl *,
624 std::unique_ptr<LateParsedTemplate>>
625 LateParsedTemplateMapT;
626 LateParsedTemplateMapT LateParsedTemplateMap;
627
628 /// \brief Callback to the parser to parse templated functions when needed.
629 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
630 typedef void LateTemplateParserCleanupCB(void *P);
631 LateTemplateParserCB *LateTemplateParser;
632 LateTemplateParserCleanupCB *LateTemplateParserCleanup;
633 void *OpaqueParser;
634
635 void SetLateTemplateParser(LateTemplateParserCB *LTP,
636 LateTemplateParserCleanupCB *LTPCleanup,
637 void *P) {
638 LateTemplateParser = LTP;
639 LateTemplateParserCleanup = LTPCleanup;
640 OpaqueParser = P;
641 }
642
643 class DelayedDiagnostics;
644
645 class DelayedDiagnosticsState {
646 sema::DelayedDiagnosticPool *SavedPool;
647 friend class Sema::DelayedDiagnostics;
648 };
649 typedef DelayedDiagnosticsState ParsingDeclState;
650 typedef DelayedDiagnosticsState ProcessingContextState;
651
652 /// A class which encapsulates the logic for delaying diagnostics
653 /// during parsing and other processing.
654 class DelayedDiagnostics {
655 /// \brief The current pool of diagnostics into which delayed
656 /// diagnostics should go.
657 sema::DelayedDiagnosticPool *CurPool;
658
659 public:
660 DelayedDiagnostics() : CurPool(nullptr) {}
661
662 /// Adds a delayed diagnostic.
663 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
664
665 /// Determines whether diagnostics should be delayed.
666 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
667
668 /// Returns the current delayed-diagnostics pool.
669 sema::DelayedDiagnosticPool *getCurrentPool() const {
670 return CurPool;
671 }
672
673 /// Enter a new scope. Access and deprecation diagnostics will be
674 /// collected in this pool.
675 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
676 DelayedDiagnosticsState state;
677 state.SavedPool = CurPool;
678 CurPool = &pool;
679 return state;
680 }
681
682 /// Leave a delayed-diagnostic state that was previously pushed.
683 /// Do not emit any of the diagnostics. This is performed as part
684 /// of the bookkeeping of popping a pool "properly".
685 void popWithoutEmitting(DelayedDiagnosticsState state) {
686 CurPool = state.SavedPool;
687 }
688
689 /// Enter a new scope where access and deprecation diagnostics are
690 /// not delayed.
691 DelayedDiagnosticsState pushUndelayed() {
692 DelayedDiagnosticsState state;
693 state.SavedPool = CurPool;
694 CurPool = nullptr;
695 return state;
696 }
697
698 /// Undo a previous pushUndelayed().
699 void popUndelayed(DelayedDiagnosticsState state) {
700 assert(CurPool == nullptr)(static_cast <bool> (CurPool == nullptr) ? void (0) : __assert_fail
("CurPool == nullptr", "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/Sema/Sema.h"
, 700, __extension__ __PRETTY_FUNCTION__))
;
701 CurPool = state.SavedPool;
702 }
703 } DelayedDiagnostics;
704
705 /// A RAII object to temporarily push a declaration context.
706 class ContextRAII {
707 private:
708 Sema &S;
709 DeclContext *SavedContext;
710 ProcessingContextState SavedContextState;
711 QualType SavedCXXThisTypeOverride;
712
713 public:
714 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
715 : S(S), SavedContext(S.CurContext),
716 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
717 SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
718 {
719 assert(ContextToPush && "pushing null context")(static_cast <bool> (ContextToPush && "pushing null context"
) ? void (0) : __assert_fail ("ContextToPush && \"pushing null context\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/Sema/Sema.h"
, 719, __extension__ __PRETTY_FUNCTION__))
;
720 S.CurContext = ContextToPush;
721 if (NewThisContext)
722 S.CXXThisTypeOverride = QualType();
723 }
724
725 void pop() {
726 if (!SavedContext) return;
727 S.CurContext = SavedContext;
728 S.DelayedDiagnostics.popUndelayed(SavedContextState);
729 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
730 SavedContext = nullptr;
731 }
732
733 ~ContextRAII() {
734 pop();
735 }
736 };
737
738 /// \brief RAII object to handle the state changes required to synthesize
739 /// a function body.
740 class SynthesizedFunctionScope {
741 Sema &S;
742 Sema::ContextRAII SavedContext;
743 bool PushedCodeSynthesisContext = false;
744
745 public:
746 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
747 : S(S), SavedContext(S, DC) {
748 S.PushFunctionScope();
749 S.PushExpressionEvaluationContext(
750 Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
751 if (auto *FD = dyn_cast<FunctionDecl>(DC))
752 FD->setWillHaveBody(true);
753 else
754 assert(isa<ObjCMethodDecl>(DC))(static_cast <bool> (isa<ObjCMethodDecl>(DC)) ? void
(0) : __assert_fail ("isa<ObjCMethodDecl>(DC)", "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/Sema/Sema.h"
, 754, __extension__ __PRETTY_FUNCTION__))
;
755 }
756
757 void addContextNote(SourceLocation UseLoc) {
758 assert(!PushedCodeSynthesisContext)(static_cast <bool> (!PushedCodeSynthesisContext) ? void
(0) : __assert_fail ("!PushedCodeSynthesisContext", "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/Sema/Sema.h"
, 758, __extension__ __PRETTY_FUNCTION__))
;
759
760 Sema::CodeSynthesisContext Ctx;
761 Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
762 Ctx.PointOfInstantiation = UseLoc;
763 Ctx.Entity = cast<Decl>(S.CurContext);
764 S.pushCodeSynthesisContext(Ctx);
765
766 PushedCodeSynthesisContext = true;
767 }
768
769 ~SynthesizedFunctionScope() {
770 if (PushedCodeSynthesisContext)
771 S.popCodeSynthesisContext();
772 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
773 FD->setWillHaveBody(false);
774 S.PopExpressionEvaluationContext();
775 S.PopFunctionScopeInfo();
776 }
777 };
778
779 /// WeakUndeclaredIdentifiers - Identifiers contained in
780 /// \#pragma weak before declared. rare. may alias another
781 /// identifier, declared or undeclared
782 llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
783
784 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
785 /// \#pragma redefine_extname before declared. Used in Solaris system headers
786 /// to define functions that occur in multiple standards to call the version
787 /// in the currently selected standard.
788 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
789
790
791 /// \brief Load weak undeclared identifiers from the external source.
792 void LoadExternalWeakUndeclaredIdentifiers();
793
794 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
795 /// \#pragma weak during processing of other Decls.
796 /// I couldn't figure out a clean way to generate these in-line, so
797 /// we store them here and handle separately -- which is a hack.
798 /// It would be best to refactor this.
799 SmallVector<Decl*,2> WeakTopLevelDecl;
800
801 IdentifierResolver IdResolver;
802
803 /// Translation Unit Scope - useful to Objective-C actions that need
804 /// to lookup file scope declarations in the "ordinary" C decl namespace.
805 /// For example, user-defined classes, built-in "id" type, etc.
806 Scope *TUScope;
807
808 /// \brief The C++ "std" namespace, where the standard library resides.
809 LazyDeclPtr StdNamespace;
810
811 /// \brief The C++ "std::bad_alloc" class, which is defined by the C++
812 /// standard library.
813 LazyDeclPtr StdBadAlloc;
814
815 /// \brief The C++ "std::align_val_t" enum class, which is defined by the C++
816 /// standard library.
817 LazyDeclPtr StdAlignValT;
818
819 /// \brief The C++ "std::experimental" namespace, where the experimental parts
820 /// of the standard library resides.
821 NamespaceDecl *StdExperimentalNamespaceCache;
822
823 /// \brief The C++ "std::initializer_list" template, which is defined in
824 /// \<initializer_list>.
825 ClassTemplateDecl *StdInitializerList;
826
827 /// \brief The C++ "type_info" declaration, which is defined in \<typeinfo>.
828 RecordDecl *CXXTypeInfoDecl;
829
830 /// \brief The MSVC "_GUID" struct, which is defined in MSVC header files.
831 RecordDecl *MSVCGuidDecl;
832
833 /// \brief Caches identifiers/selectors for NSFoundation APIs.
834 std::unique_ptr<NSAPI> NSAPIObj;
835
836 /// \brief The declaration of the Objective-C NSNumber class.
837 ObjCInterfaceDecl *NSNumberDecl;
838
839 /// \brief The declaration of the Objective-C NSValue class.
840 ObjCInterfaceDecl *NSValueDecl;
841
842 /// \brief Pointer to NSNumber type (NSNumber *).
843 QualType NSNumberPointer;
844
845 /// \brief Pointer to NSValue type (NSValue *).
846 QualType NSValuePointer;
847
848 /// \brief The Objective-C NSNumber methods used to create NSNumber literals.
849 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
850
851 /// \brief The declaration of the Objective-C NSString class.
852 ObjCInterfaceDecl *NSStringDecl;
853
854 /// \brief Pointer to NSString type (NSString *).
855 QualType NSStringPointer;
856
857 /// \brief The declaration of the stringWithUTF8String: method.
858 ObjCMethodDecl *StringWithUTF8StringMethod;
859
860 /// \brief The declaration of the valueWithBytes:objCType: method.
861 ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
862
863 /// \brief The declaration of the Objective-C NSArray class.
864 ObjCInterfaceDecl *NSArrayDecl;
865
866 /// \brief The declaration of the arrayWithObjects:count: method.
867 ObjCMethodDecl *ArrayWithObjectsMethod;
868
869 /// \brief The declaration of the Objective-C NSDictionary class.
870 ObjCInterfaceDecl *NSDictionaryDecl;
871
872 /// \brief The declaration of the dictionaryWithObjects:forKeys:count: method.
873 ObjCMethodDecl *DictionaryWithObjectsMethod;
874
875 /// \brief id<NSCopying> type.
876 QualType QIDNSCopying;
877
878 /// \brief will hold 'respondsToSelector:'
879 Selector RespondsToSelectorSel;
880
881 /// A flag to remember whether the implicit forms of operator new and delete
882 /// have been declared.
883 bool GlobalNewDeleteDeclared;
884
885 /// A flag to indicate that we're in a context that permits abstract
886 /// references to fields. This is really a
887 bool AllowAbstractFieldReference;
888
889 /// \brief Describes how the expressions currently being parsed are
890 /// evaluated at run-time, if at all.
891 enum class ExpressionEvaluationContext {
892 /// \brief The current expression and its subexpressions occur within an
893 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
894 /// \c sizeof, where the type of the expression may be significant but
895 /// no code will be generated to evaluate the value of the expression at
896 /// run time.
897 Unevaluated,
898
899 /// \brief The current expression occurs within a braced-init-list within
900 /// an unevaluated operand. This is mostly like a regular unevaluated
901 /// context, except that we still instantiate constexpr functions that are
902 /// referenced here so that we can perform narrowing checks correctly.
903 UnevaluatedList,
904
905 /// \brief The current expression occurs within a discarded statement.
906 /// This behaves largely similarly to an unevaluated operand in preventing
907 /// definitions from being required, but not in other ways.
908 DiscardedStatement,
909
910 /// \brief The current expression occurs within an unevaluated
911 /// operand that unconditionally permits abstract references to
912 /// fields, such as a SIZE operator in MS-style inline assembly.
913 UnevaluatedAbstract,
914
915 /// \brief The current context is "potentially evaluated" in C++11 terms,
916 /// but the expression is evaluated at compile-time (like the values of
917 /// cases in a switch statement).
918 ConstantEvaluated,
919
920 /// \brief The current expression is potentially evaluated at run time,
921 /// which means that code may be generated to evaluate the value of the
922 /// expression at run time.
923 PotentiallyEvaluated,
924
925 /// \brief The current expression is potentially evaluated, but any
926 /// declarations referenced inside that expression are only used if
927 /// in fact the current expression is used.
928 ///
929 /// This value is used when parsing default function arguments, for which
930 /// we would like to provide diagnostics (e.g., passing non-POD arguments
931 /// through varargs) but do not want to mark declarations as "referenced"
932 /// until the default argument is used.
933 PotentiallyEvaluatedIfUsed
934 };
935
936 /// \brief Data structure used to record current or nested
937 /// expression evaluation contexts.
938 struct ExpressionEvaluationContextRecord {
939 /// \brief The expression evaluation context.
940 ExpressionEvaluationContext Context;
941
942 /// \brief Whether the enclosing context needed a cleanup.
943 CleanupInfo ParentCleanup;
944
945 /// \brief Whether we are in a decltype expression.
946 bool IsDecltype;
947
948 /// \brief The number of active cleanup objects when we entered
949 /// this expression evaluation context.
950 unsigned NumCleanupObjects;
951
952 /// \brief The number of typos encountered during this expression evaluation
953 /// context (i.e. the number of TypoExprs created).
954 unsigned NumTypos;
955
956 llvm::SmallPtrSet<Expr*, 2> SavedMaybeODRUseExprs;
957
958 /// \brief The lambdas that are present within this context, if it
959 /// is indeed an unevaluated context.
960 SmallVector<LambdaExpr *, 2> Lambdas;
961
962 /// \brief The declaration that provides context for lambda expressions
963 /// and block literals if the normal declaration context does not
964 /// suffice, e.g., in a default function argument.
965 Decl *ManglingContextDecl;
966
967 /// \brief The context information used to mangle lambda expressions
968 /// and block literals within this context.
969 ///
970 /// This mangling information is allocated lazily, since most contexts
971 /// do not have lambda expressions or block literals.
972 std::unique_ptr<MangleNumberingContext> MangleNumbering;
973
974 /// \brief If we are processing a decltype type, a set of call expressions
975 /// for which we have deferred checking the completeness of the return type.
976 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
977
978 /// \brief If we are processing a decltype type, a set of temporary binding
979 /// expressions for which we have deferred checking the destructor.
980 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
981
982 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
983 unsigned NumCleanupObjects,
984 CleanupInfo ParentCleanup,
985 Decl *ManglingContextDecl,
986 bool IsDecltype)
987 : Context(Context), ParentCleanup(ParentCleanup),
988 IsDecltype(IsDecltype), NumCleanupObjects(NumCleanupObjects),
989 NumTypos(0),
990 ManglingContextDecl(ManglingContextDecl), MangleNumbering() { }
991
992 /// \brief Retrieve the mangling numbering context, used to consistently
993 /// number constructs like lambdas for mangling.
994 MangleNumberingContext &getMangleNumberingContext(ASTContext &Ctx);
995
996 bool isUnevaluated() const {
997 return Context == ExpressionEvaluationContext::Unevaluated ||
998 Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
999 Context == ExpressionEvaluationContext::UnevaluatedList;
1000 }
1001 bool isConstantEvaluated() const {
1002 return Context == ExpressionEvaluationContext::ConstantEvaluated;
1003 }
1004 };
1005
1006 /// A stack of expression evaluation contexts.
1007 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
1008
1009 /// \brief Compute the mangling number context for a lambda expression or
1010 /// block literal.
1011 ///
1012 /// \param DC - The DeclContext containing the lambda expression or
1013 /// block literal.
1014 /// \param[out] ManglingContextDecl - Returns the ManglingContextDecl
1015 /// associated with the context, if relevant.
1016 MangleNumberingContext *getCurrentMangleNumberContext(
1017 const DeclContext *DC,
1018 Decl *&ManglingContextDecl);
1019
1020
1021 /// SpecialMemberOverloadResult - The overloading result for a special member
1022 /// function.
1023 ///
1024 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1025 /// integer are used to determine whether overload resolution succeeded.
1026 class SpecialMemberOverloadResult {
1027 public:
1028 enum Kind {
1029 NoMemberOrDeleted,
1030 Ambiguous,
1031 Success
1032 };
1033
1034 private:
1035 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
1036
1037 public:
1038 SpecialMemberOverloadResult() : Pair() {}
1039 SpecialMemberOverloadResult(CXXMethodDecl *MD)
1040 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1041
1042 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
1043 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1044
1045 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
1046 void setKind(Kind K) { Pair.setInt(K); }
1047 };
1048
1049 class SpecialMemberOverloadResultEntry
1050 : public llvm::FastFoldingSetNode,
1051 public SpecialMemberOverloadResult {
1052 public:
1053 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1054 : FastFoldingSetNode(ID)
1055 {}
1056 };
1057
1058 /// \brief A cache of special member function overload resolution results
1059 /// for C++ records.
1060 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1061
1062 /// \brief A cache of the flags available in enumerations with the flag_bits
1063 /// attribute.
1064 mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1065
1066 /// \brief The kind of translation unit we are processing.
1067 ///
1068 /// When we're processing a complete translation unit, Sema will perform
1069 /// end-of-translation-unit semantic tasks (such as creating
1070 /// initializers for tentative definitions in C) once parsing has
1071 /// completed. Modules and precompiled headers perform different kinds of
1072 /// checks.
1073 TranslationUnitKind TUKind;
1074
1075 llvm::BumpPtrAllocator BumpAlloc;
1076
1077 /// \brief The number of SFINAE diagnostics that have been trapped.
1078 unsigned NumSFINAEErrors;
1079
1080 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1081 UnparsedDefaultArgInstantiationsMap;
1082
1083 /// \brief A mapping from parameters with unparsed default arguments to the
1084 /// set of instantiations of each parameter.
1085 ///
1086 /// This mapping is a temporary data structure used when parsing
1087 /// nested class templates or nested classes of class templates,
1088 /// where we might end up instantiating an inner class before the
1089 /// default arguments of its methods have been parsed.
1090 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1091
1092 // Contains the locations of the beginning of unparsed default
1093 // argument locations.
1094 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1095
1096 /// UndefinedInternals - all the used, undefined objects which require a
1097 /// definition in this translation unit.
1098 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1099
1100 /// Determine if VD, which must be a variable or function, is an external
1101 /// symbol that nonetheless can't be referenced from outside this translation
1102 /// unit because its type has no linkage and it's not extern "C".
1103 bool isExternalWithNoLinkageType(ValueDecl *VD);
1104
1105 /// Obtain a sorted list of functions that are undefined but ODR-used.
1106 void getUndefinedButUsed(
1107 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1108
1109 /// Retrieves list of suspicious delete-expressions that will be checked at
1110 /// the end of translation unit.
1111 const llvm::MapVector<FieldDecl *, DeleteLocs> &
1112 getMismatchingDeleteExpressions() const;
1113
1114 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
1115 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
1116
1117 /// Method Pool - allows efficient lookup when typechecking messages to "id".
1118 /// We need to maintain a list, since selectors can have differing signatures
1119 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1120 /// of selectors are "overloaded").
1121 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1122 /// methods inside categories with a particular selector.
1123 GlobalMethodPool MethodPool;
1124
1125 /// Method selectors used in a \@selector expression. Used for implementation
1126 /// of -Wselector.
1127 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1128
1129 /// Kinds of C++ special members.
1130 enum CXXSpecialMember {
1131 CXXDefaultConstructor,
1132 CXXCopyConstructor,
1133 CXXMoveConstructor,
1134 CXXCopyAssignment,
1135 CXXMoveAssignment,
1136 CXXDestructor,
1137 CXXInvalid
1138 };
1139
1140 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1141 SpecialMemberDecl;
1142
1143 /// The C++ special members which we are currently in the process of
1144 /// declaring. If this process recursively triggers the declaration of the
1145 /// same special member, we should act as if it is not yet declared.
1146 llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1147
1148 /// The function definitions which were renamed as part of typo-correction
1149 /// to match their respective declarations. We want to keep track of them
1150 /// to ensure that we don't emit a "redefinition" error if we encounter a
1151 /// correctly named definition after the renamed definition.
1152 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
1153
1154 /// Stack of types that correspond to the parameter entities that are
1155 /// currently being copy-initialized. Can be empty.
1156 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
1157
1158 void ReadMethodPool(Selector Sel);
1159 void updateOutOfDateSelector(Selector Sel);
1160
1161 /// Private Helper predicate to check for 'self'.
1162 bool isSelfExpr(Expr *RExpr);
1163 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1164
1165 /// \brief Cause the active diagnostic on the DiagosticsEngine to be
1166 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1167 /// should not be used elsewhere.
1168 void EmitCurrentDiagnostic(unsigned DiagID);
1169
1170 /// Records and restores the FP_CONTRACT state on entry/exit of compound
1171 /// statements.
1172 class FPContractStateRAII {
1173 public:
1174 FPContractStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.FPFeatures) {}
1175 ~FPContractStateRAII() { S.FPFeatures = OldFPFeaturesState; }
1176
1177 private:
1178 Sema& S;
1179 FPOptions OldFPFeaturesState;
1180 };
1181
1182 void addImplicitTypedef(StringRef Name, QualType T);
1183
1184public:
1185 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1186 TranslationUnitKind TUKind = TU_Complete,
1187 CodeCompleteConsumer *CompletionConsumer = nullptr);
1188 ~Sema();
1189
1190 /// \brief Perform initialization that occurs after the parser has been
1191 /// initialized but before it parses anything.
1192 void Initialize();
1193
1194 const LangOptions &getLangOpts() const { return LangOpts; }
1195 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1196 FPOptions &getFPOptions() { return FPFeatures; }
1197
1198 DiagnosticsEngine &getDiagnostics() const { return Diags; }
1199 SourceManager &getSourceManager() const { return SourceMgr; }
1200 Preprocessor &getPreprocessor() const { return PP; }
1201 ASTContext &getASTContext() const { return Context; }
1202 ASTConsumer &getASTConsumer() const { return Consumer; }
1203 ASTMutationListener *getASTMutationListener() const;
1204 ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1205
1206 ///\brief Registers an external source. If an external source already exists,
1207 /// creates a multiplex external source and appends to it.
1208 ///
1209 ///\param[in] E - A non-null external sema source.
1210 ///
1211 void addExternalSource(ExternalSemaSource *E);
1212
1213 void PrintStats() const;
1214
1215 /// \brief Helper class that creates diagnostics with optional
1216 /// template instantiation stacks.
1217 ///
1218 /// This class provides a wrapper around the basic DiagnosticBuilder
1219 /// class that emits diagnostics. SemaDiagnosticBuilder is
1220 /// responsible for emitting the diagnostic (as DiagnosticBuilder
1221 /// does) and, if the diagnostic comes from inside a template
1222 /// instantiation, printing the template instantiation stack as
1223 /// well.
1224 class SemaDiagnosticBuilder : public DiagnosticBuilder {
1225 Sema &SemaRef;
1226 unsigned DiagID;
1227
1228 public:
1229 SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1230 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
1231
1232 // This is a cunning lie. DiagnosticBuilder actually performs move
1233 // construction in its copy constructor (but due to varied uses, it's not
1234 // possible to conveniently express this as actual move construction). So
1235 // the default copy ctor here is fine, because the base class disables the
1236 // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op
1237 // in that case anwyay.
1238 SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default;
1239
1240 ~SemaDiagnosticBuilder() {
1241 // If we aren't active, there is nothing to do.
1242 if (!isActive()) return;
1243
1244 // Otherwise, we need to emit the diagnostic. First flush the underlying
1245 // DiagnosticBuilder data, and clear the diagnostic builder itself so it
1246 // won't emit the diagnostic in its own destructor.
1247 //
1248 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1249 // do its own needless checks to see if the diagnostic needs to be
1250 // emitted. However, because we take care to ensure that the builder
1251 // objects never escape, a sufficiently smart compiler will be able to
1252 // eliminate that code.
1253 FlushCounts();
1254 Clear();
1255
1256 // Dispatch to Sema to emit the diagnostic.
1257 SemaRef.EmitCurrentDiagnostic(DiagID);
1258 }
1259
1260 /// Teach operator<< to produce an object of the correct type.
1261 template<typename T>
1262 friend const SemaDiagnosticBuilder &operator<<(
1263 const SemaDiagnosticBuilder &Diag, const T &Value) {
1264 const DiagnosticBuilder &BaseDiag = Diag;
1265 BaseDiag << Value;
1266 return Diag;
1267 }
1268 };
1269
1270 /// \brief Emit a diagnostic.
1271 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
1272 DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
1273 return SemaDiagnosticBuilder(DB, *this, DiagID);
1274 }
1275
1276 /// \brief Emit a partial diagnostic.
1277 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
1278
1279 /// \brief Build a partial diagnostic.
1280 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1281
1282 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1283
1284 /// \brief Get a string to suggest for zero-initialization of a type.
1285 std::string
1286 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1287 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1288
1289 /// \brief Calls \c Lexer::getLocForEndOfToken()
1290 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1291
1292 /// \brief Retrieve the module loader associated with the preprocessor.
1293 ModuleLoader &getModuleLoader() const;
1294
1295 void emitAndClearUnusedLocalTypedefWarnings();
1296
1297 void ActOnStartOfTranslationUnit();
1298 void ActOnEndOfTranslationUnit();
1299
1300 void CheckDelegatingCtorCycles();
1301
1302 Scope *getScopeForContext(DeclContext *Ctx);
1303
1304 void PushFunctionScope();
1305 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1306 sema::LambdaScopeInfo *PushLambdaScope();
1307
1308 /// \brief This is used to inform Sema what the current TemplateParameterDepth
1309 /// is during Parsing. Currently it is used to pass on the depth
1310 /// when parsing generic lambda 'auto' parameters.
1311 void RecordParsingTemplateParameterDepth(unsigned Depth);
1312
1313 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1314 RecordDecl *RD,
1315 CapturedRegionKind K);
1316 void
1317 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1318 const Decl *D = nullptr,
1319 const BlockExpr *blkExpr = nullptr);
1320
1321 sema::FunctionScopeInfo *getCurFunction() const {
1322 return FunctionScopes.back();
1323 }
1324
1325 sema::FunctionScopeInfo *getEnclosingFunction() const {
1326 if (FunctionScopes.empty())
1327 return nullptr;
1328
1329 for (int e = FunctionScopes.size()-1; e >= 0; --e) {
1330 if (isa<sema::BlockScopeInfo>(FunctionScopes[e]))
1331 continue;
1332 return FunctionScopes[e];
1333 }
1334 return nullptr;
1335 }
1336
1337 template <typename ExprT>
1338 void recordUseOfEvaluatedWeak(const ExprT *E, bool IsRead=true) {
1339 if (!isUnevaluatedContext())
1340 getCurFunction()->recordUseOfWeak(E, IsRead);
1341 }
1342
1343 void PushCompoundScope(bool IsStmtExpr);
1344 void PopCompoundScope();
1345
1346 sema::CompoundScopeInfo &getCurCompoundScope() const;
1347
1348 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1349
1350 /// \brief Retrieve the current block, if any.
1351 sema::BlockScopeInfo *getCurBlock();
1352
1353 /// Retrieve the current lambda scope info, if any.
1354 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1355 /// lambda scope info ignoring all inner capturing scopes that are not
1356 /// lambda scopes.
1357 sema::LambdaScopeInfo *
1358 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1359
1360 /// \brief Retrieve the current generic lambda info, if any.
1361 sema::LambdaScopeInfo *getCurGenericLambda();
1362
1363 /// \brief Retrieve the current captured region, if any.
1364 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1365
1366 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1367 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1368
1369 void ActOnComment(SourceRange Comment);
1370
1371 //===--------------------------------------------------------------------===//
1372 // Type Analysis / Processing: SemaType.cpp.
1373 //
1374
1375 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1376 const DeclSpec *DS = nullptr);
1377 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1378 const DeclSpec *DS = nullptr);
1379 QualType BuildPointerType(QualType T,
1380 SourceLocation Loc, DeclarationName Entity);
1381 QualType BuildReferenceType(QualType T, bool LValueRef,
1382 SourceLocation Loc, DeclarationName Entity);
1383 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1384 Expr *ArraySize, unsigned Quals,
1385 SourceRange Brackets, DeclarationName Entity);
1386 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1387 SourceLocation AttrLoc);
1388 QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
1389 SourceLocation AttrLoc);
1390
1391 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1392
1393 /// \brief Build a function type.
1394 ///
1395 /// This routine checks the function type according to C++ rules and
1396 /// under the assumption that the result type and parameter types have
1397 /// just been instantiated from a template. It therefore duplicates
1398 /// some of the behavior of GetTypeForDeclarator, but in a much
1399 /// simpler form that is only suitable for this narrow use case.
1400 ///
1401 /// \param T The return type of the function.
1402 ///
1403 /// \param ParamTypes The parameter types of the function. This array
1404 /// will be modified to account for adjustments to the types of the
1405 /// function parameters.
1406 ///
1407 /// \param Loc The location of the entity whose type involves this
1408 /// function type or, if there is no such entity, the location of the
1409 /// type that will have function type.
1410 ///
1411 /// \param Entity The name of the entity that involves the function
1412 /// type, if known.
1413 ///
1414 /// \param EPI Extra information about the function type. Usually this will
1415 /// be taken from an existing function with the same prototype.
1416 ///
1417 /// \returns A suitable function type, if there are no errors. The
1418 /// unqualified type will always be a FunctionProtoType.
1419 /// Otherwise, returns a NULL type.
1420 QualType BuildFunctionType(QualType T,
1421 MutableArrayRef<QualType> ParamTypes,
1422 SourceLocation Loc, DeclarationName Entity,
1423 const FunctionProtoType::ExtProtoInfo &EPI);
1424
1425 QualType BuildMemberPointerType(QualType T, QualType Class,
1426 SourceLocation Loc,
1427 DeclarationName Entity);
1428 QualType BuildBlockPointerType(QualType T,
1429 SourceLocation Loc, DeclarationName Entity);
1430 QualType BuildParenType(QualType T);
1431 QualType BuildAtomicType(QualType T, SourceLocation Loc);
1432 QualType BuildReadPipeType(QualType T,
1433 SourceLocation Loc);
1434 QualType BuildWritePipeType(QualType T,
1435 SourceLocation Loc);
1436
1437 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1438 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1439 TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
1440 TypeSourceInfo *ReturnTypeInfo);
1441
1442 /// \brief Package the given type and TSI into a ParsedType.
1443 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1444 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1445 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1446 static QualType GetTypeFromParser(ParsedType Ty,
1447 TypeSourceInfo **TInfo = nullptr);
1448 CanThrowResult canThrow(const Expr *E);
1449 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1450 const FunctionProtoType *FPT);
1451 void UpdateExceptionSpec(FunctionDecl *FD,
1452 const FunctionProtoType::ExceptionSpecInfo &ESI);
1453 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
1454 bool CheckDistantExceptionSpec(QualType T);
1455 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1456 bool CheckEquivalentExceptionSpec(
1457 const FunctionProtoType *Old, SourceLocation OldLoc,
1458 const FunctionProtoType *New, SourceLocation NewLoc);
1459 bool CheckEquivalentExceptionSpec(
1460 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1461 const FunctionProtoType *Old, SourceLocation OldLoc,
1462 const FunctionProtoType *New, SourceLocation NewLoc);
1463 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
1464 bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
1465 const PartialDiagnostic &NestedDiagID,
1466 const PartialDiagnostic &NoteID,
1467 const FunctionProtoType *Superset,
1468 SourceLocation SuperLoc,
1469 const FunctionProtoType *Subset,
1470 SourceLocation SubLoc);
1471 bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
1472 const PartialDiagnostic &NoteID,
1473 const FunctionProtoType *Target,
1474 SourceLocation TargetLoc,
1475 const FunctionProtoType *Source,
1476 SourceLocation SourceLoc);
1477
1478 TypeResult ActOnTypeName(Scope *S, Declarator &D);
1479
1480 /// \brief The parser has parsed the context-sensitive type 'instancetype'
1481 /// in an Objective-C message declaration. Return the appropriate type.
1482 ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1483
1484 /// \brief Abstract class used to diagnose incomplete types.
1485 struct TypeDiagnoser {
1486 TypeDiagnoser() {}
1487
1488 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
1489 virtual ~TypeDiagnoser() {}
1490 };
1491
1492 static int getPrintable(int I) { return I; }
1493 static unsigned getPrintable(unsigned I) { return I; }
1494 static bool getPrintable(bool B) { return B; }
1495 static const char * getPrintable(const char *S) { return S; }
1496 static StringRef getPrintable(StringRef S) { return S; }
1497 static const std::string &getPrintable(const std::string &S) { return S; }
1498 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1499 return II;
1500 }
1501 static DeclarationName getPrintable(DeclarationName N) { return N; }
1502 static QualType getPrintable(QualType T) { return T; }
1503 static SourceRange getPrintable(SourceRange R) { return R; }
1504 static SourceRange getPrintable(SourceLocation L) { return L; }
1505 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
1506 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1507
1508 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
1509 unsigned DiagID;
1510 std::tuple<const Ts &...> Args;
1511
1512 template <std::size_t... Is>
1513 void emit(const SemaDiagnosticBuilder &DB,
1514 llvm::index_sequence<Is...>) const {
1515 // Apply all tuple elements to the builder in order.
1516 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
1517 (void)Dummy;
1518 }
1519
1520 public:
1521 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
1522 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
1523 assert(DiagID != 0 && "no diagnostic for type diagnoser")(static_cast <bool> (DiagID != 0 && "no diagnostic for type diagnoser"
) ? void (0) : __assert_fail ("DiagID != 0 && \"no diagnostic for type diagnoser\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/Sema/Sema.h"
, 1523, __extension__ __PRETTY_FUNCTION__))
;
1524 }
1525
1526 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1527 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
1528 emit(DB, llvm::index_sequence_for<Ts...>());
1529 DB << T;
1530 }
1531 };
1532
1533private:
1534 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
1535 TypeDiagnoser *Diagnoser);
1536
1537 struct ModuleScope {
1538 clang::Module *Module = nullptr;
1539 bool ModuleInterface = false;
1540 VisibleModuleSet OuterVisibleModules;
1541 };
1542 /// The modules we're currently parsing.
1543 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
1544
1545 /// Get the module whose scope we are currently within.
1546 Module *getCurrentModule() const {
1547 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
1548 }
1549
1550 VisibleModuleSet VisibleModules;
1551
1552public:
1553 /// \brief Get the module owning an entity.
1554 Module *getOwningModule(Decl *Entity) { return Entity->getOwningModule(); }
1555
1556 /// \brief Make a merged definition of an existing hidden definition \p ND
1557 /// visible at the specified location.
1558 void makeMergedDefinitionVisible(NamedDecl *ND);
1559
1560 bool isModuleVisible(const Module *M) { return VisibleModules.isVisible(M); }
1561
1562 /// Determine whether a declaration is visible to name lookup.
1563 bool isVisible(const NamedDecl *D) {
1564 return !D->isHidden() || isVisibleSlow(D);
1565 }
1566
1567 /// Determine whether any declaration of an entity is visible.
1568 bool
1569 hasVisibleDeclaration(const NamedDecl *D,
1570 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
1571 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
1572 }
1573 bool hasVisibleDeclarationSlow(const NamedDecl *D,
1574 llvm::SmallVectorImpl<Module *> *Modules);
1575
1576 bool hasVisibleMergedDefinition(NamedDecl *Def);
1577 bool hasMergedDefinitionInCurrentModule(NamedDecl *Def);
1578
1579 /// Determine if \p D and \p Suggested have a structurally compatible
1580 /// layout as described in C11 6.2.7/1.
1581 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
1582
1583 /// Determine if \p D has a visible definition. If not, suggest a declaration
1584 /// that should be made visible to expose the definition.
1585 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
1586 bool OnlyNeedComplete = false);
1587 bool hasVisibleDefinition(const NamedDecl *D) {
1588 NamedDecl *Hidden;
1589 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
1590 }
1591
1592 /// Determine if the template parameter \p D has a visible default argument.
1593 bool
1594 hasVisibleDefaultArgument(const NamedDecl *D,
1595 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1596
1597 /// Determine if there is a visible declaration of \p D that is an explicit
1598 /// specialization declaration for a specialization of a template. (For a
1599 /// member specialization, use hasVisibleMemberSpecialization.)
1600 bool hasVisibleExplicitSpecialization(
1601 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1602
1603 /// Determine if there is a visible declaration of \p D that is a member
1604 /// specialization declaration (as opposed to an instantiated declaration).
1605 bool hasVisibleMemberSpecialization(
1606 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1607
1608 /// Determine if \p A and \p B are equivalent internal linkage declarations
1609 /// from different modules, and thus an ambiguity error can be downgraded to
1610 /// an extension warning.
1611 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
1612 const NamedDecl *B);
1613 void diagnoseEquivalentInternalLinkageDeclarations(
1614 SourceLocation Loc, const NamedDecl *D,
1615 ArrayRef<const NamedDecl *> Equiv);
1616
1617 bool isCompleteType(SourceLocation Loc, QualType T) {
1618 return !RequireCompleteTypeImpl(Loc, T, nullptr);
1619 }
1620 bool RequireCompleteType(SourceLocation Loc, QualType T,
1621 TypeDiagnoser &Diagnoser);
1622 bool RequireCompleteType(SourceLocation Loc, QualType T,
1623 unsigned DiagID);
1624
1625 template <typename... Ts>
1626 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
1627 const Ts &...Args) {
1628 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1629 return RequireCompleteType(Loc, T, Diagnoser);
1630 }
1631
1632 void completeExprArrayBound(Expr *E);
1633 bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
1634 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
1635
1636 template <typename... Ts>
1637 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
1638 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1639 return RequireCompleteExprType(E, Diagnoser);
1640 }
1641
1642 bool RequireLiteralType(SourceLocation Loc, QualType T,
1643 TypeDiagnoser &Diagnoser);
1644 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
1645
1646 template <typename... Ts>
1647 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
1648 const Ts &...Args) {
1649 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1650 return RequireLiteralType(Loc, T, Diagnoser);
1651 }
1652
1653 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1654 const CXXScopeSpec &SS, QualType T);
1655
1656 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
1657 /// If AsUnevaluated is false, E is treated as though it were an evaluated
1658 /// context, such as when building a type for decltype(auto).
1659 QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
1660 bool AsUnevaluated = true);
1661 QualType BuildUnaryTransformType(QualType BaseType,
1662 UnaryTransformType::UTTKind UKind,
1663 SourceLocation Loc);
1664
1665 //===--------------------------------------------------------------------===//
1666 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
1667 //
1668
1669 struct SkipBodyInfo {
1670 SkipBodyInfo()
1671 : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr),
1672 New(nullptr) {}
1673 bool ShouldSkip;
1674 bool CheckSameAsPrevious;
1675 NamedDecl *Previous;
1676 NamedDecl *New;
1677 };
1678
1679 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
1680
1681 void DiagnoseUseOfUnimplementedSelectors();
1682
1683 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
1684
1685 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
1686 Scope *S, CXXScopeSpec *SS = nullptr,
1687 bool isClassName = false, bool HasTrailingDot = false,
1688 ParsedType ObjectType = nullptr,
1689 bool IsCtorOrDtorName = false,
1690 bool WantNontrivialTypeSourceInfo = false,
1691 bool IsClassTemplateDeductionContext = true,
1692 IdentifierInfo **CorrectedII = nullptr);
1693 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
1694 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
1695 void DiagnoseUnknownTypeName(IdentifierInfo *&II,
1696 SourceLocation IILoc,
1697 Scope *S,
1698 CXXScopeSpec *SS,
1699 ParsedType &SuggestedType,
1700 bool IsTemplateName = false);
1701
1702 /// Attempt to behave like MSVC in situations where lookup of an unqualified
1703 /// type name has failed in a dependent context. In these situations, we
1704 /// automatically form a DependentTypeName that will retry lookup in a related
1705 /// scope during instantiation.
1706 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
1707 SourceLocation NameLoc,
1708 bool IsTemplateTypeArg);
1709
1710 /// \brief Describes the result of the name lookup and resolution performed
1711 /// by \c ClassifyName().
1712 enum NameClassificationKind {
1713 NC_Unknown,
1714 NC_Error,
1715 NC_Keyword,
1716 NC_Type,
1717 NC_Expression,
1718 NC_NestedNameSpecifier,
1719 NC_TypeTemplate,
1720 NC_VarTemplate,
1721 NC_FunctionTemplate
1722 };
1723
1724 class NameClassification {
1725 NameClassificationKind Kind;
1726 ExprResult Expr;
1727 TemplateName Template;
1728 ParsedType Type;
1729
1730 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1731
1732 public:
1733 NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {}
1734
1735 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1736
1737 NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
1738
1739 static NameClassification Error() {
1740 return NameClassification(NC_Error);
1741 }
1742
1743 static NameClassification Unknown() {
1744 return NameClassification(NC_Unknown);
1745 }
1746
1747 static NameClassification NestedNameSpecifier() {
1748 return NameClassification(NC_NestedNameSpecifier);
1749 }
1750
1751 static NameClassification TypeTemplate(TemplateName Name) {
1752 NameClassification Result(NC_TypeTemplate);
1753 Result.Template = Name;
1754 return Result;
1755 }
1756
1757 static NameClassification VarTemplate(TemplateName Name) {
1758 NameClassification Result(NC_VarTemplate);
1759 Result.Template = Name;
1760 return Result;
1761 }
1762
1763 static NameClassification FunctionTemplate(TemplateName Name) {
1764 NameClassification Result(NC_FunctionTemplate);
1765 Result.Template = Name;
1766 return Result;
1767 }
1768
1769 NameClassificationKind getKind() const { return Kind; }
1770
1771 ParsedType getType() const {
1772 assert(Kind == NC_Type)(static_cast <bool> (Kind == NC_Type) ? void (0) : __assert_fail
("Kind == NC_Type", "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/Sema/Sema.h"
, 1772, __extension__ __PRETTY_FUNCTION__))
;
1773 return Type;
1774 }
1775
1776 ExprResult getExpression() const {
1777 assert(Kind == NC_Expression)(static_cast <bool> (Kind == NC_Expression) ? void (0) :
__assert_fail ("Kind == NC_Expression", "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/Sema/Sema.h"
, 1777, __extension__ __PRETTY_FUNCTION__))
;
1778 return Expr;
1779 }
1780
1781 TemplateName getTemplateName() const {
1782 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||(static_cast <bool> (Kind == NC_TypeTemplate || Kind ==
NC_FunctionTemplate || Kind == NC_VarTemplate) ? void (0) : __assert_fail
("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate"
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/Sema/Sema.h"
, 1783, __extension__ __PRETTY_FUNCTION__))
1783 Kind == NC_VarTemplate)(static_cast <bool> (Kind == NC_TypeTemplate || Kind ==
NC_FunctionTemplate || Kind == NC_VarTemplate) ? void (0) : __assert_fail
("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate"
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/Sema/Sema.h"
, 1783, __extension__ __PRETTY_FUNCTION__))
;
1784 return Template;
1785 }
1786
1787 TemplateNameKind getTemplateNameKind() const {
1788 switch (Kind) {
1789 case NC_TypeTemplate:
1790 return TNK_Type_template;
1791 case NC_FunctionTemplate:
1792 return TNK_Function_template;
1793 case NC_VarTemplate:
1794 return TNK_Var_template;
1795 default:
1796 llvm_unreachable("unsupported name classification.")::llvm::llvm_unreachable_internal("unsupported name classification."
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/Sema/Sema.h"
, 1796)
;
1797 }
1798 }
1799 };
1800
1801 /// \brief Perform name lookup on the given name, classifying it based on
1802 /// the results of name lookup and the following token.
1803 ///
1804 /// This routine is used by the parser to resolve identifiers and help direct
1805 /// parsing. When the identifier cannot be found, this routine will attempt
1806 /// to correct the typo and classify based on the resulting name.
1807 ///
1808 /// \param S The scope in which we're performing name lookup.
1809 ///
1810 /// \param SS The nested-name-specifier that precedes the name.
1811 ///
1812 /// \param Name The identifier. If typo correction finds an alternative name,
1813 /// this pointer parameter will be updated accordingly.
1814 ///
1815 /// \param NameLoc The location of the identifier.
1816 ///
1817 /// \param NextToken The token following the identifier. Used to help
1818 /// disambiguate the name.
1819 ///
1820 /// \param IsAddressOfOperand True if this name is the operand of a unary
1821 /// address of ('&') expression, assuming it is classified as an
1822 /// expression.
1823 ///
1824 /// \param CCC The correction callback, if typo correction is desired.
1825 NameClassification
1826 ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
1827 SourceLocation NameLoc, const Token &NextToken,
1828 bool IsAddressOfOperand,
1829 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr);
1830
1831 /// Describes the detailed kind of a template name. Used in diagnostics.
1832 enum class TemplateNameKindForDiagnostics {
1833 ClassTemplate,
1834 FunctionTemplate,
1835 VarTemplate,
1836 AliasTemplate,
1837 TemplateTemplateParam,
1838 DependentTemplate
1839 };
1840 TemplateNameKindForDiagnostics
1841 getTemplateNameKindForDiagnostics(TemplateName Name);
1842
1843 /// Determine whether it's plausible that E was intended to be a
1844 /// template-name.
1845 bool mightBeIntendedToBeTemplateName(ExprResult E) {
1846 if (!getLangOpts().CPlusPlus || E.isInvalid())
1847 return false;
1848 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
1849 return !DRE->hasExplicitTemplateArgs();
1850 if (auto *ME = dyn_cast<MemberExpr>(E.get()))
1851 return !ME->hasExplicitTemplateArgs();
1852 // Any additional cases recognized here should also be handled by
1853 // diagnoseExprIntendedAsTemplateName.
1854 return false;
1855 }
1856 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
1857 SourceLocation Less,
1858 SourceLocation Greater);
1859
1860 Decl *ActOnDeclarator(Scope *S, Declarator &D);
1861
1862 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
1863 MultiTemplateParamsArg TemplateParameterLists);
1864 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
1865 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
1866 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
1867 DeclarationName Name,
1868 SourceLocation Loc);
1869 void
1870 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
1871 SourceLocation FallbackLoc,
1872 SourceLocation ConstQualLoc = SourceLocation(),
1873 SourceLocation VolatileQualLoc = SourceLocation(),
1874 SourceLocation RestrictQualLoc = SourceLocation(),
1875 SourceLocation AtomicQualLoc = SourceLocation(),
1876 SourceLocation UnalignedQualLoc = SourceLocation());
1877
1878 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
1879 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
1880 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
1881 const LookupResult &R);
1882 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
1883 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
1884 const LookupResult &R);
1885 void CheckShadow(Scope *S, VarDecl *D);
1886
1887 /// Warn if 'E', which is an expression that is about to be modified, refers
1888 /// to a shadowing declaration.
1889 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
1890
1891 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
1892
1893private:
1894 /// Map of current shadowing declarations to shadowed declarations. Warn if
1895 /// it looks like the user is trying to modify the shadowing declaration.
1896 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
1897
1898public:
1899 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
1900 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
1901 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
1902 TypedefNameDecl *NewTD);
1903 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
1904 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1905 TypeSourceInfo *TInfo,
1906 LookupResult &Previous);
1907 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
1908 LookupResult &Previous, bool &Redeclaration);
1909 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
1910 TypeSourceInfo *TInfo,
1911 LookupResult &Previous,
1912 MultiTemplateParamsArg TemplateParamLists,
1913 bool &AddToScope,
1914 ArrayRef<BindingDecl *> Bindings = None);
1915 NamedDecl *
1916 ActOnDecompositionDeclarator(Scope *S, Declarator &D,
1917 MultiTemplateParamsArg TemplateParamLists);
1918 // Returns true if the variable declaration is a redeclaration
1919 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
1920 void CheckVariableDeclarationType(VarDecl *NewVD);
1921 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
1922 Expr *Init);
1923 void CheckCompleteVariableDeclaration(VarDecl *VD);
1924 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
1925 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
1926
1927 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1928 TypeSourceInfo *TInfo,
1929 LookupResult &Previous,
1930 MultiTemplateParamsArg TemplateParamLists,
1931 bool &AddToScope);
1932 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
1933
1934 bool CheckConstexprFunctionDecl(const FunctionDecl *FD);
1935 bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body);
1936
1937 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
1938 void FindHiddenVirtualMethods(CXXMethodDecl *MD,
1939 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1940 void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
1941 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1942 // Returns true if the function declaration is a redeclaration
1943 bool CheckFunctionDeclaration(Scope *S,
1944 FunctionDecl *NewFD, LookupResult &Previous,
1945 bool IsMemberSpecialization);
1946 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
1947 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
1948 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
1949 Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
1950 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
1951 SourceLocation Loc,
1952 QualType T);
1953 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
1954 SourceLocation NameLoc, IdentifierInfo *Name,
1955 QualType T, TypeSourceInfo *TSInfo,
1956 StorageClass SC);
1957 void ActOnParamDefaultArgument(Decl *param,
1958 SourceLocation EqualLoc,
1959 Expr *defarg);
1960 void ActOnParamUnparsedDefaultArgument(Decl *param,
1961 SourceLocation EqualLoc,
1962 SourceLocation ArgLoc);
1963 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
1964 bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
1965 SourceLocation EqualLoc);
1966
1967 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
1968 void ActOnUninitializedDecl(Decl *dcl);
1969 void ActOnInitializerError(Decl *Dcl);
1970
1971 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
1972 void ActOnCXXForRangeDecl(Decl *D);
1973 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
1974 IdentifierInfo *Ident,
1975 ParsedAttributes &Attrs,
1976 SourceLocation AttrEnd);
1977 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
1978 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
1979 void FinalizeDeclaration(Decl *D);
1980 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
1981 ArrayRef<Decl *> Group);
1982 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
1983
1984 /// Should be called on all declarations that might have attached
1985 /// documentation comments.
1986 void ActOnDocumentableDecl(Decl *D);
1987 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
1988
1989 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
1990 SourceLocation LocAfterDecls);
1991 void CheckForFunctionRedefinition(
1992 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
1993 SkipBodyInfo *SkipBody = nullptr);
1994 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
1995 MultiTemplateParamsArg TemplateParamLists,
1996 SkipBodyInfo *SkipBody = nullptr);
1997 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
1998 SkipBodyInfo *SkipBody = nullptr);
1999 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
2000 bool isObjCMethodDecl(Decl *D) {
2001 return D && isa<ObjCMethodDecl>(D);
2002 }
2003
2004 /// \brief Determine whether we can delay parsing the body of a function or
2005 /// function template until it is used, assuming we don't care about emitting
2006 /// code for that function.
2007 ///
2008 /// This will be \c false if we may need the body of the function in the
2009 /// middle of parsing an expression (where it's impractical to switch to
2010 /// parsing a different function), for instance, if it's constexpr in C++11
2011 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
2012 bool canDelayFunctionBody(const Declarator &D);
2013
2014 /// \brief Determine whether we can skip parsing the body of a function
2015 /// definition, assuming we don't care about analyzing its body or emitting
2016 /// code for that function.
2017 ///
2018 /// This will be \c false only if we may need the body of the function in
2019 /// order to parse the rest of the program (for instance, if it is
2020 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
2021 bool canSkipFunctionBody(Decl *D);
2022
2023 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
2024 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
2025 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
2026 Decl *ActOnSkippedFunctionBody(Decl *Decl);
2027 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
2028
2029 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
2030 /// attribute for which parsing is delayed.
2031 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
2032
2033 /// \brief Diagnose any unused parameters in the given sequence of
2034 /// ParmVarDecl pointers.
2035 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
2036
2037 /// \brief Diagnose whether the size of parameters or return value of a
2038 /// function or obj-c method definition is pass-by-value and larger than a
2039 /// specified threshold.
2040 void
2041 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
2042 QualType ReturnTy, NamedDecl *D);
2043
2044 void DiagnoseInvalidJumps(Stmt *Body);
2045 Decl *ActOnFileScopeAsmDecl(Expr *expr,
2046 SourceLocation AsmLoc,
2047 SourceLocation RParenLoc);
2048
2049 /// \brief Handle a C++11 empty-declaration and attribute-declaration.
2050 Decl *ActOnEmptyDeclaration(Scope *S,
2051 AttributeList *AttrList,
2052 SourceLocation SemiLoc);
2053
2054 enum class ModuleDeclKind {
2055 Interface, ///< 'export module X;'
2056 Implementation, ///< 'module X;'
2057 Partition, ///< 'module partition X;'
2058 };
2059
2060 /// The parser has processed a module-declaration that begins the definition
2061 /// of a module interface or implementation.
2062 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
2063 SourceLocation ModuleLoc, ModuleDeclKind MDK,
2064 ModuleIdPath Path);
2065
2066 /// \brief The parser has processed a module import declaration.
2067 ///
2068 /// \param AtLoc The location of the '@' symbol, if any.
2069 ///
2070 /// \param ImportLoc The location of the 'import' keyword.
2071 ///
2072 /// \param Path The module access path.
2073 DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc,
2074 ModuleIdPath Path);
2075
2076 /// \brief The parser has processed a module import translated from a
2077 /// #include or similar preprocessing directive.
2078 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2079 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2080
2081 /// \brief The parsed has entered a submodule.
2082 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
2083 /// \brief The parser has left a submodule.
2084 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
2085
2086 /// \brief Create an implicit import of the given module at the given
2087 /// source location, for error recovery, if possible.
2088 ///
2089 /// This routine is typically used when an entity found by name lookup
2090 /// is actually hidden within a module that we know about but the user
2091 /// has forgotten to import.
2092 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
2093 Module *Mod);
2094
2095 /// Kinds of missing import. Note, the values of these enumerators correspond
2096 /// to %select values in diagnostics.
2097 enum class MissingImportKind {
2098 Declaration,
2099 Definition,
2100 DefaultArgument,
2101 ExplicitSpecialization,
2102 PartialSpecialization
2103 };
2104
2105 /// \brief Diagnose that the specified declaration needs to be visible but
2106 /// isn't, and suggest a module import that would resolve the problem.
2107 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2108 MissingImportKind MIK, bool Recover = true);
2109 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2110 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
2111 MissingImportKind MIK, bool Recover);
2112
2113 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
2114 SourceLocation LBraceLoc);
2115 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
2116 SourceLocation RBraceLoc);
2117
2118 /// \brief We've found a use of a templated declaration that would trigger an
2119 /// implicit instantiation. Check that any relevant explicit specializations
2120 /// and partial specializations are visible, and diagnose if not.
2121 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
2122
2123 /// \brief We've found a use of a template specialization that would select a
2124 /// partial specialization. Check that the partial specialization is visible,
2125 /// and diagnose if not.
2126 void checkPartialSpecializationVisibility(SourceLocation Loc,
2127 NamedDecl *Spec);
2128
2129 /// \brief Retrieve a suitable printing policy.
2130 PrintingPolicy getPrintingPolicy() const {
2131 return getPrintingPolicy(Context, PP);
2132 }
2133
2134 /// \brief Retrieve a suitable printing policy.
2135 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
2136 const Preprocessor &PP);
2137
2138 /// Scope actions.
2139 void ActOnPopScope(SourceLocation Loc, Scope *S);
2140 void ActOnTranslationUnitScope(Scope *S);
2141
2142 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2143 RecordDecl *&AnonRecord);
2144 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2145 MultiTemplateParamsArg TemplateParams,
2146 bool IsExplicitInstantiation,
2147 RecordDecl *&AnonRecord);
2148
2149 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2150 AccessSpecifier AS,
2151 RecordDecl *Record,
2152 const PrintingPolicy &Policy);
2153
2154 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2155 RecordDecl *Record);
2156
2157 /// Common ways to introduce type names without a tag for use in diagnostics.
2158 /// Keep in sync with err_tag_reference_non_tag.
2159 enum NonTagKind {
2160 NTK_NonStruct,
2161 NTK_NonClass,
2162 NTK_NonUnion,
2163 NTK_NonEnum,
2164 NTK_Typedef,
2165 NTK_TypeAlias,
2166 NTK_Template,
2167 NTK_TypeAliasTemplate,
2168 NTK_TemplateTemplateArgument,
2169 };
2170
2171 /// Given a non-tag type declaration, returns an enum useful for indicating
2172 /// what kind of non-tag type this is.
2173 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
2174
2175 bool isAcceptableTagRedeclaration(const TagDecl *Previous,
2176 TagTypeKind NewTag, bool isDefinition,
2177 SourceLocation NewTagLoc,
2178 const IdentifierInfo *Name);
2179
2180 enum TagUseKind {
2181 TUK_Reference, // Reference to a tag: 'struct foo *X;'
2182 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
2183 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
2184 TUK_Friend // Friend declaration: 'friend struct foo;'
2185 };
2186
2187 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
2188 SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name,
2189 SourceLocation NameLoc, AttributeList *Attr,
2190 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
2191 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
2192 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
2193 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
2194 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
2195 SkipBodyInfo *SkipBody = nullptr);
2196
2197 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
2198 unsigned TagSpec, SourceLocation TagLoc,
2199 CXXScopeSpec &SS,
2200 IdentifierInfo *Name, SourceLocation NameLoc,
2201 AttributeList *Attr,
2202 MultiTemplateParamsArg TempParamLists);
2203
2204 TypeResult ActOnDependentTag(Scope *S,
2205 unsigned TagSpec,
2206 TagUseKind TUK,
2207 const CXXScopeSpec &SS,
2208 IdentifierInfo *Name,
2209 SourceLocation TagLoc,
2210 SourceLocation NameLoc);
2211
2212 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
2213 IdentifierInfo *ClassName,
2214 SmallVectorImpl<Decl *> &Decls);
2215 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
2216 Declarator &D, Expr *BitfieldWidth);
2217
2218 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
2219 Declarator &D, Expr *BitfieldWidth,
2220 InClassInitStyle InitStyle,
2221 AccessSpecifier AS);
2222 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
2223 SourceLocation DeclStart,
2224 Declarator &D, Expr *BitfieldWidth,
2225 InClassInitStyle InitStyle,
2226 AccessSpecifier AS,
2227 AttributeList *MSPropertyAttr);
2228
2229 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
2230 TypeSourceInfo *TInfo,
2231 RecordDecl *Record, SourceLocation Loc,
2232 bool Mutable, Expr *BitfieldWidth,
2233 InClassInitStyle InitStyle,
2234 SourceLocation TSSL,
2235 AccessSpecifier AS, NamedDecl *PrevDecl,
2236 Declarator *D = nullptr);
2237
2238 bool CheckNontrivialField(FieldDecl *FD);
2239 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
2240
2241 enum TrivialABIHandling {
2242 /// The triviality of a method unaffected by "trivial_abi".
2243 TAH_IgnoreTrivialABI,
2244
2245 /// The triviality of a method affected by "trivial_abi".
2246 TAH_ConsiderTrivialABI
2247 };
2248
2249 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
2250 TrivialABIHandling TAH = TAH_IgnoreTrivialABI,
2251 bool Diagnose = false);
2252 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
2253 void ActOnLastBitfield(SourceLocation DeclStart,
2254 SmallVectorImpl<Decl *> &AllIvarDecls);
2255 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
2256 Declarator &D, Expr *BitfieldWidth,
2257 tok::ObjCKeywordKind visibility);
2258
2259 // This is used for both record definitions and ObjC interface declarations.
2260 void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl,
2261 ArrayRef<Decl *> Fields,
2262 SourceLocation LBrac, SourceLocation RBrac,
2263 AttributeList *AttrList);
2264
2265 /// ActOnTagStartDefinition - Invoked when we have entered the
2266 /// scope of a tag's definition (e.g., for an enumeration, class,
2267 /// struct, or union).
2268 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
2269
2270 /// Perform ODR-like check for C/ObjC when merging tag types from modules.
2271 /// Differently from C++, actually parse the body and reject / error out
2272 /// in case of a structural mismatch.
2273 bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
2274 SkipBodyInfo &SkipBody);
2275
2276 typedef void *SkippedDefinitionContext;
2277
2278 /// \brief Invoked when we enter a tag definition that we're skipping.
2279 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
2280
2281 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
2282
2283 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
2284 /// C++ record definition's base-specifiers clause and are starting its
2285 /// member declarations.
2286 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
2287 SourceLocation FinalLoc,
2288 bool IsFinalSpelledSealed,
2289 SourceLocation LBraceLoc);
2290
2291 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
2292 /// the definition of a tag (enumeration, class, struct, or union).
2293 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
2294 SourceRange BraceRange);
2295
2296 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
2297
2298 void ActOnObjCContainerFinishDefinition();
2299
2300 /// \brief Invoked when we must temporarily exit the objective-c container
2301 /// scope for parsing/looking-up C constructs.
2302 ///
2303 /// Must be followed by a call to \see ActOnObjCReenterContainerContext
2304 void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
2305 void ActOnObjCReenterContainerContext(DeclContext *DC);
2306
2307 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
2308 /// error parsing the definition of a tag.
2309 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
2310
2311 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
2312 EnumConstantDecl *LastEnumConst,
2313 SourceLocation IdLoc,
2314 IdentifierInfo *Id,
2315 Expr *val);
2316 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
2317 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
2318 QualType EnumUnderlyingTy, bool IsFixed,
2319 const EnumDecl *Prev);
2320
2321 /// Determine whether the body of an anonymous enumeration should be skipped.
2322 /// \param II The name of the first enumerator.
2323 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
2324 SourceLocation IILoc);
2325
2326 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
2327 SourceLocation IdLoc, IdentifierInfo *Id,
2328 AttributeList *Attrs, SourceLocation EqualLoc,
2329 Expr *Val);
2330 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
2331 Decl *EnumDecl,
2332 ArrayRef<Decl *> Elements,
2333 Scope *S, AttributeList *Attr);
2334
2335 DeclContext *getContainingDC(DeclContext *DC);
2336
2337 /// Set the current declaration context until it gets popped.
2338 void PushDeclContext(Scope *S, DeclContext *DC);
2339 void PopDeclContext();
2340
2341 /// EnterDeclaratorContext - Used when we must lookup names in the context
2342 /// of a declarator's nested name specifier.
2343 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
2344 void ExitDeclaratorContext(Scope *S);
2345
2346 /// Push the parameters of D, which must be a function, into scope.
2347 void ActOnReenterFunctionContext(Scope* S, Decl* D);
2348 void ActOnExitFunctionContext();
2349
2350 DeclContext *getFunctionLevelDeclContext();
2351
2352 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
2353 /// to the function decl for the function being parsed. If we're currently
2354 /// in a 'block', this returns the containing context.
2355 FunctionDecl *getCurFunctionDecl();
2356
2357 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
2358 /// the method decl for the method being parsed. If we're currently
2359 /// in a 'block', this returns the containing context.
2360 ObjCMethodDecl *getCurMethodDecl();
2361
2362 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
2363 /// or C function we're in, otherwise return null. If we're currently
2364 /// in a 'block', this returns the containing context.
2365 NamedDecl *getCurFunctionOrMethodDecl();
2366
2367 /// Add this decl to the scope shadowed decl chains.
2368 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
2369
2370 /// \brief Make the given externally-produced declaration visible at the
2371 /// top level scope.
2372 ///
2373 /// \param D The externally-produced declaration to push.
2374 ///
2375 /// \param Name The name of the externally-produced declaration.
2376 void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
2377
2378 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
2379 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
2380 /// true if 'D' belongs to the given declaration context.
2381 ///
2382 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
2383 /// enclosing namespace set of the context, rather than contained
2384 /// directly within it.
2385 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
2386 bool AllowInlineNamespace = false);
2387
2388 /// Finds the scope corresponding to the given decl context, if it
2389 /// happens to be an enclosing scope. Otherwise return NULL.
2390 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
2391
2392 /// Subroutines of ActOnDeclarator().
2393 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
2394 TypeSourceInfo *TInfo);
2395 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
2396
2397 /// \brief Describes the kind of merge to perform for availability
2398 /// attributes (including "deprecated", "unavailable", and "availability").
2399 enum AvailabilityMergeKind {
2400 /// \brief Don't merge availability attributes at all.
2401 AMK_None,
2402 /// \brief Merge availability attributes for a redeclaration, which requires
2403 /// an exact match.
2404 AMK_Redeclaration,
2405 /// \brief Merge availability attributes for an override, which requires
2406 /// an exact match or a weakening of constraints.
2407 AMK_Override,
2408 /// \brief Merge availability attributes for an implementation of
2409 /// a protocol requirement.
2410 AMK_ProtocolImplementation,
2411 };
2412
2413 /// Attribute merging methods. Return true if a new attribute was added.
2414 AvailabilityAttr *mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
2415 IdentifierInfo *Platform,
2416 bool Implicit,
2417 VersionTuple Introduced,
2418 VersionTuple Deprecated,
2419 VersionTuple Obsoleted,
2420 bool IsUnavailable,
2421 StringRef Message,
2422 bool IsStrict, StringRef Replacement,
2423 AvailabilityMergeKind AMK,
2424 unsigned AttrSpellingListIndex);
2425 TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2426 TypeVisibilityAttr::VisibilityType Vis,
2427 unsigned AttrSpellingListIndex);
2428 VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range,
2429 VisibilityAttr::VisibilityType Vis,
2430 unsigned AttrSpellingListIndex);
2431 UuidAttr *mergeUuidAttr(Decl *D, SourceRange Range,
2432 unsigned AttrSpellingListIndex, StringRef Uuid);
2433 DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range,
2434 unsigned AttrSpellingListIndex);
2435 DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range,
2436 unsigned AttrSpellingListIndex);
2437 MSInheritanceAttr *
2438 mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
2439 unsigned AttrSpellingListIndex,
2440 MSInheritanceAttr::Spelling SemanticSpelling);
2441 FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range,
2442 IdentifierInfo *Format, int FormatIdx,
2443 int FirstArg, unsigned AttrSpellingListIndex);
2444 SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name,
2445 unsigned AttrSpellingListIndex);
2446 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
2447 IdentifierInfo *Ident,
2448 unsigned AttrSpellingListIndex);
2449 MinSizeAttr *mergeMinSizeAttr(Decl *D, SourceRange Range,
2450 unsigned AttrSpellingListIndex);
2451 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
2452 unsigned AttrSpellingListIndex);
2453 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, SourceRange Range,
2454 IdentifierInfo *Ident,
2455 unsigned AttrSpellingListIndex);
2456 CommonAttr *mergeCommonAttr(Decl *D, SourceRange Range, IdentifierInfo *Ident,
2457 unsigned AttrSpellingListIndex);
2458
2459 void mergeDeclAttributes(NamedDecl *New, Decl *Old,
2460 AvailabilityMergeKind AMK = AMK_Redeclaration);
2461 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2462 LookupResult &OldDecls);
2463 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
2464 bool MergeTypeWithOld);
2465 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2466 Scope *S, bool MergeTypeWithOld);
2467 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
2468 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
2469 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
2470 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
2471 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
2472 void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
2473 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
2474
2475 // AssignmentAction - This is used by all the assignment diagnostic functions
2476 // to represent what is actually causing the operation
2477 enum AssignmentAction {
2478 AA_Assigning,
2479 AA_Passing,
2480 AA_Returning,
2481 AA_Converting,
2482 AA_Initializing,
2483 AA_Sending,
2484 AA_Casting,
2485 AA_Passing_CFAudited
2486 };
2487
2488 /// C++ Overloading.
2489 enum OverloadKind {
2490 /// This is a legitimate overload: the existing declarations are
2491 /// functions or function templates with different signatures.
2492 Ovl_Overload,
2493
2494 /// This is not an overload because the signature exactly matches
2495 /// an existing declaration.
2496 Ovl_Match,
2497
2498 /// This is not an overload because the lookup results contain a
2499 /// non-function.
2500 Ovl_NonFunction
2501 };
2502 OverloadKind CheckOverload(Scope *S,
2503 FunctionDecl *New,
2504 const LookupResult &OldDecls,
2505 NamedDecl *&OldDecl,
2506 bool IsForUsingDecl);
2507 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
2508 bool ConsiderCudaAttrs = true);
2509
2510 /// \brief Checks availability of the function depending on the current
2511 /// function context.Inside an unavailable function,unavailability is ignored.
2512 ///
2513 /// \returns true if \p FD is unavailable and current context is inside
2514 /// an available function, false otherwise.
2515 bool isFunctionConsideredUnavailable(FunctionDecl *FD);
2516
2517 ImplicitConversionSequence
2518 TryImplicitConversion(Expr *From, QualType ToType,
2519 bool SuppressUserConversions,
2520 bool AllowExplicit,
2521 bool InOverloadResolution,
2522 bool CStyle,
2523 bool AllowObjCWritebackConversion);
2524
2525 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
2526 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
2527 bool IsComplexPromotion(QualType FromType, QualType ToType);
2528 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2529 bool InOverloadResolution,
2530 QualType& ConvertedType, bool &IncompatibleObjC);
2531 bool isObjCPointerConversion(QualType FromType, QualType ToType,
2532 QualType& ConvertedType, bool &IncompatibleObjC);
2533 bool isObjCWritebackConversion(QualType FromType, QualType ToType,
2534 QualType &ConvertedType);
2535 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
2536 QualType& ConvertedType);
2537 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2538 const FunctionProtoType *NewType,
2539 unsigned *ArgPos = nullptr);
2540 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2541 QualType FromType, QualType ToType);
2542
2543 void maybeExtendBlockObject(ExprResult &E);
2544 CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
2545 bool CheckPointerConversion(Expr *From, QualType ToType,
2546 CastKind &Kind,
2547 CXXCastPath& BasePath,
2548 bool IgnoreBaseAccess,
2549 bool Diagnose = true);
2550 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
2551 bool InOverloadResolution,
2552 QualType &ConvertedType);
2553 bool CheckMemberPointerConversion(Expr *From, QualType ToType,
2554 CastKind &Kind,
2555 CXXCastPath &BasePath,
2556 bool IgnoreBaseAccess);
2557 bool IsQualificationConversion(QualType FromType, QualType ToType,
2558 bool CStyle, bool &ObjCLifetimeConversion);
2559 bool IsFunctionConversion(QualType FromType, QualType ToType,
2560 QualType &ResultTy);
2561 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
2562 bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
2563
2564 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2565 const VarDecl *NRVOCandidate,
2566 QualType ResultType,
2567 Expr *Value,
2568 bool AllowNRVO = true);
2569
2570 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
2571 ExprResult Init);
2572 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
2573 SourceLocation EqualLoc,
2574 ExprResult Init,
2575 bool TopLevelOfInitList = false,
2576 bool AllowExplicit = false);
2577 ExprResult PerformObjectArgumentInitialization(Expr *From,
2578 NestedNameSpecifier *Qualifier,
2579 NamedDecl *FoundDecl,
2580 CXXMethodDecl *Method);
2581
2582 ExprResult PerformContextuallyConvertToBool(Expr *From);
2583 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
2584
2585 /// Contexts in which a converted constant expression is required.
2586 enum CCEKind {
2587 CCEK_CaseValue, ///< Expression in a case label.
2588 CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
2589 CCEK_TemplateArg, ///< Value of a non-type template parameter.
2590 CCEK_NewExpr, ///< Constant expression in a noptr-new-declarator.
2591 CCEK_ConstexprIf ///< Condition in a constexpr if statement.
2592 };
2593 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2594 llvm::APSInt &Value, CCEKind CCE);
2595 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2596 APValue &Value, CCEKind CCE);
2597
2598 /// \brief Abstract base class used to perform a contextual implicit
2599 /// conversion from an expression to any type passing a filter.
2600 class ContextualImplicitConverter {
2601 public:
2602 bool Suppress;
2603 bool SuppressConversion;
2604
2605 ContextualImplicitConverter(bool Suppress = false,
2606 bool SuppressConversion = false)
2607 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
2608
2609 /// \brief Determine whether the specified type is a valid destination type
2610 /// for this conversion.
2611 virtual bool match(QualType T) = 0;
2612
2613 /// \brief Emits a diagnostic complaining that the expression does not have
2614 /// integral or enumeration type.
2615 virtual SemaDiagnosticBuilder
2616 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
2617
2618 /// \brief Emits a diagnostic when the expression has incomplete class type.
2619 virtual SemaDiagnosticBuilder
2620 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
2621
2622 /// \brief Emits a diagnostic when the only matching conversion function
2623 /// is explicit.
2624 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
2625 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2626
2627 /// \brief Emits a note for the explicit conversion function.
2628 virtual SemaDiagnosticBuilder
2629 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2630
2631 /// \brief Emits a diagnostic when there are multiple possible conversion
2632 /// functions.
2633 virtual SemaDiagnosticBuilder
2634 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
2635
2636 /// \brief Emits a note for one of the candidate conversions.
2637 virtual SemaDiagnosticBuilder
2638 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2639
2640 /// \brief Emits a diagnostic when we picked a conversion function
2641 /// (for cases when we are not allowed to pick a conversion function).
2642 virtual SemaDiagnosticBuilder diagnoseConversion(
2643 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2644
2645 virtual ~ContextualImplicitConverter() {}
2646 };
2647
2648 class ICEConvertDiagnoser : public ContextualImplicitConverter {
2649 bool AllowScopedEnumerations;
2650
2651 public:
2652 ICEConvertDiagnoser(bool AllowScopedEnumerations,
2653 bool Suppress, bool SuppressConversion)
2654 : ContextualImplicitConverter(Suppress, SuppressConversion),
2655 AllowScopedEnumerations(AllowScopedEnumerations) {}
2656
2657 /// Match an integral or (possibly scoped) enumeration type.
2658 bool match(QualType T) override;
2659
2660 SemaDiagnosticBuilder
2661 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
2662 return diagnoseNotInt(S, Loc, T);
2663 }
2664
2665 /// \brief Emits a diagnostic complaining that the expression does not have
2666 /// integral or enumeration type.
2667 virtual SemaDiagnosticBuilder
2668 diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
2669 };
2670
2671 /// Perform a contextual implicit conversion.
2672 ExprResult PerformContextualImplicitConversion(
2673 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
2674
2675
2676 enum ObjCSubscriptKind {
2677 OS_Array,
2678 OS_Dictionary,
2679 OS_Error
2680 };
2681 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
2682
2683 // Note that LK_String is intentionally after the other literals, as
2684 // this is used for diagnostics logic.
2685 enum ObjCLiteralKind {
2686 LK_Array,
2687 LK_Dictionary,
2688 LK_Numeric,
2689 LK_Boxed,
2690 LK_String,
2691 LK_Block,
2692 LK_None
2693 };
2694 ObjCLiteralKind CheckLiteralKind(Expr *FromE);
2695
2696 ExprResult PerformObjectMemberConversion(Expr *From,
2697 NestedNameSpecifier *Qualifier,
2698 NamedDecl *FoundDecl,
2699 NamedDecl *Member);
2700
2701 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
2702 // TODO: make this is a typesafe union.
2703 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
2704 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
2705
2706 void AddOverloadCandidate(FunctionDecl *Function,
2707 DeclAccessPair FoundDecl,
2708 ArrayRef<Expr *> Args,
2709 OverloadCandidateSet &CandidateSet,
2710 bool SuppressUserConversions = false,
2711 bool PartialOverloading = false,
2712 bool AllowExplicit = false,
2713 ConversionSequenceList EarlyConversions = None);
2714 void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
2715 ArrayRef<Expr *> Args,
2716 OverloadCandidateSet &CandidateSet,
2717 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
2718 bool SuppressUserConversions = false,
2719 bool PartialOverloading = false,
2720 bool FirstArgumentIsBase = false);
2721 void AddMethodCandidate(DeclAccessPair FoundDecl,
2722 QualType ObjectType,
2723 Expr::Classification ObjectClassification,
2724 ArrayRef<Expr *> Args,
2725 OverloadCandidateSet& CandidateSet,
2726 bool SuppressUserConversion = false);
2727 void AddMethodCandidate(CXXMethodDecl *Method,
2728 DeclAccessPair FoundDecl,
2729 CXXRecordDecl *ActingContext, QualType ObjectType,
2730 Expr::Classification ObjectClassification,
2731 ArrayRef<Expr *> Args,
2732 OverloadCandidateSet& CandidateSet,
2733 bool SuppressUserConversions = false,
2734 bool PartialOverloading = false,
2735 ConversionSequenceList EarlyConversions = None);
2736 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2737 DeclAccessPair FoundDecl,
2738 CXXRecordDecl *ActingContext,
2739 TemplateArgumentListInfo *ExplicitTemplateArgs,
2740 QualType ObjectType,
2741 Expr::Classification ObjectClassification,
2742 ArrayRef<Expr *> Args,
2743 OverloadCandidateSet& CandidateSet,
2744 bool SuppressUserConversions = false,
2745 bool PartialOverloading = false);
2746 void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
2747 DeclAccessPair FoundDecl,
2748 TemplateArgumentListInfo *ExplicitTemplateArgs,
2749 ArrayRef<Expr *> Args,
2750 OverloadCandidateSet& CandidateSet,
2751 bool SuppressUserConversions = false,
2752 bool PartialOverloading = false);
2753 bool CheckNonDependentConversions(FunctionTemplateDecl *FunctionTemplate,
2754 ArrayRef<QualType> ParamTypes,
2755 ArrayRef<Expr *> Args,
2756 OverloadCandidateSet &CandidateSet,
2757 ConversionSequenceList &Conversions,
2758 bool SuppressUserConversions,
2759 CXXRecordDecl *ActingContext = nullptr,
2760 QualType ObjectType = QualType(),
2761 Expr::Classification
2762 ObjectClassification = {});
2763 void AddConversionCandidate(CXXConversionDecl *Conversion,
2764 DeclAccessPair FoundDecl,
2765 CXXRecordDecl *ActingContext,
2766 Expr *From, QualType ToType,
2767 OverloadCandidateSet& CandidateSet,
2768 bool AllowObjCConversionOnExplicit,
2769 bool AllowResultConversion = true);
2770 void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2771 DeclAccessPair FoundDecl,
2772 CXXRecordDecl *ActingContext,
2773 Expr *From, QualType ToType,
2774 OverloadCandidateSet &CandidateSet,
2775 bool AllowObjCConversionOnExplicit,
2776 bool AllowResultConversion = true);
2777 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
2778 DeclAccessPair FoundDecl,
2779 CXXRecordDecl *ActingContext,
2780 const FunctionProtoType *Proto,
2781 Expr *Object, ArrayRef<Expr *> Args,
2782 OverloadCandidateSet& CandidateSet);
2783 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2784 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2785 OverloadCandidateSet& CandidateSet,
2786 SourceRange OpRange = SourceRange());
2787 void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
2788 OverloadCandidateSet& CandidateSet,
2789 bool IsAssignmentOperator = false,
2790 unsigned NumContextualBoolArguments = 0);
2791 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2792 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2793 OverloadCandidateSet& CandidateSet);
2794 void AddArgumentDependentLookupCandidates(DeclarationName Name,
2795 SourceLocation Loc,
2796 ArrayRef<Expr *> Args,
2797 TemplateArgumentListInfo *ExplicitTemplateArgs,
2798 OverloadCandidateSet& CandidateSet,
2799 bool PartialOverloading = false);
2800
2801 // Emit as a 'note' the specific overload candidate
2802 void NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
2803 QualType DestType = QualType(),
2804 bool TakingAddress = false);
2805
2806 // Emit as a series of 'note's all template and non-templates identified by
2807 // the expression Expr
2808 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
2809 bool TakingAddress = false);
2810
2811 /// Check the enable_if expressions on the given function. Returns the first
2812 /// failing attribute, or NULL if they were all successful.
2813 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
2814 bool MissingImplicitThis = false);
2815
2816 /// Find the failed Boolean condition within a given Boolean
2817 /// constant expression, and describe it with a string.
2818 ///
2819 /// \param AllowTopLevelCond Whether to allow the result to be the
2820 /// complete top-level condition.
2821 std::pair<Expr *, std::string>
2822 findFailedBooleanCondition(Expr *Cond, bool AllowTopLevelCond);
2823
2824 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
2825 /// non-ArgDependent DiagnoseIfAttrs.
2826 ///
2827 /// Argument-dependent diagnose_if attributes should be checked each time a
2828 /// function is used as a direct callee of a function call.
2829 ///
2830 /// Returns true if any errors were emitted.
2831 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
2832 const Expr *ThisArg,
2833 ArrayRef<const Expr *> Args,
2834 SourceLocation Loc);
2835
2836 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
2837 /// ArgDependent DiagnoseIfAttrs.
2838 ///
2839 /// Argument-independent diagnose_if attributes should be checked on every use
2840 /// of a function.
2841 ///
2842 /// Returns true if any errors were emitted.
2843 bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
2844 SourceLocation Loc);
2845
2846 /// Returns whether the given function's address can be taken or not,
2847 /// optionally emitting a diagnostic if the address can't be taken.
2848 ///
2849 /// Returns false if taking the address of the function is illegal.
2850 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
2851 bool Complain = false,
2852 SourceLocation Loc = SourceLocation());
2853
2854 // [PossiblyAFunctionType] --> [Return]
2855 // NonFunctionType --> NonFunctionType
2856 // R (A) --> R(A)
2857 // R (*)(A) --> R (A)
2858 // R (&)(A) --> R (A)
2859 // R (S::*)(A) --> R (A)
2860 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
2861
2862 FunctionDecl *
2863 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
2864 QualType TargetType,
2865 bool Complain,
2866 DeclAccessPair &Found,
2867 bool *pHadMultipleCandidates = nullptr);
2868
2869 FunctionDecl *
2870 resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
2871 DeclAccessPair &FoundResult);
2872
2873 bool resolveAndFixAddressOfOnlyViableOverloadCandidate(
2874 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
2875
2876 FunctionDecl *
2877 ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
2878 bool Complain = false,
2879 DeclAccessPair *Found = nullptr);
2880
2881 bool ResolveAndFixSingleFunctionTemplateSpecialization(
2882 ExprResult &SrcExpr,
2883 bool DoFunctionPointerConverion = false,
2884 bool Complain = false,
2885 SourceRange OpRangeForComplaining = SourceRange(),
2886 QualType DestTypeForComplaining = QualType(),
2887 unsigned DiagIDForComplaining = 0);
2888
2889
2890 Expr *FixOverloadedFunctionReference(Expr *E,
2891 DeclAccessPair FoundDecl,
2892 FunctionDecl *Fn);
2893 ExprResult FixOverloadedFunctionReference(ExprResult,
2894 DeclAccessPair FoundDecl,
2895 FunctionDecl *Fn);
2896
2897 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
2898 ArrayRef<Expr *> Args,
2899 OverloadCandidateSet &CandidateSet,
2900 bool PartialOverloading = false);
2901
2902 // An enum used to represent the different possible results of building a
2903 // range-based for loop.
2904 enum ForRangeStatus {
2905 FRS_Success,
2906 FRS_NoViableFunction,
2907 FRS_DiagnosticIssued
2908 };
2909
2910 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
2911 SourceLocation RangeLoc,
2912 const DeclarationNameInfo &NameInfo,
2913 LookupResult &MemberLookup,
2914 OverloadCandidateSet *CandidateSet,
2915 Expr *Range, ExprResult *CallExpr);
2916
2917 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
2918 UnresolvedLookupExpr *ULE,
2919 SourceLocation LParenLoc,
2920 MultiExprArg Args,
2921 SourceLocation RParenLoc,
2922 Expr *ExecConfig,
2923 bool AllowTypoCorrection=true,
2924 bool CalleesAddressIsTaken=false);
2925
2926 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
2927 MultiExprArg Args, SourceLocation RParenLoc,
2928 OverloadCandidateSet *CandidateSet,
2929 ExprResult *Result);
2930
2931 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
2932 UnaryOperatorKind Opc,
2933 const UnresolvedSetImpl &Fns,
2934 Expr *input, bool RequiresADL = true);
2935
2936 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
2937 BinaryOperatorKind Opc,
2938 const UnresolvedSetImpl &Fns,
2939 Expr *LHS, Expr *RHS,
2940 bool RequiresADL = true);
2941
2942 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
2943 SourceLocation RLoc,
2944 Expr *Base,Expr *Idx);
2945
2946 ExprResult
2947 BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
2948 SourceLocation LParenLoc,
2949 MultiExprArg Args,
2950 SourceLocation RParenLoc);
2951 ExprResult
2952 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
2953 MultiExprArg Args,
2954 SourceLocation RParenLoc);
2955
2956 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
2957 SourceLocation OpLoc,
2958 bool *NoArrowOperatorFound = nullptr);
2959
2960 /// CheckCallReturnType - Checks that a call expression's return type is
2961 /// complete. Returns true on failure. The location passed in is the location
2962 /// that best represents the call.
2963 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
2964 CallExpr *CE, FunctionDecl *FD);
2965
2966 /// Helpers for dealing with blocks and functions.
2967 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
2968 bool CheckParameterNames);
2969 void CheckCXXDefaultArguments(FunctionDecl *FD);
2970 void CheckExtraCXXDefaultArguments(Declarator &D);
2971 Scope *getNonFieldDeclScope(Scope *S);
2972
2973 /// \name Name lookup
2974 ///
2975 /// These routines provide name lookup that is used during semantic
2976 /// analysis to resolve the various kinds of names (identifiers,
2977 /// overloaded operator names, constructor names, etc.) into zero or
2978 /// more declarations within a particular scope. The major entry
2979 /// points are LookupName, which performs unqualified name lookup,
2980 /// and LookupQualifiedName, which performs qualified name lookup.
2981 ///
2982 /// All name lookup is performed based on some specific criteria,
2983 /// which specify what names will be visible to name lookup and how
2984 /// far name lookup should work. These criteria are important both
2985 /// for capturing language semantics (certain lookups will ignore
2986 /// certain names, for example) and for performance, since name
2987 /// lookup is often a bottleneck in the compilation of C++. Name
2988 /// lookup criteria is specified via the LookupCriteria enumeration.
2989 ///
2990 /// The results of name lookup can vary based on the kind of name
2991 /// lookup performed, the current language, and the translation
2992 /// unit. In C, for example, name lookup will either return nothing
2993 /// (no entity found) or a single declaration. In C++, name lookup
2994 /// can additionally refer to a set of overloaded functions or
2995 /// result in an ambiguity. All of the possible results of name
2996 /// lookup are captured by the LookupResult class, which provides
2997 /// the ability to distinguish among them.
2998 //@{
2999
3000 /// @brief Describes the kind of name lookup to perform.
3001 enum LookupNameKind {
3002 /// Ordinary name lookup, which finds ordinary names (functions,
3003 /// variables, typedefs, etc.) in C and most kinds of names
3004 /// (functions, variables, members, types, etc.) in C++.
3005 LookupOrdinaryName = 0,
3006 /// Tag name lookup, which finds the names of enums, classes,
3007 /// structs, and unions.
3008 LookupTagName,
3009 /// Label name lookup.
3010 LookupLabel,
3011 /// Member name lookup, which finds the names of
3012 /// class/struct/union members.
3013 LookupMemberName,
3014 /// Look up of an operator name (e.g., operator+) for use with
3015 /// operator overloading. This lookup is similar to ordinary name
3016 /// lookup, but will ignore any declarations that are class members.
3017 LookupOperatorName,
3018 /// Look up of a name that precedes the '::' scope resolution
3019 /// operator in C++. This lookup completely ignores operator, object,
3020 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
3021 LookupNestedNameSpecifierName,
3022 /// Look up a namespace name within a C++ using directive or
3023 /// namespace alias definition, ignoring non-namespace names (C++
3024 /// [basic.lookup.udir]p1).
3025 LookupNamespaceName,
3026 /// Look up all declarations in a scope with the given name,
3027 /// including resolved using declarations. This is appropriate
3028 /// for checking redeclarations for a using declaration.
3029 LookupUsingDeclName,
3030 /// Look up an ordinary name that is going to be redeclared as a
3031 /// name with linkage. This lookup ignores any declarations that
3032 /// are outside of the current scope unless they have linkage. See
3033 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
3034 LookupRedeclarationWithLinkage,
3035 /// Look up a friend of a local class. This lookup does not look
3036 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
3037 LookupLocalFriendName,
3038 /// Look up the name of an Objective-C protocol.
3039 LookupObjCProtocolName,
3040 /// Look up implicit 'self' parameter of an objective-c method.
3041 LookupObjCImplicitSelfParam,
3042 /// \brief Look up the name of an OpenMP user-defined reduction operation.
3043 LookupOMPReductionName,
3044 /// \brief Look up any declaration with any name.
3045 LookupAnyName
3046 };
3047
3048 /// \brief Specifies whether (or how) name lookup is being performed for a
3049 /// redeclaration (vs. a reference).
3050 enum RedeclarationKind {
3051 /// \brief The lookup is a reference to this name that is not for the
3052 /// purpose of redeclaring the name.
3053 NotForRedeclaration = 0,
3054 /// \brief The lookup results will be used for redeclaration of a name,
3055 /// if an entity by that name already exists and is visible.
3056 ForVisibleRedeclaration,
3057 /// \brief The lookup results will be used for redeclaration of a name
3058 /// with external linkage; non-visible lookup results with external linkage
3059 /// may also be found.
3060 ForExternalRedeclaration
3061 };
3062
3063 RedeclarationKind forRedeclarationInCurContext() {
3064 // A declaration with an owning module for linkage can never link against
3065 // anything that is not visible. We don't need to check linkage here; if
3066 // the context has internal linkage, redeclaration lookup won't find things
3067 // from other TUs, and we can't safely compute linkage yet in general.
3068 if (cast<Decl>(CurContext)
3069 ->getOwningModuleForLinkage(/*IgnoreLinkage*/true))
3070 return ForVisibleRedeclaration;
3071 return ForExternalRedeclaration;
3072 }
3073
3074 /// \brief The possible outcomes of name lookup for a literal operator.
3075 enum LiteralOperatorLookupResult {
3076 /// \brief The lookup resulted in an error.
3077 LOLR_Error,
3078 /// \brief The lookup found no match but no diagnostic was issued.
3079 LOLR_ErrorNoDiagnostic,
3080 /// \brief The lookup found a single 'cooked' literal operator, which
3081 /// expects a normal literal to be built and passed to it.
3082 LOLR_Cooked,
3083 /// \brief The lookup found a single 'raw' literal operator, which expects
3084 /// a string literal containing the spelling of the literal token.
3085 LOLR_Raw,
3086 /// \brief The lookup found an overload set of literal operator templates,
3087 /// which expect the characters of the spelling of the literal token to be
3088 /// passed as a non-type template argument pack.
3089 LOLR_Template,
3090 /// \brief The lookup found an overload set of literal operator templates,
3091 /// which expect the character type and characters of the spelling of the
3092 /// string literal token to be passed as template arguments.
3093 LOLR_StringTemplate
3094 };
3095
3096 SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
3097 CXXSpecialMember SM,
3098 bool ConstArg,
3099 bool VolatileArg,
3100 bool RValueThis,
3101 bool ConstThis,
3102 bool VolatileThis);
3103
3104 typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
3105 typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
3106 TypoRecoveryCallback;
3107
3108private:
3109 bool CppLookupName(LookupResult &R, Scope *S);
3110
3111 struct TypoExprState {
3112 std::unique_ptr<TypoCorrectionConsumer> Consumer;
3113 TypoDiagnosticGenerator DiagHandler;
3114 TypoRecoveryCallback RecoveryHandler;
3115 TypoExprState();
3116 TypoExprState(TypoExprState &&other) noexcept;
3117 TypoExprState &operator=(TypoExprState &&other) noexcept;
3118 };
3119
3120 /// \brief The set of unhandled TypoExprs and their associated state.
3121 llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
3122
3123 /// \brief Creates a new TypoExpr AST node.
3124 TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
3125 TypoDiagnosticGenerator TDG,
3126 TypoRecoveryCallback TRC);
3127
3128 // \brief The set of known/encountered (unique, canonicalized) NamespaceDecls.
3129 //
3130 // The boolean value will be true to indicate that the namespace was loaded
3131 // from an AST/PCH file, or false otherwise.
3132 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
3133
3134 /// \brief Whether we have already loaded known namespaces from an extenal
3135 /// source.
3136 bool LoadedExternalKnownNamespaces;
3137
3138 /// \brief Helper for CorrectTypo and CorrectTypoDelayed used to create and
3139 /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
3140 /// should be skipped entirely.
3141 std::unique_ptr<TypoCorrectionConsumer>
3142 makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
3143 Sema::LookupNameKind LookupKind, Scope *S,
3144 CXXScopeSpec *SS,
3145 std::unique_ptr<CorrectionCandidateCallback> CCC,
3146 DeclContext *MemberContext, bool EnteringContext,
3147 const ObjCObjectPointerType *OPT,
3148 bool ErrorRecovery);
3149
3150public:
3151 const TypoExprState &getTypoExprState(TypoExpr *TE) const;
3152
3153 /// \brief Clears the state of the given TypoExpr.
3154 void clearDelayedTypo(TypoExpr *TE);
3155
3156 /// \brief Look up a name, looking for a single declaration. Return
3157 /// null if the results were absent, ambiguous, or overloaded.
3158 ///
3159 /// It is preferable to use the elaborated form and explicitly handle
3160 /// ambiguity and overloaded.
3161 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
3162 SourceLocation Loc,
3163 LookupNameKind NameKind,
3164 RedeclarationKind Redecl
3165 = NotForRedeclaration);
3166 bool LookupName(LookupResult &R, Scope *S,
3167 bool AllowBuiltinCreation = false);
3168 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3169 bool InUnqualifiedLookup = false);
3170 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3171 CXXScopeSpec &SS);
3172 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
3173 bool AllowBuiltinCreation = false,
3174 bool EnteringContext = false);
3175 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
3176 RedeclarationKind Redecl
3177 = NotForRedeclaration);
3178 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
3179
3180 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
3181 QualType T1, QualType T2,
3182 UnresolvedSetImpl &Functions);
3183
3184 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
3185 SourceLocation GnuLabelLoc = SourceLocation());
3186
3187 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
3188 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
3189 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
3190 unsigned Quals);
3191 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
3192 bool RValueThis, unsigned ThisQuals);
3193 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
3194 unsigned Quals);
3195 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
3196 bool RValueThis, unsigned ThisQuals);
3197 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
3198
3199 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
3200 LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
3201 ArrayRef<QualType> ArgTys,
3202 bool AllowRaw,
3203 bool AllowTemplate,
3204 bool AllowStringTemplate,
3205 bool DiagnoseMissing);
3206 bool isKnownName(StringRef name);
3207
3208 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3209 ArrayRef<Expr *> Args, ADLResult &Functions);
3210
3211 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
3212 VisibleDeclConsumer &Consumer,
3213 bool IncludeGlobalScope = true,
3214 bool LoadExternal = true);
3215 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
3216 VisibleDeclConsumer &Consumer,
3217 bool IncludeGlobalScope = true,
3218 bool IncludeDependentBases = false,
3219 bool LoadExternal = true);
3220
3221 enum CorrectTypoKind {
3222 CTK_NonError, // CorrectTypo used in a non error recovery situation.
3223 CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
3224 };
3225
3226 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
3227 Sema::LookupNameKind LookupKind,
3228 Scope *S, CXXScopeSpec *SS,
3229 std::unique_ptr<CorrectionCandidateCallback> CCC,
3230 CorrectTypoKind Mode,
3231 DeclContext *MemberContext = nullptr,
3232 bool EnteringContext = false,
3233 const ObjCObjectPointerType *OPT = nullptr,
3234 bool RecordFailure = true);
3235
3236 TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
3237 Sema::LookupNameKind LookupKind, Scope *S,
3238 CXXScopeSpec *SS,
3239 std::unique_ptr<CorrectionCandidateCallback> CCC,
3240 TypoDiagnosticGenerator TDG,
3241 TypoRecoveryCallback TRC, CorrectTypoKind Mode,
3242 DeclContext *MemberContext = nullptr,
3243 bool EnteringContext = false,
3244 const ObjCObjectPointerType *OPT = nullptr);
3245
3246 /// \brief Process any TypoExprs in the given Expr and its children,
3247 /// generating diagnostics as appropriate and returning a new Expr if there
3248 /// were typos that were all successfully corrected and ExprError if one or
3249 /// more typos could not be corrected.
3250 ///
3251 /// \param E The Expr to check for TypoExprs.
3252 ///
3253 /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
3254 /// initializer.
3255 ///
3256 /// \param Filter A function applied to a newly rebuilt Expr to determine if
3257 /// it is an acceptable/usable result from a single combination of typo
3258 /// corrections. As long as the filter returns ExprError, different
3259 /// combinations of corrections will be tried until all are exhausted.
3260 ExprResult
3261 CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr,
3262 llvm::function_ref<ExprResult(Expr *)> Filter =
3263 [](Expr *E) -> ExprResult { return E; });
3264
3265 ExprResult
3266 CorrectDelayedTyposInExpr(Expr *E,
3267 llvm::function_ref<ExprResult(Expr *)> Filter) {
3268 return CorrectDelayedTyposInExpr(E, nullptr, Filter);
3269 }
3270
3271 ExprResult
3272 CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr,
3273 llvm::function_ref<ExprResult(Expr *)> Filter =
3274 [](Expr *E) -> ExprResult { return E; }) {
3275 return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter);
3276 }
3277
3278 ExprResult
3279 CorrectDelayedTyposInExpr(ExprResult ER,
3280 llvm::function_ref<ExprResult(Expr *)> Filter) {
3281 return CorrectDelayedTyposInExpr(ER, nullptr, Filter);
3282 }
3283
3284 void diagnoseTypo(const TypoCorrection &Correction,
3285 const PartialDiagnostic &TypoDiag,
3286 bool ErrorRecovery = true);
3287
3288 void diagnoseTypo(const TypoCorrection &Correction,
3289 const PartialDiagnostic &TypoDiag,
3290 const PartialDiagnostic &PrevNote,
3291 bool ErrorRecovery = true);
3292
3293 void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
3294
3295 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
3296 ArrayRef<Expr *> Args,
3297 AssociatedNamespaceSet &AssociatedNamespaces,
3298 AssociatedClassSet &AssociatedClasses);
3299
3300 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
3301 bool ConsiderLinkage, bool AllowInlineNamespace);
3302
3303 bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
3304
3305 void DiagnoseAmbiguousLookup(LookupResult &Result);
3306 //@}
3307
3308 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
3309 SourceLocation IdLoc,
3310 bool TypoCorrection = false);
3311 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
3312 Scope *S, bool ForRedeclaration,
3313 SourceLocation Loc);
3314 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
3315 Scope *S);
3316 void AddKnownFunctionAttributes(FunctionDecl *FD);
3317
3318 // More parsing and symbol table subroutines.
3319
3320 void ProcessPragmaWeak(Scope *S, Decl *D);
3321 // Decl attributes - this routine is the top level dispatcher.
3322 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
3323 // Helper for delayed processing of attributes.
3324 void ProcessDeclAttributeDelayed(Decl *D, const AttributeList *AttrList);
3325 void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL,
3326 bool IncludeCXX11Attributes = true);
3327 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
3328 const AttributeList *AttrList);
3329
3330 void checkUnusedDeclAttributes(Declarator &D);
3331
3332 /// Determine if type T is a valid subject for a nonnull and similar
3333 /// attributes. By default, we look through references (the behavior used by
3334 /// nonnull), but if the second parameter is true, then we treat a reference
3335 /// type as valid.
3336 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
3337
3338 bool CheckRegparmAttr(const AttributeList &attr, unsigned &value);
3339 bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
3340 const FunctionDecl *FD = nullptr);
3341 bool CheckNoReturnAttr(const AttributeList &attr);
3342 bool CheckNoCallerSavedRegsAttr(const AttributeList &attr);
3343 bool checkStringLiteralArgumentAttr(const AttributeList &Attr,
3344 unsigned ArgNum, StringRef &Str,
3345 SourceLocation *ArgLocation = nullptr);
3346 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
3347 bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
3348 bool checkMSInheritanceAttrOnDefinition(
3349 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3350 MSInheritanceAttr::Spelling SemanticSpelling);
3351
3352 void CheckAlignasUnderalignment(Decl *D);
3353
3354 /// Adjust the calling convention of a method to be the ABI default if it
3355 /// wasn't specified explicitly. This handles method types formed from
3356 /// function type typedefs and typename template arguments.
3357 void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
3358 SourceLocation Loc);
3359
3360 // Check if there is an explicit attribute, but only look through parens.
3361 // The intent is to look for an attribute on the current declarator, but not
3362 // one that came from a typedef.
3363 bool hasExplicitCallingConv(QualType &T);
3364
3365 /// Get the outermost AttributedType node that sets a calling convention.
3366 /// Valid types should not have multiple attributes with different CCs.
3367 const AttributedType *getCallingConvAttributedType(QualType T) const;
3368
3369 /// Check whether a nullability type specifier can be added to the given
3370 /// type.
3371 ///
3372 /// \param type The type to which the nullability specifier will be
3373 /// added. On success, this type will be updated appropriately.
3374 ///
3375 /// \param nullability The nullability specifier to add.
3376 ///
3377 /// \param nullabilityLoc The location of the nullability specifier.
3378 ///
3379 /// \param isContextSensitive Whether this nullability specifier was
3380 /// written as a context-sensitive keyword (in an Objective-C
3381 /// method) or an Objective-C property attribute, rather than as an
3382 /// underscored type specifier.
3383 ///
3384 /// \param allowArrayTypes Whether to accept nullability specifiers on an
3385 /// array type (e.g., because it will decay to a pointer).
3386 ///
3387 /// \returns true if nullability cannot be applied, false otherwise.
3388 bool checkNullabilityTypeSpecifier(QualType &type, NullabilityKind nullability,
3389 SourceLocation nullabilityLoc,
3390 bool isContextSensitive,
3391 bool allowArrayTypes);
3392
3393 /// \brief Stmt attributes - this routine is the top level dispatcher.
3394 StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *Attrs,
3395 SourceRange Range);
3396
3397 void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
3398 ObjCMethodDecl *MethodDecl,
3399 bool IsProtocolMethodDecl);
3400
3401 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
3402 ObjCMethodDecl *Overridden,
3403 bool IsProtocolMethodDecl);
3404
3405 /// WarnExactTypedMethods - This routine issues a warning if method
3406 /// implementation declaration matches exactly that of its declaration.
3407 void WarnExactTypedMethods(ObjCMethodDecl *Method,
3408 ObjCMethodDecl *MethodDecl,
3409 bool IsProtocolMethodDecl);
3410
3411 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
3412
3413 /// CheckImplementationIvars - This routine checks if the instance variables
3414 /// listed in the implelementation match those listed in the interface.
3415 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
3416 ObjCIvarDecl **Fields, unsigned nIvars,
3417 SourceLocation Loc);
3418
3419 /// ImplMethodsVsClassMethods - This is main routine to warn if any method
3420 /// remains unimplemented in the class or category \@implementation.
3421 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
3422 ObjCContainerDecl* IDecl,
3423 bool IncompleteImpl = false);
3424
3425 /// DiagnoseUnimplementedProperties - This routine warns on those properties
3426 /// which must be implemented by this implementation.
3427 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
3428 ObjCContainerDecl *CDecl,
3429 bool SynthesizeProperties);
3430
3431 /// Diagnose any null-resettable synthesized setters.
3432 void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
3433
3434 /// DefaultSynthesizeProperties - This routine default synthesizes all
3435 /// properties which must be synthesized in the class's \@implementation.
3436 void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl,
3437 ObjCInterfaceDecl *IDecl,
3438 SourceLocation AtEnd);
3439 void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd);
3440
3441 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
3442 /// an ivar synthesized for 'Method' and 'Method' is a property accessor
3443 /// declared in class 'IFace'.
3444 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
3445 ObjCMethodDecl *Method, ObjCIvarDecl *IV);
3446
3447 /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
3448 /// backs the property is not used in the property's accessor.
3449 void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
3450 const ObjCImplementationDecl *ImplD);
3451
3452 /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
3453 /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
3454 /// It also returns ivar's property on success.
3455 ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
3456 const ObjCPropertyDecl *&PDecl) const;
3457
3458 /// Called by ActOnProperty to handle \@property declarations in
3459 /// class extensions.
3460 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
3461 SourceLocation AtLoc,
3462 SourceLocation LParenLoc,
3463 FieldDeclarator &FD,
3464 Selector GetterSel,
3465 SourceLocation GetterNameLoc,
3466 Selector SetterSel,
3467 SourceLocation SetterNameLoc,
3468 const bool isReadWrite,
3469 unsigned &Attributes,
3470 const unsigned AttributesAsWritten,
3471 QualType T,
3472 TypeSourceInfo *TSI,
3473 tok::ObjCKeywordKind MethodImplKind);
3474
3475 /// Called by ActOnProperty and HandlePropertyInClassExtension to
3476 /// handle creating the ObjcPropertyDecl for a category or \@interface.
3477 ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
3478 ObjCContainerDecl *CDecl,
3479 SourceLocation AtLoc,
3480 SourceLocation LParenLoc,
3481 FieldDeclarator &FD,
3482 Selector GetterSel,
3483 SourceLocation GetterNameLoc,
3484 Selector SetterSel,
3485 SourceLocation SetterNameLoc,
3486 const bool isReadWrite,
3487 const unsigned Attributes,
3488 const unsigned AttributesAsWritten,
3489 QualType T,
3490 TypeSourceInfo *TSI,
3491 tok::ObjCKeywordKind MethodImplKind,
3492 DeclContext *lexicalDC = nullptr);
3493
3494 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
3495 /// warning) when atomic property has one but not the other user-declared
3496 /// setter or getter.
3497 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
3498 ObjCInterfaceDecl* IDecl);
3499
3500 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
3501
3502 void DiagnoseMissingDesignatedInitOverrides(
3503 const ObjCImplementationDecl *ImplD,
3504 const ObjCInterfaceDecl *IFD);
3505
3506 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
3507
3508 enum MethodMatchStrategy {
3509 MMS_loose,
3510 MMS_strict
3511 };
3512
3513 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
3514 /// true, or false, accordingly.
3515 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
3516 const ObjCMethodDecl *PrevMethod,
3517 MethodMatchStrategy strategy = MMS_strict);
3518
3519 /// MatchAllMethodDeclarations - Check methods declaraed in interface or
3520 /// or protocol against those declared in their implementations.
3521 void MatchAllMethodDeclarations(const SelectorSet &InsMap,
3522 const SelectorSet &ClsMap,
3523 SelectorSet &InsMapSeen,
3524 SelectorSet &ClsMapSeen,
3525 ObjCImplDecl* IMPDecl,
3526 ObjCContainerDecl* IDecl,
3527 bool &IncompleteImpl,
3528 bool ImmediateClass,
3529 bool WarnCategoryMethodImpl=false);
3530
3531 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
3532 /// category matches with those implemented in its primary class and
3533 /// warns each time an exact match is found.
3534 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
3535
3536 /// \brief Add the given method to the list of globally-known methods.
3537 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
3538
3539private:
3540 /// AddMethodToGlobalPool - Add an instance or factory method to the global
3541 /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
3542 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
3543
3544 /// LookupMethodInGlobalPool - Returns the instance or factory method and
3545 /// optionally warns if there are multiple signatures.
3546 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
3547 bool receiverIdOrClass,
3548 bool instance);
3549
3550public:
3551 /// \brief - Returns instance or factory methods in global method pool for
3552 /// given selector. It checks the desired kind first, if none is found, and
3553 /// parameter checkTheOther is set, it then checks the other kind. If no such
3554 /// method or only one method is found, function returns false; otherwise, it
3555 /// returns true.
3556 bool
3557 CollectMultipleMethodsInGlobalPool(Selector Sel,
3558 SmallVectorImpl<ObjCMethodDecl*>& Methods,
3559 bool InstanceFirst, bool CheckTheOther,
3560 const ObjCObjectType *TypeBound = nullptr);
3561
3562 bool
3563 AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
3564 SourceRange R, bool receiverIdOrClass,
3565 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3566
3567 void
3568 DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3569 Selector Sel, SourceRange R,
3570 bool receiverIdOrClass);
3571
3572private:
3573 /// \brief - Returns a selector which best matches given argument list or
3574 /// nullptr if none could be found
3575 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
3576 bool IsInstance,
3577 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3578
3579
3580 /// \brief Record the typo correction failure and return an empty correction.
3581 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
3582 bool RecordFailure = true) {
3583 if (RecordFailure)
3584 TypoCorrectionFailures[Typo].insert(TypoLoc);
3585 return TypoCorrection();
3586 }
3587
3588public:
3589 /// AddInstanceMethodToGlobalPool - All instance methods in a translation
3590 /// unit are added to a global pool. This allows us to efficiently associate
3591 /// a selector with a method declaraation for purposes of typechecking
3592 /// messages sent to "id" (where the class of the object is unknown).
3593 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3594 AddMethodToGlobalPool(Method, impl, /*instance*/true);
3595 }
3596
3597 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
3598 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3599 AddMethodToGlobalPool(Method, impl, /*instance*/false);
3600 }
3601
3602 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
3603 /// pool.
3604 void AddAnyMethodToGlobalPool(Decl *D);
3605
3606 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
3607 /// there are multiple signatures.
3608 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
3609 bool receiverIdOrClass=false) {
3610 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3611 /*instance*/true);
3612 }
3613
3614 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
3615 /// there are multiple signatures.
3616 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
3617 bool receiverIdOrClass=false) {
3618 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3619 /*instance*/false);
3620 }
3621
3622 const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
3623 QualType ObjectType=QualType());
3624 /// LookupImplementedMethodInGlobalPool - Returns the method which has an
3625 /// implementation.
3626 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
3627
3628 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
3629 /// initialization.
3630 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
3631 SmallVectorImpl<ObjCIvarDecl*> &Ivars);
3632
3633 //===--------------------------------------------------------------------===//
3634 // Statement Parsing Callbacks: SemaStmt.cpp.
3635public:
3636 class FullExprArg {
3637 public:
3638 FullExprArg() : E(nullptr) { }
3639 FullExprArg(Sema &actions) : E(nullptr) { }
3640
3641 ExprResult release() {
3642 return E;
3643 }
3644
3645 Expr *get() const { return E; }
3646
3647 Expr *operator->() {
3648 return E;
3649 }
3650
3651 private:
3652 // FIXME: No need to make the entire Sema class a friend when it's just
3653 // Sema::MakeFullExpr that needs access to the constructor below.
3654 friend class Sema;
3655
3656 explicit FullExprArg(Expr *expr) : E(expr) {}
3657
3658 Expr *E;
3659 };
3660
3661 FullExprArg MakeFullExpr(Expr *Arg) {
3662 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
3663 }
3664 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
3665 return FullExprArg(ActOnFinishFullExpr(Arg, CC).get());
3666 }
3667 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
3668 ExprResult FE =
3669 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
3670 /*DiscardedValue*/ true);
3671 return FullExprArg(FE.get());
3672 }
3673
3674 StmtResult ActOnExprStmt(ExprResult Arg);
3675 StmtResult ActOnExprStmtError();
3676
3677 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
3678 bool HasLeadingEmptyMacro = false);
3679
3680 void ActOnStartOfCompoundStmt(bool IsStmtExpr);
3681 void ActOnFinishOfCompoundStmt();
3682 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
3683 ArrayRef<Stmt *> Elts, bool isStmtExpr);
3684
3685 /// \brief A RAII object to enter scope of a compound statement.
3686 class CompoundScopeRAII {
3687 public:
3688 CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
3689 S.ActOnStartOfCompoundStmt(IsStmtExpr);
3690 }
3691
3692 ~CompoundScopeRAII() {
3693 S.ActOnFinishOfCompoundStmt();
3694 }
3695
3696 private:
3697 Sema &S;
3698 };
3699
3700 /// An RAII helper that pops function a function scope on exit.
3701 struct FunctionScopeRAII {
3702 Sema &S;
3703 bool Active;
3704 FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
3705 ~FunctionScopeRAII() {
3706 if (Active)
3707 S.PopFunctionScopeInfo();
3708 }
3709 void disable() { Active = false; }
3710 };
3711
3712 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
3713 SourceLocation StartLoc,
3714 SourceLocation EndLoc);
3715 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
3716 StmtResult ActOnForEachLValueExpr(Expr *E);
3717 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
3718 SourceLocation DotDotDotLoc, Expr *RHSVal,
3719 SourceLocation ColonLoc);
3720 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
3721
3722 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
3723 SourceLocation ColonLoc,
3724 Stmt *SubStmt, Scope *CurScope);
3725 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
3726 SourceLocation ColonLoc, Stmt *SubStmt);
3727
3728 StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
3729 ArrayRef<const Attr*> Attrs,
3730 Stmt *SubStmt);
3731
3732 class ConditionResult;
3733 StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3734 Stmt *InitStmt,
3735 ConditionResult Cond, Stmt *ThenVal,
3736 SourceLocation ElseLoc, Stmt *ElseVal);
3737 StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3738 Stmt *InitStmt,
3739 ConditionResult Cond, Stmt *ThenVal,
3740 SourceLocation ElseLoc, Stmt *ElseVal);
3741 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
3742 Stmt *InitStmt,
3743 ConditionResult Cond);
3744 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
3745 Stmt *Switch, Stmt *Body);
3746 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
3747 Stmt *Body);
3748 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
3749 SourceLocation WhileLoc, SourceLocation CondLParen,
3750 Expr *Cond, SourceLocation CondRParen);
3751
3752 StmtResult ActOnForStmt(SourceLocation ForLoc,
3753 SourceLocation LParenLoc,
3754 Stmt *First,
3755 ConditionResult Second,
3756 FullExprArg Third,
3757 SourceLocation RParenLoc,
3758 Stmt *Body);
3759 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
3760 Expr *collection);
3761 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
3762 Stmt *First, Expr *collection,
3763 SourceLocation RParenLoc);
3764 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
3765
3766 enum BuildForRangeKind {
3767 /// Initial building of a for-range statement.
3768 BFRK_Build,
3769 /// Instantiation or recovery rebuild of a for-range statement. Don't
3770 /// attempt any typo-correction.
3771 BFRK_Rebuild,
3772 /// Determining whether a for-range statement could be built. Avoid any
3773 /// unnecessary or irreversible actions.
3774 BFRK_Check
3775 };
3776
3777 StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
3778 SourceLocation CoawaitLoc,
3779 Stmt *LoopVar,
3780 SourceLocation ColonLoc, Expr *Collection,
3781 SourceLocation RParenLoc,
3782 BuildForRangeKind Kind);
3783 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
3784 SourceLocation CoawaitLoc,
3785 SourceLocation ColonLoc,
3786 Stmt *RangeDecl, Stmt *Begin, Stmt *End,
3787 Expr *Cond, Expr *Inc,
3788 Stmt *LoopVarDecl,
3789 SourceLocation RParenLoc,
3790 BuildForRangeKind Kind);
3791 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
3792
3793 StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
3794 SourceLocation LabelLoc,
3795 LabelDecl *TheDecl);
3796 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
3797 SourceLocation StarLoc,
3798 Expr *DestExp);
3799 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
3800 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
3801
3802 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3803 CapturedRegionKind Kind, unsigned NumParams);
3804 typedef std::pair<StringRef, QualType> CapturedParamNameType;
3805 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3806 CapturedRegionKind Kind,
3807 ArrayRef<CapturedParamNameType> Params);
3808 StmtResult ActOnCapturedRegionEnd(Stmt *S);
3809 void ActOnCapturedRegionError();
3810 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
3811 SourceLocation Loc,
3812 unsigned NumParams);
3813 VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
3814 bool AllowParamOrMoveConstructible);
3815 bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
3816 bool AllowParamOrMoveConstructible);
3817
3818 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3819 Scope *CurScope);
3820 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3821 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3822
3823 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
3824 bool IsVolatile, unsigned NumOutputs,
3825 unsigned NumInputs, IdentifierInfo **Names,
3826 MultiExprArg Constraints, MultiExprArg Exprs,
3827 Expr *AsmString, MultiExprArg Clobbers,
3828 SourceLocation RParenLoc);
3829
3830 void FillInlineAsmIdentifierInfo(Expr *Res,
3831 llvm::InlineAsmIdentifierInfo &Info);
3832 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
3833 SourceLocation TemplateKWLoc,
3834 UnqualifiedId &Id,
3835 bool IsUnevaluatedContext);
3836 bool LookupInlineAsmField(StringRef Base, StringRef Member,
3837 unsigned &Offset, SourceLocation AsmLoc);
3838 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
3839 SourceLocation AsmLoc);
3840 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
3841 ArrayRef<Token> AsmToks,
3842 StringRef AsmString,
3843 unsigned NumOutputs, unsigned NumInputs,
3844 ArrayRef<StringRef> Constraints,
3845 ArrayRef<StringRef> Clobbers,
3846 ArrayRef<Expr*> Exprs,
3847 SourceLocation EndLoc);
3848 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
3849 SourceLocation Location,
3850 bool AlwaysCreate);
3851
3852 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
3853 SourceLocation StartLoc,
3854 SourceLocation IdLoc, IdentifierInfo *Id,
3855 bool Invalid = false);
3856
3857 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
3858
3859 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
3860 Decl *Parm, Stmt *Body);
3861
3862 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
3863
3864 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
3865 MultiStmtArg Catch, Stmt *Finally);
3866
3867 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
3868 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
3869 Scope *CurScope);
3870 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
3871 Expr *operand);
3872 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
3873 Expr *SynchExpr,
3874 Stmt *SynchBody);
3875
3876 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
3877
3878 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
3879 SourceLocation StartLoc,
3880 SourceLocation IdLoc,
3881 IdentifierInfo *Id);
3882
3883 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
3884
3885 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
3886 Decl *ExDecl, Stmt *HandlerBlock);
3887 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3888 ArrayRef<Stmt *> Handlers);
3889
3890 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
3891 SourceLocation TryLoc, Stmt *TryBlock,
3892 Stmt *Handler);
3893 StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
3894 Expr *FilterExpr,
3895 Stmt *Block);
3896 void ActOnStartSEHFinallyBlock();
3897 void ActOnAbortSEHFinallyBlock();
3898 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
3899 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
3900
3901 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
3902
3903 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
3904
3905 /// \brief If it's a file scoped decl that must warn if not used, keep track
3906 /// of it.
3907 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
3908
3909 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
3910 /// whose result is unused, warn.
3911 void DiagnoseUnusedExprResult(const Stmt *S);
3912 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
3913 void DiagnoseUnusedDecl(const NamedDecl *ND);
3914
3915 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
3916 /// statement as a \p Body, and it is located on the same line.
3917 ///
3918 /// This helps prevent bugs due to typos, such as:
3919 /// if (condition);
3920 /// do_stuff();
3921 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
3922 const Stmt *Body,
3923 unsigned DiagID);
3924
3925 /// Warn if a for/while loop statement \p S, which is followed by
3926 /// \p PossibleBody, has a suspicious null statement as a body.
3927 void DiagnoseEmptyLoopBody(const Stmt *S,
3928 const Stmt *PossibleBody);
3929
3930 /// Warn if a value is moved to itself.
3931 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
3932 SourceLocation OpLoc);
3933
3934 /// \brief Warn if we're implicitly casting from a _Nullable pointer type to a
3935 /// _Nonnull one.
3936 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
3937 SourceLocation Loc);
3938
3939 /// Warn when implicitly casting 0 to nullptr.
3940 void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
3941
3942 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
3943 return DelayedDiagnostics.push(pool);
3944 }
3945 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
3946
3947 typedef ProcessingContextState ParsingClassState;
3948 ParsingClassState PushParsingClass() {
3949 return DelayedDiagnostics.pushUndelayed();
3950 }
3951 void PopParsingClass(ParsingClassState state) {
3952 DelayedDiagnostics.popUndelayed(state);
3953 }
3954
3955 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
3956
3957 void DiagnoseAvailabilityOfDecl(NamedDecl *D, SourceLocation Loc,
3958 const ObjCInterfaceDecl *UnknownObjCClass,
3959 bool ObjCPropertyAccess,
3960 bool AvoidPartialAvailabilityChecks = false);
3961
3962 bool makeUnavailableInSystemHeader(SourceLocation loc,
3963 UnavailableAttr::ImplicitReason reason);
3964
3965 /// \brief Issue any -Wunguarded-availability warnings in \c FD
3966 void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
3967
3968 //===--------------------------------------------------------------------===//
3969 // Expression Parsing Callbacks: SemaExpr.cpp.
3970
3971 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
3972 bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
3973 const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
3974 bool ObjCPropertyAccess = false,
3975 bool AvoidPartialAvailabilityChecks = false);
3976 void NoteDeletedFunction(FunctionDecl *FD);
3977 void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
3978 std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD);
3979 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
3980 ObjCMethodDecl *Getter,
3981 SourceLocation Loc);
3982 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
3983 ArrayRef<Expr *> Args);
3984
3985 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3986 Decl *LambdaContextDecl = nullptr,
3987 bool IsDecltype = false);
3988 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
3989 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3990 ReuseLambdaContextDecl_t,
3991 bool IsDecltype = false);
3992 void PopExpressionEvaluationContext();
3993
3994 void DiscardCleanupsInEvaluationContext();
3995
3996 ExprResult TransformToPotentiallyEvaluated(Expr *E);
3997 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
3998
3999 ExprResult ActOnConstantExpression(ExprResult Res);
4000
4001 // Functions for marking a declaration referenced. These functions also
4002 // contain the relevant logic for marking if a reference to a function or
4003 // variable is an odr-use (in the C++11 sense). There are separate variants
4004 // for expressions referring to a decl; these exist because odr-use marking
4005 // needs to be delayed for some constant variables when we build one of the
4006 // named expressions.
4007 //
4008 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
4009 // should usually be true. This only needs to be set to false if the lack of
4010 // odr-use cannot be determined from the current context (for instance,
4011 // because the name denotes a virtual function and was written without an
4012 // explicit nested-name-specifier).
4013 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
4014 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
4015 bool MightBeOdrUse = true);
4016 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
4017 void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
4018 void MarkMemberReferenced(MemberExpr *E);
4019
4020 void UpdateMarkingForLValueToRValue(Expr *E);
4021 void CleanupVarDeclMarking();
4022
4023 enum TryCaptureKind {
4024 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
4025 };
4026
4027 /// \brief Try to capture the given variable.
4028 ///
4029 /// \param Var The variable to capture.
4030 ///
4031 /// \param Loc The location at which the capture occurs.
4032 ///
4033 /// \param Kind The kind of capture, which may be implicit (for either a
4034 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
4035 ///
4036 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
4037 /// an explicit lambda capture.
4038 ///
4039 /// \param BuildAndDiagnose Whether we are actually supposed to add the
4040 /// captures or diagnose errors. If false, this routine merely check whether
4041 /// the capture can occur without performing the capture itself or complaining
4042 /// if the variable cannot be captured.
4043 ///
4044 /// \param CaptureType Will be set to the type of the field used to capture
4045 /// this variable in the innermost block or lambda. Only valid when the
4046 /// variable can be captured.
4047 ///
4048 /// \param DeclRefType Will be set to the type of a reference to the capture
4049 /// from within the current scope. Only valid when the variable can be
4050 /// captured.
4051 ///
4052 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
4053 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
4054 /// This is useful when enclosing lambdas must speculatively capture
4055 /// variables that may or may not be used in certain specializations of
4056 /// a nested generic lambda.
4057 ///
4058 /// \returns true if an error occurred (i.e., the variable cannot be
4059 /// captured) and false if the capture succeeded.
4060 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
4061 SourceLocation EllipsisLoc, bool BuildAndDiagnose,
4062 QualType &CaptureType,
4063 QualType &DeclRefType,
4064 const unsigned *const FunctionScopeIndexToStopAt);
4065
4066 /// \brief Try to capture the given variable.
4067 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
4068 TryCaptureKind Kind = TryCapture_Implicit,
4069 SourceLocation EllipsisLoc = SourceLocation());
4070
4071 /// \brief Checks if the variable must be captured.
4072 bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
4073
4074 /// \brief Given a variable, determine the type that a reference to that
4075 /// variable will have in the given scope.
4076 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
4077
4078 /// Mark all of the declarations referenced within a particular AST node as
4079 /// referenced. Used when template instantiation instantiates a non-dependent
4080 /// type -- entities referenced by the type are now referenced.
4081 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
4082 void MarkDeclarationsReferencedInExpr(Expr *E,
4083 bool SkipLocalVariables = false);
4084
4085 /// \brief Try to recover by turning the given expression into a
4086 /// call. Returns true if recovery was attempted or an error was
4087 /// emitted; this may also leave the ExprResult invalid.
4088 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
4089 bool ForceComplain = false,
4090 bool (*IsPlausibleResult)(QualType) = nullptr);
4091
4092 /// \brief Figure out if an expression could be turned into a call.
4093 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
4094 UnresolvedSetImpl &NonTemplateOverloads);
4095
4096 /// \brief Conditionally issue a diagnostic based on the current
4097 /// evaluation context.
4098 ///
4099 /// \param Statement If Statement is non-null, delay reporting the
4100 /// diagnostic until the function body is parsed, and then do a basic
4101 /// reachability analysis to determine if the statement is reachable.
4102 /// If it is unreachable, the diagnostic will not be emitted.
4103 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
4104 const PartialDiagnostic &PD);
4105
4106 // Primary Expressions.
4107 SourceRange getExprRange(Expr *E) const;
4108
4109 ExprResult ActOnIdExpression(
4110 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4111 UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
4112 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr,
4113 bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
4114
4115 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
4116 TemplateArgumentListInfo &Buffer,
4117 DeclarationNameInfo &NameInfo,
4118 const TemplateArgumentListInfo *&TemplateArgs);
4119
4120 bool
4121 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
4122 std::unique_ptr<CorrectionCandidateCallback> CCC,
4123 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
4124 ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
4125
4126 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
4127 IdentifierInfo *II,
4128 bool AllowBuiltinCreation=false);
4129
4130 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
4131 SourceLocation TemplateKWLoc,
4132 const DeclarationNameInfo &NameInfo,
4133 bool isAddressOfOperand,
4134 const TemplateArgumentListInfo *TemplateArgs);
4135
4136 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
4137 ExprValueKind VK,
4138 SourceLocation Loc,
4139 const CXXScopeSpec *SS = nullptr);
4140 ExprResult
4141 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4142 const DeclarationNameInfo &NameInfo,
4143 const CXXScopeSpec *SS = nullptr,
4144 NamedDecl *FoundD = nullptr,
4145 const TemplateArgumentListInfo *TemplateArgs = nullptr);
4146 ExprResult
4147 BuildAnonymousStructUnionMemberReference(
4148 const CXXScopeSpec &SS,
4149 SourceLocation nameLoc,
4150 IndirectFieldDecl *indirectField,
4151 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
4152 Expr *baseObjectExpr = nullptr,
4153 SourceLocation opLoc = SourceLocation());
4154
4155 ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
4156 SourceLocation TemplateKWLoc,
4157 LookupResult &R,
4158 const TemplateArgumentListInfo *TemplateArgs,
4159 const Scope *S);
4160 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
4161 SourceLocation TemplateKWLoc,
4162 LookupResult &R,
4163 const TemplateArgumentListInfo *TemplateArgs,
4164 bool IsDefiniteInstance,
4165 const Scope *S);
4166 bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
4167 const LookupResult &R,
4168 bool HasTrailingLParen);
4169
4170 ExprResult
4171 BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
4172 const DeclarationNameInfo &NameInfo,
4173 bool IsAddressOfOperand, const Scope *S,
4174 TypeSourceInfo **RecoveryTSI = nullptr);
4175
4176 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
4177 SourceLocation TemplateKWLoc,
4178 const DeclarationNameInfo &NameInfo,
4179 const TemplateArgumentListInfo *TemplateArgs);
4180
4181 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
4182 LookupResult &R,
4183 bool NeedsADL,
4184 bool AcceptInvalidDecl = false);
4185 ExprResult BuildDeclarationNameExpr(
4186 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
4187 NamedDecl *FoundD = nullptr,
4188 const TemplateArgumentListInfo *TemplateArgs = nullptr,
4189 bool AcceptInvalidDecl = false);
4190
4191 ExprResult BuildLiteralOperatorCall(LookupResult &R,
4192 DeclarationNameInfo &SuffixInfo,
4193 ArrayRef<Expr *> Args,
4194 SourceLocation LitEndLoc,
4195 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
4196
4197 ExprResult BuildPredefinedExpr(SourceLocation Loc,
4198 PredefinedExpr::IdentType IT);
4199 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
4200 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
4201
4202 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
4203
4204 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
4205 ExprResult ActOnCharacterConstant(const Token &Tok,
4206 Scope *UDLScope = nullptr);
4207 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
4208 ExprResult ActOnParenListExpr(SourceLocation L,
4209 SourceLocation R,
4210 MultiExprArg Val);
4211
4212 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
4213 /// fragments (e.g. "foo" "bar" L"baz").
4214 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
4215 Scope *UDLScope = nullptr);
4216
4217 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
4218 SourceLocation DefaultLoc,
4219 SourceLocation RParenLoc,
4220 Expr *ControllingExpr,
4221 ArrayRef<ParsedType> ArgTypes,
4222 ArrayRef<Expr *> ArgExprs);
4223 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
4224 SourceLocation DefaultLoc,
4225 SourceLocation RParenLoc,
4226 Expr *ControllingExpr,
4227 ArrayRef<TypeSourceInfo *> Types,
4228 ArrayRef<Expr *> Exprs);
4229
4230 // Binary/Unary Operators. 'Tok' is the token for the operator.
4231 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
4232 Expr *InputExpr);
4233 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
4234 UnaryOperatorKind Opc, Expr *Input);
4235 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4236 tok::TokenKind Op, Expr *Input);
4237
4238 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
4239
4240 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4241 SourceLocation OpLoc,
4242 UnaryExprOrTypeTrait ExprKind,
4243 SourceRange R);
4244 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4245 UnaryExprOrTypeTrait ExprKind);
4246 ExprResult
4247 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4248 UnaryExprOrTypeTrait ExprKind,
4249 bool IsType, void *TyOrEx,
4250 SourceRange ArgRange);
4251
4252 ExprResult CheckPlaceholderExpr(Expr *E);
4253 bool CheckVecStepExpr(Expr *E);
4254
4255 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
4256 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
4257 SourceRange ExprRange,
4258 UnaryExprOrTypeTrait ExprKind);
4259 ExprResult ActOnSizeofParameterPackExpr(Scope *S,
4260 SourceLocation OpLoc,
4261 IdentifierInfo &Name,
4262 SourceLocation NameLoc,
4263 SourceLocation RParenLoc);
4264 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4265 tok::TokenKind Kind, Expr *Input);
4266
4267 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
4268 Expr *Idx, SourceLocation RLoc);
4269 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4270 Expr *Idx, SourceLocation RLoc);
4271 ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4272 Expr *LowerBound, SourceLocation ColonLoc,
4273 Expr *Length, SourceLocation RBLoc);
4274
4275 // This struct is for use by ActOnMemberAccess to allow
4276 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
4277 // changing the access operator from a '.' to a '->' (to see if that is the
4278 // change needed to fix an error about an unknown member, e.g. when the class
4279 // defines a custom operator->).
4280 struct ActOnMemberAccessExtraArgs {
4281 Scope *S;
4282 UnqualifiedId &Id;
4283 Decl *ObjCImpDecl;
4284 };
4285
4286 ExprResult BuildMemberReferenceExpr(
4287 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
4288 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4289 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
4290 const TemplateArgumentListInfo *TemplateArgs,
4291 const Scope *S,
4292 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4293
4294 ExprResult
4295 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
4296 bool IsArrow, const CXXScopeSpec &SS,
4297 SourceLocation TemplateKWLoc,
4298 NamedDecl *FirstQualifierInScope, LookupResult &R,
4299 const TemplateArgumentListInfo *TemplateArgs,
4300 const Scope *S,
4301 bool SuppressQualifierCheck = false,
4302 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4303
4304 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
4305 SourceLocation OpLoc,
4306 const CXXScopeSpec &SS, FieldDecl *Field,
4307 DeclAccessPair FoundDecl,
4308 const DeclarationNameInfo &MemberNameInfo);
4309
4310 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
4311
4312 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
4313 const CXXScopeSpec &SS,
4314 const LookupResult &R);
4315
4316 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
4317 bool IsArrow, SourceLocation OpLoc,
4318 const CXXScopeSpec &SS,
4319 SourceLocation TemplateKWLoc,
4320 NamedDecl *FirstQualifierInScope,
4321 const DeclarationNameInfo &NameInfo,
4322 const TemplateArgumentListInfo *TemplateArgs);
4323
4324 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
4325 SourceLocation OpLoc,
4326 tok::TokenKind OpKind,
4327 CXXScopeSpec &SS,
4328 SourceLocation TemplateKWLoc,
4329 UnqualifiedId &Member,
4330 Decl *ObjCImpDecl);
4331
4332 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
4333 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4334 FunctionDecl *FDecl,
4335 const FunctionProtoType *Proto,
4336 ArrayRef<Expr *> Args,
4337 SourceLocation RParenLoc,
4338 bool ExecConfig = false);
4339 void CheckStaticArrayArgument(SourceLocation CallLoc,
4340 ParmVarDecl *Param,
4341 const Expr *ArgExpr);
4342
4343 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4344 /// This provides the location of the left/right parens and a list of comma
4345 /// locations.
4346 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4347 MultiExprArg ArgExprs, SourceLocation RParenLoc,
4348 Expr *ExecConfig = nullptr,
4349 bool IsExecConfig = false);
4350 ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4351 SourceLocation LParenLoc,
4352 ArrayRef<Expr *> Arg,
4353 SourceLocation RParenLoc,
4354 Expr *Config = nullptr,
4355 bool IsExecConfig = false);
4356
4357 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4358 MultiExprArg ExecConfig,
4359 SourceLocation GGGLoc);
4360
4361 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4362 Declarator &D, ParsedType &Ty,
4363 SourceLocation RParenLoc, Expr *CastExpr);
4364 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
4365 TypeSourceInfo *Ty,
4366 SourceLocation RParenLoc,
4367 Expr *Op);
4368 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
4369
4370 /// \brief Build an altivec or OpenCL literal.
4371 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
4372 SourceLocation RParenLoc, Expr *E,
4373 TypeSourceInfo *TInfo);
4374
4375 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
4376
4377 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
4378 ParsedType Ty,
4379 SourceLocation RParenLoc,
4380 Expr *InitExpr);
4381
4382 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
4383 TypeSourceInfo *TInfo,
4384 SourceLocation RParenLoc,
4385 Expr *LiteralExpr);
4386
4387 ExprResult ActOnInitList(SourceLocation LBraceLoc,
4388 MultiExprArg InitArgList,
4389 SourceLocation RBraceLoc);
4390
4391 ExprResult ActOnDesignatedInitializer(Designation &Desig,
4392 SourceLocation Loc,
4393 bool GNUSyntax,
4394 ExprResult Init);
4395
4396private:
4397 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
4398
4399public:
4400 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
4401 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
4402 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
4403 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
4404 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
4405 Expr *LHSExpr, Expr *RHSExpr);
4406
4407 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
4408
4409 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
4410 /// in the case of a the GNU conditional expr extension.
4411 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
4412 SourceLocation ColonLoc,
4413 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
4414
4415 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4416 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
4417 LabelDecl *TheDecl);
4418
4419 void ActOnStartStmtExpr();
4420 ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
4421 SourceLocation RPLoc); // "({..})"
4422 void ActOnStmtExprError();
4423
4424 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
4425 struct OffsetOfComponent {
4426 SourceLocation LocStart, LocEnd;
4427 bool isBrackets; // true if [expr], false if .ident
4428 union {
4429 IdentifierInfo *IdentInfo;
4430 Expr *E;
4431 } U;
4432 };
4433
4434 /// __builtin_offsetof(type, a.b[123][456].c)
4435 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
4436 TypeSourceInfo *TInfo,
4437 ArrayRef<OffsetOfComponent> Components,
4438 SourceLocation RParenLoc);
4439 ExprResult ActOnBuiltinOffsetOf(Scope *S,
4440 SourceLocation BuiltinLoc,
4441 SourceLocation TypeLoc,
4442 ParsedType ParsedArgTy,
4443 ArrayRef<OffsetOfComponent> Components,
4444 SourceLocation RParenLoc);
4445
4446 // __builtin_choose_expr(constExpr, expr1, expr2)
4447 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
4448 Expr *CondExpr, Expr *LHSExpr,
4449 Expr *RHSExpr, SourceLocation RPLoc);
4450
4451 // __builtin_va_arg(expr, type)
4452 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
4453 SourceLocation RPLoc);
4454 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
4455 TypeSourceInfo *TInfo, SourceLocation RPLoc);
4456
4457 // __null
4458 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
4459
4460 bool CheckCaseExpression(Expr *E);
4461
4462 /// \brief Describes the result of an "if-exists" condition check.
4463 enum IfExistsResult {
4464 /// \brief The symbol exists.
4465 IER_Exists,
4466
4467 /// \brief The symbol does not exist.
4468 IER_DoesNotExist,
4469
4470 /// \brief The name is a dependent name, so the results will differ
4471 /// from one instantiation to the next.
4472 IER_Dependent,
4473
4474 /// \brief An error occurred.
4475 IER_Error
4476 };
4477
4478 IfExistsResult
4479 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
4480 const DeclarationNameInfo &TargetNameInfo);
4481
4482 IfExistsResult
4483 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
4484 bool IsIfExists, CXXScopeSpec &SS,
4485 UnqualifiedId &Name);
4486
4487 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4488 bool IsIfExists,
4489 NestedNameSpecifierLoc QualifierLoc,
4490 DeclarationNameInfo NameInfo,
4491 Stmt *Nested);
4492 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
4493 bool IsIfExists,
4494 CXXScopeSpec &SS, UnqualifiedId &Name,
4495 Stmt *Nested);
4496
4497 //===------------------------- "Block" Extension ------------------------===//
4498
4499 /// ActOnBlockStart - This callback is invoked when a block literal is
4500 /// started.
4501 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
4502
4503 /// ActOnBlockArguments - This callback allows processing of block arguments.
4504 /// If there are no arguments, this is still invoked.
4505 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
4506 Scope *CurScope);
4507
4508 /// ActOnBlockError - If there is an error parsing a block, this callback
4509 /// is invoked to pop the information about the block from the action impl.
4510 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
4511
4512 /// ActOnBlockStmtExpr - This is called when the body of a block statement
4513 /// literal was successfully completed. ^(int x){...}
4514 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
4515 Scope *CurScope);
4516
4517 //===---------------------------- Clang Extensions ----------------------===//
4518
4519 /// __builtin_convertvector(...)
4520 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4521 SourceLocation BuiltinLoc,
4522 SourceLocation RParenLoc);
4523
4524 //===---------------------------- OpenCL Features -----------------------===//
4525
4526 /// __builtin_astype(...)
4527 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4528 SourceLocation BuiltinLoc,
4529 SourceLocation RParenLoc);
4530
4531 //===---------------------------- C++ Features --------------------------===//
4532
4533 // Act on C++ namespaces
4534 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
4535 SourceLocation NamespaceLoc,
4536 SourceLocation IdentLoc,
4537 IdentifierInfo *Ident,
4538 SourceLocation LBrace,
4539 AttributeList *AttrList,
4540 UsingDirectiveDecl * &UsingDecl);
4541 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
4542
4543 NamespaceDecl *getStdNamespace() const;
4544 NamespaceDecl *getOrCreateStdNamespace();
4545
4546 NamespaceDecl *lookupStdExperimentalNamespace();
4547
4548 CXXRecordDecl *getStdBadAlloc() const;
4549 EnumDecl *getStdAlignValT() const;
4550
4551 /// \brief Tests whether Ty is an instance of std::initializer_list and, if
4552 /// it is and Element is not NULL, assigns the element type to Element.
4553 bool isStdInitializerList(QualType Ty, QualType *Element);
4554
4555 /// \brief Looks for the std::initializer_list template and instantiates it
4556 /// with Element, or emits an error if it's not found.
4557 ///
4558 /// \returns The instantiated template, or null on error.
4559 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
4560
4561 /// \brief Determine whether Ctor is an initializer-list constructor, as
4562 /// defined in [dcl.init.list]p2.
4563 bool isInitListConstructor(const FunctionDecl *Ctor);
4564
4565 Decl *ActOnUsingDirective(Scope *CurScope,
4566 SourceLocation UsingLoc,
4567 SourceLocation NamespcLoc,
4568 CXXScopeSpec &SS,
4569 SourceLocation IdentLoc,
4570 IdentifierInfo *NamespcName,
4571 AttributeList *AttrList);
4572
4573 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
4574
4575 Decl *ActOnNamespaceAliasDef(Scope *CurScope,
4576 SourceLocation NamespaceLoc,
4577 SourceLocation AliasLoc,
4578 IdentifierInfo *Alias,
4579 CXXScopeSpec &SS,
4580 SourceLocation IdentLoc,
4581 IdentifierInfo *Ident);
4582
4583 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
4584 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
4585 const LookupResult &PreviousDecls,
4586 UsingShadowDecl *&PrevShadow);
4587 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
4588 NamedDecl *Target,
4589 UsingShadowDecl *PrevDecl);
4590
4591 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4592 bool HasTypenameKeyword,
4593 const CXXScopeSpec &SS,
4594 SourceLocation NameLoc,
4595 const LookupResult &Previous);
4596 bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
4597 bool HasTypename,
4598 const CXXScopeSpec &SS,
4599 const DeclarationNameInfo &NameInfo,
4600 SourceLocation NameLoc);
4601
4602 NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
4603 SourceLocation UsingLoc,
4604 bool HasTypenameKeyword,
4605 SourceLocation TypenameLoc,
4606 CXXScopeSpec &SS,
4607 DeclarationNameInfo NameInfo,
4608 SourceLocation EllipsisLoc,
4609 AttributeList *AttrList,
4610 bool IsInstantiation);
4611 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
4612 ArrayRef<NamedDecl *> Expansions);
4613
4614 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
4615
4616 /// Given a derived-class using shadow declaration for a constructor and the
4617 /// correspnding base class constructor, find or create the implicit
4618 /// synthesized derived class constructor to use for this initialization.
4619 CXXConstructorDecl *
4620 findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
4621 ConstructorUsingShadowDecl *DerivedShadow);
4622
4623 Decl *ActOnUsingDeclaration(Scope *CurScope,
4624 AccessSpecifier AS,
4625 SourceLocation UsingLoc,
4626 SourceLocation TypenameLoc,
4627 CXXScopeSpec &SS,
4628 UnqualifiedId &Name,
4629 SourceLocation EllipsisLoc,
4630 AttributeList *AttrList);
4631 Decl *ActOnAliasDeclaration(Scope *CurScope,
4632 AccessSpecifier AS,
4633 MultiTemplateParamsArg TemplateParams,
4634 SourceLocation UsingLoc,
4635 UnqualifiedId &Name,
4636 AttributeList *AttrList,
4637 TypeResult Type,
4638 Decl *DeclFromDeclSpec);
4639
4640 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
4641 /// including handling of its default argument expressions.
4642 ///
4643 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
4644 ExprResult
4645 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4646 NamedDecl *FoundDecl,
4647 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
4648 bool HadMultipleCandidates, bool IsListInitialization,
4649 bool IsStdInitListInitialization,
4650 bool RequiresZeroInit, unsigned ConstructKind,
4651 SourceRange ParenRange);
4652
4653 /// Build a CXXConstructExpr whose constructor has already been resolved if
4654 /// it denotes an inherited constructor.
4655 ExprResult
4656 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4657 CXXConstructorDecl *Constructor, bool Elidable,
4658 MultiExprArg Exprs,
4659 bool HadMultipleCandidates, bool IsListInitialization,
4660 bool IsStdInitListInitialization,
4661 bool RequiresZeroInit, unsigned ConstructKind,
4662 SourceRange ParenRange);
4663
4664 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
4665 // the constructor can be elidable?
4666 ExprResult
4667 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4668 NamedDecl *FoundDecl,
4669 CXXConstructorDecl *Constructor, bool Elidable,
4670 MultiExprArg Exprs, bool HadMultipleCandidates,
4671 bool IsListInitialization,
4672 bool IsStdInitListInitialization, bool RequiresZeroInit,
4673 unsigned ConstructKind, SourceRange ParenRange);
4674
4675 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
4676
4677
4678 /// Instantiate or parse a C++ default argument expression as necessary.
4679 /// Return true on error.
4680 bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4681 ParmVarDecl *Param);
4682
4683 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
4684 /// the default expr if needed.
4685 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4686 FunctionDecl *FD,
4687 ParmVarDecl *Param);
4688
4689 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
4690 /// constructed variable.
4691 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
4692
4693 /// \brief Helper class that collects exception specifications for
4694 /// implicitly-declared special member functions.
4695 class ImplicitExceptionSpecification {
4696 // Pointer to allow copying
4697 Sema *Self;
4698 // We order exception specifications thus:
4699 // noexcept is the most restrictive, but is only used in C++11.
4700 // throw() comes next.
4701 // Then a throw(collected exceptions)
4702 // Finally no specification, which is expressed as noexcept(false).
4703 // throw(...) is used instead if any called function uses it.
4704 ExceptionSpecificationType ComputedEST;
4705 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
4706 SmallVector<QualType, 4> Exceptions;
4707
4708 void ClearExceptions() {
4709 ExceptionsSeen.clear();
4710 Exceptions.clear();
4711 }
4712
4713 public:
4714 explicit ImplicitExceptionSpecification(Sema &Self)
4715 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
4716 if (!Self.getLangOpts().CPlusPlus11)
4717 ComputedEST = EST_DynamicNone;
4718 }
4719
4720 /// \brief Get the computed exception specification type.
4721 ExceptionSpecificationType getExceptionSpecType() const {
4722 assert(ComputedEST != EST_ComputedNoexcept &&(static_cast <bool> (ComputedEST != EST_ComputedNoexcept
&& "noexcept(expr) should not be a possible result")
? void (0) : __assert_fail ("ComputedEST != EST_ComputedNoexcept && \"noexcept(expr) should not be a possible result\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/Sema/Sema.h"
, 4723, __extension__ __PRETTY_FUNCTION__))
4723 "noexcept(expr) should not be a possible result")(static_cast <bool> (ComputedEST != EST_ComputedNoexcept
&& "noexcept(expr) should not be a possible result")
? void (0) : __assert_fail ("ComputedEST != EST_ComputedNoexcept && \"noexcept(expr) should not be a possible result\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/Sema/Sema.h"
, 4723, __extension__ __PRETTY_FUNCTION__))
;
4724 return ComputedEST;
4725 }
4726
4727 /// \brief The number of exceptions in the exception specification.
4728 unsigned size() const { return Exceptions.size(); }
4729
4730 /// \brief The set of exceptions in the exception specification.
4731 const QualType *data() const { return Exceptions.data(); }
4732
4733 /// \brief Integrate another called method into the collected data.
4734 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
4735
4736 /// \brief Integrate an invoked expression into the collected data.
4737 void CalledExpr(Expr *E);
4738
4739 /// \brief Overwrite an EPI's exception specification with this
4740 /// computed exception specification.
4741 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
4742 FunctionProtoType::ExceptionSpecInfo ESI;
4743 ESI.Type = getExceptionSpecType();
4744 if (ESI.Type == EST_Dynamic) {
4745 ESI.Exceptions = Exceptions;
4746 } else if (ESI.Type == EST_None) {
4747 /// C++11 [except.spec]p14:
4748 /// The exception-specification is noexcept(false) if the set of
4749 /// potential exceptions of the special member function contains "any"
4750 ESI.Type = EST_ComputedNoexcept;
4751 ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
4752 tok::kw_false).get();
4753 }
4754 return ESI;
4755 }
4756 };
4757
4758 /// \brief Determine what sort of exception specification a defaulted
4759 /// copy constructor of a class will have.
4760 ImplicitExceptionSpecification
4761 ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
4762 CXXMethodDecl *MD);
4763
4764 /// \brief Determine what sort of exception specification a defaulted
4765 /// default constructor of a class will have, and whether the parameter
4766 /// will be const.
4767 ImplicitExceptionSpecification
4768 ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
4769
4770 /// \brief Determine what sort of exception specification a defautled
4771 /// copy assignment operator of a class will have, and whether the
4772 /// parameter will be const.
4773 ImplicitExceptionSpecification
4774 ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
4775
4776 /// \brief Determine what sort of exception specification a defaulted move
4777 /// constructor of a class will have.
4778 ImplicitExceptionSpecification
4779 ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
4780
4781 /// \brief Determine what sort of exception specification a defaulted move
4782 /// assignment operator of a class will have.
4783 ImplicitExceptionSpecification
4784 ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
4785
4786 /// \brief Determine what sort of exception specification a defaulted
4787 /// destructor of a class will have.
4788 ImplicitExceptionSpecification
4789 ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
4790
4791 /// \brief Determine what sort of exception specification an inheriting
4792 /// constructor of a class will have.
4793 ImplicitExceptionSpecification
4794 ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
4795 CXXConstructorDecl *CD);
4796
4797 /// \brief Evaluate the implicit exception specification for a defaulted
4798 /// special member function.
4799 void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
4800
4801 /// \brief Check the given exception-specification and update the
4802 /// exception specification information with the results.
4803 void checkExceptionSpecification(bool IsTopLevel,
4804 ExceptionSpecificationType EST,
4805 ArrayRef<ParsedType> DynamicExceptions,
4806 ArrayRef<SourceRange> DynamicExceptionRanges,
4807 Expr *NoexceptExpr,
4808 SmallVectorImpl<QualType> &Exceptions,
4809 FunctionProtoType::ExceptionSpecInfo &ESI);
4810
4811 /// \brief Determine if we're in a case where we need to (incorrectly) eagerly
4812 /// parse an exception specification to work around a libstdc++ bug.
4813 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
4814
4815 /// \brief Add an exception-specification to the given member function
4816 /// (or member function template). The exception-specification was parsed
4817 /// after the method itself was declared.
4818 void actOnDelayedExceptionSpecification(Decl *Method,
4819 ExceptionSpecificationType EST,
4820 SourceRange SpecificationRange,
4821 ArrayRef<ParsedType> DynamicExceptions,
4822 ArrayRef<SourceRange> DynamicExceptionRanges,
4823 Expr *NoexceptExpr);
4824
4825 class InheritedConstructorInfo;
4826
4827 /// \brief Determine if a special member function should have a deleted
4828 /// definition when it is defaulted.
4829 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4830 InheritedConstructorInfo *ICI = nullptr,
4831 bool Diagnose = false);
4832
4833 /// \brief Declare the implicit default constructor for the given class.
4834 ///
4835 /// \param ClassDecl The class declaration into which the implicit
4836 /// default constructor will be added.
4837 ///
4838 /// \returns The implicitly-declared default constructor.
4839 CXXConstructorDecl *DeclareImplicitDefaultConstructor(
4840 CXXRecordDecl *ClassDecl);
4841
4842 /// DefineImplicitDefaultConstructor - Checks for feasibility of
4843 /// defining this constructor as the default constructor.
4844 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4845 CXXConstructorDecl *Constructor);
4846
4847 /// \brief Declare the implicit destructor for the given class.
4848 ///
4849 /// \param ClassDecl The class declaration into which the implicit
4850 /// destructor will be added.
4851 ///
4852 /// \returns The implicitly-declared destructor.
4853 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
4854
4855 /// DefineImplicitDestructor - Checks for feasibility of
4856 /// defining this destructor as the default destructor.
4857 void DefineImplicitDestructor(SourceLocation CurrentLocation,
4858 CXXDestructorDecl *Destructor);
4859
4860 /// \brief Build an exception spec for destructors that don't have one.
4861 ///
4862 /// C++11 says that user-defined destructors with no exception spec get one
4863 /// that looks as if the destructor was implicitly declared.
4864 void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
4865 CXXDestructorDecl *Destructor);
4866
4867 /// \brief Define the specified inheriting constructor.
4868 void DefineInheritingConstructor(SourceLocation UseLoc,
4869 CXXConstructorDecl *Constructor);
4870
4871 /// \brief Declare the implicit copy constructor for the given class.
4872 ///
4873 /// \param ClassDecl The class declaration into which the implicit
4874 /// copy constructor will be added.
4875 ///
4876 /// \returns The implicitly-declared copy constructor.
4877 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
4878
4879 /// DefineImplicitCopyConstructor - Checks for feasibility of
4880 /// defining this constructor as the copy constructor.
4881 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
4882 CXXConstructorDecl *Constructor);
4883
4884 /// \brief Declare the implicit move constructor for the given class.
4885 ///
4886 /// \param ClassDecl The Class declaration into which the implicit
4887 /// move constructor will be added.
4888 ///
4889 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
4890 /// declared.
4891 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
4892
4893 /// DefineImplicitMoveConstructor - Checks for feasibility of
4894 /// defining this constructor as the move constructor.
4895 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
4896 CXXConstructorDecl *Constructor);
4897
4898 /// \brief Declare the implicit copy assignment operator for the given class.
4899 ///
4900 /// \param ClassDecl The class declaration into which the implicit
4901 /// copy assignment operator will be added.
4902 ///
4903 /// \returns The implicitly-declared copy assignment operator.
4904 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
4905
4906 /// \brief Defines an implicitly-declared copy assignment operator.
4907 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4908 CXXMethodDecl *MethodDecl);
4909
4910 /// \brief Declare the implicit move assignment operator for the given class.
4911 ///
4912 /// \param ClassDecl The Class declaration into which the implicit
4913 /// move assignment operator will be added.
4914 ///
4915 /// \returns The implicitly-declared move assignment operator, or NULL if it
4916 /// wasn't declared.
4917 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
4918
4919 /// \brief Defines an implicitly-declared move assignment operator.
4920 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
4921 CXXMethodDecl *MethodDecl);
4922
4923 /// \brief Force the declaration of any implicitly-declared members of this
4924 /// class.
4925 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
4926
4927 /// \brief Check a completed declaration of an implicit special member.
4928 void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
4929
4930 /// \brief Determine whether the given function is an implicitly-deleted
4931 /// special member function.
4932 bool isImplicitlyDeleted(FunctionDecl *FD);
4933
4934 /// \brief Check whether 'this' shows up in the type of a static member
4935 /// function after the (naturally empty) cv-qualifier-seq would be.
4936 ///
4937 /// \returns true if an error occurred.
4938 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
4939
4940 /// \brief Whether this' shows up in the exception specification of a static
4941 /// member function.
4942 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
4943
4944 /// \brief Check whether 'this' shows up in the attributes of the given
4945 /// static member function.
4946 ///
4947 /// \returns true if an error occurred.
4948 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
4949
4950 /// MaybeBindToTemporary - If the passed in expression has a record type with
4951 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
4952 /// it simply returns the passed in expression.
4953 ExprResult MaybeBindToTemporary(Expr *E);
4954
4955 bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
4956 MultiExprArg ArgsPtr,
4957 SourceLocation Loc,
4958 SmallVectorImpl<Expr*> &ConvertedArgs,
4959 bool AllowExplicit = false,
4960 bool IsListInitialization = false);
4961
4962 ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
4963 SourceLocation NameLoc,
4964 IdentifierInfo &Name);
4965
4966 ParsedType getDestructorName(SourceLocation TildeLoc,
4967 IdentifierInfo &II, SourceLocation NameLoc,
4968 Scope *S, CXXScopeSpec &SS,
4969 ParsedType ObjectType,
4970 bool EnteringContext);
4971
4972 ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
4973 ParsedType ObjectType);
4974
4975 // Checks that reinterpret casts don't have undefined behavior.
4976 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
4977 bool IsDereference, SourceRange Range);
4978
4979 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
4980 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
4981 tok::TokenKind Kind,
4982 SourceLocation LAngleBracketLoc,
4983 Declarator &D,
4984 SourceLocation RAngleBracketLoc,
4985 SourceLocation LParenLoc,
4986 Expr *E,
4987 SourceLocation RParenLoc);
4988
4989 ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
4990 tok::TokenKind Kind,
4991 TypeSourceInfo *Ty,
4992 Expr *E,
4993 SourceRange AngleBrackets,
4994 SourceRange Parens);
4995
4996 ExprResult BuildCXXTypeId(QualType TypeInfoType,
4997 SourceLocation TypeidLoc,
4998 TypeSourceInfo *Operand,
4999 SourceLocation RParenLoc);
5000 ExprResult BuildCXXTypeId(QualType TypeInfoType,
5001 SourceLocation TypeidLoc,
5002 Expr *Operand,
5003 SourceLocation RParenLoc);
5004
5005 /// ActOnCXXTypeid - Parse typeid( something ).
5006 ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
5007 SourceLocation LParenLoc, bool isType,
5008 void *TyOrExpr,
5009 SourceLocation RParenLoc);
5010
5011 ExprResult BuildCXXUuidof(QualType TypeInfoType,
5012 SourceLocation TypeidLoc,
5013 TypeSourceInfo *Operand,
5014 SourceLocation RParenLoc);
5015 ExprResult BuildCXXUuidof(QualType TypeInfoType,
5016 SourceLocation TypeidLoc,
5017 Expr *Operand,
5018 SourceLocation RParenLoc);
5019
5020 /// ActOnCXXUuidof - Parse __uuidof( something ).
5021 ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
5022 SourceLocation LParenLoc, bool isType,
5023 void *TyOrExpr,
5024 SourceLocation RParenLoc);
5025
5026 /// \brief Handle a C++1z fold-expression: ( expr op ... op expr ).
5027 ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
5028 tok::TokenKind Operator,
5029 SourceLocation EllipsisLoc, Expr *RHS,
5030 SourceLocation RParenLoc);
5031 ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
5032 BinaryOperatorKind Operator,
5033 SourceLocation EllipsisLoc, Expr *RHS,
5034 SourceLocation RParenLoc);
5035 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
5036 BinaryOperatorKind Operator);
5037
5038 //// ActOnCXXThis - Parse 'this' pointer.
5039 ExprResult ActOnCXXThis(SourceLocation loc);
5040
5041 /// \brief Try to retrieve the type of the 'this' pointer.
5042 ///
5043 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
5044 QualType getCurrentThisType();
5045
5046 /// \brief When non-NULL, the C++ 'this' expression is allowed despite the
5047 /// current context not being a non-static member function. In such cases,
5048 /// this provides the type used for 'this'.
5049 QualType CXXThisTypeOverride;
5050
5051 /// \brief RAII object used to temporarily allow the C++ 'this' expression
5052 /// to be used, with the given qualifiers on the current class type.
5053 class CXXThisScopeRAII {
5054 Sema &S;
5055 QualType OldCXXThisTypeOverride;
5056 bool Enabled;
5057
5058 public:
5059 /// \brief Introduce a new scope where 'this' may be allowed (when enabled),
5060 /// using the given declaration (which is either a class template or a
5061 /// class) along with the given qualifiers.
5062 /// along with the qualifiers placed on '*this'.
5063 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals,
5064 bool Enabled = true);
5065
5066 ~CXXThisScopeRAII();
5067 };
5068
5069 /// \brief Make sure the value of 'this' is actually available in the current
5070 /// context, if it is a potentially evaluated context.
5071 ///
5072 /// \param Loc The location at which the capture of 'this' occurs.
5073 ///
5074 /// \param Explicit Whether 'this' is explicitly captured in a lambda
5075 /// capture list.
5076 ///
5077 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
5078 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
5079 /// This is useful when enclosing lambdas must speculatively capture
5080 /// 'this' that may or may not be used in certain specializations of
5081 /// a nested generic lambda (depending on whether the name resolves to
5082 /// a non-static member function or a static function).
5083 /// \return returns 'true' if failed, 'false' if success.
5084 bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
5085 bool BuildAndDiagnose = true,
5086 const unsigned *const FunctionScopeIndexToStopAt = nullptr,
5087 bool ByCopy = false);
5088
5089 /// \brief Determine whether the given type is the type of *this that is used
5090 /// outside of the body of a member function for a type that is currently
5091 /// being defined.
5092 bool isThisOutsideMemberFunctionBody(QualType BaseType);
5093
5094 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
5095 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
5096
5097
5098 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
5099 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
5100
5101 ExprResult
5102 ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
5103 SourceLocation AtLoc, SourceLocation RParen);
5104
5105 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
5106 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
5107
5108 //// ActOnCXXThrow - Parse throw expressions.
5109 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
5110 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
5111 bool IsThrownVarInScope);
5112 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
5113
5114 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
5115 /// Can be interpreted either as function-style casting ("int(x)")
5116 /// or class type construction ("ClassType(x,y,z)")
5117 /// or creation of a value-initialized type ("int()").
5118 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
5119 SourceLocation LParenOrBraceLoc,
5120 MultiExprArg Exprs,
5121 SourceLocation RParenOrBraceLoc,
5122 bool ListInitialization);
5123
5124 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
5125 SourceLocation LParenLoc,
5126 MultiExprArg Exprs,
5127 SourceLocation RParenLoc,
5128 bool ListInitialization);
5129
5130 /// ActOnCXXNew - Parsed a C++ 'new' expression.
5131 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
5132 SourceLocation PlacementLParen,
5133 MultiExprArg PlacementArgs,
5134 SourceLocation PlacementRParen,
5135 SourceRange TypeIdParens, Declarator &D,
5136 Expr *Initializer);
5137 ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
5138 SourceLocation PlacementLParen,
5139 MultiExprArg PlacementArgs,
5140 SourceLocation PlacementRParen,
5141 SourceRange TypeIdParens,
5142 QualType AllocType,
5143 TypeSourceInfo *AllocTypeInfo,
5144 Expr *ArraySize,
5145 SourceRange DirectInitRange,
5146 Expr *Initializer);
5147
5148 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
5149 SourceRange R);
5150 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
5151 bool UseGlobal, QualType AllocType, bool IsArray,
5152 bool &PassAlignment, MultiExprArg PlaceArgs,
5153 FunctionDecl *&OperatorNew,
5154 FunctionDecl *&OperatorDelete,
5155 bool Diagnose = true);
5156 void DeclareGlobalNewDelete();
5157 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
5158 ArrayRef<QualType> Params);
5159
5160 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
5161 DeclarationName Name, FunctionDecl* &Operator,
5162 bool Diagnose = true);
5163 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
5164 bool CanProvideSize,
5165 bool Overaligned,
5166 DeclarationName Name);
5167 FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
5168 CXXRecordDecl *RD);
5169
5170 /// ActOnCXXDelete - Parsed a C++ 'delete' expression
5171 ExprResult ActOnCXXDelete(SourceLocation StartLoc,
5172 bool UseGlobal, bool ArrayForm,
5173 Expr *Operand);
5174 void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
5175 bool IsDelete, bool CallCanBeVirtual,
5176 bool WarnOnNonAbstractTypes,
5177 SourceLocation DtorLoc);
5178
5179 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
5180 Expr *Operand, SourceLocation RParen);
5181 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
5182 SourceLocation RParen);
5183
5184 /// \brief Parsed one of the type trait support pseudo-functions.
5185 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5186 ArrayRef<ParsedType> Args,
5187 SourceLocation RParenLoc);
5188 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5189 ArrayRef<TypeSourceInfo *> Args,
5190 SourceLocation RParenLoc);
5191
5192 /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
5193 /// pseudo-functions.
5194 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5195 SourceLocation KWLoc,
5196 ParsedType LhsTy,
5197 Expr *DimExpr,
5198 SourceLocation RParen);
5199
5200 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
5201 SourceLocation KWLoc,
5202 TypeSourceInfo *TSInfo,
5203 Expr *DimExpr,
5204 SourceLocation RParen);
5205
5206 /// ActOnExpressionTrait - Parsed one of the unary type trait support
5207 /// pseudo-functions.
5208 ExprResult ActOnExpressionTrait(ExpressionTrait OET,
5209 SourceLocation KWLoc,
5210 Expr *Queried,
5211 SourceLocation RParen);
5212
5213 ExprResult BuildExpressionTrait(ExpressionTrait OET,
5214 SourceLocation KWLoc,
5215 Expr *Queried,
5216 SourceLocation RParen);
5217
5218 ExprResult ActOnStartCXXMemberReference(Scope *S,
5219 Expr *Base,
5220 SourceLocation OpLoc,
5221 tok::TokenKind OpKind,
5222 ParsedType &ObjectType,
5223 bool &MayBePseudoDestructor);
5224
5225 ExprResult BuildPseudoDestructorExpr(Expr *Base,
5226 SourceLocation OpLoc,
5227 tok::TokenKind OpKind,
5228 const CXXScopeSpec &SS,
5229 TypeSourceInfo *ScopeType,
5230 SourceLocation CCLoc,
5231 SourceLocation TildeLoc,
5232 PseudoDestructorTypeStorage DestroyedType);
5233
5234 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5235 SourceLocation OpLoc,
5236 tok::TokenKind OpKind,
5237 CXXScopeSpec &SS,
5238 UnqualifiedId &FirstTypeName,
5239 SourceLocation CCLoc,
5240 SourceLocation TildeLoc,
5241 UnqualifiedId &SecondTypeName);
5242
5243 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5244 SourceLocation OpLoc,
5245 tok::TokenKind OpKind,
5246 SourceLocation TildeLoc,
5247 const DeclSpec& DS);
5248
5249 /// MaybeCreateExprWithCleanups - If the current full-expression
5250 /// requires any cleanups, surround it with a ExprWithCleanups node.
5251 /// Otherwise, just returns the passed-in expression.
5252 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
5253 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
5254 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
5255
5256 MaterializeTemporaryExpr *
5257 CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
5258 bool BoundToLvalueReference);
5259
5260 ExprResult ActOnFinishFullExpr(Expr *Expr) {
5261 return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc()
5262 : SourceLocation());
5263 }
5264 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
5265 bool DiscardedValue = false,
5266 bool IsConstexpr = false,
5267 bool IsLambdaInitCaptureInitializer = false);
5268 StmtResult ActOnFinishFullStmt(Stmt *Stmt);
5269
5270 // Marks SS invalid if it represents an incomplete type.
5271 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
5272
5273 DeclContext *computeDeclContext(QualType T);
5274 DeclContext *computeDeclContext(const CXXScopeSpec &SS,
5275 bool EnteringContext = false);
5276 bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
5277 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
5278
5279 /// \brief The parser has parsed a global nested-name-specifier '::'.
5280 ///
5281 /// \param CCLoc The location of the '::'.
5282 ///
5283 /// \param SS The nested-name-specifier, which will be updated in-place
5284 /// to reflect the parsed nested-name-specifier.
5285 ///
5286 /// \returns true if an error occurred, false otherwise.
5287 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
5288
5289 /// \brief The parser has parsed a '__super' nested-name-specifier.
5290 ///
5291 /// \param SuperLoc The location of the '__super' keyword.
5292 ///
5293 /// \param ColonColonLoc The location of the '::'.
5294 ///
5295 /// \param SS The nested-name-specifier, which will be updated in-place
5296 /// to reflect the parsed nested-name-specifier.
5297 ///
5298 /// \returns true if an error occurred, false otherwise.
5299 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
5300 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
5301
5302 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
5303 bool *CanCorrect = nullptr);
5304 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
5305
5306 /// \brief Keeps information about an identifier in a nested-name-spec.
5307 ///
5308 struct NestedNameSpecInfo {
5309 /// \brief The type of the object, if we're parsing nested-name-specifier in
5310 /// a member access expression.
5311 ParsedType ObjectType;
5312
5313 /// \brief The identifier preceding the '::'.
5314 IdentifierInfo *Identifier;
5315
5316 /// \brief The location of the identifier.
5317 SourceLocation IdentifierLoc;
5318
5319 /// \brief The location of the '::'.
5320 SourceLocation CCLoc;
5321
5322 /// \brief Creates info object for the most typical case.
5323 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5324 SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType())
5325 : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
5326 CCLoc(ColonColonLoc) {
5327 }
5328
5329 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5330 SourceLocation ColonColonLoc, QualType ObjectType)
5331 : ObjectType(ParsedType::make(ObjectType)), Identifier(II),
5332 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {
5333 }
5334 };
5335
5336 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
5337 NestedNameSpecInfo &IdInfo);
5338
5339 bool BuildCXXNestedNameSpecifier(Scope *S,
5340 NestedNameSpecInfo &IdInfo,
5341 bool EnteringContext,
5342 CXXScopeSpec &SS,
5343 NamedDecl *ScopeLookupResult,
5344 bool ErrorRecoveryLookup,
5345 bool *IsCorrectedToColon = nullptr,
5346 bool OnlyNamespace = false);
5347
5348 /// \brief The parser has parsed a nested-name-specifier 'identifier::'.
5349 ///
5350 /// \param S The scope in which this nested-name-specifier occurs.
5351 ///
5352 /// \param IdInfo Parser information about an identifier in the
5353 /// nested-name-spec.
5354 ///
5355 /// \param EnteringContext Whether we're entering the context nominated by
5356 /// this nested-name-specifier.
5357 ///
5358 /// \param SS The nested-name-specifier, which is both an input
5359 /// parameter (the nested-name-specifier before this type) and an
5360 /// output parameter (containing the full nested-name-specifier,
5361 /// including this new type).
5362 ///
5363 /// \param ErrorRecoveryLookup If true, then this method is called to improve
5364 /// error recovery. In this case do not emit error message.
5365 ///
5366 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
5367 /// are allowed. The bool value pointed by this parameter is set to 'true'
5368 /// if the identifier is treated as if it was followed by ':', not '::'.
5369 ///
5370 /// \param OnlyNamespace If true, only considers namespaces in lookup.
5371 ///
5372 /// \returns true if an error occurred, false otherwise.
5373 bool ActOnCXXNestedNameSpecifier(Scope *S,
5374 NestedNameSpecInfo &IdInfo,
5375 bool EnteringContext,
5376 CXXScopeSpec &SS,
5377 bool ErrorRecoveryLookup = false,
5378 bool *IsCorrectedToColon = nullptr,
5379 bool OnlyNamespace = false);
5380
5381 ExprResult ActOnDecltypeExpression(Expr *E);
5382
5383 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
5384 const DeclSpec &DS,
5385 SourceLocation ColonColonLoc);
5386
5387 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
5388 NestedNameSpecInfo &IdInfo,
5389 bool EnteringContext);
5390
5391 /// \brief The parser has parsed a nested-name-specifier
5392 /// 'template[opt] template-name < template-args >::'.
5393 ///
5394 /// \param S The scope in which this nested-name-specifier occurs.
5395 ///
5396 /// \param SS The nested-name-specifier, which is both an input
5397 /// parameter (the nested-name-specifier before this type) and an
5398 /// output parameter (containing the full nested-name-specifier,
5399 /// including this new type).
5400 ///
5401 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
5402 /// \param TemplateName the template name.
5403 /// \param TemplateNameLoc The location of the template name.
5404 /// \param LAngleLoc The location of the opening angle bracket ('<').
5405 /// \param TemplateArgs The template arguments.
5406 /// \param RAngleLoc The location of the closing angle bracket ('>').
5407 /// \param CCLoc The location of the '::'.
5408 ///
5409 /// \param EnteringContext Whether we're entering the context of the
5410 /// nested-name-specifier.
5411 ///
5412 ///
5413 /// \returns true if an error occurred, false otherwise.
5414 bool ActOnCXXNestedNameSpecifier(Scope *S,
5415 CXXScopeSpec &SS,
5416 SourceLocation TemplateKWLoc,
5417 TemplateTy TemplateName,
5418 SourceLocation TemplateNameLoc,
5419 SourceLocation LAngleLoc,
5420 ASTTemplateArgsPtr TemplateArgs,
5421 SourceLocation RAngleLoc,
5422 SourceLocation CCLoc,
5423 bool EnteringContext);
5424
5425 /// \brief Given a C++ nested-name-specifier, produce an annotation value
5426 /// that the parser can use later to reconstruct the given
5427 /// nested-name-specifier.
5428 ///
5429 /// \param SS A nested-name-specifier.
5430 ///
5431 /// \returns A pointer containing all of the information in the
5432 /// nested-name-specifier \p SS.
5433 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
5434
5435 /// \brief Given an annotation pointer for a nested-name-specifier, restore
5436 /// the nested-name-specifier structure.
5437 ///
5438 /// \param Annotation The annotation pointer, produced by
5439 /// \c SaveNestedNameSpecifierAnnotation().
5440 ///
5441 /// \param AnnotationRange The source range corresponding to the annotation.
5442 ///
5443 /// \param SS The nested-name-specifier that will be updated with the contents
5444 /// of the annotation pointer.
5445 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
5446 SourceRange AnnotationRange,
5447 CXXScopeSpec &SS);
5448
5449 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5450
5451 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
5452 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
5453 /// After this method is called, according to [C++ 3.4.3p3], names should be
5454 /// looked up in the declarator-id's scope, until the declarator is parsed and
5455 /// ActOnCXXExitDeclaratorScope is called.
5456 /// The 'SS' should be a non-empty valid CXXScopeSpec.
5457 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
5458
5459 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
5460 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
5461 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
5462 /// Used to indicate that names should revert to being looked up in the
5463 /// defining scope.
5464 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5465
5466 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
5467 /// initializer for the declaration 'Dcl'.
5468 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5469 /// static data member of class X, names should be looked up in the scope of
5470 /// class X.
5471 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
5472
5473 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5474 /// initializer for the declaration 'Dcl'.
5475 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
5476
5477 /// \brief Create a new lambda closure type.
5478 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
5479 TypeSourceInfo *Info,
5480 bool KnownDependent,
5481 LambdaCaptureDefault CaptureDefault);
5482
5483 /// \brief Start the definition of a lambda expression.
5484 CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
5485 SourceRange IntroducerRange,
5486 TypeSourceInfo *MethodType,
5487 SourceLocation EndLoc,
5488 ArrayRef<ParmVarDecl *> Params,
5489 bool IsConstexprSpecified);
5490
5491 /// \brief Endow the lambda scope info with the relevant properties.
5492 void buildLambdaScope(sema::LambdaScopeInfo *LSI,
5493 CXXMethodDecl *CallOperator,
5494 SourceRange IntroducerRange,
5495 LambdaCaptureDefault CaptureDefault,
5496 SourceLocation CaptureDefaultLoc,
5497 bool ExplicitParams,
5498 bool ExplicitResultType,
5499 bool Mutable);
5500
5501 /// \brief Perform initialization analysis of the init-capture and perform
5502 /// any implicit conversions such as an lvalue-to-rvalue conversion if
5503 /// not being used to initialize a reference.
5504 ParsedType actOnLambdaInitCaptureInitialization(
5505 SourceLocation Loc, bool ByRef, IdentifierInfo *Id,
5506 LambdaCaptureInitKind InitKind, Expr *&Init) {
5507 return ParsedType::make(buildLambdaInitCaptureInitialization(
5508 Loc, ByRef, Id, InitKind != LambdaCaptureInitKind::CopyInit, Init));
5509 }
5510 QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef,
5511 IdentifierInfo *Id,
5512 bool DirectInit, Expr *&Init);
5513
5514 /// \brief Create a dummy variable within the declcontext of the lambda's
5515 /// call operator, for name lookup purposes for a lambda init capture.
5516 ///
5517 /// CodeGen handles emission of lambda captures, ignoring these dummy
5518 /// variables appropriately.
5519 VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
5520 QualType InitCaptureType,
5521 IdentifierInfo *Id,
5522 unsigned InitStyle, Expr *Init);
5523
5524 /// \brief Build the implicit field for an init-capture.
5525 FieldDecl *buildInitCaptureField(sema::LambdaScopeInfo *LSI, VarDecl *Var);
5526
5527 /// \brief Note that we have finished the explicit captures for the
5528 /// given lambda.
5529 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
5530
5531 /// \brief Introduce the lambda parameters into scope.
5532 void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope);
5533
5534 /// \brief Deduce a block or lambda's return type based on the return
5535 /// statements present in the body.
5536 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
5537
5538 /// ActOnStartOfLambdaDefinition - This is called just before we start
5539 /// parsing the body of a lambda; it analyzes the explicit captures and
5540 /// arguments, and sets up various data-structures for the body of the
5541 /// lambda.
5542 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
5543 Declarator &ParamInfo, Scope *CurScope);
5544
5545 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
5546 /// is invoked to pop the information about the lambda.
5547 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
5548 bool IsInstantiation = false);
5549
5550 /// ActOnLambdaExpr - This is called when the body of a lambda expression
5551 /// was successfully completed.
5552 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
5553 Scope *CurScope);
5554
5555 /// \brief Does copying/destroying the captured variable have side effects?
5556 bool CaptureHasSideEffects(const sema::LambdaScopeInfo::Capture &From);
5557
5558 /// \brief Diagnose if an explicit lambda capture is unused.
5559 void DiagnoseUnusedLambdaCapture(const sema::LambdaScopeInfo::Capture &From);
5560
5561 /// \brief Complete a lambda-expression having processed and attached the
5562 /// lambda body.
5563 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
5564 sema::LambdaScopeInfo *LSI);
5565
5566 /// Get the return type to use for a lambda's conversion function(s) to
5567 /// function pointer type, given the type of the call operator.
5568 QualType
5569 getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType);
5570
5571 /// \brief Define the "body" of the conversion from a lambda object to a
5572 /// function pointer.
5573 ///
5574 /// This routine doesn't actually define a sensible body; rather, it fills
5575 /// in the initialization expression needed to copy the lambda object into
5576 /// the block, and IR generation actually generates the real body of the
5577 /// block pointer conversion.
5578 void DefineImplicitLambdaToFunctionPointerConversion(
5579 SourceLocation CurrentLoc, CXXConversionDecl *Conv);
5580
5581 /// \brief Define the "body" of the conversion from a lambda object to a
5582 /// block pointer.
5583 ///
5584 /// This routine doesn't actually define a sensible body; rather, it fills
5585 /// in the initialization expression needed to copy the lambda object into
5586 /// the block, and IR generation actually generates the real body of the
5587 /// block pointer conversion.
5588 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
5589 CXXConversionDecl *Conv);
5590
5591 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
5592 SourceLocation ConvLocation,
5593 CXXConversionDecl *Conv,
5594 Expr *Src);
5595
5596 // ParseObjCStringLiteral - Parse Objective-C string literals.
5597 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
5598 ArrayRef<Expr *> Strings);
5599
5600 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
5601
5602 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
5603 /// numeric literal expression. Type of the expression will be "NSNumber *"
5604 /// or "id" if NSNumber is unavailable.
5605 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
5606 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
5607 bool Value);
5608 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
5609
5610 /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
5611 /// '@' prefixed parenthesized expression. The type of the expression will
5612 /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
5613 /// of ValueType, which is allowed to be a built-in numeric type, "char *",
5614 /// "const char *" or C structure with attribute 'objc_boxable'.
5615 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
5616
5617 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
5618 Expr *IndexExpr,
5619 ObjCMethodDecl *getterMethod,
5620 ObjCMethodDecl *setterMethod);
5621
5622 ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
5623 MutableArrayRef<ObjCDictionaryElement> Elements);
5624
5625 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
5626 TypeSourceInfo *EncodedTypeInfo,
5627 SourceLocation RParenLoc);
5628 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
5629 CXXConversionDecl *Method,
5630 bool HadMultipleCandidates);
5631
5632 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
5633 SourceLocation EncodeLoc,
5634 SourceLocation LParenLoc,
5635 ParsedType Ty,
5636 SourceLocation RParenLoc);
5637
5638 /// ParseObjCSelectorExpression - Build selector expression for \@selector
5639 ExprResult ParseObjCSelectorExpression(Selector Sel,
5640 SourceLocation AtLoc,
5641 SourceLocation SelLoc,
5642 SourceLocation LParenLoc,
5643 SourceLocation RParenLoc,
5644 bool WarnMultipleSelectors);
5645
5646 /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
5647 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
5648 SourceLocation AtLoc,
5649 SourceLocation ProtoLoc,
5650 SourceLocation LParenLoc,
5651 SourceLocation ProtoIdLoc,
5652 SourceLocation RParenLoc);
5653
5654 //===--------------------------------------------------------------------===//
5655 // C++ Declarations
5656 //
5657 Decl *ActOnStartLinkageSpecification(Scope *S,
5658 SourceLocation ExternLoc,
5659 Expr *LangStr,
5660 SourceLocation LBraceLoc);
5661 Decl *ActOnFinishLinkageSpecification(Scope *S,
5662 Decl *LinkageSpec,
5663 SourceLocation RBraceLoc);
5664
5665
5666 //===--------------------------------------------------------------------===//
5667 // C++ Classes
5668 //
5669 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
5670 const CXXScopeSpec *SS = nullptr);
5671 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
5672
5673 bool ActOnAccessSpecifier(AccessSpecifier Access,
5674 SourceLocation ASLoc,
5675 SourceLocation ColonLoc,
5676 AttributeList *Attrs = nullptr);
5677
5678 NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
5679 Declarator &D,
5680 MultiTemplateParamsArg TemplateParameterLists,
5681 Expr *BitfieldWidth, const VirtSpecifiers &VS,
5682 InClassInitStyle InitStyle);
5683
5684 void ActOnStartCXXInClassMemberInitializer();
5685 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
5686 SourceLocation EqualLoc,
5687 Expr *Init);
5688
5689 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5690 Scope *S,
5691 CXXScopeSpec &SS,
5692 IdentifierInfo *MemberOrBase,
5693 ParsedType TemplateTypeTy,
5694 const DeclSpec &DS,
5695 SourceLocation IdLoc,
5696 SourceLocation LParenLoc,
5697 ArrayRef<Expr *> Args,
5698 SourceLocation RParenLoc,
5699 SourceLocation EllipsisLoc);
5700
5701 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5702 Scope *S,
5703 CXXScopeSpec &SS,
5704 IdentifierInfo *MemberOrBase,
5705 ParsedType TemplateTypeTy,
5706 const DeclSpec &DS,
5707 SourceLocation IdLoc,
5708 Expr *InitList,
5709 SourceLocation EllipsisLoc);
5710
5711 MemInitResult BuildMemInitializer(Decl *ConstructorD,
5712 Scope *S,
5713 CXXScopeSpec &SS,
5714 IdentifierInfo *MemberOrBase,
5715 ParsedType TemplateTypeTy,
5716 const DeclSpec &DS,
5717 SourceLocation IdLoc,
5718 Expr *Init,
5719 SourceLocation EllipsisLoc);
5720
5721 MemInitResult BuildMemberInitializer(ValueDecl *Member,
5722 Expr *Init,
5723 SourceLocation IdLoc);
5724
5725 MemInitResult BuildBaseInitializer(QualType BaseType,
5726 TypeSourceInfo *BaseTInfo,
5727 Expr *Init,
5728 CXXRecordDecl *ClassDecl,
5729 SourceLocation EllipsisLoc);
5730
5731 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
5732 Expr *Init,
5733 CXXRecordDecl *ClassDecl);
5734
5735 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5736 CXXCtorInitializer *Initializer);
5737
5738 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5739 ArrayRef<CXXCtorInitializer *> Initializers = None);
5740
5741 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
5742
5743
5744 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
5745 /// mark all the non-trivial destructors of its members and bases as
5746 /// referenced.
5747 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
5748 CXXRecordDecl *Record);
5749
5750 /// \brief The list of classes whose vtables have been used within
5751 /// this translation unit, and the source locations at which the
5752 /// first use occurred.
5753 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
5754
5755 /// \brief The list of vtables that are required but have not yet been
5756 /// materialized.
5757 SmallVector<VTableUse, 16> VTableUses;
5758
5759 /// \brief The set of classes whose vtables have been used within
5760 /// this translation unit, and a bit that will be true if the vtable is
5761 /// required to be emitted (otherwise, it should be emitted only if needed
5762 /// by code generation).
5763 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
5764
5765 /// \brief Load any externally-stored vtable uses.
5766 void LoadExternalVTableUses();
5767
5768 /// \brief Note that the vtable for the given class was used at the
5769 /// given location.
5770 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
5771 bool DefinitionRequired = false);
5772
5773 /// \brief Mark the exception specifications of all virtual member functions
5774 /// in the given class as needed.
5775 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
5776 const CXXRecordDecl *RD);
5777
5778 /// MarkVirtualMembersReferenced - Will mark all members of the given
5779 /// CXXRecordDecl referenced.
5780 void MarkVirtualMembersReferenced(SourceLocation Loc,
5781 const CXXRecordDecl *RD);
5782
5783 /// \brief Define all of the vtables that have been used in this
5784 /// translation unit and reference any virtual members used by those
5785 /// vtables.
5786 ///
5787 /// \returns true if any work was done, false otherwise.
5788 bool DefineUsedVTables();
5789
5790 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
5791
5792 void ActOnMemInitializers(Decl *ConstructorDecl,
5793 SourceLocation ColonLoc,
5794 ArrayRef<CXXCtorInitializer*> MemInits,
5795 bool AnyErrors);
5796
5797 /// \brief Check class-level dllimport/dllexport attribute. The caller must
5798 /// ensure that referenceDLLExportedClassMethods is called some point later
5799 /// when all outer classes of Class are complete.
5800 void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
5801
5802 void referenceDLLExportedClassMethods();
5803
5804 void propagateDLLAttrToBaseClassTemplate(
5805 CXXRecordDecl *Class, Attr *ClassAttr,
5806 ClassTemplateSpecializationDecl *BaseTemplateSpec,
5807 SourceLocation BaseLoc);
5808
5809 void CheckCompletedCXXClass(CXXRecordDecl *Record);
5810
5811 /// Check that the C++ class annoated with "trivial_abi" satisfies all the
5812 /// conditions that are needed for the attribute to have an effect.
5813 void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD);
5814
5815 void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
5816 Decl *TagDecl,
5817 SourceLocation LBrac,
5818 SourceLocation RBrac,
5819 AttributeList *AttrList);
5820 void ActOnFinishCXXMemberDecls();
5821 void ActOnFinishCXXNonNestedClass(Decl *D);
5822
5823 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
5824 unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template);
5825 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
5826 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5827 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
5828 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
5829 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5830 void ActOnFinishDelayedMemberInitializers(Decl *Record);
5831 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
5832 CachedTokens &Toks);
5833 void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
5834 bool IsInsideALocalClassWithinATemplateFunction();
5835
5836 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5837 Expr *AssertExpr,
5838 Expr *AssertMessageExpr,
5839 SourceLocation RParenLoc);
5840 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5841 Expr *AssertExpr,
5842 StringLiteral *AssertMessageExpr,
5843 SourceLocation RParenLoc,
5844 bool Failed);
5845
5846 FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
5847 SourceLocation FriendLoc,
5848 TypeSourceInfo *TSInfo);
5849 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
5850 MultiTemplateParamsArg TemplateParams);
5851 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
5852 MultiTemplateParamsArg TemplateParams);
5853
5854 QualType CheckConstructorDeclarator(Declarator &D, QualType R,
5855 StorageClass& SC);
5856 void CheckConstructor(CXXConstructorDecl *Constructor);
5857 QualType CheckDestructorDeclarator(Declarator &D, QualType R,
5858 StorageClass& SC);
5859 bool CheckDestructor(CXXDestructorDecl *Destructor);
5860 void CheckConversionDeclarator(Declarator &D, QualType &R,
5861 StorageClass& SC);
5862 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
5863 void CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
5864 StorageClass &SC);
5865 void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
5866
5867 void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD);
5868 void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD,
5869 const FunctionProtoType *T);
5870 void CheckDelayedMemberExceptionSpecs();
5871
5872 //===--------------------------------------------------------------------===//
5873 // C++ Derived Classes
5874 //
5875
5876 /// ActOnBaseSpecifier - Parsed a base specifier
5877 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
5878 SourceRange SpecifierRange,
5879 bool Virtual, AccessSpecifier Access,
5880 TypeSourceInfo *TInfo,
5881 SourceLocation EllipsisLoc);
5882
5883 BaseResult ActOnBaseSpecifier(Decl *classdecl,
5884 SourceRange SpecifierRange,
5885 ParsedAttributes &Attrs,
5886 bool Virtual, AccessSpecifier Access,
5887 ParsedType basetype,
5888 SourceLocation BaseLoc,
5889 SourceLocation EllipsisLoc);
5890
5891 bool AttachBaseSpecifiers(CXXRecordDecl *Class,
5892 MutableArrayRef<CXXBaseSpecifier *> Bases);
5893 void ActOnBaseSpecifiers(Decl *ClassDecl,
5894 MutableArrayRef<CXXBaseSpecifier *> Bases);
5895
5896 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
5897 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
5898 CXXBasePaths &Paths);
5899
5900 // FIXME: I don't like this name.
5901 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
5902
5903 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5904 SourceLocation Loc, SourceRange Range,
5905 CXXCastPath *BasePath = nullptr,
5906 bool IgnoreAccess = false);
5907 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5908 unsigned InaccessibleBaseID,
5909 unsigned AmbigiousBaseConvID,
5910 SourceLocation Loc, SourceRange Range,
5911 DeclarationName Name,
5912 CXXCastPath *BasePath,
5913 bool IgnoreAccess = false);
5914
5915 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
5916
5917 bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5918 const CXXMethodDecl *Old);
5919
5920 /// CheckOverridingFunctionReturnType - Checks whether the return types are
5921 /// covariant, according to C++ [class.virtual]p5.
5922 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
5923 const CXXMethodDecl *Old);
5924
5925 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
5926 /// spec is a subset of base spec.
5927 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
5928 const CXXMethodDecl *Old);
5929
5930 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
5931
5932 /// CheckOverrideControl - Check C++11 override control semantics.
5933 void CheckOverrideControl(NamedDecl *D);
5934
5935 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
5936 /// not used in the declaration of an overriding method.
5937 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D);
5938
5939 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
5940 /// overrides a virtual member function marked 'final', according to
5941 /// C++11 [class.virtual]p4.
5942 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
5943 const CXXMethodDecl *Old);
5944
5945
5946 //===--------------------------------------------------------------------===//
5947 // C++ Access Control
5948 //
5949
5950 enum AccessResult {
5951 AR_accessible,
5952 AR_inaccessible,
5953 AR_dependent,
5954 AR_delayed
5955 };
5956
5957 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
5958 NamedDecl *PrevMemberDecl,
5959 AccessSpecifier LexicalAS);
5960
5961 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
5962 DeclAccessPair FoundDecl);
5963 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
5964 DeclAccessPair FoundDecl);
5965 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
5966 SourceRange PlacementRange,
5967 CXXRecordDecl *NamingClass,
5968 DeclAccessPair FoundDecl,
5969 bool Diagnose = true);
5970 AccessResult CheckConstructorAccess(SourceLocation Loc,
5971 CXXConstructorDecl *D,
5972 DeclAccessPair FoundDecl,
5973 const InitializedEntity &Entity,
5974 bool IsCopyBindingRefToTemp = false);
5975 AccessResult CheckConstructorAccess(SourceLocation Loc,
5976 CXXConstructorDecl *D,
5977 DeclAccessPair FoundDecl,
5978 const InitializedEntity &Entity,
5979 const PartialDiagnostic &PDiag);
5980 AccessResult CheckDestructorAccess(SourceLocation Loc,
5981 CXXDestructorDecl *Dtor,
5982 const PartialDiagnostic &PDiag,
5983 QualType objectType = QualType());
5984 AccessResult CheckFriendAccess(NamedDecl *D);
5985 AccessResult CheckMemberAccess(SourceLocation UseLoc,
5986 CXXRecordDecl *NamingClass,
5987 DeclAccessPair Found);
5988 AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
5989 Expr *ObjectExpr,
5990 Expr *ArgExpr,
5991 DeclAccessPair FoundDecl);
5992 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
5993 DeclAccessPair FoundDecl);
5994 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
5995 QualType Base, QualType Derived,
5996 const CXXBasePath &Path,
5997 unsigned DiagID,
5998 bool ForceCheck = false,
5999 bool ForceUnprivileged = false);
6000 void CheckLookupAccess(const LookupResult &R);
6001 bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx);
6002 bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
6003 AccessSpecifier access,
6004 QualType objectType);
6005
6006 void HandleDependentAccessCheck(const DependentDiagnostic &DD,
6007 const MultiLevelTemplateArgumentList &TemplateArgs);
6008 void PerformDependentDiagnostics(const DeclContext *Pattern,
6009 const MultiLevelTemplateArgumentList &TemplateArgs);
6010
6011 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
6012
6013 /// \brief When true, access checking violations are treated as SFINAE
6014 /// failures rather than hard errors.
6015 bool AccessCheckingSFINAE;
6016
6017 enum AbstractDiagSelID {
6018 AbstractNone = -1,
6019 AbstractReturnType,
6020 AbstractParamType,
6021 AbstractVariableType,
6022 AbstractFieldType,
6023 AbstractIvarType,
6024 AbstractSynthesizedIvarType,
6025 AbstractArrayType
6026 };
6027
6028 bool isAbstractType(SourceLocation Loc, QualType T);
6029 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
6030 TypeDiagnoser &Diagnoser);
6031 template <typename... Ts>
6032 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
6033 const Ts &...Args) {
6034 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
6035 return RequireNonAbstractType(Loc, T, Diagnoser);
6036 }
6037
6038 void DiagnoseAbstractType(const CXXRecordDecl *RD);
6039
6040 //===--------------------------------------------------------------------===//
6041 // C++ Overloaded Operators [C++ 13.5]
6042 //
6043
6044 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
6045
6046 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
6047
6048 //===--------------------------------------------------------------------===//
6049 // C++ Templates [C++ 14]
6050 //
6051 void FilterAcceptableTemplateNames(LookupResult &R,
6052 bool AllowFunctionTemplates = true);
6053 bool hasAnyAcceptableTemplateNames(LookupResult &R,
6054 bool AllowFunctionTemplates = true);
6055
6056 void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
6057 QualType ObjectType, bool EnteringContext,
6058 bool &MemberOfUnknownSpecialization);
6059
6060 TemplateNameKind isTemplateName(Scope *S,
6061 CXXScopeSpec &SS,
6062 bool hasTemplateKeyword,
6063 UnqualifiedId &Name,
6064 ParsedType ObjectType,
6065 bool EnteringContext,
6066 TemplateTy &Template,
6067 bool &MemberOfUnknownSpecialization);
6068
6069 /// Determine whether a particular identifier might be the name in a C++1z
6070 /// deduction-guide declaration.
6071 bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
6072 SourceLocation NameLoc,
6073 ParsedTemplateTy *Template = nullptr);
6074
6075 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
6076 SourceLocation IILoc,
6077 Scope *S,
6078 const CXXScopeSpec *SS,
6079 TemplateTy &SuggestedTemplate,
6080 TemplateNameKind &SuggestedKind);
6081
6082 bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
6083 NamedDecl *Instantiation,
6084 bool InstantiatedFromMember,
6085 const NamedDecl *Pattern,
6086 const NamedDecl *PatternDef,
6087 TemplateSpecializationKind TSK,
6088 bool Complain = true);
6089
6090 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
6091 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
6092
6093 NamedDecl *ActOnTypeParameter(Scope *S, bool Typename,
6094 SourceLocation EllipsisLoc,
6095 SourceLocation KeyLoc,
6096 IdentifierInfo *ParamName,
6097 SourceLocation ParamNameLoc,
6098 unsigned Depth, unsigned Position,
6099 SourceLocation EqualLoc,
6100 ParsedType DefaultArg);
6101
6102 QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
6103 SourceLocation Loc);
6104 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
6105
6106 NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
6107 unsigned Depth,
6108 unsigned Position,
6109 SourceLocation EqualLoc,
6110 Expr *DefaultArg);
6111 NamedDecl *ActOnTemplateTemplateParameter(Scope *S,
6112 SourceLocation TmpLoc,
6113 TemplateParameterList *Params,
6114 SourceLocation EllipsisLoc,
6115 IdentifierInfo *ParamName,
6116 SourceLocation ParamNameLoc,
6117 unsigned Depth,
6118 unsigned Position,
6119 SourceLocation EqualLoc,
6120 ParsedTemplateArgument DefaultArg);
6121
6122 TemplateParameterList *
6123 ActOnTemplateParameterList(unsigned Depth,
6124 SourceLocation ExportLoc,
6125 SourceLocation TemplateLoc,
6126 SourceLocation LAngleLoc,
6127 ArrayRef<NamedDecl *> Params,
6128 SourceLocation RAngleLoc,
6129 Expr *RequiresClause);
6130
6131 /// \brief The context in which we are checking a template parameter list.
6132 enum TemplateParamListContext {
6133 TPC_ClassTemplate,
6134 TPC_VarTemplate,
6135 TPC_FunctionTemplate,
6136 TPC_ClassTemplateMember,
6137 TPC_FriendClassTemplate,
6138 TPC_FriendFunctionTemplate,
6139 TPC_FriendFunctionTemplateDefinition,
6140 TPC_TypeAliasTemplate
6141 };
6142
6143 bool CheckTemplateParameterList(TemplateParameterList *NewParams,
6144 TemplateParameterList *OldParams,
6145 TemplateParamListContext TPC);
6146 TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
6147 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
6148 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
6149 ArrayRef<TemplateParameterList *> ParamLists,
6150 bool IsFriend, bool &IsMemberSpecialization, bool &Invalid);
6151
6152 DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
6153 SourceLocation KWLoc, CXXScopeSpec &SS,
6154 IdentifierInfo *Name, SourceLocation NameLoc,
6155 AttributeList *Attr,
6156 TemplateParameterList *TemplateParams,
6157 AccessSpecifier AS,
6158 SourceLocation ModulePrivateLoc,
6159 SourceLocation FriendLoc,
6160 unsigned NumOuterTemplateParamLists,
6161 TemplateParameterList **OuterTemplateParamLists,
6162 SkipBodyInfo *SkipBody = nullptr);
6163
6164 TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
6165 QualType NTTPType,
6166 SourceLocation Loc);
6167
6168 void translateTemplateArguments(const ASTTemplateArgsPtr &In,
6169 TemplateArgumentListInfo &Out);
6170
6171 ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType);
6172
6173 void NoteAllFoundTemplates(TemplateName Name);
6174
6175 QualType CheckTemplateIdType(TemplateName Template,
6176 SourceLocation TemplateLoc,
6177 TemplateArgumentListInfo &TemplateArgs);
6178
6179 TypeResult
6180 ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
6181 TemplateTy Template, IdentifierInfo *TemplateII,
6182 SourceLocation TemplateIILoc,
6183 SourceLocation LAngleLoc,
6184 ASTTemplateArgsPtr TemplateArgs,
6185 SourceLocation RAngleLoc,
6186 bool IsCtorOrDtorName = false,
6187 bool IsClassName = false);
6188
6189 /// \brief Parsed an elaborated-type-specifier that refers to a template-id,
6190 /// such as \c class T::template apply<U>.
6191 TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
6192 TypeSpecifierType TagSpec,
6193 SourceLocation TagLoc,
6194 CXXScopeSpec &SS,
6195 SourceLocation TemplateKWLoc,
6196 TemplateTy TemplateD,
6197 SourceLocation TemplateLoc,
6198 SourceLocation LAngleLoc,
6199 ASTTemplateArgsPtr TemplateArgsIn,
6200 SourceLocation RAngleLoc);
6201
6202 DeclResult ActOnVarTemplateSpecialization(
6203 Scope *S, Declarator &D, TypeSourceInfo *DI,
6204 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
6205 StorageClass SC, bool IsPartialSpecialization);
6206
6207 DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
6208 SourceLocation TemplateLoc,
6209 SourceLocation TemplateNameLoc,
6210 const TemplateArgumentListInfo &TemplateArgs);
6211
6212 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
6213 const DeclarationNameInfo &NameInfo,
6214 VarTemplateDecl *Template,
6215 SourceLocation TemplateLoc,
6216 const TemplateArgumentListInfo *TemplateArgs);
6217
6218 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
6219 SourceLocation TemplateKWLoc,
6220 LookupResult &R,
6221 bool RequiresADL,
6222 const TemplateArgumentListInfo *TemplateArgs);
6223
6224 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
6225 SourceLocation TemplateKWLoc,
6226 const DeclarationNameInfo &NameInfo,
6227 const TemplateArgumentListInfo *TemplateArgs);
6228
6229 TemplateNameKind ActOnDependentTemplateName(
6230 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
6231 UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext,
6232 TemplateTy &Template, bool AllowInjectedClassName = false);
6233
6234 DeclResult
6235 ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
6236 SourceLocation KWLoc,
6237 SourceLocation ModulePrivateLoc,
6238 TemplateIdAnnotation &TemplateId,
6239 AttributeList *Attr,
6240 MultiTemplateParamsArg TemplateParameterLists,
6241 SkipBodyInfo *SkipBody = nullptr);
6242
6243 bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
6244 TemplateDecl *PrimaryTemplate,
6245 unsigned NumExplicitArgs,
6246 ArrayRef<TemplateArgument> Args);
6247 void CheckTemplatePartialSpecialization(
6248 ClassTemplatePartialSpecializationDecl *Partial);
6249 void CheckTemplatePartialSpecialization(
6250 VarTemplatePartialSpecializationDecl *Partial);
6251
6252 Decl *ActOnTemplateDeclarator(Scope *S,
6253 MultiTemplateParamsArg TemplateParameterLists,
6254 Declarator &D);
6255
6256 bool
6257 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6258 TemplateSpecializationKind NewTSK,
6259 NamedDecl *PrevDecl,
6260 TemplateSpecializationKind PrevTSK,
6261 SourceLocation PrevPtOfInstantiation,
6262 bool &SuppressNew);
6263
6264 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6265 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6266 LookupResult &Previous);
6267
6268 bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
6269 TemplateArgumentListInfo *ExplicitTemplateArgs,
6270 LookupResult &Previous);
6271 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
6272 void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
6273
6274 DeclResult
6275 ActOnExplicitInstantiation(Scope *S,
6276 SourceLocation ExternLoc,
6277 SourceLocation TemplateLoc,
6278 unsigned TagSpec,
6279 SourceLocation KWLoc,
6280 const CXXScopeSpec &SS,
6281 TemplateTy Template,
6282 SourceLocation TemplateNameLoc,
6283 SourceLocation LAngleLoc,
6284 ASTTemplateArgsPtr TemplateArgs,
6285 SourceLocation RAngleLoc,
6286 AttributeList *Attr);
6287
6288 DeclResult
6289 ActOnExplicitInstantiation(Scope *S,
6290 SourceLocation ExternLoc,
6291 SourceLocation TemplateLoc,
6292 unsigned TagSpec,
6293 SourceLocation KWLoc,
6294 CXXScopeSpec &SS,
6295 IdentifierInfo *Name,
6296 SourceLocation NameLoc,
6297 AttributeList *Attr);
6298
6299 DeclResult ActOnExplicitInstantiation(Scope *S,
6300 SourceLocation ExternLoc,
6301 SourceLocation TemplateLoc,
6302 Declarator &D);
6303
6304 TemplateArgumentLoc
6305 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
6306 SourceLocation TemplateLoc,
6307 SourceLocation RAngleLoc,
6308 Decl *Param,
6309 SmallVectorImpl<TemplateArgument>
6310 &Converted,
6311 bool &HasDefaultArg);
6312
6313 /// \brief Specifies the context in which a particular template
6314 /// argument is being checked.
6315 enum CheckTemplateArgumentKind {
6316 /// \brief The template argument was specified in the code or was
6317 /// instantiated with some deduced template arguments.
6318 CTAK_Specified,
6319
6320 /// \brief The template argument was deduced via template argument
6321 /// deduction.
6322 CTAK_Deduced,
6323
6324 /// \brief The template argument was deduced from an array bound
6325 /// via template argument deduction.
6326 CTAK_DeducedFromArrayBound
6327 };
6328
6329 bool CheckTemplateArgument(NamedDecl *Param,
6330 TemplateArgumentLoc &Arg,
6331 NamedDecl *Template,
6332 SourceLocation TemplateLoc,
6333 SourceLocation RAngleLoc,
6334 unsigned ArgumentPackIndex,
6335 SmallVectorImpl<TemplateArgument> &Converted,
6336 CheckTemplateArgumentKind CTAK = CTAK_Specified);
6337
6338 /// \brief Check that the given template arguments can be be provided to
6339 /// the given template, converting the arguments along the way.
6340 ///
6341 /// \param Template The template to which the template arguments are being
6342 /// provided.
6343 ///
6344 /// \param TemplateLoc The location of the template name in the source.
6345 ///
6346 /// \param TemplateArgs The list of template arguments. If the template is
6347 /// a template template parameter, this function may extend the set of
6348 /// template arguments to also include substituted, defaulted template
6349 /// arguments.
6350 ///
6351 /// \param PartialTemplateArgs True if the list of template arguments is
6352 /// intentionally partial, e.g., because we're checking just the initial
6353 /// set of template arguments.
6354 ///
6355 /// \param Converted Will receive the converted, canonicalized template
6356 /// arguments.
6357 ///
6358 /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
6359 /// contain the converted forms of the template arguments as written.
6360 /// Otherwise, \p TemplateArgs will not be modified.
6361 ///
6362 /// \returns true if an error occurred, false otherwise.
6363 bool CheckTemplateArgumentList(TemplateDecl *Template,
6364 SourceLocation TemplateLoc,
6365 TemplateArgumentListInfo &TemplateArgs,
6366 bool PartialTemplateArgs,
6367 SmallVectorImpl<TemplateArgument> &Converted,
6368 bool UpdateArgsWithConversions = true);
6369
6370 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
6371 TemplateArgumentLoc &Arg,
6372 SmallVectorImpl<TemplateArgument> &Converted);
6373
6374 bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
6375 TypeSourceInfo *Arg);
6376 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
6377 QualType InstantiatedParamType, Expr *Arg,
6378 TemplateArgument &Converted,
6379 CheckTemplateArgumentKind CTAK = CTAK_Specified);
6380 bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
6381 TemplateArgumentLoc &Arg,
6382 unsigned ArgumentPackIndex);
6383
6384 ExprResult
6385 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6386 QualType ParamType,
6387 SourceLocation Loc);
6388 ExprResult
6389 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6390 SourceLocation Loc);
6391
6392 /// \brief Enumeration describing how template parameter lists are compared
6393 /// for equality.
6394 enum TemplateParameterListEqualKind {
6395 /// \brief We are matching the template parameter lists of two templates
6396 /// that might be redeclarations.
6397 ///
6398 /// \code
6399 /// template<typename T> struct X;
6400 /// template<typename T> struct X;
6401 /// \endcode
6402 TPL_TemplateMatch,
6403
6404 /// \brief We are matching the template parameter lists of two template
6405 /// template parameters as part of matching the template parameter lists
6406 /// of two templates that might be redeclarations.
6407 ///
6408 /// \code
6409 /// template<template<int I> class TT> struct X;
6410 /// template<template<int Value> class Other> struct X;
6411 /// \endcode
6412 TPL_TemplateTemplateParmMatch,
6413
6414 /// \brief We are matching the template parameter lists of a template
6415 /// template argument against the template parameter lists of a template
6416 /// template parameter.
6417 ///
6418 /// \code
6419 /// template<template<int Value> class Metafun> struct X;
6420 /// template<int Value> struct integer_c;
6421 /// X<integer_c> xic;
6422 /// \endcode
6423 TPL_TemplateTemplateArgumentMatch
6424 };
6425
6426 bool TemplateParameterListsAreEqual(TemplateParameterList *New,
6427 TemplateParameterList *Old,
6428 bool Complain,
6429 TemplateParameterListEqualKind Kind,
6430 SourceLocation TemplateArgLoc
6431 = SourceLocation());
6432
6433 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
6434
6435 /// \brief Called when the parser has parsed a C++ typename
6436 /// specifier, e.g., "typename T::type".
6437 ///
6438 /// \param S The scope in which this typename type occurs.
6439 /// \param TypenameLoc the location of the 'typename' keyword
6440 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6441 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
6442 /// \param IdLoc the location of the identifier.
6443 TypeResult
6444 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6445 const CXXScopeSpec &SS, const IdentifierInfo &II,
6446 SourceLocation IdLoc);
6447
6448 /// \brief Called when the parser has parsed a C++ typename
6449 /// specifier that ends in a template-id, e.g.,
6450 /// "typename MetaFun::template apply<T1, T2>".
6451 ///
6452 /// \param S The scope in which this typename type occurs.
6453 /// \param TypenameLoc the location of the 'typename' keyword
6454 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6455 /// \param TemplateLoc the location of the 'template' keyword, if any.
6456 /// \param TemplateName The template name.
6457 /// \param TemplateII The identifier used to name the template.
6458 /// \param TemplateIILoc The location of the template name.
6459 /// \param LAngleLoc The location of the opening angle bracket ('<').
6460 /// \param TemplateArgs The template arguments.
6461 /// \param RAngleLoc The location of the closing angle bracket ('>').
6462 TypeResult
6463 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6464 const CXXScopeSpec &SS,
6465 SourceLocation TemplateLoc,
6466 TemplateTy TemplateName,
6467 IdentifierInfo *TemplateII,
6468 SourceLocation TemplateIILoc,
6469 SourceLocation LAngleLoc,
6470 ASTTemplateArgsPtr TemplateArgs,
6471 SourceLocation RAngleLoc);
6472
6473 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
6474 SourceLocation KeywordLoc,
6475 NestedNameSpecifierLoc QualifierLoc,
6476 const IdentifierInfo &II,
6477 SourceLocation IILoc);
6478
6479 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
6480 SourceLocation Loc,
6481 DeclarationName Name);
6482 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
6483
6484 ExprResult RebuildExprInCurrentInstantiation(Expr *E);
6485 bool RebuildTemplateParamsInCurrentInstantiation(
6486 TemplateParameterList *Params);
6487
6488 std::string
6489 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6490 const TemplateArgumentList &Args);
6491
6492 std::string
6493 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6494 const TemplateArgument *Args,
6495 unsigned NumArgs);
6496
6497 //===--------------------------------------------------------------------===//
6498 // C++ Variadic Templates (C++0x [temp.variadic])
6499 //===--------------------------------------------------------------------===//
6500
6501 /// Determine whether an unexpanded parameter pack might be permitted in this
6502 /// location. Useful for error recovery.
6503 bool isUnexpandedParameterPackPermitted();
6504
6505 /// \brief The context in which an unexpanded parameter pack is
6506 /// being diagnosed.
6507 ///
6508 /// Note that the values of this enumeration line up with the first
6509 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
6510 enum UnexpandedParameterPackContext {
6511 /// \brief An arbitrary expression.
6512 UPPC_Expression = 0,
6513
6514 /// \brief The base type of a class type.
6515 UPPC_BaseType,
6516
6517 /// \brief The type of an arbitrary declaration.
6518 UPPC_DeclarationType,
6519
6520 /// \brief The type of a data member.
6521 UPPC_DataMemberType,
6522
6523 /// \brief The size of a bit-field.
6524 UPPC_BitFieldWidth,
6525
6526 /// \brief The expression in a static assertion.
6527 UPPC_StaticAssertExpression,
6528
6529 /// \brief The fixed underlying type of an enumeration.
6530 UPPC_FixedUnderlyingType,
6531
6532 /// \brief The enumerator value.
6533 UPPC_EnumeratorValue,
6534
6535 /// \brief A using declaration.
6536 UPPC_UsingDeclaration,
6537
6538 /// \brief A friend declaration.
6539 UPPC_FriendDeclaration,
6540
6541 /// \brief A declaration qualifier.
6542 UPPC_DeclarationQualifier,
6543
6544 /// \brief An initializer.
6545 UPPC_Initializer,
6546
6547 /// \brief A default argument.
6548 UPPC_DefaultArgument,
6549
6550 /// \brief The type of a non-type template parameter.
6551 UPPC_NonTypeTemplateParameterType,
6552
6553 /// \brief The type of an exception.
6554 UPPC_ExceptionType,
6555
6556 /// \brief Partial specialization.
6557 UPPC_PartialSpecialization,
6558
6559 /// \brief Microsoft __if_exists.
6560 UPPC_IfExists,
6561
6562 /// \brief Microsoft __if_not_exists.
6563 UPPC_IfNotExists,
6564
6565 /// \brief Lambda expression.
6566 UPPC_Lambda,
6567
6568 /// \brief Block expression,
6569 UPPC_Block
6570 };
6571
6572 /// \brief Diagnose unexpanded parameter packs.
6573 ///
6574 /// \param Loc The location at which we should emit the diagnostic.
6575 ///
6576 /// \param UPPC The context in which we are diagnosing unexpanded
6577 /// parameter packs.
6578 ///
6579 /// \param Unexpanded the set of unexpanded parameter packs.
6580 ///
6581 /// \returns true if an error occurred, false otherwise.
6582 bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
6583 UnexpandedParameterPackContext UPPC,
6584 ArrayRef<UnexpandedParameterPack> Unexpanded);
6585
6586 /// \brief If the given type contains an unexpanded parameter pack,
6587 /// diagnose the error.
6588 ///
6589 /// \param Loc The source location where a diagnostc should be emitted.
6590 ///
6591 /// \param T The type that is being checked for unexpanded parameter
6592 /// packs.
6593 ///
6594 /// \returns true if an error occurred, false otherwise.
6595 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
6596 UnexpandedParameterPackContext UPPC);
6597
6598 /// \brief If the given expression contains an unexpanded parameter
6599 /// pack, diagnose the error.
6600 ///
6601 /// \param E The expression that is being checked for unexpanded
6602 /// parameter packs.
6603 ///
6604 /// \returns true if an error occurred, false otherwise.
6605 bool DiagnoseUnexpandedParameterPack(Expr *E,
6606 UnexpandedParameterPackContext UPPC = UPPC_Expression);
6607
6608 /// \brief If the given nested-name-specifier contains an unexpanded
6609 /// parameter pack, diagnose the error.
6610 ///
6611 /// \param SS The nested-name-specifier that is being checked for
6612 /// unexpanded parameter packs.
6613 ///
6614 /// \returns true if an error occurred, false otherwise.
6615 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
6616 UnexpandedParameterPackContext UPPC);
6617
6618 /// \brief If the given name contains an unexpanded parameter pack,
6619 /// diagnose the error.
6620 ///
6621 /// \param NameInfo The name (with source location information) that
6622 /// is being checked for unexpanded parameter packs.
6623 ///
6624 /// \returns true if an error occurred, false otherwise.
6625 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
6626 UnexpandedParameterPackContext UPPC);
6627
6628 /// \brief If the given template name contains an unexpanded parameter pack,
6629 /// diagnose the error.
6630 ///
6631 /// \param Loc The location of the template name.
6632 ///
6633 /// \param Template The template name that is being checked for unexpanded
6634 /// parameter packs.
6635 ///
6636 /// \returns true if an error occurred, false otherwise.
6637 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
6638 TemplateName Template,
6639 UnexpandedParameterPackContext UPPC);
6640
6641 /// \brief If the given template argument contains an unexpanded parameter
6642 /// pack, diagnose the error.
6643 ///
6644 /// \param Arg The template argument that is being checked for unexpanded
6645 /// parameter packs.
6646 ///
6647 /// \returns true if an error occurred, false otherwise.
6648 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
6649 UnexpandedParameterPackContext UPPC);
6650
6651 /// \brief Collect the set of unexpanded parameter packs within the given
6652 /// template argument.
6653 ///
6654 /// \param Arg The template argument that will be traversed to find
6655 /// unexpanded parameter packs.
6656 void collectUnexpandedParameterPacks(TemplateArgument Arg,
6657 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6658
6659 /// \brief Collect the set of unexpanded parameter packs within the given
6660 /// template argument.
6661 ///
6662 /// \param Arg The template argument that will be traversed to find
6663 /// unexpanded parameter packs.
6664 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
6665 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6666
6667 /// \brief Collect the set of unexpanded parameter packs within the given
6668 /// type.
6669 ///
6670 /// \param T The type that will be traversed to find
6671 /// unexpanded parameter packs.
6672 void collectUnexpandedParameterPacks(QualType T,
6673 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6674
6675 /// \brief Collect the set of unexpanded parameter packs within the given
6676 /// type.
6677 ///
6678 /// \param TL The type that will be traversed to find
6679 /// unexpanded parameter packs.
6680 void collectUnexpandedParameterPacks(TypeLoc TL,
6681 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6682
6683 /// \brief Collect the set of unexpanded parameter packs within the given
6684 /// nested-name-specifier.
6685 ///
6686 /// \param NNS The nested-name-specifier that will be traversed to find
6687 /// unexpanded parameter packs.
6688 void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS,
6689 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6690
6691 /// \brief Collect the set of unexpanded parameter packs within the given
6692 /// name.
6693 ///
6694 /// \param NameInfo The name that will be traversed to find
6695 /// unexpanded parameter packs.
6696 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
6697 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6698
6699 /// \brief Invoked when parsing a template argument followed by an
6700 /// ellipsis, which creates a pack expansion.
6701 ///
6702 /// \param Arg The template argument preceding the ellipsis, which
6703 /// may already be invalid.
6704 ///
6705 /// \param EllipsisLoc The location of the ellipsis.
6706 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
6707 SourceLocation EllipsisLoc);
6708
6709 /// \brief Invoked when parsing a type followed by an ellipsis, which
6710 /// creates a pack expansion.
6711 ///
6712 /// \param Type The type preceding the ellipsis, which will become
6713 /// the pattern of the pack expansion.
6714 ///
6715 /// \param EllipsisLoc The location of the ellipsis.
6716 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
6717
6718 /// \brief Construct a pack expansion type from the pattern of the pack
6719 /// expansion.
6720 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
6721 SourceLocation EllipsisLoc,
6722 Optional<unsigned> NumExpansions);
6723
6724 /// \brief Construct a pack expansion type from the pattern of the pack
6725 /// expansion.
6726 QualType CheckPackExpansion(QualType Pattern,
6727 SourceRange PatternRange,
6728 SourceLocation EllipsisLoc,
6729 Optional<unsigned> NumExpansions);
6730
6731 /// \brief Invoked when parsing an expression followed by an ellipsis, which
6732 /// creates a pack expansion.
6733 ///
6734 /// \param Pattern The expression preceding the ellipsis, which will become
6735 /// the pattern of the pack expansion.
6736 ///
6737 /// \param EllipsisLoc The location of the ellipsis.
6738 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
6739
6740 /// \brief Invoked when parsing an expression followed by an ellipsis, which
6741 /// creates a pack expansion.
6742 ///
6743 /// \param Pattern The expression preceding the ellipsis, which will become
6744 /// the pattern of the pack expansion.
6745 ///
6746 /// \param EllipsisLoc The location of the ellipsis.
6747 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
6748 Optional<unsigned> NumExpansions);
6749
6750 /// \brief Determine whether we could expand a pack expansion with the
6751 /// given set of parameter packs into separate arguments by repeatedly
6752 /// transforming the pattern.
6753 ///
6754 /// \param EllipsisLoc The location of the ellipsis that identifies the
6755 /// pack expansion.
6756 ///
6757 /// \param PatternRange The source range that covers the entire pattern of
6758 /// the pack expansion.
6759 ///
6760 /// \param Unexpanded The set of unexpanded parameter packs within the
6761 /// pattern.
6762 ///
6763 /// \param ShouldExpand Will be set to \c true if the transformer should
6764 /// expand the corresponding pack expansions into separate arguments. When
6765 /// set, \c NumExpansions must also be set.
6766 ///
6767 /// \param RetainExpansion Whether the caller should add an unexpanded
6768 /// pack expansion after all of the expanded arguments. This is used
6769 /// when extending explicitly-specified template argument packs per
6770 /// C++0x [temp.arg.explicit]p9.
6771 ///
6772 /// \param NumExpansions The number of separate arguments that will be in
6773 /// the expanded form of the corresponding pack expansion. This is both an
6774 /// input and an output parameter, which can be set by the caller if the
6775 /// number of expansions is known a priori (e.g., due to a prior substitution)
6776 /// and will be set by the callee when the number of expansions is known.
6777 /// The callee must set this value when \c ShouldExpand is \c true; it may
6778 /// set this value in other cases.
6779 ///
6780 /// \returns true if an error occurred (e.g., because the parameter packs
6781 /// are to be instantiated with arguments of different lengths), false
6782 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
6783 /// must be set.
6784 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
6785 SourceRange PatternRange,
6786 ArrayRef<UnexpandedParameterPack> Unexpanded,
6787 const MultiLevelTemplateArgumentList &TemplateArgs,
6788 bool &ShouldExpand,
6789 bool &RetainExpansion,
6790 Optional<unsigned> &NumExpansions);
6791
6792 /// \brief Determine the number of arguments in the given pack expansion
6793 /// type.
6794 ///
6795 /// This routine assumes that the number of arguments in the expansion is
6796 /// consistent across all of the unexpanded parameter packs in its pattern.
6797 ///
6798 /// Returns an empty Optional if the type can't be expanded.
6799 Optional<unsigned> getNumArgumentsInExpansion(QualType T,
6800 const MultiLevelTemplateArgumentList &TemplateArgs);
6801
6802 /// \brief Determine whether the given declarator contains any unexpanded
6803 /// parameter packs.
6804 ///
6805 /// This routine is used by the parser to disambiguate function declarators
6806 /// with an ellipsis prior to the ')', e.g.,
6807 ///
6808 /// \code
6809 /// void f(T...);
6810 /// \endcode
6811 ///
6812 /// To determine whether we have an (unnamed) function parameter pack or
6813 /// a variadic function.
6814 ///
6815 /// \returns true if the declarator contains any unexpanded parameter packs,
6816 /// false otherwise.
6817 bool containsUnexpandedParameterPacks(Declarator &D);
6818
6819 /// \brief Returns the pattern of the pack expansion for a template argument.
6820 ///
6821 /// \param OrigLoc The template argument to expand.
6822 ///
6823 /// \param Ellipsis Will be set to the location of the ellipsis.
6824 ///
6825 /// \param NumExpansions Will be set to the number of expansions that will
6826 /// be generated from this pack expansion, if known a priori.
6827 TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
6828 TemplateArgumentLoc OrigLoc,
6829 SourceLocation &Ellipsis,
6830 Optional<unsigned> &NumExpansions) const;
6831
6832 /// Given a template argument that contains an unexpanded parameter pack, but
6833 /// which has already been substituted, attempt to determine the number of
6834 /// elements that will be produced once this argument is fully-expanded.
6835 ///
6836 /// This is intended for use when transforming 'sizeof...(Arg)' in order to
6837 /// avoid actually expanding the pack where possible.
6838 Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg);
6839
6840 //===--------------------------------------------------------------------===//
6841 // C++ Template Argument Deduction (C++ [temp.deduct])
6842 //===--------------------------------------------------------------------===//
6843
6844 /// Adjust the type \p ArgFunctionType to match the calling convention,
6845 /// noreturn, and optionally the exception specification of \p FunctionType.
6846 /// Deduction often wants to ignore these properties when matching function
6847 /// types.
6848 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
6849 bool AdjustExceptionSpec = false);
6850
6851 /// \brief Describes the result of template argument deduction.
6852 ///
6853 /// The TemplateDeductionResult enumeration describes the result of
6854 /// template argument deduction, as returned from
6855 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
6856 /// structure provides additional information about the results of
6857 /// template argument deduction, e.g., the deduced template argument
6858 /// list (if successful) or the specific template parameters or
6859 /// deduced arguments that were involved in the failure.
6860 enum TemplateDeductionResult {
6861 /// \brief Template argument deduction was successful.
6862 TDK_Success = 0,
6863 /// \brief The declaration was invalid; do nothing.
6864 TDK_Invalid,
6865 /// \brief Template argument deduction exceeded the maximum template
6866 /// instantiation depth (which has already been diagnosed).
6867 TDK_InstantiationDepth,
6868 /// \brief Template argument deduction did not deduce a value
6869 /// for every template parameter.
6870 TDK_Incomplete,
6871 /// \brief Template argument deduction produced inconsistent
6872 /// deduced values for the given template parameter.
6873 TDK_Inconsistent,
6874 /// \brief Template argument deduction failed due to inconsistent
6875 /// cv-qualifiers on a template parameter type that would
6876 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
6877 /// but were given a non-const "X".
6878 TDK_Underqualified,
6879 /// \brief Substitution of the deduced template argument values
6880 /// resulted in an error.
6881 TDK_SubstitutionFailure,
6882 /// \brief After substituting deduced template arguments, a dependent
6883 /// parameter type did not match the corresponding argument.
6884 TDK_DeducedMismatch,
6885 /// \brief After substituting deduced template arguments, an element of
6886 /// a dependent parameter type did not match the corresponding element
6887 /// of the corresponding argument (when deducing from an initializer list).
6888 TDK_DeducedMismatchNested,
6889 /// \brief A non-depnedent component of the parameter did not match the
6890 /// corresponding component of the argument.
6891 TDK_NonDeducedMismatch,
6892 /// \brief When performing template argument deduction for a function
6893 /// template, there were too many call arguments.
6894 TDK_TooManyArguments,
6895 /// \brief When performing template argument deduction for a function
6896 /// template, there were too few call arguments.
6897 TDK_TooFewArguments,
6898 /// \brief The explicitly-specified template arguments were not valid
6899 /// template arguments for the given template.
6900 TDK_InvalidExplicitArguments,
6901 /// \brief Checking non-dependent argument conversions failed.
6902 TDK_NonDependentConversionFailure,
6903 /// \brief Deduction failed; that's all we know.
6904 TDK_MiscellaneousDeductionFailure,
6905 /// \brief CUDA Target attributes do not match.
6906 TDK_CUDATargetMismatch
6907 };
6908
6909 TemplateDeductionResult
6910 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
6911 const TemplateArgumentList &TemplateArgs,
6912 sema::TemplateDeductionInfo &Info);
6913
6914 TemplateDeductionResult
6915 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
6916 const TemplateArgumentList &TemplateArgs,
6917 sema::TemplateDeductionInfo &Info);
6918
6919 TemplateDeductionResult SubstituteExplicitTemplateArguments(
6920 FunctionTemplateDecl *FunctionTemplate,
6921 TemplateArgumentListInfo &ExplicitTemplateArgs,
6922 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6923 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
6924 sema::TemplateDeductionInfo &Info);
6925
6926 /// brief A function argument from which we performed template argument
6927 // deduction for a call.
6928 struct OriginalCallArg {
6929 OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
6930 unsigned ArgIdx, QualType OriginalArgType)
6931 : OriginalParamType(OriginalParamType),
6932 DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
6933 OriginalArgType(OriginalArgType) {}
6934
6935 QualType OriginalParamType;
6936 bool DecomposedParam;
6937 unsigned ArgIdx;
6938 QualType OriginalArgType;
6939 };
6940
6941 TemplateDeductionResult FinishTemplateArgumentDeduction(
6942 FunctionTemplateDecl *FunctionTemplate,
6943 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6944 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
6945 sema::TemplateDeductionInfo &Info,
6946 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
6947 bool PartialOverloading = false,
6948 llvm::function_ref<bool()> CheckNonDependent = []{ return false; });
6949
6950 TemplateDeductionResult DeduceTemplateArguments(
6951 FunctionTemplateDecl *FunctionTemplate,
6952 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
6953 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
6954 bool PartialOverloading,
6955 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent);
6956
6957 TemplateDeductionResult
6958 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6959 TemplateArgumentListInfo *ExplicitTemplateArgs,
6960 QualType ArgFunctionType,
6961 FunctionDecl *&Specialization,
6962 sema::TemplateDeductionInfo &Info,
6963 bool IsAddressOfFunction = false);
6964
6965 TemplateDeductionResult
6966 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6967 QualType ToType,
6968 CXXConversionDecl *&Specialization,
6969 sema::TemplateDeductionInfo &Info);
6970
6971 TemplateDeductionResult
6972 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6973 TemplateArgumentListInfo *ExplicitTemplateArgs,
6974 FunctionDecl *&Specialization,
6975 sema::TemplateDeductionInfo &Info,
6976 bool IsAddressOfFunction = false);
6977
6978 /// \brief Substitute Replacement for \p auto in \p TypeWithAuto
6979 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
6980 /// \brief Substitute Replacement for auto in TypeWithAuto
6981 TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
6982 QualType Replacement);
6983 /// \brief Completely replace the \c auto in \p TypeWithAuto by
6984 /// \p Replacement. This does not retain any \c auto type sugar.
6985 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
6986
6987 /// \brief Result type of DeduceAutoType.
6988 enum DeduceAutoResult {
6989 DAR_Succeeded,
6990 DAR_Failed,
6991 DAR_FailedAlreadyDiagnosed
6992 };
6993
6994 DeduceAutoResult
6995 DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result,
6996 Optional<unsigned> DependentDeductionDepth = None);
6997 DeduceAutoResult
6998 DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result,
6999 Optional<unsigned> DependentDeductionDepth = None);
7000 void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
7001 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
7002 bool Diagnose = true);
7003
7004 /// \brief Declare implicit deduction guides for a class template if we've
7005 /// not already done so.
7006 void DeclareImplicitDeductionGuides(TemplateDecl *Template,
7007 SourceLocation Loc);
7008
7009 QualType DeduceTemplateSpecializationFromInitializer(
7010 TypeSourceInfo *TInfo, const InitializedEntity &Entity,
7011 const InitializationKind &Kind, MultiExprArg Init);
7012
7013 QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
7014 QualType Type, TypeSourceInfo *TSI,
7015 SourceRange Range, bool DirectInit,
7016 Expr *Init);
7017
7018 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
7019
7020 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
7021 SourceLocation ReturnLoc,
7022 Expr *&RetExpr, AutoType *AT);
7023
7024 FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
7025 FunctionTemplateDecl *FT2,
7026 SourceLocation Loc,
7027 TemplatePartialOrderingContext TPOC,
7028 unsigned NumCallArguments1,
7029 unsigned NumCallArguments2);
7030 UnresolvedSetIterator
7031 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
7032 TemplateSpecCandidateSet &FailedCandidates,
7033 SourceLocation Loc,
7034 const PartialDiagnostic &NoneDiag,
7035 const PartialDiagnostic &AmbigDiag,
7036 const PartialDiagnostic &CandidateDiag,
7037 bool Complain = true, QualType TargetType = QualType());
7038
7039 ClassTemplatePartialSpecializationDecl *
7040 getMoreSpecializedPartialSpecialization(
7041 ClassTemplatePartialSpecializationDecl *PS1,
7042 ClassTemplatePartialSpecializationDecl *PS2,
7043 SourceLocation Loc);
7044
7045 bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
7046 sema::TemplateDeductionInfo &Info);
7047
7048 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
7049 VarTemplatePartialSpecializationDecl *PS1,
7050 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
7051
7052 bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
7053 sema::TemplateDeductionInfo &Info);
7054
7055 bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
7056 TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc);
7057
7058 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
7059 bool OnlyDeduced,
7060 unsigned Depth,
7061 llvm::SmallBitVector &Used);
7062 void MarkDeducedTemplateParameters(
7063 const FunctionTemplateDecl *FunctionTemplate,
7064 llvm::SmallBitVector &Deduced) {
7065 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
7066 }
7067 static void MarkDeducedTemplateParameters(ASTContext &Ctx,
7068 const FunctionTemplateDecl *FunctionTemplate,
7069 llvm::SmallBitVector &Deduced);
7070
7071 //===--------------------------------------------------------------------===//
7072 // C++ Template Instantiation
7073 //
7074
7075 MultiLevelTemplateArgumentList
7076 getTemplateInstantiationArgs(NamedDecl *D,
7077 const TemplateArgumentList *Innermost = nullptr,
7078 bool RelativeToPrimary = false,
7079 const FunctionDecl *Pattern = nullptr);
7080
7081 /// A context in which code is being synthesized (where a source location
7082 /// alone is not sufficient to identify the context). This covers template
7083 /// instantiation and various forms of implicitly-generated functions.
7084 struct CodeSynthesisContext {
7085 /// \brief The kind of template instantiation we are performing
7086 enum SynthesisKind {
7087 /// We are instantiating a template declaration. The entity is
7088 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
7089 TemplateInstantiation,
7090
7091 /// We are instantiating a default argument for a template
7092 /// parameter. The Entity is the template parameter whose argument is
7093 /// being instantiated, the Template is the template, and the
7094 /// TemplateArgs/NumTemplateArguments provide the template arguments as
7095 /// specified.
7096 DefaultTemplateArgumentInstantiation,
7097
7098 /// We are instantiating a default argument for a function.
7099 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
7100 /// provides the template arguments as specified.
7101 DefaultFunctionArgumentInstantiation,
7102
7103 /// We are substituting explicit template arguments provided for
7104 /// a function template. The entity is a FunctionTemplateDecl.
7105 ExplicitTemplateArgumentSubstitution,
7106
7107 /// We are substituting template argument determined as part of
7108 /// template argument deduction for either a class template
7109 /// partial specialization or a function template. The
7110 /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
7111 /// a TemplateDecl.
7112 DeducedTemplateArgumentSubstitution,
7113
7114 /// We are substituting prior template arguments into a new
7115 /// template parameter. The template parameter itself is either a
7116 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
7117 PriorTemplateArgumentSubstitution,
7118
7119 /// We are checking the validity of a default template argument that
7120 /// has been used when naming a template-id.
7121 DefaultTemplateArgumentChecking,
7122
7123 /// We are instantiating the exception specification for a function
7124 /// template which was deferred until it was needed.
7125 ExceptionSpecInstantiation,
7126
7127 /// We are declaring an implicit special member function.
7128 DeclaringSpecialMember,
7129
7130 /// We are defining a synthesized function (such as a defaulted special
7131 /// member).
7132 DefiningSynthesizedFunction,
7133
7134 /// Added for Template instantiation observation.
7135 /// Memoization means we are _not_ instantiating a template because
7136 /// it is already instantiated (but we entered a context where we
7137 /// would have had to if it was not already instantiated).
7138 Memoization
7139 } Kind;
7140
7141 /// \brief Was the enclosing context a non-instantiation SFINAE context?
7142 bool SavedInNonInstantiationSFINAEContext;
7143
7144 /// \brief The point of instantiation or synthesis within the source code.
7145 SourceLocation PointOfInstantiation;
7146
7147 /// \brief The entity that is being synthesized.
7148 Decl *Entity;
7149
7150 /// \brief The template (or partial specialization) in which we are
7151 /// performing the instantiation, for substitutions of prior template
7152 /// arguments.
7153 NamedDecl *Template;
7154
7155 /// \brief The list of template arguments we are substituting, if they
7156 /// are not part of the entity.
7157 const TemplateArgument *TemplateArgs;
7158
7159 // FIXME: Wrap this union around more members, or perhaps store the
7160 // kind-specific members in the RAII object owning the context.
7161 union {
7162 /// \brief The number of template arguments in TemplateArgs.
7163 unsigned NumTemplateArgs;
7164
7165 /// \brief The special member being declared or defined.
7166 CXXSpecialMember SpecialMember;
7167 };
7168
7169 ArrayRef<TemplateArgument> template_arguments() const {
7170 assert(Kind != DeclaringSpecialMember)(static_cast <bool> (Kind != DeclaringSpecialMember) ? void
(0) : __assert_fail ("Kind != DeclaringSpecialMember", "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/Sema/Sema.h"
, 7170, __extension__ __PRETTY_FUNCTION__))
;
7171 return {TemplateArgs, NumTemplateArgs};
7172 }
7173
7174 /// \brief The template deduction info object associated with the
7175 /// substitution or checking of explicit or deduced template arguments.
7176 sema::TemplateDeductionInfo *DeductionInfo;
7177
7178 /// \brief The source range that covers the construct that cause
7179 /// the instantiation, e.g., the template-id that causes a class
7180 /// template instantiation.
7181 SourceRange InstantiationRange;
7182
7183 CodeSynthesisContext()
7184 : Kind(TemplateInstantiation), Entity(nullptr), Template(nullptr),
7185 TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {}
7186
7187 /// \brief Determines whether this template is an actual instantiation
7188 /// that should be counted toward the maximum instantiation depth.
7189 bool isInstantiationRecord() const;
7190 };
7191
7192 /// \brief List of active code synthesis contexts.
7193 ///
7194 /// This vector is treated as a stack. As synthesis of one entity requires
7195 /// synthesis of another, additional contexts are pushed onto the stack.
7196 SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
7197
7198 /// Specializations whose definitions are currently being instantiated.
7199 llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations;
7200
7201 /// Non-dependent types used in templates that have already been instantiated
7202 /// by some template instantiation.
7203 llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
7204
7205 /// \brief Extra modules inspected when performing a lookup during a template
7206 /// instantiation. Computed lazily.
7207 SmallVector<Module*, 16> CodeSynthesisContextLookupModules;
7208
7209 /// \brief Cache of additional modules that should be used for name lookup
7210 /// within the current template instantiation. Computed lazily; use
7211 /// getLookupModules() to get a complete set.
7212 llvm::DenseSet<Module*> LookupModulesCache;
7213
7214 /// \brief Get the set of additional modules that should be checked during
7215 /// name lookup. A module and its imports become visible when instanting a
7216 /// template defined within it.
7217 llvm::DenseSet<Module*> &getLookupModules();
7218
7219 /// \brief Map from the most recent declaration of a namespace to the most
7220 /// recent visible declaration of that namespace.
7221 llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
7222
7223 /// \brief Whether we are in a SFINAE context that is not associated with
7224 /// template instantiation.
7225 ///
7226 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
7227 /// of a template instantiation or template argument deduction.
7228 bool InNonInstantiationSFINAEContext;
7229
7230 /// \brief The number of \p CodeSynthesisContexts that are not template
7231 /// instantiations and, therefore, should not be counted as part of the
7232 /// instantiation depth.
7233 ///
7234 /// When the instantiation depth reaches the user-configurable limit
7235 /// \p LangOptions::InstantiationDepth we will abort instantiation.
7236 // FIXME: Should we have a similar limit for other forms of synthesis?
7237 unsigned NonInstantiationEntries;
7238
7239 /// \brief The depth of the context stack at the point when the most recent
7240 /// error or warning was produced.
7241 ///
7242 /// This value is used to suppress printing of redundant context stacks
7243 /// when there are multiple errors or warnings in the same instantiation.
7244 // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
7245 unsigned LastEmittedCodeSynthesisContextDepth = 0;
7246
7247 /// \brief The template instantiation callbacks to trace or track
7248 /// instantiations (objects can be chained).
7249 ///
7250 /// This callbacks is used to print, trace or track template
7251 /// instantiations as they are being constructed.
7252 std::vector<std::unique_ptr<TemplateInstantiationCallback>>
7253 TemplateInstCallbacks;
7254
7255 /// \brief The current index into pack expansion arguments that will be
7256 /// used for substitution of parameter packs.
7257 ///
7258 /// The pack expansion index will be -1 to indicate that parameter packs
7259 /// should be instantiated as themselves. Otherwise, the index specifies
7260 /// which argument within the parameter pack will be used for substitution.
7261 int ArgumentPackSubstitutionIndex;
7262
7263 /// \brief RAII object used to change the argument pack substitution index
7264 /// within a \c Sema object.
7265 ///
7266 /// See \c ArgumentPackSubstitutionIndex for more information.
7267 class ArgumentPackSubstitutionIndexRAII {
7268 Sema &Self;
7269 int OldSubstitutionIndex;
7270
7271 public:
7272 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
7273 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
7274 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
7275 }
7276
7277 ~ArgumentPackSubstitutionIndexRAII() {
7278 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
7279 }
7280 };
7281
7282 friend class ArgumentPackSubstitutionRAII;
7283
7284 /// \brief For each declaration that involved template argument deduction, the
7285 /// set of diagnostics that were suppressed during that template argument
7286 /// deduction.
7287 ///
7288 /// FIXME: Serialize this structure to the AST file.
7289 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
7290 SuppressedDiagnosticsMap;
7291 SuppressedDiagnosticsMap SuppressedDiagnostics;
7292
7293 /// \brief A stack object to be created when performing template
7294 /// instantiation.
7295 ///
7296 /// Construction of an object of type \c InstantiatingTemplate
7297 /// pushes the current instantiation onto the stack of active
7298 /// instantiations. If the size of this stack exceeds the maximum
7299 /// number of recursive template instantiations, construction
7300 /// produces an error and evaluates true.
7301 ///
7302 /// Destruction of this object will pop the named instantiation off
7303 /// the stack.
7304 struct InstantiatingTemplate {
7305 /// \brief Note that we are instantiating a class template,
7306 /// function template, variable template, alias template,
7307 /// or a member thereof.
7308 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7309 Decl *Entity,
7310 SourceRange InstantiationRange = SourceRange());
7311
7312 struct ExceptionSpecification {};
7313 /// \brief Note that we are instantiating an exception specification
7314 /// of a function template.
7315 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7316 FunctionDecl *Entity, ExceptionSpecification,
7317 SourceRange InstantiationRange = SourceRange());
7318
7319 /// \brief Note that we are instantiating a default argument in a
7320 /// template-id.
7321 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7322 TemplateParameter Param, TemplateDecl *Template,
7323 ArrayRef<TemplateArgument> TemplateArgs,
7324 SourceRange InstantiationRange = SourceRange());
7325
7326 /// \brief Note that we are substituting either explicitly-specified or
7327 /// deduced template arguments during function template argument deduction.
7328 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7329 FunctionTemplateDecl *FunctionTemplate,
7330 ArrayRef<TemplateArgument> TemplateArgs,
7331 CodeSynthesisContext::SynthesisKind Kind,
7332 sema::TemplateDeductionInfo &DeductionInfo,
7333 SourceRange InstantiationRange = SourceRange());
7334
7335 /// \brief Note that we are instantiating as part of template
7336 /// argument deduction for a class template declaration.
7337 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7338 TemplateDecl *Template,
7339 ArrayRef<TemplateArgument> TemplateArgs,
7340 sema::TemplateDeductionInfo &DeductionInfo,
7341 SourceRange InstantiationRange = SourceRange());
7342
7343 /// \brief Note that we are instantiating as part of template
7344 /// argument deduction for a class template partial
7345 /// specialization.
7346 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7347 ClassTemplatePartialSpecializationDecl *PartialSpec,
7348 ArrayRef<TemplateArgument> TemplateArgs,
7349 sema::TemplateDeductionInfo &DeductionInfo,
7350 SourceRange InstantiationRange = SourceRange());
7351
7352 /// \brief Note that we are instantiating as part of template
7353 /// argument deduction for a variable template partial
7354 /// specialization.
7355 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7356 VarTemplatePartialSpecializationDecl *PartialSpec,
7357 ArrayRef<TemplateArgument> TemplateArgs,
7358 sema::TemplateDeductionInfo &DeductionInfo,
7359 SourceRange InstantiationRange = SourceRange());
7360
7361 /// \brief Note that we are instantiating a default argument for a function
7362 /// parameter.
7363 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7364 ParmVarDecl *Param,
7365 ArrayRef<TemplateArgument> TemplateArgs,
7366 SourceRange InstantiationRange = SourceRange());
7367
7368 /// \brief Note that we are substituting prior template arguments into a
7369 /// non-type parameter.
7370 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7371 NamedDecl *Template,
7372 NonTypeTemplateParmDecl *Param,
7373 ArrayRef<TemplateArgument> TemplateArgs,
7374 SourceRange InstantiationRange);
7375
7376 /// \brief Note that we are substituting prior template arguments into a
7377 /// template template parameter.
7378 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7379 NamedDecl *Template,
7380 TemplateTemplateParmDecl *Param,
7381 ArrayRef<TemplateArgument> TemplateArgs,
7382 SourceRange InstantiationRange);
7383
7384 /// \brief Note that we are checking the default template argument
7385 /// against the template parameter for a given template-id.
7386 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7387 TemplateDecl *Template,
7388 NamedDecl *Param,
7389 ArrayRef<TemplateArgument> TemplateArgs,
7390 SourceRange InstantiationRange);
7391
7392
7393 /// \brief Note that we have finished instantiating this template.
7394 void Clear();
7395
7396 ~InstantiatingTemplate() { Clear(); }
7397
7398 /// \brief Determines whether we have exceeded the maximum
7399 /// recursive template instantiations.
7400 bool isInvalid() const { return Invalid; }
7401
7402 /// \brief Determine whether we are already instantiating this
7403 /// specialization in some surrounding active instantiation.
7404 bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
7405
7406 private:
7407 Sema &SemaRef;
7408 bool Invalid;
7409 bool AlreadyInstantiating;
7410 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
7411 SourceRange InstantiationRange);
7412
7413 InstantiatingTemplate(
7414 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
7415 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
7416 Decl *Entity, NamedDecl *Template = nullptr,
7417 ArrayRef<TemplateArgument> TemplateArgs = None,
7418 sema::TemplateDeductionInfo *DeductionInfo = nullptr);
7419
7420 InstantiatingTemplate(const InstantiatingTemplate&) = delete;
7421
7422 InstantiatingTemplate&
7423 operator=(const InstantiatingTemplate&) = delete;
7424 };
7425
7426 void pushCodeSynthesisContext(CodeSynthesisContext Ctx);
7427 void popCodeSynthesisContext();
7428
7429 /// Determine whether we are currently performing template instantiation.
7430 bool inTemplateInstantiation() const {
7431 return CodeSynthesisContexts.size() > NonInstantiationEntries;
7432 }
7433
7434 void PrintContextStack() {
7435 if (!CodeSynthesisContexts.empty() &&
7436 CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
7437 PrintInstantiationStack();
7438 LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
7439 }
7440 if (PragmaAttributeCurrentTargetDecl)
7441 PrintPragmaAttributeInstantiationPoint();
7442 }
7443 void PrintInstantiationStack();
7444
7445 void PrintPragmaAttributeInstantiationPoint();
7446
7447 /// \brief Determines whether we are currently in a context where
7448 /// template argument substitution failures are not considered
7449 /// errors.
7450 ///
7451 /// \returns An empty \c Optional if we're not in a SFINAE context.
7452 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
7453 /// template-deduction context object, which can be used to capture
7454 /// diagnostics that will be suppressed.
7455 Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
7456
7457 /// \brief Determines whether we are currently in a context that
7458 /// is not evaluated as per C++ [expr] p5.
7459 bool isUnevaluatedContext() const {
7460 assert(!ExprEvalContexts.empty() &&(static_cast <bool> (!ExprEvalContexts.empty() &&
"Must be in an expression evaluation context") ? void (0) : __assert_fail
("!ExprEvalContexts.empty() && \"Must be in an expression evaluation context\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/Sema/Sema.h"
, 7461, __extension__ __PRETTY_FUNCTION__))
7461 "Must be in an expression evaluation context")(static_cast <bool> (!ExprEvalContexts.empty() &&
"Must be in an expression evaluation context") ? void (0) : __assert_fail
("!ExprEvalContexts.empty() && \"Must be in an expression evaluation context\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/Sema/Sema.h"
, 7461, __extension__ __PRETTY_FUNCTION__))
;
7462 return ExprEvalContexts.back().isUnevaluated();
7463 }
7464
7465 /// \brief RAII class used to determine whether SFINAE has
7466 /// trapped any errors that occur during template argument
7467 /// deduction.
7468 class SFINAETrap {
7469 Sema &SemaRef;
7470 unsigned PrevSFINAEErrors;
7471 bool PrevInNonInstantiationSFINAEContext;
7472 bool PrevAccessCheckingSFINAE;
7473 bool PrevLastDiagnosticIgnored;
7474
7475 public:
7476 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
7477 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
7478 PrevInNonInstantiationSFINAEContext(
7479 SemaRef.InNonInstantiationSFINAEContext),
7480 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE),
7481 PrevLastDiagnosticIgnored(
7482 SemaRef.getDiagnostics().isLastDiagnosticIgnored())
7483 {
7484 if (!SemaRef.isSFINAEContext())
7485 SemaRef.InNonInstantiationSFINAEContext = true;
7486 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
7487 }
7488
7489 ~SFINAETrap() {
7490 SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
7491 SemaRef.InNonInstantiationSFINAEContext
7492 = PrevInNonInstantiationSFINAEContext;
7493 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
7494 SemaRef.getDiagnostics().setLastDiagnosticIgnored(
7495 PrevLastDiagnosticIgnored);
7496 }
7497
7498 /// \brief Determine whether any SFINAE errors have been trapped.
7499 bool hasErrorOccurred() const {
7500 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
7501 }
7502 };
7503
7504 /// \brief RAII class used to indicate that we are performing provisional
7505 /// semantic analysis to determine the validity of a construct, so
7506 /// typo-correction and diagnostics in the immediate context (not within
7507 /// implicitly-instantiated templates) should be suppressed.
7508 class TentativeAnalysisScope {
7509 Sema &SemaRef;
7510 // FIXME: Using a SFINAETrap for this is a hack.
7511 SFINAETrap Trap;
7512 bool PrevDisableTypoCorrection;
7513 public:
7514 explicit TentativeAnalysisScope(Sema &SemaRef)
7515 : SemaRef(SemaRef), Trap(SemaRef, true),
7516 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
7517 SemaRef.DisableTypoCorrection = true;
7518 }
7519 ~TentativeAnalysisScope() {
7520 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
7521 }
7522 };
7523
7524 /// \brief The current instantiation scope used to store local
7525 /// variables.
7526 LocalInstantiationScope *CurrentInstantiationScope;
7527
7528 /// \brief Tracks whether we are in a context where typo correction is
7529 /// disabled.
7530 bool DisableTypoCorrection;
7531
7532 /// \brief The number of typos corrected by CorrectTypo.
7533 unsigned TyposCorrected;
7534
7535 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
7536 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
7537
7538 /// \brief A cache containing identifiers for which typo correction failed and
7539 /// their locations, so that repeated attempts to correct an identifier in a
7540 /// given location are ignored if typo correction already failed for it.
7541 IdentifierSourceLocations TypoCorrectionFailures;
7542
7543 /// \brief Worker object for performing CFG-based warnings.
7544 sema::AnalysisBasedWarnings AnalysisWarnings;
7545 threadSafety::BeforeSet *ThreadSafetyDeclCache;
7546
7547 /// \brief An entity for which implicit template instantiation is required.
7548 ///
7549 /// The source location associated with the declaration is the first place in
7550 /// the source code where the declaration was "used". It is not necessarily
7551 /// the point of instantiation (which will be either before or after the
7552 /// namespace-scope declaration that triggered this implicit instantiation),
7553 /// However, it is the location that diagnostics should generally refer to,
7554 /// because users will need to know what code triggered the instantiation.
7555 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
7556
7557 /// \brief The queue of implicit template instantiations that are required
7558 /// but have not yet been performed.
7559 std::deque<PendingImplicitInstantiation> PendingInstantiations;
7560
7561 class GlobalEagerInstantiationScope {
7562 public:
7563 GlobalEagerInstantiationScope(Sema &S, bool Enabled)
7564 : S(S), Enabled(Enabled) {
7565 if (!Enabled) return;
7566
7567 SavedPendingInstantiations.swap(S.PendingInstantiations);
7568 SavedVTableUses.swap(S.VTableUses);
7569 }
7570
7571 void perform() {
7572 if (Enabled) {
7573 S.DefineUsedVTables();
7574 S.PerformPendingInstantiations();
7575 }
7576 }
7577
7578 ~GlobalEagerInstantiationScope() {
7579 if (!Enabled) return;
7580
7581 // Restore the set of pending vtables.
7582 assert(S.VTableUses.empty() &&(static_cast <bool> (S.VTableUses.empty() && "VTableUses should be empty before it is discarded."
) ? void (0) : __assert_fail ("S.VTableUses.empty() && \"VTableUses should be empty before it is discarded.\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/Sema/Sema.h"
, 7583, __extension__ __PRETTY_FUNCTION__))
7583 "VTableUses should be empty before it is discarded.")(static_cast <bool> (S.VTableUses.empty() && "VTableUses should be empty before it is discarded."
) ? void (0) : __assert_fail ("S.VTableUses.empty() && \"VTableUses should be empty before it is discarded.\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/Sema/Sema.h"
, 7583, __extension__ __PRETTY_FUNCTION__))
;
7584 S.VTableUses.swap(SavedVTableUses);
7585
7586 // Restore the set of pending implicit instantiations.
7587 assert(S.PendingInstantiations.empty() &&(static_cast <bool> (S.PendingInstantiations.empty() &&
"PendingInstantiations should be empty before it is discarded."
) ? void (0) : __assert_fail ("S.PendingInstantiations.empty() && \"PendingInstantiations should be empty before it is discarded.\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/Sema/Sema.h"
, 7588, __extension__ __PRETTY_FUNCTION__))
7588 "PendingInstantiations should be empty before it is discarded.")(static_cast <bool> (S.PendingInstantiations.empty() &&
"PendingInstantiations should be empty before it is discarded."
) ? void (0) : __assert_fail ("S.PendingInstantiations.empty() && \"PendingInstantiations should be empty before it is discarded.\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/Sema/Sema.h"
, 7588, __extension__ __PRETTY_FUNCTION__))
;
7589 S.PendingInstantiations.swap(SavedPendingInstantiations);
7590 }
7591
7592 private:
7593 Sema &S;
7594 SmallVector<VTableUse, 16> SavedVTableUses;
7595 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
7596 bool Enabled;
7597 };
7598
7599 /// \brief The queue of implicit template instantiations that are required
7600 /// and must be performed within the current local scope.
7601 ///
7602 /// This queue is only used for member functions of local classes in
7603 /// templates, which must be instantiated in the same scope as their
7604 /// enclosing function, so that they can reference function-local
7605 /// types, static variables, enumerators, etc.
7606 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
7607
7608 class LocalEagerInstantiationScope {
7609 public:
7610 LocalEagerInstantiationScope(Sema &S) : S(S) {
7611 SavedPendingLocalImplicitInstantiations.swap(
7612 S.PendingLocalImplicitInstantiations);
7613 }
7614
7615 void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); }
7616
7617 ~LocalEagerInstantiationScope() {
7618 assert(S.PendingLocalImplicitInstantiations.empty() &&(static_cast <bool> (S.PendingLocalImplicitInstantiations
.empty() && "there shouldn't be any pending local implicit instantiations"
) ? void (0) : __assert_fail ("S.PendingLocalImplicitInstantiations.empty() && \"there shouldn't be any pending local implicit instantiations\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/Sema/Sema.h"
, 7619, __extension__ __PRETTY_FUNCTION__))
7619 "there shouldn't be any pending local implicit instantiations")(static_cast <bool> (S.PendingLocalImplicitInstantiations
.empty() && "there shouldn't be any pending local implicit instantiations"
) ? void (0) : __assert_fail ("S.PendingLocalImplicitInstantiations.empty() && \"there shouldn't be any pending local implicit instantiations\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/Sema/Sema.h"
, 7619, __extension__ __PRETTY_FUNCTION__))
;
7620 SavedPendingLocalImplicitInstantiations.swap(
7621 S.PendingLocalImplicitInstantiations);
7622 }
7623
7624 private:
7625 Sema &S;
7626 std::deque<PendingImplicitInstantiation>
7627 SavedPendingLocalImplicitInstantiations;
7628 };
7629
7630 /// A helper class for building up ExtParameterInfos.
7631 class ExtParameterInfoBuilder {
7632 SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
7633 bool HasInteresting = false;
7634
7635 public:
7636 /// Set the ExtParameterInfo for the parameter at the given index,
7637 ///
7638 void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
7639 assert(Infos.size() <= index)(static_cast <bool> (Infos.size() <= index) ? void (
0) : __assert_fail ("Infos.size() <= index", "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/Sema/Sema.h"
, 7639, __extension__ __PRETTY_FUNCTION__))
;
7640 Infos.resize(index);
7641 Infos.push_back(info);
7642
7643 if (!HasInteresting)
7644 HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
7645 }
7646
7647 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
7648 /// ExtParameterInfo array we've built up.
7649 const FunctionProtoType::ExtParameterInfo *
7650 getPointerOrNull(unsigned numParams) {
7651 if (!HasInteresting) return nullptr;
7652 Infos.resize(numParams);
7653 return Infos.data();
7654 }
7655 };
7656
7657 void PerformPendingInstantiations(bool LocalOnly = false);
7658
7659 TypeSourceInfo *SubstType(TypeSourceInfo *T,
7660 const MultiLevelTemplateArgumentList &TemplateArgs,
7661 SourceLocation Loc, DeclarationName Entity,
7662 bool AllowDeducedTST = false);
7663
7664 QualType SubstType(QualType T,
7665 const MultiLevelTemplateArgumentList &TemplateArgs,
7666 SourceLocation Loc, DeclarationName Entity);
7667
7668 TypeSourceInfo *SubstType(TypeLoc TL,
7669 const MultiLevelTemplateArgumentList &TemplateArgs,
7670 SourceLocation Loc, DeclarationName Entity);
7671
7672 TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
7673 const MultiLevelTemplateArgumentList &TemplateArgs,
7674 SourceLocation Loc,
7675 DeclarationName Entity,
7676 CXXRecordDecl *ThisContext,
7677 unsigned ThisTypeQuals);
7678 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
7679 const MultiLevelTemplateArgumentList &Args);
7680 bool SubstExceptionSpec(SourceLocation Loc,
7681 FunctionProtoType::ExceptionSpecInfo &ESI,
7682 SmallVectorImpl<QualType> &ExceptionStorage,
7683 const MultiLevelTemplateArgumentList &Args);
7684 ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
7685 const MultiLevelTemplateArgumentList &TemplateArgs,
7686 int indexAdjustment,
7687 Optional<unsigned> NumExpansions,
7688 bool ExpectParameterPack);
7689 bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
7690 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
7691 const MultiLevelTemplateArgumentList &TemplateArgs,
7692 SmallVectorImpl<QualType> &ParamTypes,
7693 SmallVectorImpl<ParmVarDecl *> *OutParams,
7694 ExtParameterInfoBuilder &ParamInfos);
7695 ExprResult SubstExpr(Expr *E,
7696 const MultiLevelTemplateArgumentList &TemplateArgs);
7697
7698 /// \brief Substitute the given template arguments into a list of
7699 /// expressions, expanding pack expansions if required.
7700 ///
7701 /// \param Exprs The list of expressions to substitute into.
7702 ///
7703 /// \param IsCall Whether this is some form of call, in which case
7704 /// default arguments will be dropped.
7705 ///
7706 /// \param TemplateArgs The set of template arguments to substitute.
7707 ///
7708 /// \param Outputs Will receive all of the substituted arguments.
7709 ///
7710 /// \returns true if an error occurred, false otherwise.
7711 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
7712 const MultiLevelTemplateArgumentList &TemplateArgs,
7713 SmallVectorImpl<Expr *> &Outputs);
7714
7715 StmtResult SubstStmt(Stmt *S,
7716 const MultiLevelTemplateArgumentList &TemplateArgs);
7717
7718 Decl *SubstDecl(Decl *D, DeclContext *Owner,
7719 const MultiLevelTemplateArgumentList &TemplateArgs);
7720
7721 ExprResult SubstInitializer(Expr *E,
7722 const MultiLevelTemplateArgumentList &TemplateArgs,
7723 bool CXXDirectInit);
7724
7725 bool
7726 SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
7727 CXXRecordDecl *Pattern,
7728 const MultiLevelTemplateArgumentList &TemplateArgs);
7729
7730 bool
7731 InstantiateClass(SourceLocation PointOfInstantiation,
7732 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
7733 const MultiLevelTemplateArgumentList &TemplateArgs,
7734 TemplateSpecializationKind TSK,
7735 bool Complain = true);
7736
7737 bool InstantiateEnum(SourceLocation PointOfInstantiation,
7738 EnumDecl *Instantiation, EnumDecl *Pattern,
7739 const MultiLevelTemplateArgumentList &TemplateArgs,
7740 TemplateSpecializationKind TSK);
7741
7742 bool InstantiateInClassInitializer(
7743 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
7744 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
7745
7746 struct LateInstantiatedAttribute {
7747 const Attr *TmplAttr;
7748 LocalInstantiationScope *Scope;
7749 Decl *NewDecl;
7750
7751 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
7752 Decl *D)
7753 : TmplAttr(A), Scope(S), NewDecl(D)
7754 { }
7755 };
7756 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
7757
7758 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
7759 const Decl *Pattern, Decl *Inst,
7760 LateInstantiatedAttrVec *LateAttrs = nullptr,
7761 LocalInstantiationScope *OuterMostScope = nullptr);
7762
7763 void
7764 InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
7765 const Decl *Pattern, Decl *Inst,
7766 LateInstantiatedAttrVec *LateAttrs = nullptr,
7767 LocalInstantiationScope *OuterMostScope = nullptr);
7768
7769 bool usesPartialOrExplicitSpecialization(
7770 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
7771
7772 bool
7773 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
7774 ClassTemplateSpecializationDecl *ClassTemplateSpec,
7775 TemplateSpecializationKind TSK,
7776 bool Complain = true);
7777
7778 void InstantiateClassMembers(SourceLocation PointOfInstantiation,
7779 CXXRecordDecl *Instantiation,
7780 const MultiLevelTemplateArgumentList &TemplateArgs,
7781 TemplateSpecializationKind TSK);
7782
7783 void InstantiateClassTemplateSpecializationMembers(
7784 SourceLocation PointOfInstantiation,
7785 ClassTemplateSpecializationDecl *ClassTemplateSpec,
7786 TemplateSpecializationKind TSK);
7787
7788 NestedNameSpecifierLoc
7789 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
7790 const MultiLevelTemplateArgumentList &TemplateArgs);
7791
7792 DeclarationNameInfo
7793 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
7794 const MultiLevelTemplateArgumentList &TemplateArgs);
7795 TemplateName
7796 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
7797 SourceLocation Loc,
7798 const MultiLevelTemplateArgumentList &TemplateArgs);
7799 bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
7800 TemplateArgumentListInfo &Result,
7801 const MultiLevelTemplateArgumentList &TemplateArgs);
7802
7803 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
7804 FunctionDecl *Function);
7805 FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
7806 const TemplateArgumentList *Args,
7807 SourceLocation Loc);
7808 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
7809 FunctionDecl *Function,
7810 bool Recursive = false,
7811 bool DefinitionRequired = false,
7812 bool AtEndOfTU = false);
7813 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
7814 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
7815 const TemplateArgumentList &TemplateArgList,
7816 const TemplateArgumentListInfo &TemplateArgsInfo,
7817 SmallVectorImpl<TemplateArgument> &Converted,
7818 SourceLocation PointOfInstantiation, void *InsertPos,
7819 LateInstantiatedAttrVec *LateAttrs = nullptr,
7820 LocalInstantiationScope *StartingScope = nullptr);
7821 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
7822 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
7823 const MultiLevelTemplateArgumentList &TemplateArgs);
7824 void
7825 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
7826 const MultiLevelTemplateArgumentList &TemplateArgs,
7827 LateInstantiatedAttrVec *LateAttrs,
7828 DeclContext *Owner,
7829 LocalInstantiationScope *StartingScope,
7830 bool InstantiatingVarTemplate = false);
7831 void InstantiateVariableInitializer(
7832 VarDecl *Var, VarDecl *OldVar,
7833 const MultiLevelTemplateArgumentList &TemplateArgs);
7834 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
7835 VarDecl *Var, bool Recursive = false,
7836 bool DefinitionRequired = false,
7837 bool AtEndOfTU = false);
7838
7839 void InstantiateMemInitializers(CXXConstructorDecl *New,
7840 const CXXConstructorDecl *Tmpl,
7841 const MultiLevelTemplateArgumentList &TemplateArgs);
7842
7843 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
7844 const MultiLevelTemplateArgumentList &TemplateArgs,
7845 bool FindingInstantiatedContext = false);
7846 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
7847 const MultiLevelTemplateArgumentList &TemplateArgs);
7848
7849 // Objective-C declarations.
7850 enum ObjCContainerKind {
7851 OCK_None = -1,
7852 OCK_Interface = 0,
7853 OCK_Protocol,
7854 OCK_Category,
7855 OCK_ClassExtension,
7856 OCK_Implementation,
7857 OCK_CategoryImplementation
7858 };
7859 ObjCContainerKind getObjCContainerKind() const;
7860
7861 DeclResult actOnObjCTypeParam(Scope *S,
7862 ObjCTypeParamVariance variance,
7863 SourceLocation varianceLoc,
7864 unsigned index,
7865 IdentifierInfo *paramName,
7866 SourceLocation paramLoc,
7867 SourceLocation colonLoc,
7868 ParsedType typeBound);
7869
7870 ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
7871 ArrayRef<Decl *> typeParams,
7872 SourceLocation rAngleLoc);
7873 void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
7874
7875 Decl *ActOnStartClassInterface(Scope *S,
7876 SourceLocation AtInterfaceLoc,
7877 IdentifierInfo *ClassName,
7878 SourceLocation ClassLoc,
7879 ObjCTypeParamList *typeParamList,
7880 IdentifierInfo *SuperName,
7881 SourceLocation SuperLoc,
7882 ArrayRef<ParsedType> SuperTypeArgs,
7883 SourceRange SuperTypeArgsRange,
7884 Decl * const *ProtoRefs,
7885 unsigned NumProtoRefs,
7886 const SourceLocation *ProtoLocs,
7887 SourceLocation EndProtoLoc,
7888 AttributeList *AttrList);
7889
7890 void ActOnSuperClassOfClassInterface(Scope *S,
7891 SourceLocation AtInterfaceLoc,
7892 ObjCInterfaceDecl *IDecl,
7893 IdentifierInfo *ClassName,
7894 SourceLocation ClassLoc,
7895 IdentifierInfo *SuperName,
7896 SourceLocation SuperLoc,
7897 ArrayRef<ParsedType> SuperTypeArgs,
7898 SourceRange SuperTypeArgsRange);
7899
7900 void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
7901 SmallVectorImpl<SourceLocation> &ProtocolLocs,
7902 IdentifierInfo *SuperName,
7903 SourceLocation SuperLoc);
7904
7905 Decl *ActOnCompatibilityAlias(
7906 SourceLocation AtCompatibilityAliasLoc,
7907 IdentifierInfo *AliasName, SourceLocation AliasLocation,
7908 IdentifierInfo *ClassName, SourceLocation ClassLocation);
7909
7910 bool CheckForwardProtocolDeclarationForCircularDependency(
7911 IdentifierInfo *PName,
7912 SourceLocation &PLoc, SourceLocation PrevLoc,
7913 const ObjCList<ObjCProtocolDecl> &PList);
7914
7915 Decl *ActOnStartProtocolInterface(
7916 SourceLocation AtProtoInterfaceLoc,
7917 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
7918 Decl * const *ProtoRefNames, unsigned NumProtoRefs,
7919 const SourceLocation *ProtoLocs,
7920 SourceLocation EndProtoLoc,
7921 AttributeList *AttrList);
7922
7923 Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
7924 IdentifierInfo *ClassName,
7925 SourceLocation ClassLoc,
7926 ObjCTypeParamList *typeParamList,
7927 IdentifierInfo *CategoryName,
7928 SourceLocation CategoryLoc,
7929 Decl * const *ProtoRefs,
7930 unsigned NumProtoRefs,
7931 const SourceLocation *ProtoLocs,
7932 SourceLocation EndProtoLoc,
7933 AttributeList *AttrList);
7934
7935 Decl *ActOnStartClassImplementation(
7936 SourceLocation AtClassImplLoc,
7937 IdentifierInfo *ClassName, SourceLocation ClassLoc,
7938 IdentifierInfo *SuperClassname,
7939 SourceLocation SuperClassLoc);
7940
7941 Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
7942 IdentifierInfo *ClassName,
7943 SourceLocation ClassLoc,
7944 IdentifierInfo *CatName,
7945 SourceLocation CatLoc);
7946
7947 DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
7948 ArrayRef<Decl *> Decls);
7949
7950 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
7951 IdentifierInfo **IdentList,
7952 SourceLocation *IdentLocs,
7953 ArrayRef<ObjCTypeParamList *> TypeParamLists,
7954 unsigned NumElts);
7955
7956 DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
7957 ArrayRef<IdentifierLocPair> IdentList,
7958 AttributeList *attrList);
7959
7960 void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
7961 ArrayRef<IdentifierLocPair> ProtocolId,
7962 SmallVectorImpl<Decl *> &Protocols);
7963
7964 void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
7965 SourceLocation ProtocolLoc,
7966 IdentifierInfo *TypeArgId,
7967 SourceLocation TypeArgLoc,
7968 bool SelectProtocolFirst = false);
7969
7970 /// Given a list of identifiers (and their locations), resolve the
7971 /// names to either Objective-C protocol qualifiers or type
7972 /// arguments, as appropriate.
7973 void actOnObjCTypeArgsOrProtocolQualifiers(
7974 Scope *S,
7975 ParsedType baseType,
7976 SourceLocation lAngleLoc,
7977 ArrayRef<IdentifierInfo *> identifiers,
7978 ArrayRef<SourceLocation> identifierLocs,
7979 SourceLocation rAngleLoc,
7980 SourceLocation &typeArgsLAngleLoc,
7981 SmallVectorImpl<ParsedType> &typeArgs,
7982 SourceLocation &typeArgsRAngleLoc,
7983 SourceLocation &protocolLAngleLoc,
7984 SmallVectorImpl<Decl *> &protocols,
7985 SourceLocation &protocolRAngleLoc,
7986 bool warnOnIncompleteProtocols);
7987
7988 /// Build a an Objective-C protocol-qualified 'id' type where no
7989 /// base type was specified.
7990 TypeResult actOnObjCProtocolQualifierType(
7991 SourceLocation lAngleLoc,
7992 ArrayRef<Decl *> protocols,
7993 ArrayRef<SourceLocation> protocolLocs,
7994 SourceLocation rAngleLoc);
7995
7996 /// Build a specialized and/or protocol-qualified Objective-C type.
7997 TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
7998 Scope *S,
7999 SourceLocation Loc,
8000 ParsedType BaseType,
8001 SourceLocation TypeArgsLAngleLoc,
8002 ArrayRef<ParsedType> TypeArgs,
8003 SourceLocation TypeArgsRAngleLoc,
8004 SourceLocation ProtocolLAngleLoc,
8005 ArrayRef<Decl *> Protocols,
8006 ArrayRef<SourceLocation> ProtocolLocs,
8007 SourceLocation ProtocolRAngleLoc);
8008
8009 /// Build an Objective-C type parameter type.
8010 QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
8011 SourceLocation ProtocolLAngleLoc,
8012 ArrayRef<ObjCProtocolDecl *> Protocols,
8013 ArrayRef<SourceLocation> ProtocolLocs,
8014 SourceLocation ProtocolRAngleLoc,
8015 bool FailOnError = false);
8016
8017 /// Build an Objective-C object pointer type.
8018 QualType BuildObjCObjectType(QualType BaseType,
8019 SourceLocation Loc,
8020 SourceLocation TypeArgsLAngleLoc,
8021 ArrayRef<TypeSourceInfo *> TypeArgs,
8022 SourceLocation TypeArgsRAngleLoc,
8023 SourceLocation ProtocolLAngleLoc,
8024 ArrayRef<ObjCProtocolDecl *> Protocols,
8025 ArrayRef<SourceLocation> ProtocolLocs,
8026 SourceLocation ProtocolRAngleLoc,
8027 bool FailOnError = false);
8028
8029 /// Check the application of the Objective-C '__kindof' qualifier to
8030 /// the given type.
8031 bool checkObjCKindOfType(QualType &type, SourceLocation loc);
8032
8033 /// Ensure attributes are consistent with type.
8034 /// \param [in, out] Attributes The attributes to check; they will
8035 /// be modified to be consistent with \p PropertyTy.
8036 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
8037 SourceLocation Loc,
8038 unsigned &Attributes,
8039 bool propertyInPrimaryClass);
8040
8041 /// Process the specified property declaration and create decls for the
8042 /// setters and getters as needed.
8043 /// \param property The property declaration being processed
8044 void ProcessPropertyDecl(ObjCPropertyDecl *property);
8045
8046
8047 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
8048 ObjCPropertyDecl *SuperProperty,
8049 const IdentifierInfo *Name,
8050 bool OverridingProtocolProperty);
8051
8052 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
8053 ObjCInterfaceDecl *ID);
8054
8055 Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
8056 ArrayRef<Decl *> allMethods = None,
8057 ArrayRef<DeclGroupPtrTy> allTUVars = None);
8058
8059 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
8060 SourceLocation LParenLoc,
8061 FieldDeclarator &FD, ObjCDeclSpec &ODS,
8062 Selector GetterSel, Selector SetterSel,
8063 tok::ObjCKeywordKind MethodImplKind,
8064 DeclContext *lexicalDC = nullptr);
8065
8066 Decl *ActOnPropertyImplDecl(Scope *S,
8067 SourceLocation AtLoc,
8068 SourceLocation PropertyLoc,
8069 bool ImplKind,
8070 IdentifierInfo *PropertyId,
8071 IdentifierInfo *PropertyIvar,
8072 SourceLocation PropertyIvarLoc,
8073 ObjCPropertyQueryKind QueryKind);
8074
8075 enum ObjCSpecialMethodKind {
8076 OSMK_None,
8077 OSMK_Alloc,
8078 OSMK_New,
8079 OSMK_Copy,
8080 OSMK_RetainingInit,
8081 OSMK_NonRetainingInit
8082 };
8083
8084 struct ObjCArgInfo {
8085 IdentifierInfo *Name;
8086 SourceLocation NameLoc;
8087 // The Type is null if no type was specified, and the DeclSpec is invalid
8088 // in this case.
8089 ParsedType Type;
8090 ObjCDeclSpec DeclSpec;
8091
8092 /// ArgAttrs - Attribute list for this argument.
8093 AttributeList *ArgAttrs;
8094 };
8095
8096 Decl *ActOnMethodDeclaration(
8097 Scope *S,
8098 SourceLocation BeginLoc, // location of the + or -.
8099 SourceLocation EndLoc, // location of the ; or {.
8100 tok::TokenKind MethodType,
8101 ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
8102 ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
8103 // optional arguments. The number of types/arguments is obtained
8104 // from the Sel.getNumArgs().
8105 ObjCArgInfo *ArgInfo,
8106 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
8107 AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind,
8108 bool isVariadic, bool MethodDefinition);
8109
8110 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
8111 const ObjCObjectPointerType *OPT,
8112 bool IsInstance);
8113 ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
8114 bool IsInstance);
8115
8116 bool CheckARCMethodDecl(ObjCMethodDecl *method);
8117 bool inferObjCARCLifetime(ValueDecl *decl);
8118
8119 ExprResult
8120 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
8121 Expr *BaseExpr,
8122 SourceLocation OpLoc,
8123 DeclarationName MemberName,
8124 SourceLocation MemberLoc,
8125 SourceLocation SuperLoc, QualType SuperType,
8126 bool Super);
8127
8128 ExprResult
8129 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
8130 IdentifierInfo &propertyName,
8131 SourceLocation receiverNameLoc,
8132 SourceLocation propertyNameLoc);
8133
8134 ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
8135
8136 /// \brief Describes the kind of message expression indicated by a message
8137 /// send that starts with an identifier.
8138 enum ObjCMessageKind {
8139 /// \brief The message is sent to 'super'.
8140 ObjCSuperMessage,
8141 /// \brief The message is an instance message.
8142 ObjCInstanceMessage,
8143 /// \brief The message is a class message, and the identifier is a type
8144 /// name.
8145 ObjCClassMessage
8146 };
8147
8148 ObjCMessageKind getObjCMessageKind(Scope *S,
8149 IdentifierInfo *Name,
8150 SourceLocation NameLoc,
8151 bool IsSuper,
8152 bool HasTrailingDot,
8153 ParsedType &ReceiverType);
8154
8155 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
8156 Selector Sel,
8157 SourceLocation LBracLoc,
8158 ArrayRef<SourceLocation> SelectorLocs,
8159 SourceLocation RBracLoc,
8160 MultiExprArg Args);
8161
8162 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
8163 QualType ReceiverType,
8164 SourceLocation SuperLoc,
8165 Selector Sel,
8166 ObjCMethodDecl *Method,
8167 SourceLocation LBracLoc,
8168 ArrayRef<SourceLocation> SelectorLocs,
8169 SourceLocation RBracLoc,
8170 MultiExprArg Args,
8171 bool isImplicit = false);
8172
8173 ExprResult BuildClassMessageImplicit(QualType ReceiverType,
8174 bool isSuperReceiver,
8175 SourceLocation Loc,
8176 Selector Sel,
8177 ObjCMethodDecl *Method,
8178 MultiExprArg Args);
8179
8180 ExprResult ActOnClassMessage(Scope *S,
8181 ParsedType Receiver,
8182 Selector Sel,
8183 SourceLocation LBracLoc,
8184 ArrayRef<SourceLocation> SelectorLocs,
8185 SourceLocation RBracLoc,
8186 MultiExprArg Args);
8187
8188 ExprResult BuildInstanceMessage(Expr *Receiver,
8189 QualType ReceiverType,
8190 SourceLocation SuperLoc,
8191 Selector Sel,
8192 ObjCMethodDecl *Method,
8193 SourceLocation LBracLoc,
8194 ArrayRef<SourceLocation> SelectorLocs,
8195 SourceLocation RBracLoc,
8196 MultiExprArg Args,
8197 bool isImplicit = false);
8198
8199 ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
8200 QualType ReceiverType,
8201 SourceLocation Loc,
8202 Selector Sel,
8203 ObjCMethodDecl *Method,
8204 MultiExprArg Args);
8205
8206 ExprResult ActOnInstanceMessage(Scope *S,
8207 Expr *Receiver,
8208 Selector Sel,
8209 SourceLocation LBracLoc,
8210 ArrayRef<SourceLocation> SelectorLocs,
8211 SourceLocation RBracLoc,
8212 MultiExprArg Args);
8213
8214 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
8215 ObjCBridgeCastKind Kind,
8216 SourceLocation BridgeKeywordLoc,
8217 TypeSourceInfo *TSInfo,
8218 Expr *SubExpr);
8219
8220 ExprResult ActOnObjCBridgedCast(Scope *S,
8221 SourceLocation LParenLoc,
8222 ObjCBridgeCastKind Kind,
8223 SourceLocation BridgeKeywordLoc,
8224 ParsedType Type,
8225 SourceLocation RParenLoc,
8226 Expr *SubExpr);
8227
8228 void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
8229
8230 void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
8231
8232 bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
8233 CastKind &Kind);
8234
8235 bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
8236 QualType DestType, QualType SrcType,
8237 ObjCInterfaceDecl *&RelatedClass,
8238 ObjCMethodDecl *&ClassMethod,
8239 ObjCMethodDecl *&InstanceMethod,
8240 TypedefNameDecl *&TDNDecl,
8241 bool CfToNs, bool Diagnose = true);
8242
8243 bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
8244 QualType DestType, QualType SrcType,
8245 Expr *&SrcExpr, bool Diagnose = true);
8246
8247 bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr,
8248 bool Diagnose = true);
8249
8250 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
8251
8252 /// \brief Check whether the given new method is a valid override of the
8253 /// given overridden method, and set any properties that should be inherited.
8254 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
8255 const ObjCMethodDecl *Overridden);
8256
8257 /// \brief Describes the compatibility of a result type with its method.
8258 enum ResultTypeCompatibilityKind {
8259 RTC_Compatible,
8260 RTC_Incompatible,
8261 RTC_Unknown
8262 };
8263
8264 void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
8265 ObjCInterfaceDecl *CurrentClass,
8266 ResultTypeCompatibilityKind RTC);
8267
8268 enum PragmaOptionsAlignKind {
8269 POAK_Native, // #pragma options align=native
8270 POAK_Natural, // #pragma options align=natural
8271 POAK_Packed, // #pragma options align=packed
8272 POAK_Power, // #pragma options align=power
8273 POAK_Mac68k, // #pragma options align=mac68k
8274 POAK_Reset // #pragma options align=reset
8275 };
8276
8277 /// ActOnPragmaClangSection - Called on well formed \#pragma clang section
8278 void ActOnPragmaClangSection(SourceLocation PragmaLoc,
8279 PragmaClangSectionAction Action,
8280 PragmaClangSectionKind SecKind, StringRef SecName);
8281
8282 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
8283 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
8284 SourceLocation PragmaLoc);
8285
8286 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
8287 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
8288 StringRef SlotLabel, Expr *Alignment);
8289
8290 enum class PragmaPackDiagnoseKind {
8291 NonDefaultStateAtInclude,
8292 ChangedStateAtExit
8293 };
8294
8295 void DiagnoseNonDefaultPragmaPack(PragmaPackDiagnoseKind Kind,
8296 SourceLocation IncludeLoc);
8297 void DiagnoseUnterminatedPragmaPack();
8298
8299 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
8300 void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
8301
8302 /// ActOnPragmaMSComment - Called on well formed
8303 /// \#pragma comment(kind, "arg").
8304 void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
8305 StringRef Arg);
8306
8307 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
8308 /// pointers_to_members(representation method[, general purpose
8309 /// representation]).
8310 void ActOnPragmaMSPointersToMembers(
8311 LangOptions::PragmaMSPointersToMembersKind Kind,
8312 SourceLocation PragmaLoc);
8313
8314 /// \brief Called on well formed \#pragma vtordisp().
8315 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
8316 SourceLocation PragmaLoc,
8317 MSVtorDispAttr::Mode Value);
8318
8319 enum PragmaSectionKind {
8320 PSK_DataSeg,
8321 PSK_BSSSeg,
8322 PSK_ConstSeg,
8323 PSK_CodeSeg,
8324 };
8325
8326 bool UnifySection(StringRef SectionName,
8327 int SectionFlags,
8328 DeclaratorDecl *TheDecl);
8329 bool UnifySection(StringRef SectionName,
8330 int SectionFlags,
8331 SourceLocation PragmaSectionLocation);
8332
8333 /// \brief Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
8334 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
8335 PragmaMsStackAction Action,
8336 llvm::StringRef StackSlotLabel,
8337 StringLiteral *SegmentName,
8338 llvm::StringRef PragmaName);
8339
8340 /// \brief Called on well formed \#pragma section().
8341 void ActOnPragmaMSSection(SourceLocation PragmaLocation,
8342 int SectionFlags, StringLiteral *SegmentName);
8343
8344 /// \brief Called on well-formed \#pragma init_seg().
8345 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
8346 StringLiteral *SegmentName);
8347
8348 /// \brief Called on #pragma clang __debug dump II
8349 void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
8350
8351 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
8352 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
8353 StringRef Value);
8354
8355 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
8356 void ActOnPragmaUnused(const Token &Identifier,
8357 Scope *curScope,
8358 SourceLocation PragmaLoc);
8359
8360 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
8361 void ActOnPragmaVisibility(const IdentifierInfo* VisType,
8362 SourceLocation PragmaLoc);
8363
8364 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
8365 SourceLocation Loc);
8366 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
8367
8368 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
8369 void ActOnPragmaWeakID(IdentifierInfo* WeakName,
8370 SourceLocation PragmaLoc,
8371 SourceLocation WeakNameLoc);
8372
8373 /// ActOnPragmaRedefineExtname - Called on well formed
8374 /// \#pragma redefine_extname oldname newname.
8375 void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
8376 IdentifierInfo* AliasName,
8377 SourceLocation PragmaLoc,
8378 SourceLocation WeakNameLoc,
8379 SourceLocation AliasNameLoc);
8380
8381 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
8382 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
8383 IdentifierInfo* AliasName,
8384 SourceLocation PragmaLoc,
8385 SourceLocation WeakNameLoc,
8386 SourceLocation AliasNameLoc);
8387
8388 /// ActOnPragmaFPContract - Called on well formed
8389 /// \#pragma {STDC,OPENCL} FP_CONTRACT and
8390 /// \#pragma clang fp contract
8391 void ActOnPragmaFPContract(LangOptions::FPContractModeKind FPC);
8392
8393 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
8394 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
8395 void AddAlignmentAttributesForRecord(RecordDecl *RD);
8396
8397 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
8398 void AddMsStructLayoutForRecord(RecordDecl *RD);
8399
8400 /// FreePackedContext - Deallocate and null out PackContext.
8401 void FreePackedContext();
8402
8403 /// PushNamespaceVisibilityAttr - Note that we've entered a
8404 /// namespace with a visibility attribute.
8405 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
8406 SourceLocation Loc);
8407
8408 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
8409 /// add an appropriate visibility attribute.
8410 void AddPushedVisibilityAttribute(Decl *RD);
8411
8412 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
8413 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
8414 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
8415
8416 /// FreeVisContext - Deallocate and null out VisContext.
8417 void FreeVisContext();
8418
8419 /// AddCFAuditedAttribute - Check whether we're currently within
8420 /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
8421 /// the appropriate attribute.
8422 void AddCFAuditedAttribute(Decl *D);
8423
8424 /// \brief Called on well-formed '\#pragma clang attribute push'.
8425 void ActOnPragmaAttributePush(AttributeList &Attribute,
8426 SourceLocation PragmaLoc,
8427 attr::ParsedSubjectMatchRuleSet Rules);
8428
8429 /// \brief Called on well-formed '\#pragma clang attribute pop'.
8430 void ActOnPragmaAttributePop(SourceLocation PragmaLoc);
8431
8432 /// \brief Adds the attributes that have been specified using the
8433 /// '\#pragma clang attribute push' directives to the given declaration.
8434 void AddPragmaAttributes(Scope *S, Decl *D);
8435
8436 void DiagnoseUnterminatedPragmaAttribute();
8437
8438 /// \brief Called on well formed \#pragma clang optimize.
8439 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
8440
8441 /// \brief Get the location for the currently active "\#pragma clang optimize
8442 /// off". If this location is invalid, then the state of the pragma is "on".
8443 SourceLocation getOptimizeOffPragmaLocation() const {
8444 return OptimizeOffPragmaLocation;
8445 }
8446
8447 /// \brief Only called on function definitions; if there is a pragma in scope
8448 /// with the effect of a range-based optnone, consider marking the function
8449 /// with attribute optnone.
8450 void AddRangeBasedOptnone(FunctionDecl *FD);
8451
8452 /// \brief Adds the 'optnone' attribute to the function declaration if there
8453 /// are no conflicts; Loc represents the location causing the 'optnone'
8454 /// attribute to be added (usually because of a pragma).
8455 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
8456
8457 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
8458 void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
8459 unsigned SpellingListIndex, bool IsPackExpansion);
8460 void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T,
8461 unsigned SpellingListIndex, bool IsPackExpansion);
8462
8463 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
8464 /// declaration.
8465 void AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, Expr *OE,
8466 unsigned SpellingListIndex);
8467
8468 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
8469 /// declaration.
8470 void AddAllocAlignAttr(SourceRange AttrRange, Decl *D, Expr *ParamExpr,
8471 unsigned SpellingListIndex);
8472
8473 /// AddAlignValueAttr - Adds an align_value attribute to a particular
8474 /// declaration.
8475 void AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
8476 unsigned SpellingListIndex);
8477
8478 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
8479 /// declaration.
8480 void AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
8481 Expr *MinBlocks, unsigned SpellingListIndex);
8482
8483 /// AddModeAttr - Adds a mode attribute to a particular declaration.
8484 void AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name,
8485 unsigned SpellingListIndex, bool InInstantiation = false);
8486
8487 void AddParameterABIAttr(SourceRange AttrRange, Decl *D,
8488 ParameterABI ABI, unsigned SpellingListIndex);
8489
8490 void AddNSConsumedAttr(SourceRange AttrRange, Decl *D,
8491 unsigned SpellingListIndex, bool isNSConsumed,
8492 bool isTemplateInstantiation);
8493
8494 bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type);
8495
8496 //===--------------------------------------------------------------------===//
8497 // C++ Coroutines TS
8498 //
8499 bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
8500 StringRef Keyword);
8501 ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
8502 ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
8503 StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
8504
8505 ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
8506 bool IsImplicit = false);
8507 ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
8508 UnresolvedLookupExpr* Lookup);
8509 ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
8510 StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
8511 bool IsImplicit = false);
8512 StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
8513 bool buildCoroutineParameterMoves(SourceLocation Loc);
8514 VarDecl *buildCoroutinePromise(SourceLocation Loc);
8515 void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
8516
8517 //===--------------------------------------------------------------------===//
8518 // OpenCL extensions.
8519 //
8520private:
8521 std::string CurrOpenCLExtension;
8522 /// Extensions required by an OpenCL type.
8523 llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap;
8524 /// Extensions required by an OpenCL declaration.
8525 llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap;
8526public:
8527 llvm::StringRef getCurrentOpenCLExtension() const {
8528 return CurrOpenCLExtension;
8529 }
8530 void setCurrentOpenCLExtension(llvm::StringRef Ext) {
8531 CurrOpenCLExtension = Ext;
8532 }
8533
8534 /// \brief Set OpenCL extensions for a type which can only be used when these
8535 /// OpenCL extensions are enabled. If \p Exts is empty, do nothing.
8536 /// \param Exts A space separated list of OpenCL extensions.
8537 void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts);
8538
8539 /// \brief Set OpenCL extensions for a declaration which can only be
8540 /// used when these OpenCL extensions are enabled. If \p Exts is empty, do
8541 /// nothing.
8542 /// \param Exts A space separated list of OpenCL extensions.
8543 void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts);
8544
8545 /// \brief Set current OpenCL extensions for a type which can only be used
8546 /// when these OpenCL extensions are enabled. If current OpenCL extension is
8547 /// empty, do nothing.
8548 void setCurrentOpenCLExtensionForType(QualType T);
8549
8550 /// \brief Set current OpenCL extensions for a declaration which
8551 /// can only be used when these OpenCL extensions are enabled. If current
8552 /// OpenCL extension is empty, do nothing.
8553 void setCurrentOpenCLExtensionForDecl(Decl *FD);
8554
8555 bool isOpenCLDisabledDecl(Decl *FD);
8556
8557 /// \brief Check if type \p T corresponding to declaration specifier \p DS
8558 /// is disabled due to required OpenCL extensions being disabled. If so,
8559 /// emit diagnostics.
8560 /// \return true if type is disabled.
8561 bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T);
8562
8563 /// \brief Check if declaration \p D used by expression \p E
8564 /// is disabled due to required OpenCL extensions being disabled. If so,
8565 /// emit diagnostics.
8566 /// \return true if type is disabled.
8567 bool checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E);
8568
8569 //===--------------------------------------------------------------------===//
8570 // OpenMP directives and clauses.
8571 //
8572private:
8573 void *VarDataSharingAttributesStack;
8574 /// Set to true inside '#pragma omp declare target' region.
8575 bool IsInOpenMPDeclareTargetContext = false;
8576 /// \brief Initialization of data-sharing attributes stack.
8577 void InitDataSharingAttributesStack();
8578 void DestroyDataSharingAttributesStack();
8579 ExprResult
8580 VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
8581 bool StrictlyPositive = true);
8582 /// Returns OpenMP nesting level for current directive.
8583 unsigned getOpenMPNestingLevel() const;
8584
8585 /// Adjusts the function scopes index for the target-based regions.
8586 void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
8587 unsigned Level) const;
8588
8589 /// Push new OpenMP function region for non-capturing function.
8590 void pushOpenMPFunctionRegion();
8591
8592 /// Pop OpenMP function region for non-capturing function.
8593 void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI);
8594
8595 /// Checks if a type or a declaration is disabled due to the owning extension
8596 /// being disabled, and emits diagnostic messages if it is disabled.
8597 /// \param D type or declaration to be checked.
8598 /// \param DiagLoc source location for the diagnostic message.
8599 /// \param DiagInfo information to be emitted for the diagnostic message.
8600 /// \param SrcRange source range of the declaration.
8601 /// \param Map maps type or declaration to the extensions.
8602 /// \param Selector selects diagnostic message: 0 for type and 1 for
8603 /// declaration.
8604 /// \return true if the type or declaration is disabled.
8605 template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT>
8606 bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo,
8607 MapT &Map, unsigned Selector = 0,
8608 SourceRange SrcRange = SourceRange());
8609
8610public:
8611 /// \brief Return true if the provided declaration \a VD should be captured by
8612 /// reference.
8613 /// \param Level Relative level of nested OpenMP construct for that the check
8614 /// is performed.
8615 bool IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level);
8616
8617 /// \brief Check if the specified variable is used in one of the private
8618 /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
8619 /// constructs.
8620 VarDecl *IsOpenMPCapturedDecl(ValueDecl *D);
8621 ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
8622 ExprObjectKind OK, SourceLocation Loc);
8623
8624 /// \brief Check if the specified variable is used in 'private' clause.
8625 /// \param Level Relative level of nested OpenMP construct for that the check
8626 /// is performed.
8627 bool isOpenMPPrivateDecl(ValueDecl *D, unsigned Level);
8628
8629 /// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.)
8630 /// for \p FD based on DSA for the provided corresponding captured declaration
8631 /// \p D.
8632 void setOpenMPCaptureKind(FieldDecl *FD, ValueDecl *D, unsigned Level);
8633
8634 /// \brief Check if the specified variable is captured by 'target' directive.
8635 /// \param Level Relative level of nested OpenMP construct for that the check
8636 /// is performed.
8637 bool isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level);
8638
8639 ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
8640 Expr *Op);
8641 /// \brief Called on start of new data sharing attribute block.
8642 void StartOpenMPDSABlock(OpenMPDirectiveKind K,
8643 const DeclarationNameInfo &DirName, Scope *CurScope,
8644 SourceLocation Loc);
8645 /// \brief Start analysis of clauses.
8646 void StartOpenMPClause(OpenMPClauseKind K);
8647 /// \brief End analysis of clauses.
8648 void EndOpenMPClause();
8649 /// \brief Called on end of data sharing attribute block.
8650 void EndOpenMPDSABlock(Stmt *CurDirective);
8651
8652 /// \brief Check if the current region is an OpenMP loop region and if it is,
8653 /// mark loop control variable, used in \p Init for loop initialization, as
8654 /// private by default.
8655 /// \param Init First part of the for loop.
8656 void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
8657
8658 // OpenMP directives and clauses.
8659 /// \brief Called on correct id-expression from the '#pragma omp
8660 /// threadprivate'.
8661 ExprResult ActOnOpenMPIdExpression(Scope *CurScope,
8662 CXXScopeSpec &ScopeSpec,
8663 const DeclarationNameInfo &Id);
8664 /// \brief Called on well-formed '#pragma omp threadprivate'.
8665 DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
8666 SourceLocation Loc,
8667 ArrayRef<Expr *> VarList);
8668 /// \brief Builds a new OpenMPThreadPrivateDecl and checks its correctness.
8669 OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(
8670 SourceLocation Loc,
8671 ArrayRef<Expr *> VarList);
8672 /// \brief Check if the specified type is allowed to be used in 'omp declare
8673 /// reduction' construct.
8674 QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
8675 TypeResult ParsedType);
8676 /// \brief Called on start of '#pragma omp declare reduction'.
8677 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(
8678 Scope *S, DeclContext *DC, DeclarationName Name,
8679 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
8680 AccessSpecifier AS, Decl *PrevDeclInScope = nullptr);
8681 /// \brief Initialize declare reduction construct initializer.
8682 void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
8683 /// \brief Finish current declare reduction construct initializer.
8684 void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
8685 /// \brief Initialize declare reduction construct initializer.
8686 /// \return omp_priv variable.
8687 VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
8688 /// \brief Finish current declare reduction construct initializer.
8689 void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
8690 VarDecl *OmpPrivParm);
8691 /// \brief Called at the end of '#pragma omp declare reduction'.
8692 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
8693 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
8694
8695 /// Called on the start of target region i.e. '#pragma omp declare target'.
8696 bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc);
8697 /// Called at the end of target region i.e. '#pragme omp end declare target'.
8698 void ActOnFinishOpenMPDeclareTargetDirective();
8699 /// Called on correct id-expression from the '#pragma omp declare target'.
8700 void ActOnOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
8701 const DeclarationNameInfo &Id,
8702 OMPDeclareTargetDeclAttr::MapTypeTy MT,
8703 NamedDeclSetType &SameDirectiveDecls);
8704 /// Check declaration inside target region.
8705 void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
8706 SourceLocation IdLoc = SourceLocation());
8707 /// Return true inside OpenMP declare target region.
8708 bool isInOpenMPDeclareTargetContext() const {
8709 return IsInOpenMPDeclareTargetContext;
8710 }
8711 /// Return true inside OpenMP target region.
8712 bool isInOpenMPTargetExecutionDirective() const;
8713 /// Return true if (un)supported features for the current target should be
8714 /// diagnosed if OpenMP (offloading) is enabled.
8715 bool shouldDiagnoseTargetSupportFromOpenMP() const {
8716 return !getLangOpts().OpenMPIsDevice || isInOpenMPDeclareTargetContext() ||
8717 isInOpenMPTargetExecutionDirective();
8718 }
8719
8720 /// Return the number of captured regions created for an OpenMP directive.
8721 static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind);
8722
8723 /// \brief Initialization of captured region for OpenMP region.
8724 void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
8725 /// \brief End of OpenMP region.
8726 ///
8727 /// \param S Statement associated with the current OpenMP region.
8728 /// \param Clauses List of clauses for the current OpenMP region.
8729 ///
8730 /// \returns Statement for finished OpenMP region.
8731 StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
8732 StmtResult ActOnOpenMPExecutableDirective(
8733 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
8734 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
8735 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
8736 /// \brief Called on well-formed '\#pragma omp parallel' after parsing
8737 /// of the associated statement.
8738 StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
8739 Stmt *AStmt,
8740 SourceLocation StartLoc,
8741 SourceLocation EndLoc);
8742 /// \brief Called on well-formed '\#pragma omp simd' after parsing
8743 /// of the associated statement.
8744 StmtResult ActOnOpenMPSimdDirective(
8745 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8746 SourceLocation EndLoc,
8747 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8748 /// \brief Called on well-formed '\#pragma omp for' after parsing
8749 /// of the associated statement.
8750 StmtResult ActOnOpenMPForDirective(
8751 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8752 SourceLocation EndLoc,
8753 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8754 /// \brief Called on well-formed '\#pragma omp for simd' after parsing
8755 /// of the associated statement.
8756 StmtResult ActOnOpenMPForSimdDirective(
8757 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8758 SourceLocation EndLoc,
8759 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8760 /// \brief Called on well-formed '\#pragma omp sections' after parsing
8761 /// of the associated statement.
8762 StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
8763 Stmt *AStmt, SourceLocation StartLoc,
8764 SourceLocation EndLoc);
8765 /// \brief Called on well-formed '\#pragma omp section' after parsing of the
8766 /// associated statement.
8767 StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
8768 SourceLocation EndLoc);
8769 /// \brief Called on well-formed '\#pragma omp single' after parsing of the
8770 /// associated statement.
8771 StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
8772 Stmt *AStmt, SourceLocation StartLoc,
8773 SourceLocation EndLoc);
8774 /// \brief Called on well-formed '\#pragma omp master' after parsing of the
8775 /// associated statement.
8776 StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
8777 SourceLocation EndLoc);
8778 /// \brief Called on well-formed '\#pragma omp critical' after parsing of the
8779 /// associated statement.
8780 StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
8781 ArrayRef<OMPClause *> Clauses,
8782 Stmt *AStmt, SourceLocation StartLoc,
8783 SourceLocation EndLoc);
8784 /// \brief Called on well-formed '\#pragma omp parallel for' after parsing
8785 /// of the associated statement.
8786 StmtResult ActOnOpenMPParallelForDirective(
8787 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8788 SourceLocation EndLoc,
8789 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8790 /// \brief Called on well-formed '\#pragma omp parallel for simd' after
8791 /// parsing of the associated statement.
8792 StmtResult ActOnOpenMPParallelForSimdDirective(
8793 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8794 SourceLocation EndLoc,
8795 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8796 /// \brief Called on well-formed '\#pragma omp parallel sections' after
8797 /// parsing of the associated statement.
8798 StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
8799 Stmt *AStmt,
8800 SourceLocation StartLoc,
8801 SourceLocation EndLoc);
8802 /// \brief Called on well-formed '\#pragma omp task' after parsing of the
8803 /// associated statement.
8804 StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
8805 Stmt *AStmt, SourceLocation StartLoc,
8806 SourceLocation EndLoc);
8807 /// \brief Called on well-formed '\#pragma omp taskyield'.
8808 StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
8809 SourceLocation EndLoc);
8810 /// \brief Called on well-formed '\#pragma omp barrier'.
8811 StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
8812 SourceLocation EndLoc);
8813 /// \brief Called on well-formed '\#pragma omp taskwait'.
8814 StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
8815 SourceLocation EndLoc);
8816 /// \brief Called on well-formed '\#pragma omp taskgroup'.
8817 StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
8818 Stmt *AStmt, SourceLocation StartLoc,
8819 SourceLocation EndLoc);
8820 /// \brief Called on well-formed '\#pragma omp flush'.
8821 StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
8822 SourceLocation StartLoc,
8823 SourceLocation EndLoc);
8824 /// \brief Called on well-formed '\#pragma omp ordered' after parsing of the
8825 /// associated statement.
8826 StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
8827 Stmt *AStmt, SourceLocation StartLoc,
8828 SourceLocation EndLoc);
8829 /// \brief Called on well-formed '\#pragma omp atomic' after parsing of the
8830 /// associated statement.
8831 StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
8832 Stmt *AStmt, SourceLocation StartLoc,
8833 SourceLocation EndLoc);
8834 /// \brief Called on well-formed '\#pragma omp target' after parsing of the
8835 /// associated statement.
8836 StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
8837 Stmt *AStmt, SourceLocation StartLoc,
8838 SourceLocation EndLoc);
8839 /// \brief Called on well-formed '\#pragma omp target data' after parsing of
8840 /// the associated statement.
8841 StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
8842 Stmt *AStmt, SourceLocation StartLoc,
8843 SourceLocation EndLoc);
8844 /// \brief Called on well-formed '\#pragma omp target enter data' after
8845 /// parsing of the associated statement.
8846 StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
8847 SourceLocation StartLoc,
8848 SourceLocation EndLoc,
8849 Stmt *AStmt);
8850 /// \brief Called on well-formed '\#pragma omp target exit data' after
8851 /// parsing of the associated statement.
8852 StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
8853 SourceLocation StartLoc,
8854 SourceLocation EndLoc,
8855 Stmt *AStmt);
8856 /// \brief Called on well-formed '\#pragma omp target parallel' after
8857 /// parsing of the associated statement.
8858 StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
8859 Stmt *AStmt,
8860 SourceLocation StartLoc,
8861 SourceLocation EndLoc);
8862 /// \brief Called on well-formed '\#pragma omp target parallel for' after
8863 /// parsing of the associated statement.
8864 StmtResult ActOnOpenMPTargetParallelForDirective(
8865 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8866 SourceLocation EndLoc,
8867 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8868 /// \brief Called on well-formed '\#pragma omp teams' after parsing of the
8869 /// associated statement.
8870 StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
8871 Stmt *AStmt, SourceLocation StartLoc,
8872 SourceLocation EndLoc);
8873 /// \brief Called on well-formed '\#pragma omp cancellation point'.
8874 StmtResult
8875 ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
8876 SourceLocation EndLoc,
8877 OpenMPDirectiveKind CancelRegion);
8878 /// \brief Called on well-formed '\#pragma omp cancel'.
8879 StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
8880 SourceLocation StartLoc,
8881 SourceLocation EndLoc,
8882 OpenMPDirectiveKind CancelRegion);
8883 /// \brief Called on well-formed '\#pragma omp taskloop' after parsing of the
8884 /// associated statement.
8885 StmtResult ActOnOpenMPTaskLoopDirective(
8886 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8887 SourceLocation EndLoc,
8888 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8889 /// \brief Called on well-formed '\#pragma omp taskloop simd' after parsing of
8890 /// the associated statement.
8891 StmtResult ActOnOpenMPTaskLoopSimdDirective(
8892 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8893 SourceLocation EndLoc,
8894 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8895 /// \brief Called on well-formed '\#pragma omp distribute' after parsing
8896 /// of the associated statement.
8897 StmtResult ActOnOpenMPDistributeDirective(
8898 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8899 SourceLocation EndLoc,
8900 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8901 /// \brief Called on well-formed '\#pragma omp target update'.
8902 StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
8903 SourceLocation StartLoc,
8904 SourceLocation EndLoc,
8905 Stmt *AStmt);
8906 /// \brief Called on well-formed '\#pragma omp distribute parallel for' after
8907 /// parsing of the associated statement.
8908 StmtResult ActOnOpenMPDistributeParallelForDirective(
8909 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8910 SourceLocation EndLoc,
8911 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8912 /// \brief Called on well-formed '\#pragma omp distribute parallel for simd'
8913 /// after parsing of the associated statement.
8914 StmtResult ActOnOpenMPDistributeParallelForSimdDirective(
8915 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8916 SourceLocation EndLoc,
8917 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8918 /// \brief Called on well-formed '\#pragma omp distribute simd' after
8919 /// parsing of the associated statement.
8920 StmtResult ActOnOpenMPDistributeSimdDirective(
8921 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8922 SourceLocation EndLoc,
8923 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8924 /// \brief Called on well-formed '\#pragma omp target parallel for simd' after
8925 /// parsing of the associated statement.
8926 StmtResult ActOnOpenMPTargetParallelForSimdDirective(
8927 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8928 SourceLocation EndLoc,
8929 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8930 /// \brief Called on well-formed '\#pragma omp target simd' after parsing of
8931 /// the associated statement.
8932 StmtResult ActOnOpenMPTargetSimdDirective(
8933 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8934 SourceLocation EndLoc,
8935 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8936 /// Called on well-formed '\#pragma omp teams distribute' after parsing of
8937 /// the associated statement.
8938 StmtResult ActOnOpenMPTeamsDistributeDirective(
8939 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8940 SourceLocation EndLoc,
8941 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8942 /// Called on well-formed '\#pragma omp teams distribute simd' after parsing
8943 /// of the associated statement.
8944 StmtResult ActOnOpenMPTeamsDistributeSimdDirective(
8945 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8946 SourceLocation EndLoc,
8947 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8948 /// Called on well-formed '\#pragma omp teams distribute parallel for simd'
8949 /// after parsing of the associated statement.
8950 StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective(
8951 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8952 SourceLocation EndLoc,
8953 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8954 /// Called on well-formed '\#pragma omp teams distribute parallel for'
8955 /// after parsing of the associated statement.
8956 StmtResult ActOnOpenMPTeamsDistributeParallelForDirective(
8957 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8958 SourceLocation EndLoc,
8959 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8960 /// Called on well-formed '\#pragma omp target teams' after parsing of the
8961 /// associated statement.
8962 StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
8963 Stmt *AStmt,
8964 SourceLocation StartLoc,
8965 SourceLocation EndLoc);
8966 /// Called on well-formed '\#pragma omp target teams distribute' after parsing
8967 /// of the associated statement.
8968 StmtResult ActOnOpenMPTargetTeamsDistributeDirective(
8969 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8970 SourceLocation EndLoc,
8971 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8972 /// Called on well-formed '\#pragma omp target teams distribute parallel for'
8973 /// after parsing of the associated statement.
8974 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective(
8975 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8976 SourceLocation EndLoc,
8977 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8978 /// Called on well-formed '\#pragma omp target teams distribute parallel for
8979 /// simd' after parsing of the associated statement.
8980 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
8981 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8982 SourceLocation EndLoc,
8983 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8984 /// Called on well-formed '\#pragma omp target teams distribute simd' after
8985 /// parsing of the associated statement.
8986 StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective(
8987 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8988 SourceLocation EndLoc,
8989 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8990
8991 /// Checks correctness of linear modifiers.
8992 bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
8993 SourceLocation LinLoc);
8994 /// Checks that the specified declaration matches requirements for the linear
8995 /// decls.
8996 bool CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
8997 OpenMPLinearClauseKind LinKind, QualType Type);
8998
8999 /// \brief Called on well-formed '\#pragma omp declare simd' after parsing of
9000 /// the associated method/function.
9001 DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(
9002 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS,
9003 Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
9004 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
9005 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR);
9006
9007 OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
9008 Expr *Expr,
9009 SourceLocation StartLoc,
9010 SourceLocation LParenLoc,
9011 SourceLocation EndLoc);
9012 /// \brief Called on well-formed 'if' clause.
9013 OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
9014 Expr *Condition, SourceLocation StartLoc,
9015 SourceLocation LParenLoc,
9016 SourceLocation NameModifierLoc,
9017 SourceLocation ColonLoc,
9018 SourceLocation EndLoc);
9019 /// \brief Called on well-formed 'final' clause.
9020 OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
9021 SourceLocation LParenLoc,
9022 SourceLocation EndLoc);
9023 /// \brief Called on well-formed 'num_threads' clause.
9024 OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
9025 SourceLocation StartLoc,
9026 SourceLocation LParenLoc,
9027 SourceLocation EndLoc);
9028 /// \brief Called on well-formed 'safelen' clause.
9029 OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
9030 SourceLocation StartLoc,
9031 SourceLocation LParenLoc,
9032 SourceLocation EndLoc);
9033 /// \brief Called on well-formed 'simdlen' clause.
9034 OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
9035 SourceLocation LParenLoc,
9036 SourceLocation EndLoc);
9037 /// \brief Called on well-formed 'collapse' clause.
9038 OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
9039 SourceLocation StartLoc,
9040 SourceLocation LParenLoc,
9041 SourceLocation EndLoc);
9042 /// \brief Called on well-formed 'ordered' clause.
9043 OMPClause *
9044 ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
9045 SourceLocation LParenLoc = SourceLocation(),
9046 Expr *NumForLoops = nullptr);
9047 /// \brief Called on well-formed 'grainsize' clause.
9048 OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc,
9049 SourceLocation LParenLoc,
9050 SourceLocation EndLoc);
9051 /// \brief Called on well-formed 'num_tasks' clause.
9052 OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
9053 SourceLocation LParenLoc,
9054 SourceLocation EndLoc);
9055 /// \brief Called on well-formed 'hint' clause.
9056 OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
9057 SourceLocation LParenLoc,
9058 SourceLocation EndLoc);
9059
9060 OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
9061 unsigned Argument,
9062 SourceLocation ArgumentLoc,
9063 SourceLocation StartLoc,
9064 SourceLocation LParenLoc,
9065 SourceLocation EndLoc);
9066 /// \brief Called on well-formed 'default' clause.
9067 OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
9068 SourceLocation KindLoc,
9069 SourceLocation StartLoc,
9070 SourceLocation LParenLoc,
9071 SourceLocation EndLoc);
9072 /// \brief Called on well-formed 'proc_bind' clause.
9073 OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
9074 SourceLocation KindLoc,
9075 SourceLocation StartLoc,
9076 SourceLocation LParenLoc,
9077 SourceLocation EndLoc);
9078
9079 OMPClause *ActOnOpenMPSingleExprWithArgClause(
9080 OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
9081 SourceLocation StartLoc, SourceLocation LParenLoc,
9082 ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
9083 SourceLocation EndLoc);
9084 /// \brief Called on well-formed 'schedule' clause.
9085 OMPClause *ActOnOpenMPScheduleClause(
9086 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
9087 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
9088 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
9089 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
9090
9091 OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
9092 SourceLocation EndLoc);
9093 /// \brief Called on well-formed 'nowait' clause.
9094 OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
9095 SourceLocation EndLoc);
9096 /// \brief Called on well-formed 'untied' clause.
9097 OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
9098 SourceLocation EndLoc);
9099 /// \brief Called on well-formed 'mergeable' clause.
9100 OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
9101 SourceLocation EndLoc);
9102 /// \brief Called on well-formed 'read' clause.
9103 OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
9104 SourceLocation EndLoc);
9105 /// \brief Called on well-formed 'write' clause.
9106 OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
9107 SourceLocation EndLoc);
9108 /// \brief Called on well-formed 'update' clause.
9109 OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
9110 SourceLocation EndLoc);
9111 /// \brief Called on well-formed 'capture' clause.
9112 OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
9113 SourceLocation EndLoc);
9114 /// \brief Called on well-formed 'seq_cst' clause.
9115 OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
9116 SourceLocation EndLoc);
9117 /// \brief Called on well-formed 'threads' clause.
9118 OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
9119 SourceLocation EndLoc);
9120 /// \brief Called on well-formed 'simd' clause.
9121 OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
9122 SourceLocation EndLoc);
9123 /// \brief Called on well-formed 'nogroup' clause.
9124 OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
9125 SourceLocation EndLoc);
9126
9127 OMPClause *ActOnOpenMPVarListClause(
9128 OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr,
9129 SourceLocation StartLoc, SourceLocation LParenLoc,
9130 SourceLocation ColonLoc, SourceLocation EndLoc,
9131 CXXScopeSpec &ReductionIdScopeSpec,
9132 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
9133 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
9134 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
9135 SourceLocation DepLinMapLoc);
9136 /// \brief Called on well-formed 'private' clause.
9137 OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
9138 SourceLocation StartLoc,
9139 SourceLocation LParenLoc,
9140 SourceLocation EndLoc);
9141 /// \brief Called on well-formed 'firstprivate' clause.
9142 OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
9143 SourceLocation StartLoc,
9144 SourceLocation LParenLoc,
9145 SourceLocation EndLoc);
9146 /// \brief Called on well-formed 'lastprivate' clause.
9147 OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
9148 SourceLocation StartLoc,
9149 SourceLocation LParenLoc,
9150 SourceLocation EndLoc);
9151 /// \brief Called on well-formed 'shared' clause.
9152 OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
9153 SourceLocation StartLoc,
9154 SourceLocation LParenLoc,
9155 SourceLocation EndLoc);
9156 /// \brief Called on well-formed 'reduction' clause.
9157 OMPClause *ActOnOpenMPReductionClause(
9158 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9159 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
9160 CXXScopeSpec &ReductionIdScopeSpec,
9161 const DeclarationNameInfo &ReductionId,
9162 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
9163 /// Called on well-formed 'task_reduction' clause.
9164 OMPClause *ActOnOpenMPTaskReductionClause(
9165 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9166 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
9167 CXXScopeSpec &ReductionIdScopeSpec,
9168 const DeclarationNameInfo &ReductionId,
9169 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
9170 /// Called on well-formed 'in_reduction' clause.
9171 OMPClause *ActOnOpenMPInReductionClause(
9172 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9173 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
9174 CXXScopeSpec &ReductionIdScopeSpec,
9175 const DeclarationNameInfo &ReductionId,
9176 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
9177 /// \brief Called on well-formed 'linear' clause.
9178 OMPClause *
9179 ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
9180 SourceLocation StartLoc, SourceLocation LParenLoc,
9181 OpenMPLinearClauseKind LinKind, SourceLocation LinLoc,
9182 SourceLocation ColonLoc, SourceLocation EndLoc);
9183 /// \brief Called on well-formed 'aligned' clause.
9184 OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
9185 Expr *Alignment,
9186 SourceLocation StartLoc,
9187 SourceLocation LParenLoc,
9188 SourceLocation ColonLoc,
9189 SourceLocation EndLoc);
9190 /// \brief Called on well-formed 'copyin' clause.
9191 OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
9192 SourceLocation StartLoc,
9193 SourceLocation LParenLoc,
9194 SourceLocation EndLoc);
9195 /// \brief Called on well-formed 'copyprivate' clause.
9196 OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
9197 SourceLocation StartLoc,
9198 SourceLocation LParenLoc,
9199 SourceLocation EndLoc);
9200 /// \brief Called on well-formed 'flush' pseudo clause.
9201 OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
9202 SourceLocation StartLoc,
9203 SourceLocation LParenLoc,
9204 SourceLocation EndLoc);
9205 /// \brief Called on well-formed 'depend' clause.
9206 OMPClause *
9207 ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
9208 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
9209 SourceLocation StartLoc, SourceLocation LParenLoc,
9210 SourceLocation EndLoc);
9211 /// \brief Called on well-formed 'device' clause.
9212 OMPClause *ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
9213 SourceLocation LParenLoc,
9214 SourceLocation EndLoc);
9215 /// \brief Called on well-formed 'map' clause.
9216 OMPClause *
9217 ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
9218 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
9219 SourceLocation MapLoc, SourceLocation ColonLoc,
9220 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9221 SourceLocation LParenLoc, SourceLocation EndLoc);
9222 /// \brief Called on well-formed 'num_teams' clause.
9223 OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
9224 SourceLocation LParenLoc,
9225 SourceLocation EndLoc);
9226 /// \brief Called on well-formed 'thread_limit' clause.
9227 OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
9228 SourceLocation StartLoc,
9229 SourceLocation LParenLoc,
9230 SourceLocation EndLoc);
9231 /// \brief Called on well-formed 'priority' clause.
9232 OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
9233 SourceLocation LParenLoc,
9234 SourceLocation EndLoc);
9235 /// \brief Called on well-formed 'dist_schedule' clause.
9236 OMPClause *ActOnOpenMPDistScheduleClause(
9237 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
9238 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc,
9239 SourceLocation CommaLoc, SourceLocation EndLoc);
9240 /// \brief Called on well-formed 'defaultmap' clause.
9241 OMPClause *ActOnOpenMPDefaultmapClause(
9242 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
9243 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
9244 SourceLocation KindLoc, SourceLocation EndLoc);
9245 /// \brief Called on well-formed 'to' clause.
9246 OMPClause *ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
9247 SourceLocation StartLoc,
9248 SourceLocation LParenLoc,
9249 SourceLocation EndLoc);
9250 /// \brief Called on well-formed 'from' clause.
9251 OMPClause *ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
9252 SourceLocation StartLoc,
9253 SourceLocation LParenLoc,
9254 SourceLocation EndLoc);
9255 /// Called on well-formed 'use_device_ptr' clause.
9256 OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
9257 SourceLocation StartLoc,
9258 SourceLocation LParenLoc,
9259 SourceLocation EndLoc);
9260 /// Called on well-formed 'is_device_ptr' clause.
9261 OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
9262 SourceLocation StartLoc,
9263 SourceLocation LParenLoc,
9264 SourceLocation EndLoc);
9265
9266 /// \brief The kind of conversion being performed.
9267 enum CheckedConversionKind {
9268 /// \brief An implicit conversion.
9269 CCK_ImplicitConversion,
9270 /// \brief A C-style cast.
9271 CCK_CStyleCast,
9272 /// \brief A functional-style cast.
9273 CCK_FunctionalCast,
9274 /// \brief A cast other than a C-style cast.
9275 CCK_OtherCast
9276 };
9277
9278 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
9279 /// cast. If there is already an implicit cast, merge into the existing one.
9280 /// If isLvalue, the result of the cast is an lvalue.
9281 ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
9282 ExprValueKind VK = VK_RValue,
9283 const CXXCastPath *BasePath = nullptr,
9284 CheckedConversionKind CCK
9285 = CCK_ImplicitConversion);
9286
9287 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
9288 /// to the conversion from scalar type ScalarTy to the Boolean type.
9289 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
9290
9291 /// IgnoredValueConversions - Given that an expression's result is
9292 /// syntactically ignored, perform any conversions that are
9293 /// required.
9294 ExprResult IgnoredValueConversions(Expr *E);
9295
9296 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
9297 // functions and arrays to their respective pointers (C99 6.3.2.1).
9298 ExprResult UsualUnaryConversions(Expr *E);
9299
9300 /// CallExprUnaryConversions - a special case of an unary conversion
9301 /// performed on a function designator of a call expression.
9302 ExprResult CallExprUnaryConversions(Expr *E);
9303
9304 // DefaultFunctionArrayConversion - converts functions and arrays
9305 // to their respective pointers (C99 6.3.2.1).
9306 ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
9307
9308 // DefaultFunctionArrayLvalueConversion - converts functions and
9309 // arrays to their respective pointers and performs the
9310 // lvalue-to-rvalue conversion.
9311 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
9312 bool Diagnose = true);
9313
9314 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
9315 // the operand. This is DefaultFunctionArrayLvalueConversion,
9316 // except that it assumes the operand isn't of function or array
9317 // type.
9318 ExprResult DefaultLvalueConversion(Expr *E);
9319
9320 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
9321 // do not have a prototype. Integer promotions are performed on each
9322 // argument, and arguments that have type float are promoted to double.
9323 ExprResult DefaultArgumentPromotion(Expr *E);
9324
9325 /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
9326 /// it as an xvalue. In C++98, the result will still be a prvalue, because
9327 /// we don't have xvalues there.
9328 ExprResult TemporaryMaterializationConversion(Expr *E);
9329
9330 // Used for emitting the right warning by DefaultVariadicArgumentPromotion
9331 enum VariadicCallType {
9332 VariadicFunction,
9333 VariadicBlock,
9334 VariadicMethod,
9335 VariadicConstructor,
9336 VariadicDoesNotApply
9337 };
9338
9339 VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
9340 const FunctionProtoType *Proto,
9341 Expr *Fn);
9342
9343 // Used for determining in which context a type is allowed to be passed to a
9344 // vararg function.
9345 enum VarArgKind {
9346 VAK_Valid,
9347 VAK_ValidInCXX11,
9348 VAK_Undefined,
9349 VAK_MSVCUndefined,
9350 VAK_Invalid
9351 };
9352
9353 // Determines which VarArgKind fits an expression.
9354 VarArgKind isValidVarArgType(const QualType &Ty);
9355
9356 /// Check to see if the given expression is a valid argument to a variadic
9357 /// function, issuing a diagnostic if not.
9358 void checkVariadicArgument(const Expr *E, VariadicCallType CT);
9359
9360 /// Check to see if a given expression could have '.c_str()' called on it.
9361 bool hasCStrMethod(const Expr *E);
9362
9363 /// GatherArgumentsForCall - Collector argument expressions for various
9364 /// form of call prototypes.
9365 bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
9366 const FunctionProtoType *Proto,
9367 unsigned FirstParam, ArrayRef<Expr *> Args,
9368 SmallVectorImpl<Expr *> &AllArgs,
9369 VariadicCallType CallType = VariadicDoesNotApply,
9370 bool AllowExplicit = false,
9371 bool IsListInitialization = false);
9372
9373 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
9374 // will create a runtime trap if the resulting type is not a POD type.
9375 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
9376 FunctionDecl *FDecl);
9377
9378 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
9379 // operands and then handles various conversions that are common to binary
9380 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
9381 // routine returns the first non-arithmetic type found. The client is
9382 // responsible for emitting appropriate error diagnostics.
9383 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
9384 bool IsCompAssign = false);
9385
9386 /// AssignConvertType - All of the 'assignment' semantic checks return this
9387 /// enum to indicate whether the assignment was allowed. These checks are
9388 /// done for simple assignments, as well as initialization, return from
9389 /// function, argument passing, etc. The query is phrased in terms of a
9390 /// source and destination type.
9391 enum AssignConvertType {
9392 /// Compatible - the types are compatible according to the standard.
9393 Compatible,
9394
9395 /// PointerToInt - The assignment converts a pointer to an int, which we
9396 /// accept as an extension.
9397 PointerToInt,
9398
9399 /// IntToPointer - The assignment converts an int to a pointer, which we
9400 /// accept as an extension.
9401 IntToPointer,
9402
9403 /// FunctionVoidPointer - The assignment is between a function pointer and
9404 /// void*, which the standard doesn't allow, but we accept as an extension.
9405 FunctionVoidPointer,
9406
9407 /// IncompatiblePointer - The assignment is between two pointers types that
9408 /// are not compatible, but we accept them as an extension.
9409 IncompatiblePointer,
9410
9411 /// IncompatiblePointerSign - The assignment is between two pointers types
9412 /// which point to integers which have a different sign, but are otherwise
9413 /// identical. This is a subset of the above, but broken out because it's by
9414 /// far the most common case of incompatible pointers.
9415 IncompatiblePointerSign,
9416
9417 /// CompatiblePointerDiscardsQualifiers - The assignment discards
9418 /// c/v/r qualifiers, which we accept as an extension.
9419 CompatiblePointerDiscardsQualifiers,
9420
9421 /// IncompatiblePointerDiscardsQualifiers - The assignment
9422 /// discards qualifiers that we don't permit to be discarded,
9423 /// like address spaces.
9424 IncompatiblePointerDiscardsQualifiers,
9425
9426 /// IncompatibleNestedPointerQualifiers - The assignment is between two
9427 /// nested pointer types, and the qualifiers other than the first two
9428 /// levels differ e.g. char ** -> const char **, but we accept them as an
9429 /// extension.
9430 IncompatibleNestedPointerQualifiers,
9431
9432 /// IncompatibleVectors - The assignment is between two vector types that
9433 /// have the same size, which we accept as an extension.
9434 IncompatibleVectors,
9435
9436 /// IntToBlockPointer - The assignment converts an int to a block
9437 /// pointer. We disallow this.
9438 IntToBlockPointer,
9439
9440 /// IncompatibleBlockPointer - The assignment is between two block
9441 /// pointers types that are not compatible.
9442 IncompatibleBlockPointer,
9443
9444 /// IncompatibleObjCQualifiedId - The assignment is between a qualified
9445 /// id type and something else (that is incompatible with it). For example,
9446 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
9447 IncompatibleObjCQualifiedId,
9448
9449 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
9450 /// object with __weak qualifier.
9451 IncompatibleObjCWeakRef,
9452
9453 /// Incompatible - We reject this conversion outright, it is invalid to
9454 /// represent it in the AST.
9455 Incompatible
9456 };
9457
9458 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
9459 /// assignment conversion type specified by ConvTy. This returns true if the
9460 /// conversion was invalid or false if the conversion was accepted.
9461 bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
9462 SourceLocation Loc,
9463 QualType DstType, QualType SrcType,
9464 Expr *SrcExpr, AssignmentAction Action,
9465 bool *Complained = nullptr);
9466
9467 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
9468 /// enum. If AllowMask is true, then we also allow the complement of a valid
9469 /// value, to be used as a mask.
9470 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
9471 bool AllowMask) const;
9472
9473 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
9474 /// integer not in the range of enum values.
9475 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
9476 Expr *SrcExpr);
9477
9478 /// CheckAssignmentConstraints - Perform type checking for assignment,
9479 /// argument passing, variable initialization, and function return values.
9480 /// C99 6.5.16.
9481 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
9482 QualType LHSType,
9483 QualType RHSType);
9484
9485 /// Check assignment constraints and optionally prepare for a conversion of
9486 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
9487 /// is true.
9488 AssignConvertType CheckAssignmentConstraints(QualType LHSType,
9489 ExprResult &RHS,
9490 CastKind &Kind,
9491 bool ConvertRHS = true);
9492
9493 /// Check assignment constraints for an assignment of RHS to LHSType.
9494 ///
9495 /// \param LHSType The destination type for the assignment.
9496 /// \param RHS The source expression for the assignment.
9497 /// \param Diagnose If \c true, diagnostics may be produced when checking
9498 /// for assignability. If a diagnostic is produced, \p RHS will be
9499 /// set to ExprError(). Note that this function may still return
9500 /// without producing a diagnostic, even for an invalid assignment.
9501 /// \param DiagnoseCFAudited If \c true, the target is a function parameter
9502 /// in an audited Core Foundation API and does not need to be checked
9503 /// for ARC retain issues.
9504 /// \param ConvertRHS If \c true, \p RHS will be updated to model the
9505 /// conversions necessary to perform the assignment. If \c false,
9506 /// \p Diagnose must also be \c false.
9507 AssignConvertType CheckSingleAssignmentConstraints(
9508 QualType LHSType, ExprResult &RHS, bool Diagnose = true,
9509 bool DiagnoseCFAudited = false, bool ConvertRHS = true);
9510
9511 // \brief If the lhs type is a transparent union, check whether we
9512 // can initialize the transparent union with the given expression.
9513 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
9514 ExprResult &RHS);
9515
9516 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
9517
9518 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
9519
9520 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9521 AssignmentAction Action,
9522 bool AllowExplicit = false);
9523 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9524 AssignmentAction Action,
9525 bool AllowExplicit,
9526 ImplicitConversionSequence& ICS);
9527 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9528 const ImplicitConversionSequence& ICS,
9529 AssignmentAction Action,
9530 CheckedConversionKind CCK
9531 = CCK_ImplicitConversion);
9532 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9533 const StandardConversionSequence& SCS,
9534 AssignmentAction Action,
9535 CheckedConversionKind CCK);
9536
9537 /// the following "Check" methods will return a valid/converted QualType
9538 /// or a null QualType (indicating an error diagnostic was issued).
9539
9540 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
9541 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9542 ExprResult &RHS);
9543 QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9544 ExprResult &RHS);
9545 QualType CheckPointerToMemberOperands( // C++ 5.5
9546 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
9547 SourceLocation OpLoc, bool isIndirect);
9548 QualType CheckMultiplyDivideOperands( // C99 6.5.5
9549 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
9550 bool IsDivide);
9551 QualType CheckRemainderOperands( // C99 6.5.5
9552 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9553 bool IsCompAssign = false);
9554 QualType CheckAdditionOperands( // C99 6.5.6
9555 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9556 BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr);
9557 QualType CheckSubtractionOperands( // C99 6.5.6
9558 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9559 QualType* CompLHSTy = nullptr);
9560 QualType CheckShiftOperands( // C99 6.5.7
9561 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9562 BinaryOperatorKind Opc, bool IsCompAssign = false);
9563 QualType CheckCompareOperands( // C99 6.5.8/9
9564 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9565 BinaryOperatorKind Opc, bool isRelational);
9566 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
9567 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9568 BinaryOperatorKind Opc);
9569 QualType CheckLogicalOperands( // C99 6.5.[13,14]
9570 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9571 BinaryOperatorKind Opc);
9572 // CheckAssignmentOperands is used for both simple and compound assignment.
9573 // For simple assignment, pass both expressions and a null converted type.
9574 // For compound assignment, pass both expressions and the converted type.
9575 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
9576 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
9577
9578 ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
9579 UnaryOperatorKind Opcode, Expr *Op);
9580 ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
9581 BinaryOperatorKind Opcode,
9582 Expr *LHS, Expr *RHS);
9583 ExprResult checkPseudoObjectRValue(Expr *E);
9584 Expr *recreateSyntacticForm(PseudoObjectExpr *E);
9585
9586 QualType CheckConditionalOperands( // C99 6.5.15
9587 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
9588 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
9589 QualType CXXCheckConditionalOperands( // C++ 5.16
9590 ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
9591 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
9592 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
9593 bool ConvertArgs = true);
9594 QualType FindCompositePointerType(SourceLocation Loc,
9595 ExprResult &E1, ExprResult &E2,
9596 bool ConvertArgs = true) {
9597 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
9598 QualType Composite =
9599 FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
9600 E1 = E1Tmp;
9601 E2 = E2Tmp;
9602 return Composite;
9603 }
9604
9605 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
9606 SourceLocation QuestionLoc);
9607
9608 bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
9609 SourceLocation QuestionLoc);
9610
9611 void DiagnoseAlwaysNonNullPointer(Expr *E,
9612 Expr::NullPointerConstantKind NullType,
9613 bool IsEqual, SourceRange Range);
9614
9615 /// type checking for vector binary operators.
9616 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9617 SourceLocation Loc, bool IsCompAssign,
9618 bool AllowBothBool, bool AllowBoolConversion);
9619 QualType GetSignedVectorType(QualType V);
9620 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9621 SourceLocation Loc,
9622 BinaryOperatorKind Opc);
9623 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9624 SourceLocation Loc);
9625
9626 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
9627 bool isLaxVectorConversion(QualType srcType, QualType destType);
9628
9629 /// type checking declaration initializers (C99 6.7.8)
9630 bool CheckForConstantInitializer(Expr *e, QualType t);
9631
9632 // type checking C++ declaration initializers (C++ [dcl.init]).
9633
9634 /// ReferenceCompareResult - Expresses the result of comparing two
9635 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
9636 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
9637 enum ReferenceCompareResult {
9638 /// Ref_Incompatible - The two types are incompatible, so direct
9639 /// reference binding is not possible.
9640 Ref_Incompatible = 0,
9641 /// Ref_Related - The two types are reference-related, which means
9642 /// that their unqualified forms (T1 and T2) are either the same
9643 /// or T1 is a base class of T2.
9644 Ref_Related,
9645 /// Ref_Compatible - The two types are reference-compatible.
9646 Ref_Compatible
9647 };
9648
9649 ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
9650 QualType T1, QualType T2,
9651 bool &DerivedToBase,
9652 bool &ObjCConversion,
9653 bool &ObjCLifetimeConversion);
9654
9655 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
9656 Expr *CastExpr, CastKind &CastKind,
9657 ExprValueKind &VK, CXXCastPath &Path);
9658
9659 /// \brief Force an expression with unknown-type to an expression of the
9660 /// given type.
9661 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
9662
9663 /// \brief Type-check an expression that's being passed to an
9664 /// __unknown_anytype parameter.
9665 ExprResult checkUnknownAnyArg(SourceLocation callLoc,
9666 Expr *result, QualType &paramType);
9667
9668 // CheckVectorCast - check type constraints for vectors.
9669 // Since vectors are an extension, there are no C standard reference for this.
9670 // We allow casting between vectors and integer datatypes of the same size.
9671 // returns true if the cast is invalid
9672 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
9673 CastKind &Kind);
9674
9675 /// \brief Prepare `SplattedExpr` for a vector splat operation, adding
9676 /// implicit casts if necessary.
9677 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
9678
9679 // CheckExtVectorCast - check type constraints for extended vectors.
9680 // Since vectors are an extension, there are no C standard reference for this.
9681 // We allow casting between vectors and integer datatypes of the same size,
9682 // or vectors and the element type of that vector.
9683 // returns the cast expr
9684 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
9685 CastKind &Kind);
9686
9687 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
9688 SourceLocation LParenLoc,
9689 Expr *CastExpr,
9690 SourceLocation RParenLoc);
9691
9692 enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error };
9693
9694 /// \brief Checks for invalid conversions and casts between
9695 /// retainable pointers and other pointer kinds for ARC and Weak.
9696 ARCConversionResult CheckObjCConversion(SourceRange castRange,
9697 QualType castType, Expr *&op,
9698 CheckedConversionKind CCK,
9699 bool Diagnose = true,
9700 bool DiagnoseCFAudited = false,
9701 BinaryOperatorKind Opc = BO_PtrMemD
9702 );
9703
9704 Expr *stripARCUnbridgedCast(Expr *e);
9705 void diagnoseARCUnbridgedCast(Expr *e);
9706
9707 bool CheckObjCARCUnavailableWeakConversion(QualType castType,
9708 QualType ExprType);
9709
9710 /// checkRetainCycles - Check whether an Objective-C message send
9711 /// might create an obvious retain cycle.
9712 void checkRetainCycles(ObjCMessageExpr *msg);
9713 void checkRetainCycles(Expr *receiver, Expr *argument);
9714 void checkRetainCycles(VarDecl *Var, Expr *Init);
9715
9716 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
9717 /// to weak/__unsafe_unretained type.
9718 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
9719
9720 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
9721 /// to weak/__unsafe_unretained expression.
9722 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
9723
9724 /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
9725 /// \param Method - May be null.
9726 /// \param [out] ReturnType - The return type of the send.
9727 /// \return true iff there were any incompatible types.
9728 bool CheckMessageArgumentTypes(QualType ReceiverType,
9729 MultiExprArg Args, Selector Sel,
9730 ArrayRef<SourceLocation> SelectorLocs,
9731 ObjCMethodDecl *Method, bool isClassMessage,
9732 bool isSuperMessage,
9733 SourceLocation lbrac, SourceLocation rbrac,
9734 SourceRange RecRange,
9735 QualType &ReturnType, ExprValueKind &VK);
9736
9737 /// \brief Determine the result of a message send expression based on
9738 /// the type of the receiver, the method expected to receive the message,
9739 /// and the form of the message send.
9740 QualType getMessageSendResultType(QualType ReceiverType,
9741 ObjCMethodDecl *Method,
9742 bool isClassMessage, bool isSuperMessage);
9743
9744 /// \brief If the given expression involves a message send to a method
9745 /// with a related result type, emit a note describing what happened.
9746 void EmitRelatedResultTypeNote(const Expr *E);
9747
9748 /// \brief Given that we had incompatible pointer types in a return
9749 /// statement, check whether we're in a method with a related result
9750 /// type, and if so, emit a note describing what happened.
9751 void EmitRelatedResultTypeNoteForReturn(QualType destType);
9752
9753 class ConditionResult {
9754 Decl *ConditionVar;
9755 FullExprArg Condition;
9756 bool Invalid;
9757 bool HasKnownValue;
9758 bool KnownValue;
9759
9760 friend class Sema;
9761 ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition,
9762 bool IsConstexpr)
9763 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false),
9764 HasKnownValue(IsConstexpr && Condition.get() &&
9765 !Condition.get()->isValueDependent()),
9766 KnownValue(HasKnownValue &&
9767 !!Condition.get()->EvaluateKnownConstInt(S.Context)) {}
9768 explicit ConditionResult(bool Invalid)
9769 : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid),
9770 HasKnownValue(false), KnownValue(false) {}
9771
9772 public:
9773 ConditionResult() : ConditionResult(false) {}
9774 bool isInvalid() const { return Invalid; }
9775 std::pair<VarDecl *, Expr *> get() const {
9776 return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
9777 Condition.get());
9778 }
9779 llvm::Optional<bool> getKnownValue() const {
9780 if (!HasKnownValue)
9781 return None;
9782 return KnownValue;
9783 }
9784 };
9785 static ConditionResult ConditionError() { return ConditionResult(true); }
9786
9787 enum class ConditionKind {
9788 Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
9789 ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
9790 Switch ///< An integral condition for a 'switch' statement.
9791 };
9792
9793 ConditionResult ActOnCondition(Scope *S, SourceLocation Loc,
9794 Expr *SubExpr, ConditionKind CK);
9795
9796 ConditionResult ActOnConditionVariable(Decl *ConditionVar,
9797 SourceLocation StmtLoc,
9798 ConditionKind CK);
9799
9800 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
9801
9802 ExprResult CheckConditionVariable(VarDecl *ConditionVar,
9803 SourceLocation StmtLoc,
9804 ConditionKind CK);
9805 ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
9806
9807 /// CheckBooleanCondition - Diagnose problems involving the use of
9808 /// the given expression as a boolean condition (e.g. in an if
9809 /// statement). Also performs the standard function and array
9810 /// decays, possibly changing the input variable.
9811 ///
9812 /// \param Loc - A location associated with the condition, e.g. the
9813 /// 'if' keyword.
9814 /// \return true iff there were any errors
9815 ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
9816 bool IsConstexpr = false);
9817
9818 /// DiagnoseAssignmentAsCondition - Given that an expression is
9819 /// being used as a boolean condition, warn if it's an assignment.
9820 void DiagnoseAssignmentAsCondition(Expr *E);
9821
9822 /// \brief Redundant parentheses over an equality comparison can indicate
9823 /// that the user intended an assignment used as condition.
9824 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
9825
9826 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
9827 ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
9828
9829 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
9830 /// the specified width and sign. If an overflow occurs, detect it and emit
9831 /// the specified diagnostic.
9832 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
9833 unsigned NewWidth, bool NewSign,
9834 SourceLocation Loc, unsigned DiagID);
9835
9836 /// Checks that the Objective-C declaration is declared in the global scope.
9837 /// Emits an error and marks the declaration as invalid if it's not declared
9838 /// in the global scope.
9839 bool CheckObjCDeclScope(Decl *D);
9840
9841 /// \brief Abstract base class used for diagnosing integer constant
9842 /// expression violations.
9843 class VerifyICEDiagnoser {
9844 public:
9845 bool Suppress;
9846
9847 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
9848
9849 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
9850 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
9851 virtual ~VerifyICEDiagnoser() { }
9852 };
9853
9854 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
9855 /// and reports the appropriate diagnostics. Returns false on success.
9856 /// Can optionally return the value of the expression.
9857 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9858 VerifyICEDiagnoser &Diagnoser,
9859 bool AllowFold = true);
9860 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9861 unsigned DiagID,
9862 bool AllowFold = true);
9863 ExprResult VerifyIntegerConstantExpression(Expr *E,
9864 llvm::APSInt *Result = nullptr);
9865
9866 /// VerifyBitField - verifies that a bit field expression is an ICE and has
9867 /// the correct width, and that the field type is valid.
9868 /// Returns false on success.
9869 /// Can optionally return whether the bit-field is of width 0
9870 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
9871 QualType FieldTy, bool IsMsStruct,
9872 Expr *BitWidth, bool *ZeroWidth = nullptr);
9873
9874private:
9875 unsigned ForceCUDAHostDeviceDepth = 0;
9876
9877public:
9878 /// Increments our count of the number of times we've seen a pragma forcing
9879 /// functions to be __host__ __device__. So long as this count is greater
9880 /// than zero, all functions encountered will be __host__ __device__.
9881 void PushForceCUDAHostDevice();
9882
9883 /// Decrements our count of the number of times we've seen a pragma forcing
9884 /// functions to be __host__ __device__. Returns false if the count is 0
9885 /// before incrementing, so you can emit an error.
9886 bool PopForceCUDAHostDevice();
9887
9888 /// Diagnostics that are emitted only if we discover that the given function
9889 /// must be codegen'ed. Because handling these correctly adds overhead to
9890 /// compilation, this is currently only enabled for CUDA compilations.
9891 llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>,
9892 std::vector<PartialDiagnosticAt>>
9893 CUDADeferredDiags;
9894
9895 /// A pair of a canonical FunctionDecl and a SourceLocation. When used as the
9896 /// key in a hashtable, both the FD and location are hashed.
9897 struct FunctionDeclAndLoc {
9898 CanonicalDeclPtr<FunctionDecl> FD;
9899 SourceLocation Loc;
9900 };
9901
9902 /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a
9903 /// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the
9904 /// same deferred diag twice.
9905 llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags;
9906
9907 /// An inverse call graph, mapping known-emitted functions to one of their
9908 /// known-emitted callers (plus the location of the call).
9909 ///
9910 /// Functions that we can tell a priori must be emitted aren't added to this
9911 /// map.
9912 llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>,
9913 /* Caller = */ FunctionDeclAndLoc>
9914 CUDAKnownEmittedFns;
9915
9916 /// A partial call graph maintained during CUDA compilation to support
9917 /// deferred diagnostics.
9918 ///
9919 /// Functions are only added here if, at the time they're considered, they are
9920 /// not known-emitted. As soon as we discover that a function is
9921 /// known-emitted, we remove it and everything it transitively calls from this
9922 /// set and add those functions to CUDAKnownEmittedFns.
9923 llvm::DenseMap</* Caller = */ CanonicalDeclPtr<FunctionDecl>,
9924 /* Callees = */ llvm::MapVector<CanonicalDeclPtr<FunctionDecl>,
9925 SourceLocation>>
9926 CUDACallGraph;
9927
9928 /// Diagnostic builder for CUDA errors which may or may not be deferred.
9929 ///
9930 /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
9931 /// which are not allowed to appear inside __device__ functions and are
9932 /// allowed to appear in __host__ __device__ functions only if the host+device
9933 /// function is never codegen'ed.
9934 ///
9935 /// To handle this, we use the notion of "deferred diagnostics", where we
9936 /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
9937 ///
9938 /// This class lets you emit either a regular diagnostic, a deferred
9939 /// diagnostic, or no diagnostic at all, according to an argument you pass to
9940 /// its constructor, thus simplifying the process of creating these "maybe
9941 /// deferred" diagnostics.
9942 class CUDADiagBuilder {
9943 public:
9944 enum Kind {
9945 /// Emit no diagnostics.
9946 K_Nop,
9947 /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
9948 K_Immediate,
9949 /// Emit the diagnostic immediately, and, if it's a warning or error, also
9950 /// emit a call stack showing how this function can be reached by an a
9951 /// priori known-emitted function.
9952 K_ImmediateWithCallStack,
9953 /// Create a deferred diagnostic, which is emitted only if the function
9954 /// it's attached to is codegen'ed. Also emit a call stack as with
9955 /// K_ImmediateWithCallStack.
9956 K_Deferred
9957 };
9958
9959 CUDADiagBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
9960 FunctionDecl *Fn, Sema &S);
9961 ~CUDADiagBuilder();
9962
9963 /// Convertible to bool: True if we immediately emitted an error, false if
9964 /// we didn't emit an error or we created a deferred error.
9965 ///
9966 /// Example usage:
9967 ///
9968 /// if (CUDADiagBuilder(...) << foo << bar)
9969 /// return ExprError();
9970 ///
9971 /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
9972 /// want to use these instead of creating a CUDADiagBuilder yourself.
9973 operator bool() const { return ImmediateDiag.hasValue(); }
9974
9975 template <typename T>
9976 friend const CUDADiagBuilder &operator<<(const CUDADiagBuilder &Diag,
9977 const T &Value) {
9978 if (Diag.ImmediateDiag.hasValue())
11
Assuming the condition is false
12
Taking false branch
9979 *Diag.ImmediateDiag << Value;
9980 else if (Diag.PartialDiag.hasValue())
13
Assuming the condition is true
14
Taking true branch
9981 *Diag.PartialDiag << Value;
15
Calling 'operator<<'
26
Returned allocated memory
9982 return Diag;
9983 }
9984
9985 private:
9986 Sema &S;
9987 SourceLocation Loc;
9988 unsigned DiagID;
9989 FunctionDecl *Fn;
9990 bool ShowCallStack;
9991
9992 // Invariant: At most one of these Optionals has a value.
9993 // FIXME: Switch these to a Variant once that exists.
9994 llvm::Optional<SemaDiagnosticBuilder> ImmediateDiag;
9995 llvm::Optional<PartialDiagnostic> PartialDiag;
9996 };
9997
9998 /// Creates a CUDADiagBuilder that emits the diagnostic if the current context
9999 /// is "used as device code".
10000 ///
10001 /// - If CurContext is a __host__ function, does not emit any diagnostics.
10002 /// - If CurContext is a __device__ or __global__ function, emits the
10003 /// diagnostics immediately.
10004 /// - If CurContext is a __host__ __device__ function and we are compiling for
10005 /// the device, creates a diagnostic which is emitted if and when we realize
10006 /// that the function will be codegen'ed.
10007 ///
10008 /// Example usage:
10009 ///
10010 /// // Variable-length arrays are not allowed in CUDA device code.
10011 /// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget())
10012 /// return ExprError();
10013 /// // Otherwise, continue parsing as normal.
10014 CUDADiagBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID);
10015
10016 /// Creates a CUDADiagBuilder that emits the diagnostic if the current context
10017 /// is "used as host code".
10018 ///
10019 /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched.
10020 CUDADiagBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID);
10021
10022 enum CUDAFunctionTarget {
10023 CFT_Device,
10024 CFT_Global,
10025 CFT_Host,
10026 CFT_HostDevice,
10027 CFT_InvalidTarget
10028 };
10029
10030 /// Determines whether the given function is a CUDA device/host/kernel/etc.
10031 /// function.
10032 ///
10033 /// Use this rather than examining the function's attributes yourself -- you
10034 /// will get it wrong. Returns CFT_Host if D is null.
10035 CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D,
10036 bool IgnoreImplicitHDAttr = false);
10037 CUDAFunctionTarget IdentifyCUDATarget(const AttributeList *Attr);
10038
10039 /// Gets the CUDA target for the current context.
10040 CUDAFunctionTarget CurrentCUDATarget() {
10041 return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext));
10042 }
10043
10044 // CUDA function call preference. Must be ordered numerically from
10045 // worst to best.
10046 enum CUDAFunctionPreference {
10047 CFP_Never, // Invalid caller/callee combination.
10048 CFP_WrongSide, // Calls from host-device to host or device
10049 // function that do not match current compilation
10050 // mode.
10051 CFP_HostDevice, // Any calls to host/device functions.
10052 CFP_SameSide, // Calls from host-device to host or device
10053 // function matching current compilation mode.
10054 CFP_Native, // host-to-host or device-to-device calls.
10055 };
10056
10057 /// Identifies relative preference of a given Caller/Callee
10058 /// combination, based on their host/device attributes.
10059 /// \param Caller function which needs address of \p Callee.
10060 /// nullptr in case of global context.
10061 /// \param Callee target function
10062 ///
10063 /// \returns preference value for particular Caller/Callee combination.
10064 CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller,
10065 const FunctionDecl *Callee);
10066
10067 /// Determines whether Caller may invoke Callee, based on their CUDA
10068 /// host/device attributes. Returns false if the call is not allowed.
10069 ///
10070 /// Note: Will return true for CFP_WrongSide calls. These may appear in
10071 /// semantically correct CUDA programs, but only if they're never codegen'ed.
10072 bool IsAllowedCUDACall(const FunctionDecl *Caller,
10073 const FunctionDecl *Callee) {
10074 return IdentifyCUDAPreference(Caller, Callee) != CFP_Never;
10075 }
10076
10077 /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD,
10078 /// depending on FD and the current compilation settings.
10079 void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD,
10080 const LookupResult &Previous);
10081
10082public:
10083 /// Check whether we're allowed to call Callee from the current context.
10084 ///
10085 /// - If the call is never allowed in a semantically-correct program
10086 /// (CFP_Never), emits an error and returns false.
10087 ///
10088 /// - If the call is allowed in semantically-correct programs, but only if
10089 /// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to
10090 /// be emitted if and when the caller is codegen'ed, and returns true.
10091 ///
10092 /// Will only create deferred diagnostics for a given SourceLocation once,
10093 /// so you can safely call this multiple times without generating duplicate
10094 /// deferred errors.
10095 ///
10096 /// - Otherwise, returns true without emitting any diagnostics.
10097 bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee);
10098
10099 /// Set __device__ or __host__ __device__ attributes on the given lambda
10100 /// operator() method.
10101 ///
10102 /// CUDA lambdas declared inside __device__ or __global__ functions inherit
10103 /// the __device__ attribute. Similarly, lambdas inside __host__ __device__
10104 /// functions become __host__ __device__ themselves.
10105 void CUDASetLambdaAttrs(CXXMethodDecl *Method);
10106
10107 /// Finds a function in \p Matches with highest calling priority
10108 /// from \p Caller context and erases all functions with lower
10109 /// calling priority.
10110 void EraseUnwantedCUDAMatches(
10111 const FunctionDecl *Caller,
10112 SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
10113
10114 /// Given a implicit special member, infer its CUDA target from the
10115 /// calls it needs to make to underlying base/field special members.
10116 /// \param ClassDecl the class for which the member is being created.
10117 /// \param CSM the kind of special member.
10118 /// \param MemberDecl the special member itself.
10119 /// \param ConstRHS true if this is a copy operation with a const object on
10120 /// its RHS.
10121 /// \param Diagnose true if this call should emit diagnostics.
10122 /// \return true if there was an error inferring.
10123 /// The result of this call is implicit CUDA target attribute(s) attached to
10124 /// the member declaration.
10125 bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
10126 CXXSpecialMember CSM,
10127 CXXMethodDecl *MemberDecl,
10128 bool ConstRHS,
10129 bool Diagnose);
10130
10131 /// \return true if \p CD can be considered empty according to CUDA
10132 /// (E.2.3.1 in CUDA 7.5 Programming guide).
10133 bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD);
10134 bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD);
10135
10136 /// Check whether NewFD is a valid overload for CUDA. Emits
10137 /// diagnostics and invalidates NewFD if not.
10138 void checkCUDATargetOverload(FunctionDecl *NewFD,
10139 const LookupResult &Previous);
10140 /// Copies target attributes from the template TD to the function FD.
10141 void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD);
10142
10143 /// \name Code completion
10144 //@{
10145 /// \brief Describes the context in which code completion occurs.
10146 enum ParserCompletionContext {
10147 /// \brief Code completion occurs at top-level or namespace context.
10148 PCC_Namespace,
10149 /// \brief Code completion occurs within a class, struct, or union.
10150 PCC_Class,
10151 /// \brief Code completion occurs within an Objective-C interface, protocol,
10152 /// or category.
10153 PCC_ObjCInterface,
10154 /// \brief Code completion occurs within an Objective-C implementation or
10155 /// category implementation
10156 PCC_ObjCImplementation,
10157 /// \brief Code completion occurs within the list of instance variables
10158 /// in an Objective-C interface, protocol, category, or implementation.
10159 PCC_ObjCInstanceVariableList,
10160 /// \brief Code completion occurs following one or more template
10161 /// headers.
10162 PCC_Template,
10163 /// \brief Code completion occurs following one or more template
10164 /// headers within a class.
10165 PCC_MemberTemplate,
10166 /// \brief Code completion occurs within an expression.
10167 PCC_Expression,
10168 /// \brief Code completion occurs within a statement, which may
10169 /// also be an expression or a declaration.
10170 PCC_Statement,
10171 /// \brief Code completion occurs at the beginning of the
10172 /// initialization statement (or expression) in a for loop.
10173 PCC_ForInit,
10174 /// \brief Code completion occurs within the condition of an if,
10175 /// while, switch, or for statement.
10176 PCC_Condition,
10177 /// \brief Code completion occurs within the body of a function on a
10178 /// recovery path, where we do not have a specific handle on our position
10179 /// in the grammar.
10180 PCC_RecoveryInFunction,
10181 /// \brief Code completion occurs where only a type is permitted.
10182 PCC_Type,
10183 /// \brief Code completion occurs in a parenthesized expression, which
10184 /// might also be a type cast.
10185 PCC_ParenthesizedExpression,
10186 /// \brief Code completion occurs within a sequence of declaration
10187 /// specifiers within a function, method, or block.
10188 PCC_LocalDeclarationSpecifiers
10189 };
10190
10191 void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
10192 void CodeCompleteOrdinaryName(Scope *S,
10193 ParserCompletionContext CompletionContext);
10194 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
10195 bool AllowNonIdentifiers,
10196 bool AllowNestedNameSpecifiers);
10197
10198 struct CodeCompleteExpressionData;
10199 void CodeCompleteExpression(Scope *S,
10200 const CodeCompleteExpressionData &Data);
10201 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
10202 SourceLocation OpLoc, bool IsArrow,
10203 bool IsBaseExprStatement);
10204 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
10205 void CodeCompleteTag(Scope *S, unsigned TagSpec);
10206 void CodeCompleteTypeQualifiers(DeclSpec &DS);
10207 void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
10208 const VirtSpecifiers *VS = nullptr);
10209 void CodeCompleteBracketDeclarator(Scope *S);
10210 void CodeCompleteCase(Scope *S);
10211 void CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args);
10212 void CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
10213 ArrayRef<Expr *> Args);
10214 void CodeCompleteInitializer(Scope *S, Decl *D);
10215 void CodeCompleteReturn(Scope *S);
10216 void CodeCompleteAfterIf(Scope *S);
10217 void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
10218
10219 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
10220 bool EnteringContext);
10221 void CodeCompleteUsing(Scope *S);
10222 void CodeCompleteUsingDirective(Scope *S);
10223 void CodeCompleteNamespaceDecl(Scope *S);
10224 void CodeCompleteNamespaceAliasDecl(Scope *S);
10225 void CodeCompleteOperatorName(Scope *S);
10226 void CodeCompleteConstructorInitializer(
10227 Decl *Constructor,
10228 ArrayRef<CXXCtorInitializer *> Initializers);
10229
10230 void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
10231 bool AfterAmpersand);
10232
10233 void CodeCompleteObjCAtDirective(Scope *S);
10234 void CodeCompleteObjCAtVisibility(Scope *S);
10235 void CodeCompleteObjCAtStatement(Scope *S);
10236 void CodeCompleteObjCAtExpression(Scope *S);
10237 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
10238 void CodeCompleteObjCPropertyGetter(Scope *S);
10239 void CodeCompleteObjCPropertySetter(Scope *S);
10240 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
10241 bool IsParameter);
10242 void CodeCompleteObjCMessageReceiver(Scope *S);
10243 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
10244 ArrayRef<IdentifierInfo *> SelIdents,
10245 bool AtArgumentExpression);
10246 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
10247 ArrayRef<IdentifierInfo *> SelIdents,
10248 bool AtArgumentExpression,
10249 bool IsSuper = false);
10250 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
10251 ArrayRef<IdentifierInfo *> SelIdents,
10252 bool AtArgumentExpression,
10253 ObjCInterfaceDecl *Super = nullptr);
10254 void CodeCompleteObjCForCollection(Scope *S,
10255 DeclGroupPtrTy IterationVar);
10256 void CodeCompleteObjCSelector(Scope *S,
10257 ArrayRef<IdentifierInfo *> SelIdents);
10258 void CodeCompleteObjCProtocolReferences(
10259 ArrayRef<IdentifierLocPair> Protocols);
10260 void CodeCompleteObjCProtocolDecl(Scope *S);
10261 void CodeCompleteObjCInterfaceDecl(Scope *S);
10262 void CodeCompleteObjCSuperclass(Scope *S,
10263 IdentifierInfo *ClassName,
10264 SourceLocation ClassNameLoc);
10265 void CodeCompleteObjCImplementationDecl(Scope *S);
10266 void CodeCompleteObjCInterfaceCategory(Scope *S,
10267 IdentifierInfo *ClassName,
10268 SourceLocation ClassNameLoc);
10269 void CodeCompleteObjCImplementationCategory(Scope *S,
10270 IdentifierInfo *ClassName,
10271 SourceLocation ClassNameLoc);
10272 void CodeCompleteObjCPropertyDefinition(Scope *S);
10273 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
10274 IdentifierInfo *PropertyName);
10275 void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod,
10276 ParsedType ReturnType);
10277 void CodeCompleteObjCMethodDeclSelector(Scope *S,
10278 bool IsInstanceMethod,
10279 bool AtParameterName,
10280 ParsedType ReturnType,
10281 ArrayRef<IdentifierInfo *> SelIdents);
10282 void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName,
10283 SourceLocation ClassNameLoc,
10284 bool IsBaseExprStatement);
10285 void CodeCompletePreprocessorDirective(bool InConditional);
10286 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
10287 void CodeCompletePreprocessorMacroName(bool IsDefinition);
10288 void CodeCompletePreprocessorExpression();
10289 void CodeCompletePreprocessorMacroArgument(Scope *S,
10290 IdentifierInfo *Macro,
10291 MacroInfo *MacroInfo,
10292 unsigned Argument);
10293 void CodeCompleteNaturalLanguage();
10294 void CodeCompleteAvailabilityPlatformName();
10295 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
10296 CodeCompletionTUInfo &CCTUInfo,
10297 SmallVectorImpl<CodeCompletionResult> &Results);
10298 //@}
10299
10300 //===--------------------------------------------------------------------===//
10301 // Extra semantic analysis beyond the C type system
10302
10303public:
10304 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
10305 unsigned ByteNo) const;
10306
10307private:
10308 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
10309 const ArraySubscriptExpr *ASE=nullptr,
10310 bool AllowOnePastEnd=true, bool IndexNegated=false);
10311 void CheckArrayAccess(const Expr *E);
10312 // Used to grab the relevant information from a FormatAttr and a
10313 // FunctionDeclaration.
10314 struct FormatStringInfo {
10315 unsigned FormatIdx;
10316 unsigned FirstDataArg;
10317 bool HasVAListArg;
10318 };
10319
10320 static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
10321 FormatStringInfo *FSI);
10322 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
10323 const FunctionProtoType *Proto);
10324 bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
10325 ArrayRef<const Expr *> Args);
10326 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
10327 const FunctionProtoType *Proto);
10328 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
10329 void CheckConstructorCall(FunctionDecl *FDecl,
10330 ArrayRef<const Expr *> Args,
10331 const FunctionProtoType *Proto,
10332 SourceLocation Loc);
10333
10334 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
10335 const Expr *ThisArg, ArrayRef<const Expr *> Args,
10336 bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
10337 VariadicCallType CallType);
10338
10339 bool CheckObjCString(Expr *Arg);
10340 ExprResult CheckOSLogFormatStringArg(Expr *Arg);
10341
10342 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
10343 unsigned BuiltinID, CallExpr *TheCall);
10344
10345 bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
10346 unsigned MaxWidth);
10347 bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10348 bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10349
10350 bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10351 bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10352 bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10353 bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall);
10354 bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall);
10355 bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10356 bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10357
10358 bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
10359 bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call);
10360 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
10361 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
10362 bool SemaBuiltinVSX(CallExpr *TheCall);
10363 bool SemaBuiltinOSLogFormat(CallExpr *TheCall);
10364
10365public:
10366 // Used by C++ template instantiation.
10367 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
10368 ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
10369 SourceLocation BuiltinLoc,
10370 SourceLocation RParenLoc);
10371
10372private:
10373 bool SemaBuiltinPrefetch(CallExpr *TheCall);
10374 bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall);
10375 bool SemaBuiltinAssume(CallExpr *TheCall);
10376 bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
10377 bool SemaBuiltinLongjmp(CallExpr *TheCall);
10378 bool SemaBuiltinSetjmp(CallExpr *TheCall);
10379 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
10380 ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult);
10381 ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
10382 AtomicExpr::AtomicOp Op);
10383 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
10384 llvm::APSInt &Result);
10385 bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
10386 int Low, int High);
10387 bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
10388 unsigned Multiple);
10389 bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
10390 int ArgNum, unsigned ExpectedFieldNum,
10391 bool AllowName);
10392public:
10393 enum FormatStringType {
10394 FST_Scanf,
10395 FST_Printf,
10396 FST_NSString,
10397 FST_Strftime,
10398 FST_Strfmon,
10399 FST_Kprintf,
10400 FST_FreeBSDKPrintf,
10401 FST_OSTrace,
10402 FST_OSLog,
10403 FST_Unknown
10404 };
10405 static FormatStringType GetFormatStringType(const FormatAttr *Format);
10406
10407 bool FormatStringHasSArg(const StringLiteral *FExpr);
10408
10409 static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
10410
10411private:
10412 bool CheckFormatArguments(const FormatAttr *Format,
10413 ArrayRef<const Expr *> Args,
10414 bool IsCXXMember,
10415 VariadicCallType CallType,
10416 SourceLocation Loc, SourceRange Range,
10417 llvm::SmallBitVector &CheckedVarArgs);
10418 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
10419 bool HasVAListArg, unsigned format_idx,
10420 unsigned firstDataArg, FormatStringType Type,
10421 VariadicCallType CallType,
10422 SourceLocation Loc, SourceRange range,
10423 llvm::SmallBitVector &CheckedVarArgs);
10424
10425 void CheckAbsoluteValueFunction(const CallExpr *Call,
10426 const FunctionDecl *FDecl);
10427
10428 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
10429
10430 void CheckMemaccessArguments(const CallExpr *Call,
10431 unsigned BId,
10432 IdentifierInfo *FnName);
10433
10434 void CheckStrlcpycatArguments(const CallExpr *Call,
10435 IdentifierInfo *FnName);
10436
10437 void CheckStrncatArguments(const CallExpr *Call,
10438 IdentifierInfo *FnName);
10439
10440 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10441 SourceLocation ReturnLoc,
10442 bool isObjCMethod = false,
10443 const AttrVec *Attrs = nullptr,
10444 const FunctionDecl *FD = nullptr);
10445
10446public:
10447 void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS);
10448
10449private:
10450 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
10451 void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
10452 void CheckForIntOverflow(Expr *E);
10453 void CheckUnsequencedOperations(Expr *E);
10454
10455 /// \brief Perform semantic checks on a completed expression. This will either
10456 /// be a full-expression or a default argument expression.
10457 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
10458 bool IsConstexpr = false);
10459
10460 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
10461 Expr *Init);
10462
10463 /// Check if there is a field shadowing.
10464 void CheckShadowInheritedFields(const SourceLocation &Loc,
10465 DeclarationName FieldName,
10466 const CXXRecordDecl *RD);
10467
10468 /// \brief Check if the given expression contains 'break' or 'continue'
10469 /// statement that produces control flow different from GCC.
10470 void CheckBreakContinueBinding(Expr *E);
10471
10472 /// \brief Check whether receiver is mutable ObjC container which
10473 /// attempts to add itself into the container
10474 void CheckObjCCircularContainer(ObjCMessageExpr *Message);
10475
10476 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
10477 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
10478 bool DeleteWasArrayForm);
10479public:
10480 /// \brief Register a magic integral constant to be used as a type tag.
10481 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
10482 uint64_t MagicValue, QualType Type,
10483 bool LayoutCompatible, bool MustBeNull);
10484
10485 struct TypeTagData {
10486 TypeTagData() {}
10487
10488 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
10489 Type(Type), LayoutCompatible(LayoutCompatible),
10490 MustBeNull(MustBeNull)
10491 {}
10492
10493 QualType Type;
10494
10495 /// If true, \c Type should be compared with other expression's types for
10496 /// layout-compatibility.
10497 unsigned LayoutCompatible : 1;
10498 unsigned MustBeNull : 1;
10499 };
10500
10501 /// A pair of ArgumentKind identifier and magic value. This uniquely
10502 /// identifies the magic value.
10503 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
10504
10505private:
10506 /// \brief A map from magic value to type information.
10507 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
10508 TypeTagForDatatypeMagicValues;
10509
10510 /// \brief Peform checks on a call of a function with argument_with_type_tag
10511 /// or pointer_with_type_tag attributes.
10512 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
10513 const ArrayRef<const Expr *> ExprArgs,
10514 SourceLocation CallSiteLoc);
10515
10516 /// \brief Check if we are taking the address of a packed field
10517 /// as this may be a problem if the pointer value is dereferenced.
10518 void CheckAddressOfPackedMember(Expr *rhs);
10519
10520 /// \brief The parser's current scope.
10521 ///
10522 /// The parser maintains this state here.
10523 Scope *CurScope;
10524
10525 mutable IdentifierInfo *Ident_super;
10526 mutable IdentifierInfo *Ident___float128;
10527
10528 /// Nullability type specifiers.
10529 IdentifierInfo *Ident__Nonnull = nullptr;
10530 IdentifierInfo *Ident__Nullable = nullptr;
10531 IdentifierInfo *Ident__Null_unspecified = nullptr;
10532
10533 IdentifierInfo *Ident_NSError = nullptr;
10534
10535 /// \brief The handler for the FileChanged preprocessor events.
10536 ///
10537 /// Used for diagnostics that implement custom semantic analysis for #include
10538 /// directives, like -Wpragma-pack.
10539 sema::SemaPPCallbacks *SemaPPCallbackHandler;
10540
10541protected:
10542 friend class Parser;
10543 friend class InitializationSequence;
10544 friend class ASTReader;
10545 friend class ASTDeclReader;
10546 friend class ASTWriter;
10547
10548public:
10549 /// Retrieve the keyword associated
10550 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
10551
10552 /// The struct behind the CFErrorRef pointer.
10553 RecordDecl *CFError = nullptr;
10554
10555 /// Retrieve the identifier "NSError".
10556 IdentifierInfo *getNSErrorIdent();
10557
10558 /// \brief Retrieve the parser's current scope.
10559 ///
10560 /// This routine must only be used when it is certain that semantic analysis
10561 /// and the parser are in precisely the same context, which is not the case
10562 /// when, e.g., we are performing any kind of template instantiation.
10563 /// Therefore, the only safe places to use this scope are in the parser
10564 /// itself and in routines directly invoked from the parser and *never* from
10565 /// template substitution or instantiation.
10566 Scope *getCurScope() const { return CurScope; }
10567
10568 void incrementMSManglingNumber() const {
10569 return CurScope->incrementMSManglingNumber();
10570 }
10571
10572 IdentifierInfo *getSuperIdentifier() const;
10573 IdentifierInfo *getFloat128Identifier() const;
10574
10575 Decl *getObjCDeclContext() const;
10576
10577 DeclContext *getCurLexicalContext() const {
10578 return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
10579 }
10580
10581 const DeclContext *getCurObjCLexicalContext() const {
10582 const DeclContext *DC = getCurLexicalContext();
10583 // A category implicitly has the attribute of the interface.
10584 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
10585 DC = CatD->getClassInterface();
10586 return DC;
10587 }
10588
10589 /// \brief To be used for checking whether the arguments being passed to
10590 /// function exceeds the number of parameters expected for it.
10591 static bool TooManyArguments(size_t NumParams, size_t NumArgs,
10592 bool PartialOverloading = false) {
10593 // We check whether we're just after a comma in code-completion.
10594 if (NumArgs > 0 && PartialOverloading)
10595 return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
10596 return NumArgs > NumParams;
10597 }
10598
10599 // Emitting members of dllexported classes is delayed until the class
10600 // (including field initializers) is fully parsed.
10601 SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses;
10602
10603private:
10604 class SavePendingParsedClassStateRAII {
10605 public:
10606 SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); }
10607
10608 ~SavePendingParsedClassStateRAII() {
10609 assert(S.DelayedExceptionSpecChecks.empty() &&(static_cast <bool> (S.DelayedExceptionSpecChecks.empty
() && "there shouldn't be any pending delayed exception spec checks"
) ? void (0) : __assert_fail ("S.DelayedExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/Sema/Sema.h"
, 10610, __extension__ __PRETTY_FUNCTION__))
10610 "there shouldn't be any pending delayed exception spec checks")(static_cast <bool> (S.DelayedExceptionSpecChecks.empty
() && "there shouldn't be any pending delayed exception spec checks"
) ? void (0) : __assert_fail ("S.DelayedExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/Sema/Sema.h"
, 10610, __extension__ __PRETTY_FUNCTION__))
;
10611 assert(S.DelayedDefaultedMemberExceptionSpecs.empty() &&(static_cast <bool> (S.DelayedDefaultedMemberExceptionSpecs
.empty() && "there shouldn't be any pending delayed defaulted member "
"exception specs") ? void (0) : __assert_fail ("S.DelayedDefaultedMemberExceptionSpecs.empty() && \"there shouldn't be any pending delayed defaulted member \" \"exception specs\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/Sema/Sema.h"
, 10613, __extension__ __PRETTY_FUNCTION__))
10612 "there shouldn't be any pending delayed defaulted member "(static_cast <bool> (S.DelayedDefaultedMemberExceptionSpecs
.empty() && "there shouldn't be any pending delayed defaulted member "
"exception specs") ? void (0) : __assert_fail ("S.DelayedDefaultedMemberExceptionSpecs.empty() && \"there shouldn't be any pending delayed defaulted member \" \"exception specs\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/Sema/Sema.h"
, 10613, __extension__ __PRETTY_FUNCTION__))
10613 "exception specs")(static_cast <bool> (S.DelayedDefaultedMemberExceptionSpecs
.empty() && "there shouldn't be any pending delayed defaulted member "
"exception specs") ? void (0) : __assert_fail ("S.DelayedDefaultedMemberExceptionSpecs.empty() && \"there shouldn't be any pending delayed defaulted member \" \"exception specs\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/Sema/Sema.h"
, 10613, __extension__ __PRETTY_FUNCTION__))
;
10614 assert(S.DelayedDllExportClasses.empty() &&(static_cast <bool> (S.DelayedDllExportClasses.empty() &&
"there shouldn't be any pending delayed DLL export classes")
? void (0) : __assert_fail ("S.DelayedDllExportClasses.empty() && \"there shouldn't be any pending delayed DLL export classes\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/Sema/Sema.h"
, 10615, __extension__ __PRETTY_FUNCTION__))
10615 "there shouldn't be any pending delayed DLL export classes")(static_cast <bool> (S.DelayedDllExportClasses.empty() &&
"there shouldn't be any pending delayed DLL export classes")
? void (0) : __assert_fail ("S.DelayedDllExportClasses.empty() && \"there shouldn't be any pending delayed DLL export classes\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/Sema/Sema.h"
, 10615, __extension__ __PRETTY_FUNCTION__))
;
10616 swapSavedState();
10617 }
10618
10619 private:
10620 Sema &S;
10621 decltype(DelayedExceptionSpecChecks) SavedExceptionSpecChecks;
10622 decltype(DelayedDefaultedMemberExceptionSpecs)
10623 SavedDefaultedMemberExceptionSpecs;
10624 decltype(DelayedDllExportClasses) SavedDllExportClasses;
10625
10626 void swapSavedState() {
10627 SavedExceptionSpecChecks.swap(S.DelayedExceptionSpecChecks);
10628 SavedDefaultedMemberExceptionSpecs.swap(
10629 S.DelayedDefaultedMemberExceptionSpecs);
10630 SavedDllExportClasses.swap(S.DelayedDllExportClasses);
10631 }
10632 };
10633
10634 /// \brief Helper class that collects misaligned member designations and
10635 /// their location info for delayed diagnostics.
10636 struct MisalignedMember {
10637 Expr *E;
10638 RecordDecl *RD;
10639 ValueDecl *MD;
10640 CharUnits Alignment;
10641
10642 MisalignedMember() : E(), RD(), MD(), Alignment() {}
10643 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
10644 CharUnits Alignment)
10645 : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
10646 explicit MisalignedMember(Expr *E)
10647 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
10648
10649 bool operator==(const MisalignedMember &m) { return this->E == m.E; }
10650 };
10651 /// \brief Small set of gathered accesses to potentially misaligned members
10652 /// due to the packed attribute.
10653 SmallVector<MisalignedMember, 4> MisalignedMembers;
10654
10655 /// \brief Adds an expression to the set of gathered misaligned members.
10656 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
10657 CharUnits Alignment);
10658
10659public:
10660 /// \brief Diagnoses the current set of gathered accesses. This typically
10661 /// happens at full expression level. The set is cleared after emitting the
10662 /// diagnostics.
10663 void DiagnoseMisalignedMembers();
10664
10665 /// \brief This function checks if the expression is in the sef of potentially
10666 /// misaligned members and it is converted to some pointer type T with lower
10667 /// or equal alignment requirements. If so it removes it. This is used when
10668 /// we do not want to diagnose such misaligned access (e.g. in conversions to
10669 /// void*).
10670 void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
10671
10672 /// \brief This function calls Action when it determines that E designates a
10673 /// misaligned member due to the packed attribute. This is used to emit
10674 /// local diagnostics like in reference binding.
10675 void RefersToMemberWithReducedAlignment(
10676 Expr *E,
10677 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
10678 Action);
10679};
10680
10681/// \brief RAII object that enters a new expression evaluation context.
10682class EnterExpressionEvaluationContext {
10683 Sema &Actions;
10684 bool Entered = true;
10685
10686public:
10687
10688 EnterExpressionEvaluationContext(Sema &Actions,
10689 Sema::ExpressionEvaluationContext NewContext,
10690 Decl *LambdaContextDecl = nullptr,
10691 bool IsDecltype = false,
10692 bool ShouldEnter = true)
10693 : Actions(Actions), Entered(ShouldEnter) {
10694 if (Entered)
10695 Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
10696 IsDecltype);
10697 }
10698 EnterExpressionEvaluationContext(Sema &Actions,
10699 Sema::ExpressionEvaluationContext NewContext,
10700 Sema::ReuseLambdaContextDecl_t,
10701 bool IsDecltype = false)
10702 : Actions(Actions) {
10703 Actions.PushExpressionEvaluationContext(NewContext,
10704 Sema::ReuseLambdaContextDecl,
10705 IsDecltype);
10706 }
10707
10708 enum InitListTag { InitList };
10709 EnterExpressionEvaluationContext(Sema &Actions, InitListTag,
10710 bool ShouldEnter = true)
10711 : Actions(Actions), Entered(false) {
10712 // In C++11 onwards, narrowing checks are performed on the contents of
10713 // braced-init-lists, even when they occur within unevaluated operands.
10714 // Therefore we still need to instantiate constexpr functions used in such
10715 // a context.
10716 if (ShouldEnter && Actions.isUnevaluatedContext() &&
10717 Actions.getLangOpts().CPlusPlus11) {
10718 Actions.PushExpressionEvaluationContext(
10719 Sema::ExpressionEvaluationContext::UnevaluatedList, nullptr, false);
10720 Entered = true;
10721 }
10722 }
10723
10724 ~EnterExpressionEvaluationContext() {
10725 if (Entered)
10726 Actions.PopExpressionEvaluationContext();
10727 }
10728};
10729
10730DeductionFailureInfo
10731MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
10732 sema::TemplateDeductionInfo &Info);
10733
10734/// \brief Contains a late templated function.
10735/// Will be parsed at the end of the translation unit, used by Sema & Parser.
10736struct LateParsedTemplate {
10737 CachedTokens Toks;
10738 /// \brief The template function declaration to be late parsed.
10739 Decl *D;
10740};
10741
10742} // end namespace clang
10743
10744namespace llvm {
10745// Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its
10746// SourceLocation.
10747template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> {
10748 using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc;
10749 using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>;
10750
10751 static FunctionDeclAndLoc getEmptyKey() {
10752 return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()};
10753 }
10754
10755 static FunctionDeclAndLoc getTombstoneKey() {
10756 return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()};
10757 }
10758
10759 static unsigned getHashValue(const FunctionDeclAndLoc &FDL) {
10760 return hash_combine(FDBaseInfo::getHashValue(FDL.FD),
10761 FDL.Loc.getRawEncoding());
10762 }
10763
10764 static bool isEqual(const FunctionDeclAndLoc &LHS,
10765 const FunctionDeclAndLoc &RHS) {
10766 return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc;
10767 }
10768};
10769} // namespace llvm
10770
10771#endif

/build/llvm-toolchain-snapshot-7~svn326425/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/// 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 LLVM_ALIGNAS(8)alignas(8) 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 /// Return the type wrapped by this type source info.
97 QualType getType() const { return Ty; }
98
99 /// Return the TypeLoc wrapper for the type source info.
100 TypeLoc getTypeLoc() const; // implemented in TypeLoc.h
101
102 /// Override the type stored in this TypeSourceInfo. Use with caution!
103 void overrideType(QualType T) { Ty = T; }
104};
105
106/// 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/// 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/// 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/// 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/// This represents a decl that may have a name. Many decls have names such
244/// as ObjCMethodDecl, but not \@class, etc.
245///
246/// Note that not every NamedDecl is actually named (e.g., a struct might
247/// be anonymous), and not every name is an identifier.
248class NamedDecl : public Decl {
249 /// The name of this declaration, which is typically a normal
250 /// identifier but may also be a special kind of name (C++
251 /// constructor, Objective-C selector, etc.)
252 DeclarationName Name;
253
254 virtual void anchor();
255
256private:
257 NamedDecl *getUnderlyingDeclImpl() LLVM_READONLY__attribute__((__pure__));
258
259protected:
260 NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N)
261 : Decl(DK, DC, L), Name(N) {}
262
263public:
264 /// Get the identifier that names this declaration, if there is one.
265 ///
266 /// This will return NULL if this declaration has no name (e.g., for
267 /// an unnamed class) or if the name is a special name (C++ constructor,
268 /// Objective-C selector, etc.).
269 IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); }
270
271 /// Get the name of identifier for this declaration as a StringRef.
272 ///
273 /// This requires that the declaration have a name and that it be a simple
274 /// identifier.
275 StringRef getName() const {
276 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-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 276, __extension__ __PRETTY_FUNCTION__))
;
277 return getIdentifier() ? getIdentifier()->getName() : "";
278 }
279
280 /// Get a human-readable name for the declaration, even if it is one of the
281 /// special kinds of names (C++ constructor, Objective-C selector, etc).
282 ///
283 /// Creating this name requires expensive string manipulation, so it should
284 /// be called only when performance doesn't matter. For simple declarations,
285 /// getNameAsCString() should suffice.
286 //
287 // FIXME: This function should be renamed to indicate that it is not just an
288 // alternate form of getName(), and clients should move as appropriate.
289 //
290 // FIXME: Deprecated, move clients to getName().
291 std::string getNameAsString() const { return Name.getAsString(); }
292
293 virtual void printName(raw_ostream &os) const;
294
295 /// Get the actual, stored name of the declaration, which may be a special
296 /// name.
297 DeclarationName getDeclName() const { return Name; }
298
299 /// Set the name of this declaration.
300 void setDeclName(DeclarationName N) { Name = N; }
301
302 /// Returns a human-readable qualified name for this declaration, like
303 /// A::B::i, for i being member of namespace A::B.
304 ///
305 /// If the declaration is not a member of context which can be named (record,
306 /// namespace), it will return the same result as printName().
307 ///
308 /// Creating this name is expensive, so it should be called only when
309 /// performance doesn't matter.
310 void printQualifiedName(raw_ostream &OS) const;
311 void printQualifiedName(raw_ostream &OS, const PrintingPolicy &Policy) const;
312
313 // FIXME: Remove string version.
314 std::string getQualifiedNameAsString() const;
315
316 /// Appends a human-readable name for this declaration into the given stream.
317 ///
318 /// This is the method invoked by Sema when displaying a NamedDecl
319 /// in a diagnostic. It does not necessarily produce the same
320 /// result as printName(); for example, class template
321 /// specializations are printed with their template arguments.
322 virtual void getNameForDiagnostic(raw_ostream &OS,
323 const PrintingPolicy &Policy,
324 bool Qualified) const;
325
326 /// Determine whether this declaration, if known to be well-formed within
327 /// its context, will replace the declaration OldD if introduced into scope.
328 ///
329 /// A declaration will replace another declaration if, for example, it is
330 /// a redeclaration of the same variable or function, but not if it is a
331 /// declaration of a different kind (function vs. class) or an overloaded
332 /// function.
333 ///
334 /// \param IsKnownNewer \c true if this declaration is known to be newer
335 /// than \p OldD (for instance, if this declaration is newly-created).
336 bool declarationReplaces(NamedDecl *OldD, bool IsKnownNewer = true) const;
337
338 /// Determine whether this declaration has linkage.
339 bool hasLinkage() const;
340
341 using Decl::isModulePrivate;
342 using Decl::setModulePrivate;
343
344 /// Determine whether this declaration is a C++ class member.
345 bool isCXXClassMember() const {
346 const DeclContext *DC = getDeclContext();
347
348 // C++0x [class.mem]p1:
349 // The enumerators of an unscoped enumeration defined in
350 // the class are members of the class.
351 if (isa<EnumDecl>(DC))
352 DC = DC->getRedeclContext();
353
354 return DC->isRecord();
355 }
356
357 /// Determine whether the given declaration is an instance member of
358 /// a C++ class.
359 bool isCXXInstanceMember() const;
360
361 /// Determine what kind of linkage this entity has.
362 ///
363 /// This is not the linkage as defined by the standard or the codegen notion
364 /// of linkage. It is just an implementation detail that is used to compute
365 /// those.
366 Linkage getLinkageInternal() const;
367
368 /// Get the linkage from a semantic point of view. Entities in
369 /// anonymous namespaces are external (in c++98).
370 Linkage getFormalLinkage() const {
371 return clang::getFormalLinkage(getLinkageInternal());
372 }
373
374 /// True if this decl has external linkage.
375 bool hasExternalFormalLinkage() const {
376 return isExternalFormalLinkage(getLinkageInternal());
377 }
378
379 bool isExternallyVisible() const {
380 return clang::isExternallyVisible(getLinkageInternal());
381 }
382
383 /// Determine whether this declaration can be redeclared in a
384 /// different translation unit.
385 bool isExternallyDeclarable() const {
386 return isExternallyVisible() && !getOwningModuleForLinkage();
387 }
388
389 /// Determines the visibility of this entity.
390 Visibility getVisibility() const {
391 return getLinkageAndVisibility().getVisibility();
392 }
393
394 /// Determines the linkage and visibility of this entity.
395 LinkageInfo getLinkageAndVisibility() const;
396
397 /// Kinds of explicit visibility.
398 enum ExplicitVisibilityKind {
399 /// Do an LV computation for, ultimately, a type.
400 /// Visibility may be restricted by type visibility settings and
401 /// the visibility of template arguments.
402 VisibilityForType,
403
404 /// Do an LV computation for, ultimately, a non-type declaration.
405 /// Visibility may be restricted by value visibility settings and
406 /// the visibility of template arguments.
407 VisibilityForValue
408 };
409
410 /// If visibility was explicitly specified for this
411 /// declaration, return that visibility.
412 Optional<Visibility>
413 getExplicitVisibility(ExplicitVisibilityKind kind) const;
414
415 /// True if the computed linkage is valid. Used for consistency
416 /// checking. Should always return true.
417 bool isLinkageValid() const;
418
419 /// True if something has required us to compute the linkage
420 /// of this declaration.
421 ///
422 /// Language features which can retroactively change linkage (like a
423 /// typedef name for linkage purposes) may need to consider this,
424 /// but hopefully only in transitory ways during parsing.
425 bool hasLinkageBeenComputed() const {
426 return hasCachedLinkage();
427 }
428
429 /// Looks through UsingDecls and ObjCCompatibleAliasDecls for
430 /// the underlying named decl.
431 NamedDecl *getUnderlyingDecl() {
432 // Fast-path the common case.
433 if (this->getKind() != UsingShadow &&
434 this->getKind() != ConstructorUsingShadow &&
435 this->getKind() != ObjCCompatibleAlias &&
436 this->getKind() != NamespaceAlias)
437 return this;
438
439 return getUnderlyingDeclImpl();
440 }
441 const NamedDecl *getUnderlyingDecl() const {
442 return const_cast<NamedDecl*>(this)->getUnderlyingDecl();
443 }
444
445 NamedDecl *getMostRecentDecl() {
446 return cast<NamedDecl>(static_cast<Decl *>(this)->getMostRecentDecl());
447 }
448 const NamedDecl *getMostRecentDecl() const {
449 return const_cast<NamedDecl*>(this)->getMostRecentDecl();
450 }
451
452 ObjCStringFormatFamily getObjCFStringFormattingFamily() const;
453
454 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
455 static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; }
456};
457
458inline raw_ostream &operator<<(raw_ostream &OS, const NamedDecl &ND) {
459 ND.printName(OS);
460 return OS;
461}
462
463/// Represents the declaration of a label. Labels also have a
464/// corresponding LabelStmt, which indicates the position that the label was
465/// defined at. For normal labels, the location of the decl is the same as the
466/// location of the statement. For GNU local labels (__label__), the decl
467/// location is where the __label__ is.
468class LabelDecl : public NamedDecl {
469 LabelStmt *TheStmt;
470 StringRef MSAsmName;
471 bool MSAsmNameResolved = false;
472
473 /// For normal labels, this is the same as the main declaration
474 /// label, i.e., the location of the identifier; for GNU local labels,
475 /// this is the location of the __label__ keyword.
476 SourceLocation LocStart;
477
478 LabelDecl(DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II,
479 LabelStmt *S, SourceLocation StartL)
480 : NamedDecl(Label, DC, IdentL, II), TheStmt(S), LocStart(StartL) {}
481
482 void anchor() override;
483
484public:
485 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
486 SourceLocation IdentL, IdentifierInfo *II);
487 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
488 SourceLocation IdentL, IdentifierInfo *II,
489 SourceLocation GnuLabelL);
490 static LabelDecl *CreateDeserialized(ASTContext &C, unsigned ID);
491
492 LabelStmt *getStmt() const { return TheStmt; }
493 void setStmt(LabelStmt *T) { TheStmt = T; }
494
495 bool isGnuLocal() const { return LocStart != getLocation(); }
496 void setLocStart(SourceLocation L) { LocStart = L; }
497
498 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
499 return SourceRange(LocStart, getLocation());
500 }
501
502 bool isMSAsmLabel() const { return !MSAsmName.empty(); }
503 bool isResolvedMSAsmLabel() const { return isMSAsmLabel() && MSAsmNameResolved; }
504 void setMSAsmLabel(StringRef Name);
505 StringRef getMSAsmLabel() const { return MSAsmName; }
506 void setMSAsmLabelResolved() { MSAsmNameResolved = true; }
507
508 // Implement isa/cast/dyncast/etc.
509 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
510 static bool classofKind(Kind K) { return K == Label; }
511};
512
513/// Represent a C++ namespace.
514class NamespaceDecl : public NamedDecl, public DeclContext,
515 public Redeclarable<NamespaceDecl>
516{
517 /// The starting location of the source range, pointing
518 /// to either the namespace or the inline keyword.
519 SourceLocation LocStart;
520
521 /// The ending location of the source range.
522 SourceLocation RBraceLoc;
523
524 /// A pointer to either the anonymous namespace that lives just inside
525 /// this namespace or to the first namespace in the chain (the latter case
526 /// only when this is not the first in the chain), along with a
527 /// boolean value indicating whether this is an inline namespace.
528 llvm::PointerIntPair<NamespaceDecl *, 1, bool> AnonOrFirstNamespaceAndInline;
529
530 NamespaceDecl(ASTContext &C, DeclContext *DC, bool Inline,
531 SourceLocation StartLoc, SourceLocation IdLoc,
532 IdentifierInfo *Id, NamespaceDecl *PrevDecl);
533
534 using redeclarable_base = Redeclarable<NamespaceDecl>;
535
536 NamespaceDecl *getNextRedeclarationImpl() override;
537 NamespaceDecl *getPreviousDeclImpl() override;
538 NamespaceDecl *getMostRecentDeclImpl() override;
539
540public:
541 friend class ASTDeclReader;
542 friend class ASTDeclWriter;
543
544 static NamespaceDecl *Create(ASTContext &C, DeclContext *DC,
545 bool Inline, SourceLocation StartLoc,
546 SourceLocation IdLoc, IdentifierInfo *Id,
547 NamespaceDecl *PrevDecl);
548
549 static NamespaceDecl *CreateDeserialized(ASTContext &C, unsigned ID);
550
551 using redecl_range = redeclarable_base::redecl_range;
552 using redecl_iterator = redeclarable_base::redecl_iterator;
553
554 using redeclarable_base::redecls_begin;
555 using redeclarable_base::redecls_end;
556 using redeclarable_base::redecls;
557 using redeclarable_base::getPreviousDecl;
558 using redeclarable_base::getMostRecentDecl;
559 using redeclarable_base::isFirstDecl;
560
561 /// Returns true if this is an anonymous namespace declaration.
562 ///
563 /// For example:
564 /// \code
565 /// namespace {
566 /// ...
567 /// };
568 /// \endcode
569 /// q.v. C++ [namespace.unnamed]
570 bool isAnonymousNamespace() const {
571 return !getIdentifier();
572 }
573
574 /// Returns true if this is an inline namespace declaration.
575 bool isInline() const {
576 return AnonOrFirstNamespaceAndInline.getInt();
577 }
578
579 /// Set whether this is an inline namespace declaration.
580 void setInline(bool Inline) {
581 AnonOrFirstNamespaceAndInline.setInt(Inline);
582 }
583
584 /// Get the original (first) namespace declaration.
585 NamespaceDecl *getOriginalNamespace();
586
587 /// Get the original (first) namespace declaration.
588 const NamespaceDecl *getOriginalNamespace() const;
589
590 /// Return true if this declaration is an original (first) declaration
591 /// of the namespace. This is false for non-original (subsequent) namespace
592 /// declarations and anonymous namespaces.
593 bool isOriginalNamespace() const;
594
595 /// Retrieve the anonymous namespace nested inside this namespace,
596 /// if any.
597 NamespaceDecl *getAnonymousNamespace() const {
598 return getOriginalNamespace()->AnonOrFirstNamespaceAndInline.getPointer();
599 }
600
601 void setAnonymousNamespace(NamespaceDecl *D) {
602 getOriginalNamespace()->AnonOrFirstNamespaceAndInline.setPointer(D);
603 }
604
605 /// Retrieves the canonical declaration of this namespace.
606 NamespaceDecl *getCanonicalDecl() override {
607 return getOriginalNamespace();
608 }
609 const NamespaceDecl *getCanonicalDecl() const {
610 return getOriginalNamespace();
611 }
612
613 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
614 return SourceRange(LocStart, RBraceLoc);
615 }
616
617 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return LocStart; }
618 SourceLocation getRBraceLoc() const { return RBraceLoc; }
619 void setLocStart(SourceLocation L) { LocStart = L; }
620 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
621
622 // Implement isa/cast/dyncast/etc.
623 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
624 static bool classofKind(Kind K) { return K == Namespace; }
625 static DeclContext *castToDeclContext(const NamespaceDecl *D) {
626 return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D));
627 }
628 static NamespaceDecl *castFromDeclContext(const DeclContext *DC) {
629 return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC));
630 }
631};
632
633/// Represent the declaration of a variable (in which case it is
634/// an lvalue) a function (in which case it is a function designator) or
635/// an enum constant.
636class ValueDecl : public NamedDecl {
637 QualType DeclType;
638
639 void anchor() override;
640
641protected:
642 ValueDecl(Kind DK, DeclContext *DC, SourceLocation L,
643 DeclarationName N, QualType T)
644 : NamedDecl(DK, DC, L, N), DeclType(T) {}
645
646public:
647 QualType getType() const { return DeclType; }
648 void setType(QualType newType) { DeclType = newType; }
649
650 /// Determine whether this symbol is weakly-imported,
651 /// or declared with the weak or weak-ref attr.
652 bool isWeak() const;
653
654 // Implement isa/cast/dyncast/etc.
655 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
656 static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; }
657};
658
659/// A struct with extended info about a syntactic
660/// name qualifier, to be used for the case of out-of-line declarations.
661struct QualifierInfo {
662 NestedNameSpecifierLoc QualifierLoc;
663
664 /// The number of "outer" template parameter lists.
665 /// The count includes all of the template parameter lists that were matched
666 /// against the template-ids occurring into the NNS and possibly (in the
667 /// case of an explicit specialization) a final "template <>".
668 unsigned NumTemplParamLists = 0;
669
670 /// A new-allocated array of size NumTemplParamLists,
671 /// containing pointers to the "outer" template parameter lists.
672 /// It includes all of the template parameter lists that were matched
673 /// against the template-ids occurring into the NNS and possibly (in the
674 /// case of an explicit specialization) a final "template <>".
675 TemplateParameterList** TemplParamLists = nullptr;
676
677 QualifierInfo() = default;
678 QualifierInfo(const QualifierInfo &) = delete;
679 QualifierInfo& operator=(const QualifierInfo &) = delete;
680
681 /// Sets info about "outer" template parameter lists.
682 void setTemplateParameterListsInfo(ASTContext &Context,
683 ArrayRef<TemplateParameterList *> TPLists);
684};
685
686/// Represents a ValueDecl that came out of a declarator.
687/// Contains type source information through TypeSourceInfo.
688class DeclaratorDecl : public ValueDecl {
689 // A struct representing both a TInfo and a syntactic qualifier,
690 // to be used for the (uncommon) case of out-of-line declarations.
691 struct ExtInfo : public QualifierInfo {
692 TypeSourceInfo *TInfo;
693 };
694
695 llvm::PointerUnion<TypeSourceInfo *, ExtInfo *> DeclInfo;
696
697 /// The start of the source range for this declaration,
698 /// ignoring outer template declarations.
699 SourceLocation InnerLocStart;
700
701 bool hasExtInfo() const { return DeclInfo.is<ExtInfo*>(); }
702 ExtInfo *getExtInfo() { return DeclInfo.get<ExtInfo*>(); }
703 const ExtInfo *getExtInfo() const { return DeclInfo.get<ExtInfo*>(); }
704
705protected:
706 DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L,
707 DeclarationName N, QualType T, TypeSourceInfo *TInfo,
708 SourceLocation StartL)
709 : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo), InnerLocStart(StartL) {}
710
711public:
712 friend class ASTDeclReader;
713 friend class ASTDeclWriter;
714
715 TypeSourceInfo *getTypeSourceInfo() const {
716 return hasExtInfo()
717 ? getExtInfo()->TInfo
718 : DeclInfo.get<TypeSourceInfo*>();
719 }
720
721 void setTypeSourceInfo(TypeSourceInfo *TI) {
722 if (hasExtInfo())
723 getExtInfo()->TInfo = TI;
724 else
725 DeclInfo = TI;
726 }
727
728 /// Return start of source range ignoring outer template declarations.
729 SourceLocation getInnerLocStart() const { return InnerLocStart; }
730 void setInnerLocStart(SourceLocation L) { InnerLocStart = L; }
731
732 /// Return start of source range taking into account any outer template
733 /// declarations.
734 SourceLocation getOuterLocStart() const;
735
736 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
737
738 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) {
739 return getOuterLocStart();
740 }
741
742 /// Retrieve the nested-name-specifier that qualifies the name of this
743 /// declaration, if it was present in the source.
744 NestedNameSpecifier *getQualifier() const {
745 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
746 : nullptr;
747 }
748
749 /// Retrieve the nested-name-specifier (with source-location
750 /// information) that qualifies the name of this declaration, if it was
751 /// present in the source.
752 NestedNameSpecifierLoc getQualifierLoc() const {
753 return hasExtInfo() ? getExtInfo()->QualifierLoc
754 : NestedNameSpecifierLoc();
755 }
756
757 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
758
759 unsigned getNumTemplateParameterLists() const {
760 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
761 }
762
763 TemplateParameterList *getTemplateParameterList(unsigned index) const {
764 assert(index < getNumTemplateParameterLists())(static_cast <bool> (index < getNumTemplateParameterLists
()) ? void (0) : __assert_fail ("index < getNumTemplateParameterLists()"
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 764, __extension__ __PRETTY_FUNCTION__))
;
765 return getExtInfo()->TemplParamLists[index];
766 }
767
768 void setTemplateParameterListsInfo(ASTContext &Context,
769 ArrayRef<TemplateParameterList *> TPLists);
770
771 SourceLocation getTypeSpecStartLoc() const;
772
773 // Implement isa/cast/dyncast/etc.
774 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
775 static bool classofKind(Kind K) {
776 return K >= firstDeclarator && K <= lastDeclarator;
777 }
778};
779
780/// Structure used to store a statement, the constant value to
781/// which it was evaluated (if any), and whether or not the statement
782/// is an integral constant expression (if known).
783struct EvaluatedStmt {
784 /// Whether this statement was already evaluated.
785 bool WasEvaluated : 1;
786
787 /// Whether this statement is being evaluated.
788 bool IsEvaluating : 1;
789
790 /// Whether we already checked whether this statement was an
791 /// integral constant expression.
792 bool CheckedICE : 1;
793
794 /// Whether we are checking whether this statement is an
795 /// integral constant expression.
796 bool CheckingICE : 1;
797
798 /// Whether this statement is an integral constant expression,
799 /// or in C++11, whether the statement is a constant expression. Only
800 /// valid if CheckedICE is true.
801 bool IsICE : 1;
802
803 Stmt *Value;
804 APValue Evaluated;
805
806 EvaluatedStmt() : WasEvaluated(false), IsEvaluating(false), CheckedICE(false),
807 CheckingICE(false), IsICE(false) {}
808
809};
810
811/// Represents a variable declaration or definition.
812class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> {
813public:
814 /// Initialization styles.
815 enum InitializationStyle {
816 /// C-style initialization with assignment
817 CInit,
818
819 /// Call-style initialization (C++98)
820 CallInit,
821
822 /// Direct list-initialization (C++11)
823 ListInit
824 };
825
826 /// Kinds of thread-local storage.
827 enum TLSKind {
828 /// Not a TLS variable.
829 TLS_None,
830
831 /// TLS with a known-constant initializer.
832 TLS_Static,
833
834 /// TLS with a dynamic initializer.
835 TLS_Dynamic
836 };
837
838 /// Return the string used to specify the storage class \p SC.
839 ///
840 /// It is illegal to call this function with SC == None.
841 static const char *getStorageClassSpecifierString(StorageClass SC);
842
843protected:
844 // A pointer union of Stmt * and EvaluatedStmt *. When an EvaluatedStmt, we
845 // have allocated the auxiliary struct of information there.
846 //
847 // TODO: It is a bit unfortunate to use a PointerUnion inside the VarDecl for
848 // this as *many* VarDecls are ParmVarDecls that don't have default
849 // arguments. We could save some space by moving this pointer union to be
850 // allocated in trailing space when necessary.
851 using InitType = llvm::PointerUnion<Stmt *, EvaluatedStmt *>;
852
853 /// The initializer for this variable or, for a ParmVarDecl, the
854 /// C++ default argument.
855 mutable InitType Init;
856
857private:
858 friend class ASTDeclReader;
859 friend class ASTNodeImporter;
860 friend class StmtIteratorBase;
861
862 class VarDeclBitfields {
863 friend class ASTDeclReader;
864 friend class VarDecl;
865
866 unsigned SClass : 3;
867 unsigned TSCSpec : 2;
868 unsigned InitStyle : 2;
869 };
870 enum { NumVarDeclBits = 7 };
871
872protected:
873 enum { NumParameterIndexBits = 8 };
874
875 enum DefaultArgKind {
876 DAK_None,
877 DAK_Unparsed,
878 DAK_Uninstantiated,
879 DAK_Normal
880 };
881
882 class ParmVarDeclBitfields {
883 friend class ASTDeclReader;
884 friend class ParmVarDecl;
885
886 unsigned : NumVarDeclBits;
887
888 /// Whether this parameter inherits a default argument from a
889 /// prior declaration.
890 unsigned HasInheritedDefaultArg : 1;
891
892 /// Describes the kind of default argument for this parameter. By default
893 /// this is none. If this is normal, then the default argument is stored in
894 /// the \c VarDecl initializer expression unless we were unable to parse
895 /// (even an invalid) expression for the default argument.
896 unsigned DefaultArgKind : 2;
897
898 /// Whether this parameter undergoes K&R argument promotion.
899 unsigned IsKNRPromoted : 1;
900
901 /// Whether this parameter is an ObjC method parameter or not.
902 unsigned IsObjCMethodParam : 1;
903
904 /// If IsObjCMethodParam, a Decl::ObjCDeclQualifier.
905 /// Otherwise, the number of function parameter scopes enclosing
906 /// the function parameter scope in which this parameter was
907 /// declared.
908 unsigned ScopeDepthOrObjCQuals : 7;
909
910 /// The number of parameters preceding this parameter in the
911 /// function parameter scope in which it was declared.
912 unsigned ParameterIndex : NumParameterIndexBits;
913 };
914
915 class NonParmVarDeclBitfields {
916 friend class ASTDeclReader;
917 friend class ImplicitParamDecl;
918 friend class VarDecl;
919
920 unsigned : NumVarDeclBits;
921
922 // FIXME: We need something similar to CXXRecordDecl::DefinitionData.
923 /// Whether this variable is a definition which was demoted due to
924 /// module merge.
925 unsigned IsThisDeclarationADemotedDefinition : 1;
926
927 /// Whether this variable is the exception variable in a C++ catch
928 /// or an Objective-C @catch statement.
929 unsigned ExceptionVar : 1;
930
931 /// Whether this local variable could be allocated in the return
932 /// slot of its function, enabling the named return value optimization
933 /// (NRVO).
934 unsigned NRVOVariable : 1;
935
936 /// Whether this variable is the for-range-declaration in a C++0x
937 /// for-range statement.
938 unsigned CXXForRangeDecl : 1;
939
940 /// Whether this variable is an ARC pseudo-__strong
941 /// variable; see isARCPseudoStrong() for details.
942 unsigned ARCPseudoStrong : 1;
943
944 /// Whether this variable is (C++1z) inline.
945 unsigned IsInline : 1;
946
947 /// Whether this variable has (C++1z) inline explicitly specified.
948 unsigned IsInlineSpecified : 1;
949
950 /// Whether this variable is (C++0x) constexpr.
951 unsigned IsConstexpr : 1;
952
953 /// Whether this variable is the implicit variable for a lambda
954 /// init-capture.
955 unsigned IsInitCapture : 1;
956
957 /// Whether this local extern variable's previous declaration was
958 /// declared in the same block scope. This controls whether we should merge
959 /// the type of this declaration with its previous declaration.
960 unsigned PreviousDeclInSameBlockScope : 1;
961
962 /// Defines kind of the ImplicitParamDecl: 'this', 'self', 'vtt', '_cmd' or
963 /// something else.
964 unsigned ImplicitParamKind : 3;
965 };
966
967 union {
968 unsigned AllBits;
969 VarDeclBitfields VarDeclBits;
970 ParmVarDeclBitfields ParmVarDeclBits;
971 NonParmVarDeclBitfields NonParmVarDeclBits;
972 };
973
974 VarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
975 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
976 TypeSourceInfo *TInfo, StorageClass SC);
977
978 using redeclarable_base = Redeclarable<VarDecl>;
979
980 VarDecl *getNextRedeclarationImpl() override {
981 return getNextRedeclaration();
982 }
983
984 VarDecl *getPreviousDeclImpl() override {
985 return getPreviousDecl();
986 }
987
988 VarDecl *getMostRecentDeclImpl() override {
989 return getMostRecentDecl();
990 }
991
992public:
993 using redecl_range = redeclarable_base::redecl_range;
994 using redecl_iterator = redeclarable_base::redecl_iterator;
995
996 using redeclarable_base::redecls_begin;
997 using redeclarable_base::redecls_end;
998 using redeclarable_base::redecls;
999 using redeclarable_base::getPreviousDecl;
1000 using redeclarable_base::getMostRecentDecl;
1001 using redeclarable_base::isFirstDecl;
1002
1003 static VarDecl *Create(ASTContext &C, DeclContext *DC,
1004 SourceLocation StartLoc, SourceLocation IdLoc,
1005 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1006 StorageClass S);
1007
1008 static VarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1009
1010 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1011
1012 /// Returns the storage class as written in the source. For the
1013 /// computed linkage of symbol, see getLinkage.
1014 StorageClass getStorageClass() const {
1015 return (StorageClass) VarDeclBits.SClass;
1016 }
1017 void setStorageClass(StorageClass SC);
1018
1019 void setTSCSpec(ThreadStorageClassSpecifier TSC) {
1020 VarDeclBits.TSCSpec = TSC;
1021 assert(VarDeclBits.TSCSpec == TSC && "truncation")(static_cast <bool> (VarDeclBits.TSCSpec == TSC &&
"truncation") ? void (0) : __assert_fail ("VarDeclBits.TSCSpec == TSC && \"truncation\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 1021, __extension__ __PRETTY_FUNCTION__))
;
1022 }
1023 ThreadStorageClassSpecifier getTSCSpec() const {
1024 return static_cast<ThreadStorageClassSpecifier>(VarDeclBits.TSCSpec);
1025 }
1026 TLSKind getTLSKind() const;
1027
1028 /// Returns true if a variable with function scope is a non-static local
1029 /// variable.
1030 bool hasLocalStorage() const {
1031 if (getStorageClass() == SC_None) {
1032 // OpenCL v1.2 s6.5.3: The __constant or constant address space name is
1033 // used to describe variables allocated in global memory and which are
1034 // accessed inside a kernel(s) as read-only variables. As such, variables
1035 // in constant address space cannot have local storage.
1036 if (getType().getAddressSpace() == LangAS::opencl_constant)
1037 return false;
1038 // Second check is for C++11 [dcl.stc]p4.
1039 return !isFileVarDecl() && getTSCSpec() == TSCS_unspecified;
1040 }
1041
1042 // Global Named Register (GNU extension)
1043 if (getStorageClass() == SC_Register && !isLocalVarDeclOrParm())
1044 return false;
1045
1046 // Return true for: Auto, Register.
1047 // Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal.
1048
1049 return getStorageClass() >= SC_Auto;
1050 }
1051
1052 /// Returns true if a variable with function scope is a static local
1053 /// variable.
1054 bool isStaticLocal() const {
1055 return (getStorageClass() == SC_Static ||
1056 // C++11 [dcl.stc]p4
1057 (getStorageClass() == SC_None && getTSCSpec() == TSCS_thread_local))
1058 && !isFileVarDecl();
1059 }
1060
1061 /// Returns true if a variable has extern or __private_extern__
1062 /// storage.
1063 bool hasExternalStorage() const {
1064 return getStorageClass() == SC_Extern ||
1065 getStorageClass() == SC_PrivateExtern;
1066 }
1067
1068 /// Returns true for all variables that do not have local storage.
1069 ///
1070 /// This includes all global variables as well as static variables declared
1071 /// within a function.
1072 bool hasGlobalStorage() const { return !hasLocalStorage(); }
1073
1074 /// Get the storage duration of this variable, per C++ [basic.stc].
1075 StorageDuration getStorageDuration() const {
1076 return hasLocalStorage() ? SD_Automatic :
1077 getTSCSpec() ? SD_Thread : SD_Static;
1078 }
1079
1080 /// Compute the language linkage.
1081 LanguageLinkage getLanguageLinkage() const;
1082
1083 /// Determines whether this variable is a variable with external, C linkage.
1084 bool isExternC() const;
1085
1086 /// Determines whether this variable's context is, or is nested within,
1087 /// a C++ extern "C" linkage spec.
1088 bool isInExternCContext() const;
1089
1090 /// Determines whether this variable's context is, or is nested within,
1091 /// a C++ extern "C++" linkage spec.
1092 bool isInExternCXXContext() const;
1093
1094 /// Returns true for local variable declarations other than parameters.
1095 /// Note that this includes static variables inside of functions. It also
1096 /// includes variables inside blocks.
1097 ///
1098 /// void foo() { int x; static int y; extern int z; }
1099 bool isLocalVarDecl() const {
1100 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1101 return false;
1102 if (const DeclContext *DC = getLexicalDeclContext())
1103 return DC->getRedeclContext()->isFunctionOrMethod();
1104 return false;
1105 }
1106
1107 /// Similar to isLocalVarDecl but also includes parameters.
1108 bool isLocalVarDeclOrParm() const {
1109 return isLocalVarDecl() || getKind() == Decl::ParmVar;
1110 }
1111
1112 /// Similar to isLocalVarDecl, but excludes variables declared in blocks.
1113 bool isFunctionOrMethodVarDecl() const {
1114 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1115 return false;
1116 const DeclContext *DC = getLexicalDeclContext()->getRedeclContext();
1117 return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block;
1118 }
1119
1120 /// Determines whether this is a static data member.
1121 ///
1122 /// This will only be true in C++, and applies to, e.g., the
1123 /// variable 'x' in:
1124 /// \code
1125 /// struct S {
1126 /// static int x;
1127 /// };
1128 /// \endcode
1129 bool isStaticDataMember() const {
1130 // If it wasn't static, it would be a FieldDecl.
1131 return getKind() != Decl::ParmVar && getDeclContext()->isRecord();
1132 }
1133
1134 VarDecl *getCanonicalDecl() override;
1135 const VarDecl *getCanonicalDecl() const {
1136 return const_cast<VarDecl*>(this)->getCanonicalDecl();
1137 }
1138
1139 enum DefinitionKind {
1140 /// This declaration is only a declaration.
1141 DeclarationOnly,
1142
1143 /// This declaration is a tentative definition.
1144 TentativeDefinition,
1145
1146 /// This declaration is definitely a definition.
1147 Definition
1148 };
1149
1150 /// Check whether this declaration is a definition. If this could be
1151 /// a tentative definition (in C), don't check whether there's an overriding
1152 /// definition.
1153 DefinitionKind isThisDeclarationADefinition(ASTContext &) const;
1154 DefinitionKind isThisDeclarationADefinition() const {
1155 return isThisDeclarationADefinition(getASTContext());
1156 }
1157
1158 /// Check whether this variable is defined in this translation unit.
1159 DefinitionKind hasDefinition(ASTContext &) const;
1160 DefinitionKind hasDefinition() const {
1161 return hasDefinition(getASTContext());
1162 }
1163
1164 /// Get the tentative definition that acts as the real definition in a TU.
1165 /// Returns null if there is a proper definition available.
1166 VarDecl *getActingDefinition();
1167 const VarDecl *getActingDefinition() const {
1168 return const_cast<VarDecl*>(this)->getActingDefinition();
1169 }
1170
1171 /// Get the real (not just tentative) definition for this declaration.
1172 VarDecl *getDefinition(ASTContext &);
1173 const VarDecl *getDefinition(ASTContext &C) const {
1174 return const_cast<VarDecl*>(this)->getDefinition(C);
1175 }
1176 VarDecl *getDefinition() {
1177 return getDefinition(getASTContext());
1178 }
1179 const VarDecl *getDefinition() const {
1180 return const_cast<VarDecl*>(this)->getDefinition();
1181 }
1182
1183 /// Determine whether this is or was instantiated from an out-of-line
1184 /// definition of a static data member.
1185 bool isOutOfLine() const override;
1186
1187 /// Returns true for file scoped variable declaration.
1188 bool isFileVarDecl() const {
1189 Kind K = getKind();
1190 if (K == ParmVar || K == ImplicitParam)
1191 return false;
1192
1193 if (getLexicalDeclContext()->getRedeclContext()->isFileContext())
1194 return true;
1195
1196 if (isStaticDataMember())
1197 return true;
1198
1199 return false;
1200 }
1201
1202 /// Get the initializer for this variable, no matter which
1203 /// declaration it is attached to.
1204 const Expr *getAnyInitializer() const {
1205 const VarDecl *D;
1206 return getAnyInitializer(D);
1207 }
1208
1209 /// Get the initializer for this variable, no matter which
1210 /// declaration it is attached to. Also get that declaration.
1211 const Expr *getAnyInitializer(const VarDecl *&D) const;
1212
1213 bool hasInit() const;
1214 const Expr *getInit() const {
1215 return const_cast<VarDecl *>(this)->getInit();
1216 }
1217 Expr *getInit();
1218
1219 /// Retrieve the address of the initializer expression.
1220 Stmt **getInitAddress();
1221
1222 void setInit(Expr *I);
1223
1224 /// Determine whether this variable's value can be used in a
1225 /// constant expression, according to the relevant language standard.
1226 /// This only checks properties of the declaration, and does not check
1227 /// whether the initializer is in fact a constant expression.
1228 bool isUsableInConstantExpressions(ASTContext &C) const;
1229
1230 EvaluatedStmt *ensureEvaluatedStmt() const;
1231
1232 /// \brief Attempt to evaluate the value of the initializer attached to this
1233 /// declaration, and produce notes explaining why it cannot be evaluated or is
1234 /// not a constant expression. Returns a pointer to the value if evaluation
1235 /// succeeded, 0 otherwise.
1236 APValue *evaluateValue() const;
1237 APValue *evaluateValue(SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
1238
1239 /// \brief Return the already-evaluated value of this variable's
1240 /// initializer, or NULL if the value is not yet known. Returns pointer
1241 /// to untyped APValue if the value could not be evaluated.
1242 APValue *getEvaluatedValue() const;
1243
1244 /// \brief Determines whether it is already known whether the
1245 /// initializer is an integral constant expression or not.
1246 bool isInitKnownICE() const;
1247
1248 /// \brief Determines whether the initializer is an integral constant
1249 /// expression, or in C++11, whether the initializer is a constant
1250 /// expression.
1251 ///
1252 /// \pre isInitKnownICE()
1253 bool isInitICE() const;
1254
1255 /// \brief Determine whether the value of the initializer attached to this
1256 /// declaration is an integral constant expression.
1257 bool checkInitIsICE() const;
1258
1259 void setInitStyle(InitializationStyle Style) {
1260 VarDeclBits.InitStyle = Style;
1261 }
1262
1263 /// \brief The style of initialization for this declaration.
1264 ///
1265 /// C-style initialization is "int x = 1;". Call-style initialization is
1266 /// a C++98 direct-initializer, e.g. "int x(1);". The Init expression will be
1267 /// the expression inside the parens or a "ClassType(a,b,c)" class constructor
1268 /// expression for class types. List-style initialization is C++11 syntax,
1269 /// e.g. "int x{1};". Clients can distinguish between different forms of
1270 /// initialization by checking this value. In particular, "int x = {1};" is
1271 /// C-style, "int x({1})" is call-style, and "int x{1};" is list-style; the
1272 /// Init expression in all three cases is an InitListExpr.
1273 InitializationStyle getInitStyle() const {
1274 return static_cast<InitializationStyle>(VarDeclBits.InitStyle);
1275 }
1276
1277 /// \brief Whether the initializer is a direct-initializer (list or call).
1278 bool isDirectInit() const {
1279 return getInitStyle() != CInit;
1280 }
1281
1282 /// \brief If this definition should pretend to be a declaration.
1283 bool isThisDeclarationADemotedDefinition() const {
1284 return isa<ParmVarDecl>(this) ? false :
1285 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition;
1286 }
1287
1288 /// \brief This is a definition which should be demoted to a declaration.
1289 ///
1290 /// In some cases (mostly module merging) we can end up with two visible
1291 /// definitions one of which needs to be demoted to a declaration to keep
1292 /// the AST invariants.
1293 void demoteThisDefinitionToDeclaration() {
1294 assert(isThisDeclarationADefinition() && "Not a definition!")(static_cast <bool> (isThisDeclarationADefinition() &&
"Not a definition!") ? void (0) : __assert_fail ("isThisDeclarationADefinition() && \"Not a definition!\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 1294, __extension__ __PRETTY_FUNCTION__))
;
1295 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-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 1295, __extension__ __PRETTY_FUNCTION__))
;
1296 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition = 1;
1297 }
1298
1299 /// \brief Determine whether this variable is the exception variable in a
1300 /// C++ catch statememt or an Objective-C \@catch statement.
1301 bool isExceptionVariable() const {
1302 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ExceptionVar;
1303 }
1304 void setExceptionVariable(bool EV) {
1305 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 1305, __extension__ __PRETTY_FUNCTION__))
;
1306 NonParmVarDeclBits.ExceptionVar = EV;
1307 }
1308
1309 /// \brief Determine whether this local variable can be used with the named
1310 /// return value optimization (NRVO).
1311 ///
1312 /// The named return value optimization (NRVO) works by marking certain
1313 /// non-volatile local variables of class type as NRVO objects. These
1314 /// locals can be allocated within the return slot of their containing
1315 /// function, in which case there is no need to copy the object to the
1316 /// return slot when returning from the function. Within the function body,
1317 /// each return that returns the NRVO object will have this variable as its
1318 /// NRVO candidate.
1319 bool isNRVOVariable() const {
1320 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.NRVOVariable;
1321 }
1322 void setNRVOVariable(bool NRVO) {
1323 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 1323, __extension__ __PRETTY_FUNCTION__))
;
1324 NonParmVarDeclBits.NRVOVariable = NRVO;
1325 }
1326
1327 /// \brief Determine whether this variable is the for-range-declaration in
1328 /// a C++0x for-range statement.
1329 bool isCXXForRangeDecl() const {
1330 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.CXXForRangeDecl;
1331 }
1332 void setCXXForRangeDecl(bool FRD) {
1333 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 1333, __extension__ __PRETTY_FUNCTION__))
;
1334 NonParmVarDeclBits.CXXForRangeDecl = FRD;
1335 }
1336
1337 /// \brief Determine whether this variable is an ARC pseudo-__strong
1338 /// variable. A pseudo-__strong variable has a __strong-qualified
1339 /// type but does not actually retain the object written into it.
1340 /// Generally such variables are also 'const' for safety.
1341 bool isARCPseudoStrong() const {
1342 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ARCPseudoStrong;
1343 }
1344 void setARCPseudoStrong(bool ps) {
1345 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 1345, __extension__ __PRETTY_FUNCTION__))
;
1346 NonParmVarDeclBits.ARCPseudoStrong = ps;
1347 }
1348
1349 /// Whether this variable is (C++1z) inline.
1350 bool isInline() const {
1351 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInline;
1352 }
1353 bool isInlineSpecified() const {
1354 return isa<ParmVarDecl>(this) ? false
1355 : NonParmVarDeclBits.IsInlineSpecified;
1356 }
1357 void setInlineSpecified() {
1358 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 1358, __extension__ __PRETTY_FUNCTION__))
;
1359 NonParmVarDeclBits.IsInline = true;
1360 NonParmVarDeclBits.IsInlineSpecified = true;
1361 }
1362 void setImplicitlyInline() {
1363 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 1363, __extension__ __PRETTY_FUNCTION__))
;
1364 NonParmVarDeclBits.IsInline = true;
1365 }
1366
1367 /// Whether this variable is (C++11) constexpr.
1368 bool isConstexpr() const {
1369 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsConstexpr;
1370 }
1371 void setConstexpr(bool IC) {
1372 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 1372, __extension__ __PRETTY_FUNCTION__))
;
1373 NonParmVarDeclBits.IsConstexpr = IC;
1374 }
1375
1376 /// Whether this variable is the implicit variable for a lambda init-capture.
1377 bool isInitCapture() const {
1378 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInitCapture;
1379 }
1380 void setInitCapture(bool IC) {
1381 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 1381, __extension__ __PRETTY_FUNCTION__))
;
1382 NonParmVarDeclBits.IsInitCapture = IC;
1383 }
1384
1385 /// Whether this local extern variable declaration's previous declaration
1386 /// was declared in the same block scope. Only correct in C++.
1387 bool isPreviousDeclInSameBlockScope() const {
1388 return isa<ParmVarDecl>(this)
1389 ? false
1390 : NonParmVarDeclBits.PreviousDeclInSameBlockScope;
1391 }
1392 void setPreviousDeclInSameBlockScope(bool Same) {
1393 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 1393, __extension__ __PRETTY_FUNCTION__))
;
1394 NonParmVarDeclBits.PreviousDeclInSameBlockScope = Same;
1395 }
1396
1397 /// \brief Retrieve the variable declaration from which this variable could
1398 /// be instantiated, if it is an instantiation (rather than a non-template).
1399 VarDecl *getTemplateInstantiationPattern() const;
1400
1401 /// \brief If this variable is an instantiated static data member of a
1402 /// class template specialization, returns the templated static data member
1403 /// from which it was instantiated.
1404 VarDecl *getInstantiatedFromStaticDataMember() const;
1405
1406 /// \brief If this variable is an instantiation of a variable template or a
1407 /// static data member of a class template, determine what kind of
1408 /// template specialization or instantiation this is.
1409 TemplateSpecializationKind getTemplateSpecializationKind() const;
1410
1411 /// \brief If this variable is an instantiation of a variable template or a
1412 /// static data member of a class template, determine its point of
1413 /// instantiation.
1414 SourceLocation getPointOfInstantiation() const;
1415
1416 /// \brief If this variable is an instantiation of a static data member of a
1417 /// class template specialization, retrieves the member specialization
1418 /// information.
1419 MemberSpecializationInfo *getMemberSpecializationInfo() const;
1420
1421 /// \brief For a static data member that was instantiated from a static
1422 /// data member of a class template, set the template specialiation kind.
1423 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1424 SourceLocation PointOfInstantiation = SourceLocation());
1425
1426 /// \brief Specify that this variable is an instantiation of the
1427 /// static data member VD.
1428 void setInstantiationOfStaticDataMember(VarDecl *VD,
1429 TemplateSpecializationKind TSK);
1430
1431 /// \brief Retrieves the variable template that is described by this
1432 /// variable declaration.
1433 ///
1434 /// Every variable template is represented as a VarTemplateDecl and a
1435 /// VarDecl. The former contains template properties (such as
1436 /// the template parameter lists) while the latter contains the
1437 /// actual description of the template's
1438 /// contents. VarTemplateDecl::getTemplatedDecl() retrieves the
1439 /// VarDecl that from a VarTemplateDecl, while
1440 /// getDescribedVarTemplate() retrieves the VarTemplateDecl from
1441 /// a VarDecl.
1442 VarTemplateDecl *getDescribedVarTemplate() const;
1443
1444 void setDescribedVarTemplate(VarTemplateDecl *Template);
1445
1446 // Implement isa/cast/dyncast/etc.
1447 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1448 static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; }
1449};
1450
1451class ImplicitParamDecl : public VarDecl {
1452 void anchor() override;
1453
1454public:
1455 /// Defines the kind of the implicit parameter: is this an implicit parameter
1456 /// with pointer to 'this', 'self', '_cmd', virtual table pointers, captured
1457 /// context or something else.
1458 enum ImplicitParamKind : unsigned {
1459 /// Parameter for Objective-C 'self' argument
1460 ObjCSelf,
1461
1462 /// Parameter for Objective-C '_cmd' argument
1463 ObjCCmd,
1464
1465 /// Parameter for C++ 'this' argument
1466 CXXThis,
1467
1468 /// Parameter for C++ virtual table pointers
1469 CXXVTT,
1470
1471 /// Parameter for captured context
1472 CapturedContext,
1473
1474 /// Other implicit parameter
1475 Other,
1476 };
1477
1478 /// Create implicit parameter.
1479 static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC,
1480 SourceLocation IdLoc, IdentifierInfo *Id,
1481 QualType T, ImplicitParamKind ParamKind);
1482 static ImplicitParamDecl *Create(ASTContext &C, QualType T,
1483 ImplicitParamKind ParamKind);
1484
1485 static ImplicitParamDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1486
1487 ImplicitParamDecl(ASTContext &C, DeclContext *DC, SourceLocation IdLoc,
1488 IdentifierInfo *Id, QualType Type,
1489 ImplicitParamKind ParamKind)
1490 : VarDecl(ImplicitParam, C, DC, IdLoc, IdLoc, Id, Type,
1491 /*TInfo=*/nullptr, SC_None) {
1492 NonParmVarDeclBits.ImplicitParamKind = ParamKind;
1493 setImplicit();
1494 }
1495
1496 ImplicitParamDecl(ASTContext &C, QualType Type, ImplicitParamKind ParamKind)
1497 : VarDecl(ImplicitParam, C, /*DC=*/nullptr, SourceLocation(),
1498 SourceLocation(), /*Id=*/nullptr, Type,
1499 /*TInfo=*/nullptr, SC_None) {
1500 NonParmVarDeclBits.ImplicitParamKind = ParamKind;
1501 setImplicit();
1502 }
1503
1504 /// Returns the implicit parameter kind.
1505 ImplicitParamKind getParameterKind() const {
1506 return static_cast<ImplicitParamKind>(NonParmVarDeclBits.ImplicitParamKind);
1507 }
1508
1509 // Implement isa/cast/dyncast/etc.
1510 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1511 static bool classofKind(Kind K) { return K == ImplicitParam; }
1512};
1513
1514/// Represents a parameter to a function.
1515class ParmVarDecl : public VarDecl {
1516public:
1517 enum { MaxFunctionScopeDepth = 255 };
1518 enum { MaxFunctionScopeIndex = 255 };
1519
1520protected:
1521 ParmVarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1522 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
1523 TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
1524 : VarDecl(DK, C, DC, StartLoc, IdLoc, Id, T, TInfo, S) {
1525 assert(ParmVarDeclBits.HasInheritedDefaultArg == false)(static_cast <bool> (ParmVarDeclBits.HasInheritedDefaultArg
== false) ? void (0) : __assert_fail ("ParmVarDeclBits.HasInheritedDefaultArg == false"
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 1525, __extension__ __PRETTY_FUNCTION__))
;
1526 assert(ParmVarDeclBits.DefaultArgKind == DAK_None)(static_cast <bool> (ParmVarDeclBits.DefaultArgKind == DAK_None
) ? void (0) : __assert_fail ("ParmVarDeclBits.DefaultArgKind == DAK_None"
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 1526, __extension__ __PRETTY_FUNCTION__))
;
1527 assert(ParmVarDeclBits.IsKNRPromoted == false)(static_cast <bool> (ParmVarDeclBits.IsKNRPromoted == false
) ? void (0) : __assert_fail ("ParmVarDeclBits.IsKNRPromoted == false"
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 1527, __extension__ __PRETTY_FUNCTION__))
;
1528 assert(ParmVarDeclBits.IsObjCMethodParam == false)(static_cast <bool> (ParmVarDeclBits.IsObjCMethodParam ==
false) ? void (0) : __assert_fail ("ParmVarDeclBits.IsObjCMethodParam == false"
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 1528, __extension__ __PRETTY_FUNCTION__))
;
1529 setDefaultArg(DefArg);
1530 }
1531
1532public:
1533 static ParmVarDecl *Create(ASTContext &C, DeclContext *DC,
1534 SourceLocation StartLoc,
1535 SourceLocation IdLoc, IdentifierInfo *Id,
1536 QualType T, TypeSourceInfo *TInfo,
1537 StorageClass S, Expr *DefArg);
1538
1539 static ParmVarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1540
1541 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1542
1543 void setObjCMethodScopeInfo(unsigned parameterIndex) {
1544 ParmVarDeclBits.IsObjCMethodParam = true;
1545 setParameterIndex(parameterIndex);
1546 }
1547
1548 void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex) {
1549 assert(!ParmVarDeclBits.IsObjCMethodParam)(static_cast <bool> (!ParmVarDeclBits.IsObjCMethodParam
) ? void (0) : __assert_fail ("!ParmVarDeclBits.IsObjCMethodParam"
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 1549, __extension__ __PRETTY_FUNCTION__))
;
1550
1551 ParmVarDeclBits.ScopeDepthOrObjCQuals = scopeDepth;
1552 assert(ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth(static_cast <bool> (ParmVarDeclBits.ScopeDepthOrObjCQuals
== scopeDepth && "truncation!") ? void (0) : __assert_fail
("ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && \"truncation!\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 1553, __extension__ __PRETTY_FUNCTION__))
1553 && "truncation!")(static_cast <bool> (ParmVarDeclBits.ScopeDepthOrObjCQuals
== scopeDepth && "truncation!") ? void (0) : __assert_fail
("ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && \"truncation!\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 1553, __extension__ __PRETTY_FUNCTION__))
;
1554
1555 setParameterIndex(parameterIndex);
1556 }
1557
1558 bool isObjCMethodParameter() const {
1559 return ParmVarDeclBits.IsObjCMethodParam;
1560 }
1561
1562 unsigned getFunctionScopeDepth() const {
1563 if (ParmVarDeclBits.IsObjCMethodParam) return 0;
1564 return ParmVarDeclBits.ScopeDepthOrObjCQuals;
1565 }
1566
1567 /// Returns the index of this parameter in its prototype or method scope.
1568 unsigned getFunctionScopeIndex() const {
1569 return getParameterIndex();
1570 }
1571
1572 ObjCDeclQualifier getObjCDeclQualifier() const {
1573 if (!ParmVarDeclBits.IsObjCMethodParam) return OBJC_TQ_None;
1574 return ObjCDeclQualifier(ParmVarDeclBits.ScopeDepthOrObjCQuals);
1575 }
1576 void setObjCDeclQualifier(ObjCDeclQualifier QTVal) {
1577 assert(ParmVarDeclBits.IsObjCMethodParam)(static_cast <bool> (ParmVarDeclBits.IsObjCMethodParam)
? void (0) : __assert_fail ("ParmVarDeclBits.IsObjCMethodParam"
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 1577, __extension__ __PRETTY_FUNCTION__))
;
1578 ParmVarDeclBits.ScopeDepthOrObjCQuals = QTVal;
1579 }
1580
1581 /// True if the value passed to this parameter must undergo
1582 /// K&R-style default argument promotion:
1583 ///
1584 /// C99 6.5.2.2.
1585 /// If the expression that denotes the called function has a type
1586 /// that does not include a prototype, the integer promotions are
1587 /// performed on each argument, and arguments that have type float
1588 /// are promoted to double.
1589 bool isKNRPromoted() const {
1590 return ParmVarDeclBits.IsKNRPromoted;
1591 }
1592 void setKNRPromoted(bool promoted) {
1593 ParmVarDeclBits.IsKNRPromoted = promoted;
1594 }
1595
1596 Expr *getDefaultArg();
1597 const Expr *getDefaultArg() const {
1598 return const_cast<ParmVarDecl *>(this)->getDefaultArg();
1599 }
1600
1601 void setDefaultArg(Expr *defarg);
1602
1603 /// \brief Retrieve the source range that covers the entire default
1604 /// argument.
1605 SourceRange getDefaultArgRange() const;
1606 void setUninstantiatedDefaultArg(Expr *arg);
1607 Expr *getUninstantiatedDefaultArg();
1608 const Expr *getUninstantiatedDefaultArg() const {
1609 return const_cast<ParmVarDecl *>(this)->getUninstantiatedDefaultArg();
1610 }
1611
1612 /// Determines whether this parameter has a default argument,
1613 /// either parsed or not.
1614 bool hasDefaultArg() const;
1615
1616 /// Determines whether this parameter has a default argument that has not
1617 /// yet been parsed. This will occur during the processing of a C++ class
1618 /// whose member functions have 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 /// Specify that this parameter has an unparsed default argument.
1634 /// The argument will be replaced with a real default argument via
1635 /// setDefaultArg when the class definition enclosing the function
1636 /// declaration that owns this default argument is completed.
1637 void setUnparsedDefaultArg() {
1638 ParmVarDeclBits.DefaultArgKind = DAK_Unparsed;
1639 }
1640
1641 bool hasInheritedDefaultArg() const {
1642 return ParmVarDeclBits.HasInheritedDefaultArg;
1643 }
1644
1645 void setHasInheritedDefaultArg(bool I = true) {
1646 ParmVarDeclBits.HasInheritedDefaultArg = I;
1647 }
1648
1649 QualType getOriginalType() const;
1650
1651 /// \brief Determine whether this parameter is actually a function
1652 /// parameter pack.
1653 bool isParameterPack() const;
1654
1655 /// Sets the function declaration that owns this
1656 /// ParmVarDecl. Since ParmVarDecls are often created before the
1657 /// FunctionDecls that own them, this routine is required to update
1658 /// the DeclContext appropriately.
1659 void setOwningFunction(DeclContext *FD) { setDeclContext(FD); }
1660
1661 // Implement isa/cast/dyncast/etc.
1662 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1663 static bool classofKind(Kind K) { return K == ParmVar; }
1664
1665private:
1666 enum { ParameterIndexSentinel = (1 << NumParameterIndexBits) - 1 };
1667
1668 void setParameterIndex(unsigned parameterIndex) {
1669 if (parameterIndex >= ParameterIndexSentinel) {
1670 setParameterIndexLarge(parameterIndex);
1671 return;
1672 }
1673
1674 ParmVarDeclBits.ParameterIndex = parameterIndex;
1675 assert(ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!")(static_cast <bool> (ParmVarDeclBits.ParameterIndex == parameterIndex
&& "truncation!") ? void (0) : __assert_fail ("ParmVarDeclBits.ParameterIndex == parameterIndex && \"truncation!\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 1675, __extension__ __PRETTY_FUNCTION__))
;
1676 }
1677 unsigned getParameterIndex() const {
1678 unsigned d = ParmVarDeclBits.ParameterIndex;
1679 return d == ParameterIndexSentinel ? getParameterIndexLarge() : d;
1680 }
1681
1682 void setParameterIndexLarge(unsigned parameterIndex);
1683 unsigned getParameterIndexLarge() const;
1684};
1685
1686/// Represents a function declaration or definition.
1687///
1688/// Since a given function can be declared several times in a program,
1689/// there may be several FunctionDecls that correspond to that
1690/// function. Only one of those FunctionDecls will be found when
1691/// traversing the list of declarations in the context of the
1692/// FunctionDecl (e.g., the translation unit); this FunctionDecl
1693/// contains all of the information known about the function. Other,
1694/// previous declarations of the function are available via the
1695/// getPreviousDecl() chain.
1696class FunctionDecl : public DeclaratorDecl, public DeclContext,
1697 public Redeclarable<FunctionDecl> {
1698public:
1699 /// \brief The kind of templated function a FunctionDecl can be.
1700 enum TemplatedKind {
1701 TK_NonTemplate,
1702 TK_FunctionTemplate,
1703 TK_MemberSpecialization,
1704 TK_FunctionTemplateSpecialization,
1705 TK_DependentFunctionTemplateSpecialization
1706 };
1707
1708private:
1709 /// A new[]'d array of pointers to VarDecls for the formal
1710 /// parameters of this function. This is null if a prototype or if there are
1711 /// no formals.
1712 ParmVarDecl **ParamInfo = nullptr;
1713
1714 LazyDeclStmtPtr Body;
1715
1716 // FIXME: This can be packed into the bitfields in DeclContext.
1717 // NOTE: VC++ packs bitfields poorly if the types differ.
1718 unsigned SClass : 3;
1719 unsigned IsInline : 1;
1720 unsigned IsInlineSpecified : 1;
1721
1722protected:
1723 // This is shared by CXXConstructorDecl, CXXConversionDecl, and
1724 // CXXDeductionGuideDecl.
1725 unsigned IsExplicitSpecified : 1;
1726
1727private:
1728 unsigned IsVirtualAsWritten : 1;
1729 unsigned IsPure : 1;
1730 unsigned HasInheritedPrototype : 1;
1731 unsigned HasWrittenPrototype : 1;
1732 unsigned IsDeleted : 1;
1733 unsigned IsTrivial : 1; // sunk from CXXMethodDecl
1734
1735 /// This flag indicates whether this function is trivial for the purpose of
1736 /// calls. This is meaningful only when this function is a copy/move
1737 /// constructor or a destructor.
1738 unsigned IsTrivialForCall : 1;
1739
1740 unsigned IsDefaulted : 1; // sunk from CXXMethoDecl
1741 unsigned IsExplicitlyDefaulted : 1; //sunk from CXXMethodDecl
1742 unsigned HasImplicitReturnZero : 1;
1743 unsigned IsLateTemplateParsed : 1;
1744 unsigned IsConstexpr : 1;
1745 unsigned InstantiationIsPending : 1;
1746
1747 /// \brief Indicates if the function uses __try.
1748 unsigned UsesSEHTry : 1;
1749
1750 /// \brief Indicates if the function was a definition but its body was
1751 /// skipped.
1752 unsigned HasSkippedBody : 1;
1753
1754 /// Indicates if the function declaration will have a body, once we're done
1755 /// parsing it.
1756 unsigned WillHaveBody : 1;
1757
1758 /// Indicates that this function is a multiversioned function using attribute
1759 /// 'target'.
1760 unsigned IsMultiVersion : 1;
1761
1762protected:
1763 /// [C++17] Only used by CXXDeductionGuideDecl. Declared here to avoid
1764 /// increasing the size of CXXDeductionGuideDecl by the size of an unsigned
1765 /// int as opposed to adding a single bit to FunctionDecl.
1766 /// Indicates that the Deduction Guide is the implicitly generated 'copy
1767 /// deduction candidate' (is used during overload resolution).
1768 unsigned IsCopyDeductionCandidate : 1;
1769
1770private:
1771
1772 /// Store the ODRHash after first calculation.
1773 unsigned HasODRHash : 1;
1774 unsigned ODRHash;
1775
1776 /// \brief End part of this FunctionDecl's source range.
1777 ///
1778 /// We could compute the full range in getSourceRange(). However, when we're
1779 /// dealing with a function definition deserialized from a PCH/AST file,
1780 /// we can only compute the full range once the function body has been
1781 /// de-serialized, so it's far better to have the (sometimes-redundant)
1782 /// EndRangeLoc.
1783 SourceLocation EndRangeLoc;
1784
1785 /// \brief The template or declaration that this declaration
1786 /// describes or was instantiated from, respectively.
1787 ///
1788 /// For non-templates, this value will be NULL. For function
1789 /// declarations that describe a function template, this will be a
1790 /// pointer to a FunctionTemplateDecl. For member functions
1791 /// of class template specializations, this will be a MemberSpecializationInfo
1792 /// pointer containing information about the specialization.
1793 /// For function template specializations, this will be a
1794 /// FunctionTemplateSpecializationInfo, which contains information about
1795 /// the template being specialized and the template arguments involved in
1796 /// that specialization.
1797 llvm::PointerUnion4<FunctionTemplateDecl *,
1798 MemberSpecializationInfo *,
1799 FunctionTemplateSpecializationInfo *,
1800 DependentFunctionTemplateSpecializationInfo *>
1801 TemplateOrSpecialization;
1802
1803 /// Provides source/type location info for the declaration name embedded in
1804 /// the DeclaratorDecl base class.
1805 DeclarationNameLoc DNLoc;
1806
1807 /// \brief Specify that this function declaration is actually a function
1808 /// template specialization.
1809 ///
1810 /// \param C the ASTContext.
1811 ///
1812 /// \param Template the function template that this function template
1813 /// specialization specializes.
1814 ///
1815 /// \param TemplateArgs the template arguments that produced this
1816 /// function template specialization from the template.
1817 ///
1818 /// \param InsertPos If non-NULL, the position in the function template
1819 /// specialization set where the function template specialization data will
1820 /// be inserted.
1821 ///
1822 /// \param TSK the kind of template specialization this is.
1823 ///
1824 /// \param TemplateArgsAsWritten location info of template arguments.
1825 ///
1826 /// \param PointOfInstantiation point at which the function template
1827 /// specialization was first instantiated.
1828 void setFunctionTemplateSpecialization(ASTContext &C,
1829 FunctionTemplateDecl *Template,
1830 const TemplateArgumentList *TemplateArgs,
1831 void *InsertPos,
1832 TemplateSpecializationKind TSK,
1833 const TemplateArgumentListInfo *TemplateArgsAsWritten,
1834 SourceLocation PointOfInstantiation);
1835
1836 /// \brief Specify that this record is an instantiation of the
1837 /// member function FD.
1838 void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD,
1839 TemplateSpecializationKind TSK);
1840
1841 void setParams(ASTContext &C, ArrayRef<ParmVarDecl *> NewParamInfo);
1842
1843protected:
1844 FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1845 const DeclarationNameInfo &NameInfo, QualType T,
1846 TypeSourceInfo *TInfo, StorageClass S, bool isInlineSpecified,
1847 bool isConstexprSpecified)
1848 : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
1849 StartLoc),
1850 DeclContext(DK), redeclarable_base(C), SClass(S),
1851 IsInline(isInlineSpecified), IsInlineSpecified(isInlineSpecified),
1852 IsExplicitSpecified(false), IsVirtualAsWritten(false), IsPure(false),
1853 HasInheritedPrototype(false), HasWrittenPrototype(true),
1854 IsDeleted(false), IsTrivial(false), IsTrivialForCall(false),
1855 IsDefaulted(false),
1856 IsExplicitlyDefaulted(false), HasImplicitReturnZero(false),
1857 IsLateTemplateParsed(false), IsConstexpr(isConstexprSpecified),
1858 InstantiationIsPending(false), UsesSEHTry(false), HasSkippedBody(false),
1859 WillHaveBody(false), IsMultiVersion(false),
1860 IsCopyDeductionCandidate(false), HasODRHash(false), ODRHash(0),
1861 EndRangeLoc(NameInfo.getEndLoc()), DNLoc(NameInfo.getInfo()) {}
1862
1863 using redeclarable_base = Redeclarable<FunctionDecl>;
1864
1865 FunctionDecl *getNextRedeclarationImpl() override {
1866 return getNextRedeclaration();
1867 }
1868
1869 FunctionDecl *getPreviousDeclImpl() override {
1870 return getPreviousDecl();
1871 }
1872
1873 FunctionDecl *getMostRecentDeclImpl() override {
1874 return getMostRecentDecl();
1875 }
1876
1877public:
1878 friend class ASTDeclReader;
1879 friend class ASTDeclWriter;
1880
1881 using redecl_range = redeclarable_base::redecl_range;
1882 using redecl_iterator = redeclarable_base::redecl_iterator;
1883
1884 using redeclarable_base::redecls_begin;
1885 using redeclarable_base::redecls_end;
1886 using redeclarable_base::redecls;
1887 using redeclarable_base::getPreviousDecl;
1888 using redeclarable_base::getMostRecentDecl;
1889 using redeclarable_base::isFirstDecl;
1890
1891 static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1892 SourceLocation StartLoc, SourceLocation NLoc,
1893 DeclarationName N, QualType T,
1894 TypeSourceInfo *TInfo,
1895 StorageClass SC,
1896 bool isInlineSpecified = false,
1897 bool hasWrittenPrototype = true,
1898 bool isConstexprSpecified = false) {
1899 DeclarationNameInfo NameInfo(N, NLoc);
1900 return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo,
1901 SC,
1902 isInlineSpecified, hasWrittenPrototype,
1903 isConstexprSpecified);
1904 }
1905
1906 static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1907 SourceLocation StartLoc,
1908 const DeclarationNameInfo &NameInfo,
1909 QualType T, TypeSourceInfo *TInfo,
1910 StorageClass SC,
1911 bool isInlineSpecified,
1912 bool hasWrittenPrototype,
1913 bool isConstexprSpecified = false);
1914
1915 static FunctionDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1916
1917 DeclarationNameInfo getNameInfo() const {
1918 return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
1919 }
1920
1921 void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
1922 bool Qualified) const override;
1923
1924 void setRangeEnd(SourceLocation E) { EndRangeLoc = E; }
1925
1926 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1927
1928 // Function definitions.
1929 //
1930 // A function declaration may be:
1931 // - a non defining declaration,
1932 // - a definition. A function may be defined because:
1933 // - it has a body, or will have it in the case of late parsing.
1934 // - it has an uninstantiated body. The body does not exist because the
1935 // function is not used yet, but the declaration is considered a
1936 // definition and does not allow other definition of this function.
1937 // - it does not have a user specified body, but it does not allow
1938 // redefinition, because it is deleted/defaulted or is defined through
1939 // some other mechanism (alias, ifunc).
1940
1941 /// Returns true if the function has a body.
1942 ///
1943 /// The function body might be in any of the (re-)declarations of this
1944 /// function. The variant that accepts a FunctionDecl pointer will set that
1945 /// function declaration to the actual declaration containing the body (if
1946 /// there is one).
1947 bool hasBody(const FunctionDecl *&Definition) const;
1948
1949 bool hasBody() const override {
1950 const FunctionDecl* Definition;
1951 return hasBody(Definition);
1952 }
1953
1954 /// Returns whether the function has a trivial body that does not require any
1955 /// specific codegen.
1956 bool hasTrivialBody() const;
1957
1958 /// Returns true if the function has a definition that does not need to be
1959 /// instantiated.
1960 ///
1961 /// The variant that accepts a FunctionDecl pointer will set that function
1962 /// declaration to the declaration that is a definition (if there is one).
1963 bool isDefined(const FunctionDecl *&Definition) const;
1964
1965 virtual bool isDefined() const {
1966 const FunctionDecl* Definition;
1967 return isDefined(Definition);
1968 }
1969
1970 /// \brief Get the definition for this declaration.
1971 FunctionDecl *getDefinition() {
1972 const FunctionDecl *Definition;
1973 if (isDefined(Definition))
1974 return const_cast<FunctionDecl *>(Definition);
1975 return nullptr;
1976 }
1977 const FunctionDecl *getDefinition() const {
1978 return const_cast<FunctionDecl *>(this)->getDefinition();
1979 }
1980
1981 /// Retrieve the body (definition) of the function. The function body might be
1982 /// in any of the (re-)declarations of this function. The variant that accepts
1983 /// a FunctionDecl pointer will set that function declaration to the actual
1984 /// declaration containing the body (if there is one).
1985 /// NOTE: For checking if there is a body, use hasBody() instead, to avoid
1986 /// unnecessary AST de-serialization of the body.
1987 Stmt *getBody(const FunctionDecl *&Definition) const;
1988
1989 Stmt *getBody() const override {
1990 const FunctionDecl* Definition;
1991 return getBody(Definition);
1992 }
1993
1994 /// Returns whether this specific declaration of the function is also a
1995 /// definition that does not contain uninstantiated body.
1996 ///
1997 /// This does not determine whether the function has been defined (e.g., in a
1998 /// previous definition); for that information, use isDefined.
1999 bool isThisDeclarationADefinition() const {
2000 return IsDeleted || IsDefaulted || Body || HasSkippedBody ||
2001 IsLateTemplateParsed || WillHaveBody || hasDefiningAttr();
2002 }
2003
2004 /// Returns whether this specific declaration of the function has a body.
2005 bool doesThisDeclarationHaveABody() const {
2006 return Body || IsLateTemplateParsed;
2007 }
2008
2009 void setBody(Stmt *B);
2010 void setLazyBody(uint64_t Offset) { Body = Offset; }
2011
2012 /// Whether this function is variadic.
2013 bool isVariadic() const;
2014
2015 /// Whether this function is marked as virtual explicitly.
2016 bool isVirtualAsWritten() const { return IsVirtualAsWritten; }
2017 void setVirtualAsWritten(bool V) { IsVirtualAsWritten = V; }
2018
2019 /// Whether this virtual function is pure, i.e. makes the containing class
2020 /// abstract.
2021 bool isPure() const { return IsPure; }
2022 void setPure(bool P = true);
2023
2024 /// Whether this templated function will be late parsed.
2025 bool isLateTemplateParsed() const { return IsLateTemplateParsed; }
2026 void setLateTemplateParsed(bool ILT = true) { IsLateTemplateParsed = ILT; }
2027
2028 /// Whether this function is "trivial" in some specialized C++ senses.
2029 /// Can only be true for default constructors, copy constructors,
2030 /// copy assignment operators, and destructors. Not meaningful until
2031 /// the class has been fully built by Sema.
2032 bool isTrivial() const { return IsTrivial; }
2033 void setTrivial(bool IT) { IsTrivial = IT; }
2034
2035 bool isTrivialForCall() const { return IsTrivialForCall; }
2036 void setTrivialForCall(bool IT) { IsTrivialForCall = IT; }
2037
2038 /// Whether this function is defaulted per C++0x. Only valid for
2039 /// special member functions.
2040 bool isDefaulted() const { return IsDefaulted; }
2041 void setDefaulted(bool D = true) { IsDefaulted = D; }
2042
2043 /// Whether this function is explicitly defaulted per C++0x. Only valid
2044 /// for special member functions.
2045 bool isExplicitlyDefaulted() const { return IsExplicitlyDefaulted; }
2046 void setExplicitlyDefaulted(bool ED = true) { IsExplicitlyDefaulted = ED; }
2047
2048 /// Whether falling off this function implicitly returns null/zero.
2049 /// If a more specific implicit return value is required, front-ends
2050 /// should synthesize the appropriate return statements.
2051 bool hasImplicitReturnZero() const { return HasImplicitReturnZero; }
2052 void setHasImplicitReturnZero(bool IRZ) { HasImplicitReturnZero = IRZ; }
2053
2054 /// \brief Whether this function has a prototype, either because one
2055 /// was explicitly written or because it was "inherited" by merging
2056 /// a declaration without a prototype with a declaration that has a
2057 /// prototype.
2058 bool hasPrototype() const {
2059 return HasWrittenPrototype || HasInheritedPrototype;
2060 }
2061
2062 bool hasWrittenPrototype() const { return HasWrittenPrototype; }
2063
2064 /// \brief Whether this function inherited its prototype from a
2065 /// previous declaration.
2066 bool hasInheritedPrototype() const { return HasInheritedPrototype; }
2067 void setHasInheritedPrototype(bool P = true) { HasInheritedPrototype = P; }
2068
2069 /// Whether this is a (C++11) constexpr function or constexpr constructor.
2070 bool isConstexpr() const { return IsConstexpr; }
2071 void setConstexpr(bool IC) { IsConstexpr = IC; }
2072
2073 /// \brief Whether the instantiation of this function is pending.
2074 /// This bit is set when the decision to instantiate this function is made
2075 /// and unset if and when the function body is created. That leaves out
2076 /// cases where instantiation did not happen because the template definition
2077 /// was not seen in this TU. This bit remains set in those cases, under the
2078 /// assumption that the instantiation will happen in some other TU.
2079 bool instantiationIsPending() const { return InstantiationIsPending; }
2080 void setInstantiationIsPending(bool IC) { InstantiationIsPending = IC; }
2081
2082 /// \brief Indicates the function uses __try.
2083 bool usesSEHTry() const { return UsesSEHTry; }
2084 void setUsesSEHTry(bool UST) { UsesSEHTry = UST; }
2085
2086 /// \brief Whether this function has been deleted.
2087 ///
2088 /// A function that is "deleted" (via the C++0x "= delete" syntax)
2089 /// acts like a normal function, except that it cannot actually be
2090 /// called or have its address taken. Deleted functions are
2091 /// typically used in C++ overload resolution to attract arguments
2092 /// whose type or lvalue/rvalue-ness would permit the use of a
2093 /// different overload that would behave incorrectly. For example,
2094 /// one might use deleted functions to ban implicit conversion from
2095 /// a floating-point number to an Integer type:
2096 ///
2097 /// @code
2098 /// struct Integer {
2099 /// Integer(long); // construct from a long
2100 /// Integer(double) = delete; // no construction from float or double
2101 /// Integer(long double) = delete; // no construction from long double
2102 /// };
2103 /// @endcode
2104 // If a function is deleted, its first declaration must be.
2105 bool isDeleted() const { return getCanonicalDecl()->IsDeleted; }
2106 bool isDeletedAsWritten() const { return IsDeleted && !IsDefaulted; }
2107 void setDeletedAsWritten(bool D = true) { IsDeleted = D; }
2108
2109 /// \brief Determines whether this function is "main", which is the
2110 /// entry point into an executable program.
2111 bool isMain() const;
2112
2113 /// \brief Determines whether this function is a MSVCRT user defined entry
2114 /// point.
2115 bool isMSVCRTEntryPoint() const;
2116
2117 /// \brief Determines whether this operator new or delete is one
2118 /// of the reserved global placement operators:
2119 /// void *operator new(size_t, void *);
2120 /// void *operator new[](size_t, void *);
2121 /// void operator delete(void *, void *);
2122 /// void operator delete[](void *, void *);
2123 /// These functions have special behavior under [new.delete.placement]:
2124 /// These functions are reserved, a C++ program may not define
2125 /// functions that displace the versions in the Standard C++ library.
2126 /// The provisions of [basic.stc.dynamic] do not apply to these
2127 /// reserved placement forms of operator new and operator delete.
2128 ///
2129 /// This function must be an allocation or deallocation function.
2130 bool isReservedGlobalPlacementOperator() const;
2131
2132 /// \brief Determines whether this function is one of the replaceable
2133 /// global allocation functions:
2134 /// void *operator new(size_t);
2135 /// void *operator new(size_t, const std::nothrow_t &) noexcept;
2136 /// void *operator new[](size_t);
2137 /// void *operator new[](size_t, const std::nothrow_t &) noexcept;
2138 /// void operator delete(void *) noexcept;
2139 /// void operator delete(void *, std::size_t) noexcept; [C++1y]
2140 /// void operator delete(void *, const std::nothrow_t &) noexcept;
2141 /// void operator delete[](void *) noexcept;
2142 /// void operator delete[](void *, std::size_t) noexcept; [C++1y]
2143 /// void operator delete[](void *, const std::nothrow_t &) noexcept;
2144 /// These functions have special behavior under C++1y [expr.new]:
2145 /// An implementation is allowed to omit a call to a replaceable global
2146 /// allocation function. [...]
2147 ///
2148 /// If this function is an aligned allocation/deallocation function, return
2149 /// true through IsAligned.
2150 bool isReplaceableGlobalAllocationFunction(bool *IsAligned = nullptr) const;
2151
2152 /// \brief Determine whether this is a destroying operator delete.
2153 bool isDestroyingOperatorDelete() const;
2154
2155 /// Compute the language linkage.
2156 LanguageLinkage getLanguageLinkage() const;
2157
2158 /// \brief Determines whether this function is a function with
2159 /// external, C linkage.
2160 bool isExternC() const;
2161
2162 /// \brief Determines whether this function's context is, or is nested within,
2163 /// a C++ extern "C" linkage spec.
2164 bool isInExternCContext() const;
2165
2166 /// \brief Determines whether this function's context is, or is nested within,
2167 /// a C++ extern "C++" linkage spec.
2168 bool isInExternCXXContext() const;
2169
2170 /// \brief Determines whether this is a global function.
2171 bool isGlobal() const;
2172
2173 /// \brief Determines whether this function is known to be 'noreturn', through
2174 /// an attribute on its declaration or its type.
2175 bool isNoReturn() const;
2176
2177 /// \brief True if the function was a definition but its body was skipped.
2178 bool hasSkippedBody() const { return HasSkippedBody; }
2179 void setHasSkippedBody(bool Skipped = true) { HasSkippedBody = Skipped; }
2180
2181 /// True if this function will eventually have a body, once it's fully parsed.
2182 bool willHaveBody() const { return WillHaveBody; }
2183 void setWillHaveBody(bool V = true) { WillHaveBody = V; }
2184
2185 /// True if this function is considered a multiversioned function.
2186 bool isMultiVersion() const { return getCanonicalDecl()->IsMultiVersion; }
2187
2188 /// Sets the multiversion state for this declaration and all of its
2189 /// redeclarations.
2190 void setIsMultiVersion(bool V = true) {
2191 getCanonicalDecl()->IsMultiVersion = V;
2192 }
2193
2194 void setPreviousDeclaration(FunctionDecl * PrevDecl);
2195
2196 FunctionDecl *getCanonicalDecl() override;
2197 const FunctionDecl *getCanonicalDecl() const {
2198 return const_cast<FunctionDecl*>(this)->getCanonicalDecl();
2199 }
2200
2201 unsigned getBuiltinID() const;
2202
2203 // ArrayRef interface to parameters.
2204 ArrayRef<ParmVarDecl *> parameters() const {
2205 return {ParamInfo, getNumParams()};
2206 }
2207 MutableArrayRef<ParmVarDecl *> parameters() {
2208 return {ParamInfo, getNumParams()};
2209 }
2210
2211 // Iterator access to formal parameters.
2212 using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator;
2213 using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator;
2214
2215 bool param_empty() const { return parameters().empty(); }
2216 param_iterator param_begin() { return parameters().begin(); }
2217 param_iterator param_end() { return parameters().end(); }
2218 param_const_iterator param_begin() const { return parameters().begin(); }
2219 param_const_iterator param_end() const { return parameters().end(); }
2220 size_t param_size() const { return parameters().size(); }
2221
2222 /// Return the number of parameters this function must have based on its
2223 /// FunctionType. This is the length of the ParamInfo array after it has been
2224 /// created.
2225 unsigned getNumParams() const;
2226
2227 const ParmVarDecl *getParamDecl(unsigned i) const {
2228 assert(i < getNumParams() && "Illegal param #")(static_cast <bool> (i < getNumParams() && "Illegal param #"
) ? void (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 2228, __extension__ __PRETTY_FUNCTION__))
;
2229 return ParamInfo[i];
2230 }
2231 ParmVarDecl *getParamDecl(unsigned i) {
2232 assert(i < getNumParams() && "Illegal param #")(static_cast <bool> (i < getNumParams() && "Illegal param #"
) ? void (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 2232, __extension__ __PRETTY_FUNCTION__))
;
2233 return ParamInfo[i];
2234 }
2235 void setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
2236 setParams(getASTContext(), NewParamInfo);
2237 }
2238
2239 /// Returns the minimum number of arguments needed to call this function. This
2240 /// may be fewer than the number of function parameters, if some of the
2241 /// parameters have default arguments (in C++).
2242 unsigned getMinRequiredArguments() const;
2243
2244 QualType getReturnType() const {
2245 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-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 2245, __extension__ __PRETTY_FUNCTION__))
;
2246 return getType()->getAs<FunctionType>()->getReturnType();
2247 }
2248
2249 /// \brief Attempt to compute an informative source range covering the
2250 /// function return type. This may omit qualifiers and other information with
2251 /// limited representation in the AST.
2252 SourceRange getReturnTypeSourceRange() const;
2253
2254 /// \brief Attempt to compute an informative source range covering the
2255 /// function exception specification, if any.
2256 SourceRange getExceptionSpecSourceRange() const;
2257
2258 /// \brief Determine the type of an expression that calls this function.
2259 QualType getCallResultType() const {
2260 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-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 2260, __extension__ __PRETTY_FUNCTION__))
;
2261 return getType()->getAs<FunctionType>()->getCallResultType(getASTContext());
2262 }
2263
2264 /// \brief Returns the WarnUnusedResultAttr that is either declared on this
2265 /// function, or its return type declaration.
2266 const Attr *getUnusedResultAttr() const;
2267
2268 /// \brief Returns true if this function or its return type has the
2269 /// warn_unused_result attribute.
2270 bool hasUnusedResultAttr() const { return getUnusedResultAttr() != nullptr; }
2271
2272 /// \brief Returns the storage class as written in the source. For the
2273 /// computed linkage of symbol, see getLinkage.
2274 StorageClass getStorageClass() const { return StorageClass(SClass); }
2275
2276 /// \brief Determine whether the "inline" keyword was specified for this
2277 /// function.
2278 bool isInlineSpecified() const { return IsInlineSpecified; }
2279
2280 /// Set whether the "inline" keyword was specified for this function.
2281 void setInlineSpecified(bool I) {
2282 IsInlineSpecified = I;
2283 IsInline = I;
2284 }
2285
2286 /// Flag that this function is implicitly inline.
2287 void setImplicitlyInline() {
2288 IsInline = true;
2289 }
2290
2291 /// \brief Determine whether this function should be inlined, because it is
2292 /// either marked "inline" or "constexpr" or is a member function of a class
2293 /// that was defined in the class body.
2294 bool isInlined() const { return IsInline; }
2295
2296 bool isInlineDefinitionExternallyVisible() const;
2297
2298 bool isMSExternInline() const;
2299
2300 bool doesDeclarationForceExternallyVisibleDefinition() const;
2301
2302 /// Whether this function declaration represents an C++ overloaded
2303 /// operator, e.g., "operator+".
2304 bool isOverloadedOperator() const {
2305 return getOverloadedOperator() != OO_None;
2306 }
2307
2308 OverloadedOperatorKind getOverloadedOperator() const;
2309
2310 const IdentifierInfo *getLiteralIdentifier() const;
2311
2312 /// \brief If this function is an instantiation of a member function
2313 /// of a class template specialization, retrieves the function from
2314 /// which it was instantiated.
2315 ///
2316 /// This routine will return non-NULL for (non-templated) member
2317 /// functions of class templates and for instantiations of function
2318 /// templates. For example, given:
2319 ///
2320 /// \code
2321 /// template<typename T>
2322 /// struct X {
2323 /// void f(T);
2324 /// };
2325 /// \endcode
2326 ///
2327 /// The declaration for X<int>::f is a (non-templated) FunctionDecl
2328 /// whose parent is the class template specialization X<int>. For
2329 /// this declaration, getInstantiatedFromFunction() will return
2330 /// the FunctionDecl X<T>::A. When a complete definition of
2331 /// X<int>::A is required, it will be instantiated from the
2332 /// declaration returned by getInstantiatedFromMemberFunction().
2333 FunctionDecl *getInstantiatedFromMemberFunction() const;
2334
2335 /// \brief What kind of templated function this is.
2336 TemplatedKind getTemplatedKind() const;
2337
2338 /// \brief If this function is an instantiation of a member function of a
2339 /// class template specialization, retrieves the member specialization
2340 /// information.
2341 MemberSpecializationInfo *getMemberSpecializationInfo() const;
2342
2343 /// \brief Specify that this record is an instantiation of the
2344 /// member function FD.
2345 void setInstantiationOfMemberFunction(FunctionDecl *FD,
2346 TemplateSpecializationKind TSK) {
2347 setInstantiationOfMemberFunction(getASTContext(), FD, TSK);
2348 }
2349
2350 /// \brief Retrieves the function template that is described by this
2351 /// function declaration.
2352 ///
2353 /// Every function template is represented as a FunctionTemplateDecl
2354 /// and a FunctionDecl (or something derived from FunctionDecl). The
2355 /// former contains template properties (such as the template
2356 /// parameter lists) while the latter contains the actual
2357 /// description of the template's
2358 /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the
2359 /// FunctionDecl that describes the function template,
2360 /// getDescribedFunctionTemplate() retrieves the
2361 /// FunctionTemplateDecl from a FunctionDecl.
2362 FunctionTemplateDecl *getDescribedFunctionTemplate() const;
2363
2364 void setDescribedFunctionTemplate(FunctionTemplateDecl *Template);
2365
2366 /// \brief Determine whether this function is a function template
2367 /// specialization.
2368 bool isFunctionTemplateSpecialization() const {
2369 return getPrimaryTemplate() != nullptr;
2370 }
2371
2372 /// \brief Retrieve the class scope template pattern that this function
2373 /// template specialization is instantiated from.
2374 FunctionDecl *getClassScopeSpecializationPattern() const;
2375
2376 /// \brief If this function is actually a function template specialization,
2377 /// retrieve information about this function template specialization.
2378 /// Otherwise, returns NULL.
2379 FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const;
2380
2381 /// \brief Determines whether this function is a function template
2382 /// specialization or a member of a class template specialization that can
2383 /// be implicitly instantiated.
2384 bool isImplicitlyInstantiable() const;
2385
2386 /// \brief Determines if the given function was instantiated from a
2387 /// function template.
2388 bool isTemplateInstantiation() const;
2389
2390 /// \brief Retrieve the function declaration from which this function could
2391 /// be instantiated, if it is an instantiation (rather than a non-template
2392 /// or a specialization, for example).
2393 FunctionDecl *getTemplateInstantiationPattern() const;
2394
2395 /// \brief Retrieve the primary template that this function template
2396 /// specialization either specializes or was instantiated from.
2397 ///
2398 /// If this function declaration is not a function template specialization,
2399 /// returns NULL.
2400 FunctionTemplateDecl *getPrimaryTemplate() const;
2401
2402 /// \brief Retrieve the template arguments used to produce this function
2403 /// template specialization from the primary template.
2404 ///
2405 /// If this function declaration is not a function template specialization,
2406 /// returns NULL.
2407 const TemplateArgumentList *getTemplateSpecializationArgs() const;
2408
2409 /// \brief Retrieve the template argument list as written in the sources,
2410 /// if any.
2411 ///
2412 /// If this function declaration is not a function template specialization
2413 /// or if it had no explicit template argument list, returns NULL.
2414 /// Note that it an explicit template argument list may be written empty,
2415 /// e.g., template<> void foo<>(char* s);
2416 const ASTTemplateArgumentListInfo*
2417 getTemplateSpecializationArgsAsWritten() const;
2418
2419 /// \brief Specify that this function declaration is actually a function
2420 /// template specialization.
2421 ///
2422 /// \param Template the function template that this function template
2423 /// specialization specializes.
2424 ///
2425 /// \param TemplateArgs the template arguments that produced this
2426 /// function template specialization from the template.
2427 ///
2428 /// \param InsertPos If non-NULL, the position in the function template
2429 /// specialization set where the function template specialization data will
2430 /// be inserted.
2431 ///
2432 /// \param TSK the kind of template specialization this is.
2433 ///
2434 /// \param TemplateArgsAsWritten location info of template arguments.
2435 ///
2436 /// \param PointOfInstantiation point at which the function template
2437 /// specialization was first instantiated.
2438 void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template,
2439 const TemplateArgumentList *TemplateArgs,
2440 void *InsertPos,
2441 TemplateSpecializationKind TSK = TSK_ImplicitInstantiation,
2442 const TemplateArgumentListInfo *TemplateArgsAsWritten = nullptr,
2443 SourceLocation PointOfInstantiation = SourceLocation()) {
2444 setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs,
2445 InsertPos, TSK, TemplateArgsAsWritten,
2446 PointOfInstantiation);
2447 }
2448
2449 /// \brief Specifies that this function declaration is actually a
2450 /// dependent function template specialization.
2451 void setDependentTemplateSpecialization(ASTContext &Context,
2452 const UnresolvedSetImpl &Templates,
2453 const TemplateArgumentListInfo &TemplateArgs);
2454
2455 DependentFunctionTemplateSpecializationInfo *
2456 getDependentSpecializationInfo() const;
2457
2458 /// \brief Determine what kind of template instantiation this function
2459 /// represents.
2460 TemplateSpecializationKind getTemplateSpecializationKind() const;
2461
2462 /// \brief Determine what kind of template instantiation this function
2463 /// represents.
2464 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2465 SourceLocation PointOfInstantiation = SourceLocation());
2466
2467 /// \brief Retrieve the (first) point of instantiation of a function template
2468 /// specialization or a member of a class template specialization.
2469 ///
2470 /// \returns the first point of instantiation, if this function was
2471 /// instantiated from a template; otherwise, returns an invalid source
2472 /// location.
2473 SourceLocation getPointOfInstantiation() const;
2474
2475 /// \brief Determine whether this is or was instantiated from an out-of-line
2476 /// definition of a member function.
2477 bool isOutOfLine() const override;
2478
2479 /// \brief Identify a memory copying or setting function.
2480 /// If the given function is a memory copy or setting function, returns
2481 /// the corresponding Builtin ID. If the function is not a memory function,
2482 /// returns 0.
2483 unsigned getMemoryFunctionKind() const;
2484
2485 /// \brief Returns ODRHash of the function. This value is calculated and
2486 /// stored on first call, then the stored value returned on the other calls.
2487 unsigned getODRHash();
2488
2489 // Implement isa/cast/dyncast/etc.
2490 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2491 static bool classofKind(Kind K) {
2492 return K >= firstFunction && K <= lastFunction;
2493 }
2494 static DeclContext *castToDeclContext(const FunctionDecl *D) {
2495 return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D));
2496 }
2497 static FunctionDecl *castFromDeclContext(const DeclContext *DC) {
2498 return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC));
2499 }
2500};
2501
2502/// Represents a member of a struct/union/class.
2503class FieldDecl : public DeclaratorDecl, public Mergeable<FieldDecl> {
2504 unsigned BitField : 1;
2505 unsigned Mutable : 1;
2506 mutable unsigned CachedFieldIndex : 30;
2507
2508 /// The kinds of value we can store in InitializerOrBitWidth.
2509 ///
2510 /// Note that this is compatible with InClassInitStyle except for
2511 /// ISK_CapturedVLAType.
2512 enum InitStorageKind {
2513 /// If the pointer is null, there's nothing special. Otherwise,
2514 /// this is a bitfield and the pointer is the Expr* storing the
2515 /// bit-width.
2516 ISK_NoInit = (unsigned) ICIS_NoInit,
2517
2518 /// The pointer is an (optional due to delayed parsing) Expr*
2519 /// holding the copy-initializer.
2520 ISK_InClassCopyInit = (unsigned) ICIS_CopyInit,
2521
2522 /// The pointer is an (optional due to delayed parsing) Expr*
2523 /// holding the list-initializer.
2524 ISK_InClassListInit = (unsigned) ICIS_ListInit,
2525
2526 /// The pointer is a VariableArrayType* that's been captured;
2527 /// the enclosing context is a lambda or captured statement.
2528 ISK_CapturedVLAType,
2529 };
2530
2531 /// If this is a bitfield with a default member initializer, this
2532 /// structure is used to represent the two expressions.
2533 struct InitAndBitWidth {
2534 Expr *Init;
2535 Expr *BitWidth;
2536 };
2537
2538 /// \brief Storage for either the bit-width, the in-class initializer, or
2539 /// both (via InitAndBitWidth), or the captured variable length array bound.
2540 ///
2541 /// If the storage kind is ISK_InClassCopyInit or
2542 /// ISK_InClassListInit, but the initializer is null, then this
2543 /// field has an in-class initializer that has not yet been parsed
2544 /// and attached.
2545 // FIXME: Tail-allocate this to reduce the size of FieldDecl in the
2546 // overwhelmingly common case that we have none of these things.
2547 llvm::PointerIntPair<void *, 2, InitStorageKind> InitStorage;
2548
2549protected:
2550 FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
2551 SourceLocation IdLoc, IdentifierInfo *Id,
2552 QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2553 InClassInitStyle InitStyle)
2554 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
2555 BitField(false), Mutable(Mutable), CachedFieldIndex(0),
2556 InitStorage(nullptr, (InitStorageKind) InitStyle) {
2557 if (BW)
2558 setBitWidth(BW);
2559 }
2560
2561public:
2562 friend class ASTDeclReader;
2563 friend class ASTDeclWriter;
2564
2565 static FieldDecl *Create(const ASTContext &C, DeclContext *DC,
2566 SourceLocation StartLoc, SourceLocation IdLoc,
2567 IdentifierInfo *Id, QualType T,
2568 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2569 InClassInitStyle InitStyle);
2570
2571 static FieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2572
2573 /// Returns the index of this field within its record,
2574 /// as appropriate for passing to ASTRecordLayout::getFieldOffset.
2575 unsigned getFieldIndex() const;
2576
2577 /// Determines whether this field is mutable (C++ only).
2578 bool isMutable() const { return Mutable; }
2579
2580 /// Determines whether this field is a bitfield.
2581 bool isBitField() const { return BitField; }
2582
2583 /// Determines whether this is an unnamed bitfield.
2584 bool isUnnamedBitfield() const { return isBitField() && !getDeclName(); }
2585
2586 /// Determines whether this field is a
2587 /// representative for an anonymous struct or union. Such fields are
2588 /// unnamed and are implicitly generated by the implementation to
2589 /// store the data for the anonymous union or struct.
2590 bool isAnonymousStructOrUnion() const;
2591
2592 Expr *getBitWidth() const {
2593 if (!BitField)
2594 return nullptr;
2595 void *Ptr = InitStorage.getPointer();
2596 if (getInClassInitStyle())
2597 return static_cast<InitAndBitWidth*>(Ptr)->BitWidth;
2598 return static_cast<Expr*>(Ptr);
2599 }
2600
2601 unsigned getBitWidthValue(const ASTContext &Ctx) const;
2602
2603 /// Set the bit-field width for this member.
2604 // Note: used by some clients (i.e., do not remove it).
2605 void setBitWidth(Expr *Width) {
2606 assert(!hasCapturedVLAType() && !BitField &&(static_cast <bool> (!hasCapturedVLAType() && !
BitField && "bit width or captured type already set")
? void (0) : __assert_fail ("!hasCapturedVLAType() && !BitField && \"bit width or captured type already set\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 2607, __extension__ __PRETTY_FUNCTION__))
2607 "bit width or captured type already set")(static_cast <bool> (!hasCapturedVLAType() && !
BitField && "bit width or captured type already set")
? void (0) : __assert_fail ("!hasCapturedVLAType() && !BitField && \"bit width or captured type already set\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 2607, __extension__ __PRETTY_FUNCTION__))
;
2608 assert(Width && "no bit width specified")(static_cast <bool> (Width && "no bit width specified"
) ? void (0) : __assert_fail ("Width && \"no bit width specified\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 2608, __extension__ __PRETTY_FUNCTION__))
;
2609 InitStorage.setPointer(
2610 InitStorage.getInt()
2611 ? new (getASTContext())
2612 InitAndBitWidth{getInClassInitializer(), Width}
2613 : static_cast<void*>(Width));
2614 BitField = true;
2615 }
2616
2617 /// Remove the bit-field width from this member.
2618 // Note: used by some clients (i.e., do not remove it).
2619 void removeBitWidth() {
2620 assert(isBitField() && "no bitfield width to remove")(static_cast <bool> (isBitField() && "no bitfield width to remove"
) ? void (0) : __assert_fail ("isBitField() && \"no bitfield width to remove\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 2620, __extension__ __PRETTY_FUNCTION__))
;
2621 InitStorage.setPointer(getInClassInitializer());
2622 BitField = false;
2623 }
2624
2625 /// Get the kind of (C++11) default member initializer that this field has.
2626 InClassInitStyle getInClassInitStyle() const {
2627 InitStorageKind storageKind = InitStorage.getInt();
2628 return (storageKind == ISK_CapturedVLAType
2629 ? ICIS_NoInit : (InClassInitStyle) storageKind);
2630 }
2631
2632 /// Determine whether this member has a C++11 default member initializer.
2633 bool hasInClassInitializer() const {
2634 return getInClassInitStyle() != ICIS_NoInit;
2635 }
2636
2637 /// Get the C++11 default member initializer for this member, or null if one
2638 /// has not been set. If a valid declaration has a default member initializer,
2639 /// but this returns null, then we have not parsed and attached it yet.
2640 Expr *getInClassInitializer() const {
2641 if (!hasInClassInitializer())
2642 return nullptr;
2643 void *Ptr = InitStorage.getPointer();
2644 if (BitField)
2645 return static_cast<InitAndBitWidth*>(Ptr)->Init;
2646 return static_cast<Expr*>(Ptr);
2647 }
2648
2649 /// Set the C++11 in-class initializer for this member.
2650 void setInClassInitializer(Expr *Init) {
2651 assert(hasInClassInitializer() && !getInClassInitializer())(static_cast <bool> (hasInClassInitializer() &&
!getInClassInitializer()) ? void (0) : __assert_fail ("hasInClassInitializer() && !getInClassInitializer()"
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 2651, __extension__ __PRETTY_FUNCTION__))
;
2652 if (BitField)
2653 static_cast<InitAndBitWidth*>(InitStorage.getPointer())->Init = Init;
2654 else
2655 InitStorage.setPointer(Init);
2656 }
2657
2658 /// Remove the C++11 in-class initializer from this member.
2659 void removeInClassInitializer() {
2660 assert(hasInClassInitializer() && "no initializer to remove")(static_cast <bool> (hasInClassInitializer() &&
"no initializer to remove") ? void (0) : __assert_fail ("hasInClassInitializer() && \"no initializer to remove\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 2660, __extension__ __PRETTY_FUNCTION__))
;
2661 InitStorage.setPointerAndInt(getBitWidth(), ISK_NoInit);
2662 }
2663
2664 /// \brief Determine whether this member captures the variable length array
2665 /// type.
2666 bool hasCapturedVLAType() const {
2667 return InitStorage.getInt() == ISK_CapturedVLAType;
2668 }
2669
2670 /// \brief Get the captured variable length array type.
2671 const VariableArrayType *getCapturedVLAType() const {
2672 return hasCapturedVLAType() ? static_cast<const VariableArrayType *>(
2673 InitStorage.getPointer())
2674 : nullptr;
2675 }
2676
2677 /// \brief Set the captured variable length array type for this field.
2678 void setCapturedVLAType(const VariableArrayType *VLAType);
2679
2680 /// Returns the parent of this field declaration, which
2681 /// is the struct in which this field is defined.
2682 const RecordDecl *getParent() const {
2683 return cast<RecordDecl>(getDeclContext());
2684 }
2685
2686 RecordDecl *getParent() {
2687 return cast<RecordDecl>(getDeclContext());
2688 }
2689
2690 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
2691
2692 /// Retrieves the canonical declaration of this field.
2693 FieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
2694 const FieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
2695
2696 // Implement isa/cast/dyncast/etc.
2697 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2698 static bool classofKind(Kind K) { return K >= firstField && K <= lastField; }
2699};
2700
2701/// An instance of this object exists for each enum constant
2702/// that is defined. For example, in "enum X {a,b}", each of a/b are
2703/// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a
2704/// TagType for the X EnumDecl.
2705class EnumConstantDecl : public ValueDecl, public Mergeable<EnumConstantDecl> {
2706 Stmt *Init; // an integer constant expression
2707 llvm::APSInt Val; // The value.
2708
2709protected:
2710 EnumConstantDecl(DeclContext *DC, SourceLocation L,
2711 IdentifierInfo *Id, QualType T, Expr *E,
2712 const llvm::APSInt &V)
2713 : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {}
2714
2715public:
2716 friend class StmtIteratorBase;
2717
2718 static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC,
2719 SourceLocation L, IdentifierInfo *Id,
2720 QualType T, Expr *E,
2721 const llvm::APSInt &V);
2722 static EnumConstantDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2723
2724 const Expr *getInitExpr() const { return (const Expr*) Init; }
2725 Expr *getInitExpr() { return (Expr*) Init; }
2726 const llvm::APSInt &getInitVal() const { return Val; }
2727
2728 void setInitExpr(Expr *E) { Init = (Stmt*) E; }
2729 void setInitVal(const llvm::APSInt &V) { Val = V; }
2730
2731 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
2732
2733 /// Retrieves the canonical declaration of this enumerator.
2734 EnumConstantDecl *getCanonicalDecl() override { return getFirstDecl(); }
2735 const EnumConstantDecl *getCanonicalDecl() const { return getFirstDecl(); }
2736
2737 // Implement isa/cast/dyncast/etc.
2738 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2739 static bool classofKind(Kind K) { return K == EnumConstant; }
2740};
2741
2742/// Represents a field injected from an anonymous union/struct into the parent
2743/// scope. These are always implicit.
2744class IndirectFieldDecl : public ValueDecl,
2745 public Mergeable<IndirectFieldDecl> {
2746 NamedDecl **Chaining;
2747 unsigned ChainingSize;
2748
2749 IndirectFieldDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
2750 DeclarationName N, QualType T,
2751 MutableArrayRef<NamedDecl *> CH);
2752
2753 void anchor() override;
2754
2755public:
2756 friend class ASTDeclReader;
2757
2758 static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC,
2759 SourceLocation L, IdentifierInfo *Id,
2760 QualType T, llvm::MutableArrayRef<NamedDecl *> CH);
2761
2762 static IndirectFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2763
2764 using chain_iterator = ArrayRef<NamedDecl *>::const_iterator;
2765
2766 ArrayRef<NamedDecl *> chain() const {
2767 return llvm::makeArrayRef(Chaining, ChainingSize);
2768 }
2769 chain_iterator chain_begin() const { return chain().begin(); }
2770 chain_iterator chain_end() const { return chain().end(); }
2771
2772 unsigned getChainingSize() const { return ChainingSize; }
2773
2774 FieldDecl *getAnonField() const {
2775 assert(chain().size() >= 2)(static_cast <bool> (chain().size() >= 2) ? void (0)
: __assert_fail ("chain().size() >= 2", "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 2775, __extension__ __PRETTY_FUNCTION__))
;
2776 return cast<FieldDecl>(chain().back());
2777 }
2778
2779 VarDecl *getVarDecl() const {
2780 assert(chain().size() >= 2)(static_cast <bool> (chain().size() >= 2) ? void (0)
: __assert_fail ("chain().size() >= 2", "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 2780, __extension__ __PRETTY_FUNCTION__))
;
2781 return dyn_cast<VarDecl>(chain().front());
2782 }
2783
2784 IndirectFieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
2785 const IndirectFieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
2786
2787 // Implement isa/cast/dyncast/etc.
2788 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2789 static bool classofKind(Kind K) { return K == IndirectField; }
2790};
2791
2792/// Represents a declaration of a type.
2793class TypeDecl : public NamedDecl {
2794 friend class ASTContext;
2795
2796 /// This indicates the Type object that represents
2797 /// this TypeDecl. It is a cache maintained by
2798 /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and
2799 /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl.
2800 mutable const Type *TypeForDecl = nullptr;
2801
2802 /// The start of the source range for this declaration.
2803 SourceLocation LocStart;
2804
2805 void anchor() override;
2806
2807protected:
2808 TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
2809 SourceLocation StartL = SourceLocation())
2810 : NamedDecl(DK, DC, L, Id), LocStart(StartL) {}
2811
2812public:
2813 // Low-level accessor. If you just want the type defined by this node,
2814 // check out ASTContext::getTypeDeclType or one of
2815 // ASTContext::getTypedefType, ASTContext::getRecordType, etc. if you
2816 // already know the specific kind of node this is.
2817 const Type *getTypeForDecl() const { return TypeForDecl; }
2818 void setTypeForDecl(const Type *TD) { TypeForDecl = TD; }
2819
2820 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return LocStart; }
2821 void setLocStart(SourceLocation L) { LocStart = L; }
2822 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
2823 if (LocStart.isValid())
2824 return SourceRange(LocStart, getLocation());
2825 else
2826 return SourceRange(getLocation());
2827 }
2828
2829 // Implement isa/cast/dyncast/etc.
2830 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2831 static bool classofKind(Kind K) { return K >= firstType && K <= lastType; }
2832};
2833
2834/// Base class for declarations which introduce a typedef-name.
2835class TypedefNameDecl : public TypeDecl, public Redeclarable<TypedefNameDecl> {
2836 struct LLVM_ALIGNAS(8)alignas(8) ModedTInfo {
2837 TypeSourceInfo *first;
2838 QualType second;
2839 };
2840
2841 /// If int part is 0, we have not computed IsTransparentTag.
2842 /// Otherwise, IsTransparentTag is (getInt() >> 1).
2843 mutable llvm::PointerIntPair<
2844 llvm::PointerUnion<TypeSourceInfo *, ModedTInfo *>, 2>
2845 MaybeModedTInfo;
2846
2847 void anchor() override;
2848
2849protected:
2850 TypedefNameDecl(Kind DK, ASTContext &C, DeclContext *DC,
2851 SourceLocation StartLoc, SourceLocation IdLoc,
2852 IdentifierInfo *Id, TypeSourceInfo *TInfo)
2853 : TypeDecl(DK, DC, IdLoc, Id, StartLoc), redeclarable_base(C),
2854 MaybeModedTInfo(TInfo, 0) {}
2855
2856 using redeclarable_base = Redeclarable<TypedefNameDecl>;
2857
2858 TypedefNameDecl *getNextRedeclarationImpl() override {
2859 return getNextRedeclaration();
2860 }
2861
2862 TypedefNameDecl *getPreviousDeclImpl() override {
2863 return getPreviousDecl();
2864 }
2865
2866 TypedefNameDecl *getMostRecentDeclImpl() override {
2867 return getMostRecentDecl();
2868 }
2869
2870public:
2871 using redecl_range = redeclarable_base::redecl_range;
2872 using redecl_iterator = redeclarable_base::redecl_iterator;
2873
2874 using redeclarable_base::redecls_begin;
2875 using redeclarable_base::redecls_end;
2876 using redeclarable_base::redecls;
2877 using redeclarable_base::getPreviousDecl;
2878 using redeclarable_base::getMostRecentDecl;
2879 using redeclarable_base::isFirstDecl;
2880
2881 bool isModed() const {
2882 return MaybeModedTInfo.getPointer().is<ModedTInfo *>();
2883 }
2884
2885 TypeSourceInfo *getTypeSourceInfo() const {
2886 return isModed() ? MaybeModedTInfo.getPointer().get<ModedTInfo *>()->first
2887 : MaybeModedTInfo.getPointer().get<TypeSourceInfo *>();
2888 }
2889
2890 QualType getUnderlyingType() const {
2891 return isModed() ? MaybeModedTInfo.getPointer().get<ModedTInfo *>()->second
2892 : MaybeModedTInfo.getPointer()
2893 .get<TypeSourceInfo *>()
2894 ->getType();
2895 }
2896
2897 void setTypeSourceInfo(TypeSourceInfo *newType) {
2898 MaybeModedTInfo.setPointer(newType);
2899 }
2900
2901 void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy) {
2902 MaybeModedTInfo.setPointer(new (getASTContext(), 8)
2903 ModedTInfo({unmodedTSI, modedTy}));
2904 }
2905
2906 /// Retrieves the canonical declaration of this typedef-name.
2907 TypedefNameDecl *getCanonicalDecl() override { return getFirstDecl(); }
2908 const TypedefNameDecl *getCanonicalDecl() const { return getFirstDecl(); }
2909
2910 /// Retrieves the tag declaration for which this is the typedef name for
2911 /// linkage purposes, if any.
2912 ///
2913 /// \param AnyRedecl Look for the tag declaration in any redeclaration of
2914 /// this typedef declaration.
2915 TagDecl *getAnonDeclWithTypedefName(bool AnyRedecl = false) const;
2916
2917 /// Determines if this typedef shares a name and spelling location with its
2918 /// underlying tag type, as is the case with the NS_ENUM macro.
2919 bool isTransparentTag() const {
2920 if (MaybeModedTInfo.getInt())
2921 return MaybeModedTInfo.getInt() & 0x2;
2922 return isTransparentTagSlow();
2923 }
2924
2925 // Implement isa/cast/dyncast/etc.
2926 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2927 static bool classofKind(Kind K) {
2928 return K >= firstTypedefName && K <= lastTypedefName;
2929 }
2930
2931private:
2932 bool isTransparentTagSlow() const;
2933};
2934
2935/// Represents the declaration of a typedef-name via the 'typedef'
2936/// type specifier.
2937class TypedefDecl : public TypedefNameDecl {
2938 TypedefDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
2939 SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
2940 : TypedefNameDecl(Typedef, C, DC, StartLoc, IdLoc, Id, TInfo) {}
2941
2942public:
2943 static TypedefDecl *Create(ASTContext &C, DeclContext *DC,
2944 SourceLocation StartLoc, SourceLocation IdLoc,
2945 IdentifierInfo *Id, TypeSourceInfo *TInfo);
2946 static TypedefDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2947
2948 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
2949
2950 // Implement isa/cast/dyncast/etc.
2951 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2952 static bool classofKind(Kind K) { return K == Typedef; }
2953};
2954
2955/// Represents the declaration of a typedef-name via a C++11
2956/// alias-declaration.
2957class TypeAliasDecl : public TypedefNameDecl {
2958 /// The template for which this is the pattern, if any.
2959 TypeAliasTemplateDecl *Template;
2960
2961 TypeAliasDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
2962 SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
2963 : TypedefNameDecl(TypeAlias, C, DC, StartLoc, IdLoc, Id, TInfo),
2964 Template(nullptr) {}
2965
2966public:
2967 static TypeAliasDecl *Create(ASTContext &C, DeclContext *DC,
2968 SourceLocation StartLoc, SourceLocation IdLoc,
2969 IdentifierInfo *Id, TypeSourceInfo *TInfo);
2970 static TypeAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2971
2972 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
2973
2974 TypeAliasTemplateDecl *getDescribedAliasTemplate() const { return Template; }
2975 void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT) { Template = TAT; }
2976
2977 // Implement isa/cast/dyncast/etc.
2978 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2979 static bool classofKind(Kind K) { return K == TypeAlias; }
2980};
2981
2982/// Represents the declaration of a struct/union/class/enum.
2983class TagDecl
2984 : public TypeDecl, public DeclContext, public Redeclarable<TagDecl> {
2985public:
2986 // This is really ugly.
2987 using TagKind = TagTypeKind;
2988
2989private:
2990 // FIXME: This can be packed into the bitfields in Decl.
2991 /// The TagKind enum.
2992 unsigned TagDeclKind : 3;
2993
2994 /// True if this is a definition ("struct foo {};"), false if it is a
2995 /// declaration ("struct foo;"). It is not considered a definition
2996 /// until the definition has been fully processed.
2997 unsigned IsCompleteDefinition : 1;
2998
2999protected:
3000 /// True if this is currently being defined.
3001 unsigned IsBeingDefined : 1;
3002
3003private:
3004 /// True if this tag declaration is "embedded" (i.e., defined or declared
3005 /// for the very first time) in the syntax of a declarator.
3006 unsigned IsEmbeddedInDeclarator : 1;
3007
3008 /// True if this tag is free standing, e.g. "struct foo;".
3009 unsigned IsFreeStanding : 1;
3010
3011protected:
3012 // These are used by (and only defined for) EnumDecl.
3013 unsigned NumPositiveBits : 8;
3014 unsigned NumNegativeBits : 8;
3015
3016 /// True if this tag declaration is a scoped enumeration. Only
3017 /// possible in C++11 mode.
3018 unsigned IsScoped : 1;
3019
3020 /// If this tag declaration is a scoped enum,
3021 /// then this is true if the scoped enum was declared using the class
3022 /// tag, false if it was declared with the struct tag. No meaning is
3023 /// associated if this tag declaration is not a scoped enum.
3024 unsigned IsScopedUsingClassTag : 1;
3025
3026 /// True if this is an enumeration with fixed underlying type. Only
3027 /// possible in C++11, Microsoft extensions, or Objective C mode.
3028 unsigned IsFixed : 1;
3029
3030 /// Indicates whether it is possible for declarations of this kind
3031 /// to have an out-of-date definition.
3032 ///
3033 /// This option is only enabled when modules are enabled.
3034 unsigned MayHaveOutOfDateDef : 1;
3035
3036 /// Has the full definition of this type been required by a use somewhere in
3037 /// the TU.
3038 unsigned IsCompleteDefinitionRequired : 1;
3039
3040private:
3041 SourceRange BraceRange;
3042
3043 // A struct representing syntactic qualifier info,
3044 // to be used for the (uncommon) case of out-of-line declarations.
3045 using ExtInfo = QualifierInfo;
3046
3047 /// \brief If the (out-of-line) tag declaration name
3048 /// is qualified, it points to the qualifier info (nns and range);
3049 /// otherwise, if the tag declaration is anonymous and it is part of
3050 /// a typedef or alias, it points to the TypedefNameDecl (used for mangling);
3051 /// otherwise, if the tag declaration is anonymous and it is used as a
3052 /// declaration specifier for variables, it points to the first VarDecl (used
3053 /// for mangling);
3054 /// otherwise, it is a null (TypedefNameDecl) pointer.
3055 llvm::PointerUnion<TypedefNameDecl *, ExtInfo *> TypedefNameDeclOrQualifier;
3056
3057 bool hasExtInfo() const { return TypedefNameDeclOrQualifier.is<ExtInfo *>(); }
3058 ExtInfo *getExtInfo() { return TypedefNameDeclOrQualifier.get<ExtInfo *>(); }
3059 const ExtInfo *getExtInfo() const {
3060 return TypedefNameDeclOrQualifier.get<ExtInfo *>();
3061 }
3062
3063protected:
3064 TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
3065 SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
3066 SourceLocation StartL)
3067 : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C),
3068 TagDeclKind(TK), IsCompleteDefinition(false), IsBeingDefined(false),
3069 IsEmbeddedInDeclarator(false), IsFreeStanding(false),
3070 IsCompleteDefinitionRequired(false),
3071 TypedefNameDeclOrQualifier((TypedefNameDecl *)nullptr) {
3072 assert((DK != Enum || TK == TTK_Enum) &&(static_cast <bool> ((DK != Enum || TK == TTK_Enum) &&
"EnumDecl not matched with TTK_Enum") ? void (0) : __assert_fail
("(DK != Enum || TK == TTK_Enum) && \"EnumDecl not matched with TTK_Enum\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 3073, __extension__ __PRETTY_FUNCTION__))
3073 "EnumDecl not matched with TTK_Enum")(static_cast <bool> ((DK != Enum || TK == TTK_Enum) &&
"EnumDecl not matched with TTK_Enum") ? void (0) : __assert_fail
("(DK != Enum || TK == TTK_Enum) && \"EnumDecl not matched with TTK_Enum\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 3073, __extension__ __PRETTY_FUNCTION__))
;
3074 setPreviousDecl(PrevDecl);
3075 }
3076
3077 using redeclarable_base = Redeclarable<TagDecl>;
3078
3079 TagDecl *getNextRedeclarationImpl() override {
3080 return getNextRedeclaration();
3081 }
3082
3083 TagDecl *getPreviousDeclImpl() override {
3084 return getPreviousDecl();
3085 }
3086
3087 TagDecl *getMostRecentDeclImpl() override {
3088 return getMostRecentDecl();
3089 }
3090
3091 /// @brief Completes the definition of this tag declaration.
3092 ///
3093 /// This is a helper function for derived classes.
3094 void completeDefinition();
3095
3096public:
3097 friend class ASTDeclReader;
3098 friend class ASTDeclWriter;
3099
3100 using redecl_range = redeclarable_base::redecl_range;
3101 using redecl_iterator = redeclarable_base::redecl_iterator;
3102
3103 using redeclarable_base::redecls_begin;
3104 using redeclarable_base::redecls_end;
3105 using redeclarable_base::redecls;
3106 using redeclarable_base::getPreviousDecl;
3107 using redeclarable_base::getMostRecentDecl;
3108 using redeclarable_base::isFirstDecl;
3109
3110 SourceRange getBraceRange() const { return BraceRange; }
3111 void setBraceRange(SourceRange R) { BraceRange = R; }
3112
3113 /// Return SourceLocation representing start of source
3114 /// range ignoring outer template declarations.
3115 SourceLocation getInnerLocStart() const { return getLocStart(); }
3116
3117 /// Return SourceLocation representing start of source
3118 /// range taking into account any outer template declarations.
3119 SourceLocation getOuterLocStart() const;
3120 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
3121
3122 TagDecl *getCanonicalDecl() override;
3123 const TagDecl *getCanonicalDecl() const {
3124 return const_cast<TagDecl*>(this)->getCanonicalDecl();
3125 }
3126
3127 /// Return true if this declaration is a completion definition of the type.
3128 /// Provided for consistency.
3129 bool isThisDeclarationADefinition() const {
3130 return isCompleteDefinition();
3131 }
3132
3133 /// Return true if this decl has its body fully specified.
3134 bool isCompleteDefinition() const {
3135 return IsCompleteDefinition;
3136 }
3137
3138 /// \brief Return true if this complete decl is
3139 /// required to be complete for some existing use.
3140 bool isCompleteDefinitionRequired() const {
3141 return IsCompleteDefinitionRequired;
3142 }
3143
3144 /// Return true if this decl is currently being defined.
3145 bool isBeingDefined() const {
3146 return IsBeingDefined;
3147 }
3148
3149 bool isEmbeddedInDeclarator() const {
3150 return IsEmbeddedInDeclarator;
3151 }
3152 void setEmbeddedInDeclarator(bool isInDeclarator) {
3153 IsEmbeddedInDeclarator = isInDeclarator;
3154 }
3155
3156 bool isFreeStanding() const { return IsFreeStanding; }
3157 void setFreeStanding(bool isFreeStanding = true) {
3158 IsFreeStanding = isFreeStanding;
3159 }
3160
3161 /// \brief Whether this declaration declares a type that is
3162 /// dependent, i.e., a type that somehow depends on template
3163 /// parameters.
3164 bool isDependentType() const { return isDependentContext(); }
3165
3166 /// Starts the definition of this tag declaration.
3167 ///
3168 /// This method should be invoked at the beginning of the definition
3169 /// of this tag declaration. It will set the tag type into a state
3170 /// where it is in the process of being defined.
3171 void startDefinition();
3172
3173 /// Returns the TagDecl that actually defines this
3174 /// struct/union/class/enum. When determining whether or not a
3175 /// struct/union/class/enum has a definition, one should use this
3176 /// method as opposed to 'isDefinition'. 'isDefinition' indicates
3177 /// whether or not a specific TagDecl is defining declaration, not
3178 /// whether or not the struct/union/class/enum type is defined.
3179 /// This method returns NULL if there is no TagDecl that defines
3180 /// the struct/union/class/enum.
3181 TagDecl *getDefinition() const;
3182
3183 void setCompleteDefinition(bool V) { IsCompleteDefinition = V; }
3184
3185 void setCompleteDefinitionRequired(bool V = true) {
3186 IsCompleteDefinitionRequired = V;
3187 }
3188
3189 StringRef getKindName() const {
3190 return TypeWithKeyword::getTagTypeKindName(getTagKind());
3191 }
3192
3193 TagKind getTagKind() const {
3194 return TagKind(TagDeclKind);
3195 }
3196
3197 void setTagKind(TagKind TK) { TagDeclKind = TK; }
3198
3199 bool isStruct() const { return getTagKind() == TTK_Struct; }
3200 bool isInterface() const { return getTagKind() == TTK_Interface; }
3201 bool isClass() const { return getTagKind() == TTK_Class; }
3202 bool isUnion() const { return getTagKind() == TTK_Union; }
3203 bool isEnum() const { return getTagKind() == TTK_Enum; }
3204
3205 /// Is this tag type named, either directly or via being defined in
3206 /// a typedef of this type?
3207 ///
3208 /// C++11 [basic.link]p8:
3209 /// A type is said to have linkage if and only if:
3210 /// - it is a class or enumeration type that is named (or has a
3211 /// name for linkage purposes) and the name has linkage; ...
3212 /// C++11 [dcl.typedef]p9:
3213 /// If the typedef declaration defines an unnamed class (or enum),
3214 /// the first typedef-name declared by the declaration to be that
3215 /// class type (or enum type) is used to denote the class type (or
3216 /// enum type) for linkage purposes only.
3217 ///
3218 /// C does not have an analogous rule, but the same concept is
3219 /// nonetheless useful in some places.
3220 bool hasNameForLinkage() const {
3221 return (getDeclName() || getTypedefNameForAnonDecl());
3222 }
3223
3224 TypedefNameDecl *getTypedefNameForAnonDecl() const {
3225 return hasExtInfo() ? nullptr
3226 : TypedefNameDeclOrQualifier.get<TypedefNameDecl *>();
3227 }
3228
3229 void setTypedefNameForAnonDecl(TypedefNameDecl *TDD);
3230
3231 /// \brief Retrieve the nested-name-specifier that qualifies the name of this
3232 /// declaration, if it was present in the source.
3233 NestedNameSpecifier *getQualifier() const {
3234 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
3235 : nullptr;
3236 }
3237
3238 /// \brief Retrieve the nested-name-specifier (with source-location
3239 /// information) that qualifies the name of this declaration, if it was
3240 /// present in the source.
3241 NestedNameSpecifierLoc getQualifierLoc() const {
3242 return hasExtInfo() ? getExtInfo()->QualifierLoc
3243 : NestedNameSpecifierLoc();
3244 }
3245
3246 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
3247
3248 unsigned getNumTemplateParameterLists() const {
3249 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
3250 }
3251
3252 TemplateParameterList *getTemplateParameterList(unsigned i) const {
3253 assert(i < getNumTemplateParameterLists())(static_cast <bool> (i < getNumTemplateParameterLists
()) ? void (0) : __assert_fail ("i < getNumTemplateParameterLists()"
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 3253, __extension__ __PRETTY_FUNCTION__))
;
3254 return getExtInfo()->TemplParamLists[i];
3255 }
3256
3257 void setTemplateParameterListsInfo(ASTContext &Context,
3258 ArrayRef<TemplateParameterList *> TPLists);
3259
3260 // Implement isa/cast/dyncast/etc.
3261 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3262 static bool classofKind(Kind K) { return K >= firstTag && K <= lastTag; }
3263
3264 static DeclContext *castToDeclContext(const TagDecl *D) {
3265 return static_cast<DeclContext *>(const_cast<TagDecl*>(D));
3266 }
3267
3268 static TagDecl *castFromDeclContext(const DeclContext *DC) {
3269 return static_cast<TagDecl *>(const_cast<DeclContext*>(DC));
3270 }
3271};
3272
3273/// Represents an enum. In C++11, enums can be forward-declared
3274/// with a fixed underlying type, and in C we allow them to be forward-declared
3275/// with no underlying type as an extension.
3276class EnumDecl : public TagDecl {
3277 /// This represent the integer type that the enum corresponds
3278 /// to for code generation purposes. Note that the enumerator constants may
3279 /// have a different type than this does.
3280 ///
3281 /// If the underlying integer type was explicitly stated in the source
3282 /// code, this is a TypeSourceInfo* for that type. Otherwise this type
3283 /// was automatically deduced somehow, and this is a Type*.
3284 ///
3285 /// Normally if IsFixed(), this would contain a TypeSourceInfo*, but in
3286 /// some cases it won't.
3287 ///
3288 /// The underlying type of an enumeration never has any qualifiers, so
3289 /// we can get away with just storing a raw Type*, and thus save an
3290 /// extra pointer when TypeSourceInfo is needed.
3291 llvm::PointerUnion<const Type *, TypeSourceInfo *> IntegerType;
3292
3293 /// The integer type that values of this type should
3294 /// promote to. In C, enumerators are generally of an integer type
3295 /// directly, but gcc-style large enumerators (and all enumerators
3296 /// in C++) are of the enum type instead.
3297 QualType PromotionType;
3298
3299 /// \brief If this enumeration is an instantiation of a member enumeration
3300 /// of a class template specialization, this is the member specialization
3301 /// information.
3302 MemberSpecializationInfo *SpecializationInfo = nullptr;
3303
3304 EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
3305 SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
3306 bool Scoped, bool ScopedUsingClassTag, bool Fixed)
3307 : TagDecl(Enum, TTK_Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
3308 assert(Scoped || !ScopedUsingClassTag)(static_cast <bool> (Scoped || !ScopedUsingClassTag) ? void
(0) : __assert_fail ("Scoped || !ScopedUsingClassTag", "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 3308, __extension__ __PRETTY_FUNCTION__))
;
3309 IntegerType = (const Type *)nullptr;
3310 NumNegativeBits = 0;
3311 NumPositiveBits = 0;
3312 IsScoped = Scoped;
3313 IsScopedUsingClassTag = ScopedUsingClassTag;
3314 IsFixed = Fixed;
3315 }
3316
3317 void anchor() override;
3318
3319 void setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3320 TemplateSpecializationKind TSK);
3321public:
3322 friend class ASTDeclReader;
3323
3324 EnumDecl *getCanonicalDecl() override {
3325 return cast<EnumDecl>(TagDecl::getCanonicalDecl());
3326 }
3327 const EnumDecl *getCanonicalDecl() const {
3328 return const_cast<EnumDecl*>(this)->getCanonicalDecl();
3329 }
3330
3331 EnumDecl *getPreviousDecl() {
3332 return cast_or_null<EnumDecl>(
3333 static_cast<TagDecl *>(this)->getPreviousDecl());
3334 }
3335 const EnumDecl *getPreviousDecl() const {
3336 return const_cast<EnumDecl*>(this)->getPreviousDecl();
3337 }
3338
3339 EnumDecl *getMostRecentDecl() {
3340 return cast<EnumDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
3341 }
3342 const EnumDecl *getMostRecentDecl() const {
3343 return const_cast<EnumDecl*>(this)->getMostRecentDecl();
3344 }
3345
3346 EnumDecl *getDefinition() const {
3347 return cast_or_null<EnumDecl>(TagDecl::getDefinition());
3348 }
3349
3350 static EnumDecl *Create(ASTContext &C, DeclContext *DC,
3351 SourceLocation StartLoc, SourceLocation IdLoc,
3352 IdentifierInfo *Id, EnumDecl *PrevDecl,
3353 bool IsScoped, bool IsScopedUsingClassTag,
3354 bool IsFixed);
3355 static EnumDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3356
3357 /// When created, the EnumDecl corresponds to a
3358 /// forward-declared enum. This method is used to mark the
3359 /// declaration as being defined; its enumerators have already been
3360 /// added (via DeclContext::addDecl). NewType is the new underlying
3361 /// type of the enumeration type.
3362 void completeDefinition(QualType NewType,
3363 QualType PromotionType,
3364 unsigned NumPositiveBits,
3365 unsigned NumNegativeBits);
3366
3367 // Iterates through the enumerators of this enumeration.
3368 using enumerator_iterator = specific_decl_iterator<EnumConstantDecl>;
3369 using enumerator_range =
3370 llvm::iterator_range<specific_decl_iterator<EnumConstantDecl>>;
3371
3372 enumerator_range enumerators() const {
3373 return enumerator_range(enumerator_begin(), enumerator_end());
3374 }
3375
3376 enumerator_iterator enumerator_begin() const {
3377 const EnumDecl *E = getDefinition();
3378 if (!E)
3379 E = this;
3380 return enumerator_iterator(E->decls_begin());
3381 }
3382
3383 enumerator_iterator enumerator_end() const {
3384 const EnumDecl *E = getDefinition();
3385 if (!E)
3386 E = this;
3387 return enumerator_iterator(E->decls_end());
3388 }
3389
3390 /// Return the integer type that enumerators should promote to.
3391 QualType getPromotionType() const { return PromotionType; }
3392
3393 /// Set the promotion type.
3394 void setPromotionType(QualType T) { PromotionType = T; }
3395
3396 /// Return the integer type this enum decl corresponds to.
3397 /// This returns a null QualType for an enum forward definition with no fixed
3398 /// underlying type.
3399 QualType getIntegerType() const {
3400 if (!IntegerType)
3401 return QualType();
3402 if (const Type *T = IntegerType.dyn_cast<const Type*>())
3403 return QualType(T, 0);
3404 return IntegerType.get<TypeSourceInfo*>()->getType().getUnqualifiedType();
3405 }
3406
3407 /// \brief Set the underlying integer type.
3408 void setIntegerType(QualType T) { IntegerType = T.getTypePtrOrNull(); }
3409
3410 /// \brief Set the underlying integer type source info.
3411 void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo) { IntegerType = TInfo; }
3412
3413 /// \brief Return the type source info for the underlying integer type,
3414 /// if no type source info exists, return 0.
3415 TypeSourceInfo *getIntegerTypeSourceInfo() const {
3416 return IntegerType.dyn_cast<TypeSourceInfo*>();
3417 }
3418
3419 /// \brief Retrieve the source range that covers the underlying type if
3420 /// specified.
3421 SourceRange getIntegerTypeRange() const LLVM_READONLY__attribute__((__pure__));
3422
3423 /// \brief Returns the width in bits required to store all the
3424 /// non-negative enumerators of this enum.
3425 unsigned getNumPositiveBits() const {
3426 return NumPositiveBits;
3427 }
3428 void setNumPositiveBits(unsigned Num) {
3429 NumPositiveBits = Num;
3430 assert(NumPositiveBits == Num && "can't store this bitcount")(static_cast <bool> (NumPositiveBits == Num && "can't store this bitcount"
) ? void (0) : __assert_fail ("NumPositiveBits == Num && \"can't store this bitcount\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 3430, __extension__ __PRETTY_FUNCTION__))
;
3431 }
3432
3433 /// \brief Returns the width in bits required to store all the
3434 /// negative enumerators of this enum. These widths include
3435 /// the rightmost leading 1; that is:
3436 ///
3437 /// MOST NEGATIVE ENUMERATOR PATTERN NUM NEGATIVE BITS
3438 /// ------------------------ ------- -----------------
3439 /// -1 1111111 1
3440 /// -10 1110110 5
3441 /// -101 1001011 8
3442 unsigned getNumNegativeBits() const {
3443 return NumNegativeBits;
3444 }
3445 void setNumNegativeBits(unsigned Num) {
3446 NumNegativeBits = Num;
3447 }
3448
3449 /// \brief Returns true if this is a C++11 scoped enumeration.
3450 bool isScoped() const {
3451 return IsScoped;
3452 }
3453
3454 /// \brief Returns true if this is a C++11 scoped enumeration.
3455 bool isScopedUsingClassTag() const {
3456 return IsScopedUsingClassTag;
3457 }
3458
3459 /// \brief Returns true if this is an Objective-C, C++11, or
3460 /// Microsoft-style enumeration with a fixed underlying type.
3461 bool isFixed() const {
3462 return IsFixed;
3463 }
3464
3465 /// \brief Returns true if this can be considered a complete type.
3466 bool isComplete() const {
3467 // IntegerType is set for fixed type enums and non-fixed but implicitly
3468 // int-sized Microsoft enums.
3469 return isCompleteDefinition() || IntegerType;
3470 }
3471
3472 /// Returns true if this enum is either annotated with
3473 /// enum_extensibility(closed) or isn't annotated with enum_extensibility.
3474 bool isClosed() const;
3475
3476 /// Returns true if this enum is annotated with flag_enum and isn't annotated
3477 /// with enum_extensibility(open).
3478 bool isClosedFlag() const;
3479
3480 /// Returns true if this enum is annotated with neither flag_enum nor
3481 /// enum_extensibility(open).
3482 bool isClosedNonFlag() const;
3483
3484 /// \brief Retrieve the enum definition from which this enumeration could
3485 /// be instantiated, if it is an instantiation (rather than a non-template).
3486 EnumDecl *getTemplateInstantiationPattern() const;
3487
3488 /// \brief Returns the enumeration (declared within the template)
3489 /// from which this enumeration type was instantiated, or NULL if
3490 /// this enumeration was not instantiated from any template.
3491 EnumDecl *getInstantiatedFromMemberEnum() const;
3492
3493 /// \brief If this enumeration is a member of a specialization of a
3494 /// templated class, determine what kind of template specialization
3495 /// or instantiation this is.
3496 TemplateSpecializationKind getTemplateSpecializationKind() const;
3497
3498 /// \brief For an enumeration member that was instantiated from a member
3499 /// enumeration of a templated class, set the template specialiation kind.
3500 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3501 SourceLocation PointOfInstantiation = SourceLocation());
3502
3503 /// \brief If this enumeration is an instantiation of a member enumeration of
3504 /// a class template specialization, retrieves the member specialization
3505 /// information.
3506 MemberSpecializationInfo *getMemberSpecializationInfo() const {
3507 return SpecializationInfo;
3508 }
3509
3510 /// \brief Specify that this enumeration is an instantiation of the
3511 /// member enumeration ED.
3512 void setInstantiationOfMemberEnum(EnumDecl *ED,
3513 TemplateSpecializationKind TSK) {
3514 setInstantiationOfMemberEnum(getASTContext(), ED, TSK);
3515 }
3516
3517 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3518 static bool classofKind(Kind K) { return K == Enum; }
3519};
3520
3521/// Represents a struct/union/class. For example:
3522/// struct X; // Forward declaration, no "body".
3523/// union Y { int A, B; }; // Has body with members A and B (FieldDecls).
3524/// This decl will be marked invalid if *any* members are invalid.
3525class RecordDecl : public TagDecl {
3526 friend class DeclContext;
3527
3528 // FIXME: This can be packed into the bitfields in Decl.
3529 /// This is true if this struct ends with a flexible
3530 /// array member (e.g. int X[]) or if this union contains a struct that does.
3531 /// If so, this cannot be contained in arrays or other structs as a member.
3532 bool HasFlexibleArrayMember : 1;
3533
3534 /// Whether this is the type of an anonymous struct or union.
3535 bool AnonymousStructOrUnion : 1;
3536
3537 /// This is true if this struct has at least one member
3538 /// containing an Objective-C object pointer type.
3539 bool HasObjectMember : 1;
3540
3541 /// This is true if struct has at least one member of
3542 /// 'volatile' type.
3543 bool HasVolatileMember : 1;
3544
3545 /// Whether the field declarations of this record have been loaded
3546 /// from external storage. To avoid unnecessary deserialization of
3547 /// methods/nested types we allow deserialization of just the fields
3548 /// when needed.
3549 mutable bool LoadedFieldsFromExternalStorage : 1;
3550
3551 /// Basic properties of non-trivial C structs.
3552 bool NonTrivialToPrimitiveDefaultInitialize : 1;
3553 bool NonTrivialToPrimitiveCopy : 1;
3554 bool NonTrivialToPrimitiveDestroy : 1;
3555
3556protected:
3557 RecordDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
3558 SourceLocation StartLoc, SourceLocation IdLoc,
3559 IdentifierInfo *Id, RecordDecl *PrevDecl);
3560
3561public:
3562 static RecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
3563 SourceLocation StartLoc, SourceLocation IdLoc,
3564 IdentifierInfo *Id, RecordDecl* PrevDecl = nullptr);
3565 static RecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
3566
3567 RecordDecl *getPreviousDecl() {
3568 return cast_or_null<RecordDecl>(
3569 static_cast<TagDecl *>(this)->getPreviousDecl());
3570 }
3571 const RecordDecl *getPreviousDecl() const {
3572 return const_cast<RecordDecl*>(this)->getPreviousDecl();
3573 }
3574
3575 RecordDecl *getMostRecentDecl() {
3576 return cast<RecordDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
3577 }
3578 const RecordDecl *getMostRecentDecl() const {
3579 return const_cast<RecordDecl*>(this)->getMostRecentDecl();
3580 }
3581
3582 bool hasFlexibleArrayMember() const { return HasFlexibleArrayMember; }
3583 void setHasFlexibleArrayMember(bool V) { HasFlexibleArrayMember = V; }
3584
3585 /// Whether this is an anonymous struct or union. To be an anonymous
3586 /// struct or union, it must have been declared without a name and
3587 /// there must be no objects of this type declared, e.g.,
3588 /// @code
3589 /// union { int i; float f; };
3590 /// @endcode
3591 /// is an anonymous union but neither of the following are:
3592 /// @code
3593 /// union X { int i; float f; };
3594 /// union { int i; float f; } obj;
3595 /// @endcode
3596 bool isAnonymousStructOrUnion() const { return AnonymousStructOrUnion; }
3597 void setAnonymousStructOrUnion(bool Anon) {
3598 AnonymousStructOrUnion = Anon;
3599 }
3600
3601 bool hasObjectMember() const { return HasObjectMember; }
3602 void setHasObjectMember (bool val) { HasObjectMember = val; }
3603
3604 bool hasVolatileMember() const { return HasVolatileMember; }
3605 void setHasVolatileMember (bool val) { HasVolatileMember = val; }
3606
3607 bool hasLoadedFieldsFromExternalStorage() const {
3608 return LoadedFieldsFromExternalStorage;
3609 }
3610 void setHasLoadedFieldsFromExternalStorage(bool val) {
3611 LoadedFieldsFromExternalStorage = val;
3612 }
3613
3614 /// Functions to query basic properties of non-trivial C structs.
3615 bool isNonTrivialToPrimitiveDefaultInitialize() const {
3616 return NonTrivialToPrimitiveDefaultInitialize;
3617 }
3618
3619 void setNonTrivialToPrimitiveDefaultInitialize() {
3620 NonTrivialToPrimitiveDefaultInitialize = true;
3621 }
3622
3623 bool isNonTrivialToPrimitiveCopy() const {
3624 return NonTrivialToPrimitiveCopy;
3625 }
3626
3627 void setNonTrivialToPrimitiveCopy() {
3628 NonTrivialToPrimitiveCopy = true;
3629 }
3630
3631 bool isNonTrivialToPrimitiveDestroy() const {
3632 return NonTrivialToPrimitiveDestroy;
3633 }
3634
3635 void setNonTrivialToPrimitiveDestroy() {
3636 NonTrivialToPrimitiveDestroy = true;
3637 }
3638
3639 /// \brief Determines whether this declaration represents the
3640 /// injected class name.
3641 ///
3642 /// The injected class name in C++ is the name of the class that
3643 /// appears inside the class itself. For example:
3644 ///
3645 /// \code
3646 /// struct C {
3647 /// // C is implicitly declared here as a synonym for the class name.
3648 /// };
3649 ///
3650 /// C::C c; // same as "C c;"
3651 /// \endcode
3652 bool isInjectedClassName() const;
3653
3654 /// \brief Determine whether this record is a class describing a lambda
3655 /// function object.
3656 bool isLambda() const;
3657
3658 /// \brief Determine whether this record is a record for captured variables in
3659 /// CapturedStmt construct.
3660 bool isCapturedRecord() const;
3661
3662 /// \brief Mark the record as a record for captured variables in CapturedStmt
3663 /// construct.
3664 void setCapturedRecord();
3665
3666 /// Returns the RecordDecl that actually defines
3667 /// this struct/union/class. When determining whether or not a
3668 /// struct/union/class is completely defined, one should use this
3669 /// method as opposed to 'isCompleteDefinition'.
3670 /// 'isCompleteDefinition' indicates whether or not a specific
3671 /// RecordDecl is a completed definition, not whether or not the
3672 /// record type is defined. This method returns NULL if there is
3673 /// no RecordDecl that defines the struct/union/tag.
3674 RecordDecl *getDefinition() const {
3675 return cast_or_null<RecordDecl>(TagDecl::getDefinition());
3676 }
3677
3678 // Iterator access to field members. The field iterator only visits
3679 // the non-static data members of this class, ignoring any static
3680 // data members, functions, constructors, destructors, etc.
3681 using field_iterator = specific_decl_iterator<FieldDecl>;
3682 using field_range = llvm::iterator_range<specific_decl_iterator<FieldDecl>>;
3683
3684 field_range fields() const { return field_range(field_begin(), field_end()); }
3685 field_iterator field_begin() const;
3686
3687 field_iterator field_end() const {
3688 return field_iterator(decl_iterator());
3689 }
3690
3691 // Whether there are any fields (non-static data members) in this record.
3692 bool field_empty() const {
3693 return field_begin() == field_end();
3694 }
3695
3696 /// Note that the definition of this type is now complete.
3697 virtual void completeDefinition();
3698
3699 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3700 static bool classofKind(Kind K) {
3701 return K >= firstRecord && K <= lastRecord;
3702 }
3703
3704 /// \brief Get whether or not this is an ms_struct which can
3705 /// be turned on with an attribute, pragma, or -mms-bitfields
3706 /// commandline option.
3707 bool isMsStruct(const ASTContext &C) const;
3708
3709 /// \brief Whether we are allowed to insert extra padding between fields.
3710 /// These padding are added to help AddressSanitizer detect
3711 /// intra-object-overflow bugs.
3712 bool mayInsertExtraPadding(bool EmitRemark = false) const;
3713
3714 /// Finds the first data member which has a name.
3715 /// nullptr is returned if no named data member exists.
3716 const FieldDecl *findFirstNamedDataMember() const;
3717
3718private:
3719 /// \brief Deserialize just the fields.
3720 void LoadFieldsFromExternalStorage() const;
3721};
3722
3723class FileScopeAsmDecl : public Decl {
3724 StringLiteral *AsmString;
3725 SourceLocation RParenLoc;
3726
3727 FileScopeAsmDecl(DeclContext *DC, StringLiteral *asmstring,
3728 SourceLocation StartL, SourceLocation EndL)
3729 : Decl(FileScopeAsm, DC, StartL), AsmString(asmstring), RParenLoc(EndL) {}
3730
3731 virtual void anchor();
3732
3733public:
3734 static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC,
3735 StringLiteral *Str, SourceLocation AsmLoc,
3736 SourceLocation RParenLoc);
3737
3738 static FileScopeAsmDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3739
3740 SourceLocation getAsmLoc() const { return getLocation(); }
3741 SourceLocation getRParenLoc() const { return RParenLoc; }
3742 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3743 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
3744 return SourceRange(getAsmLoc(), getRParenLoc());
3745 }
3746
3747 const StringLiteral *getAsmString() const { return AsmString; }
3748 StringLiteral *getAsmString() { return AsmString; }
3749 void setAsmString(StringLiteral *Asm) { AsmString = Asm; }
3750
3751 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3752 static bool classofKind(Kind K) { return K == FileScopeAsm; }
3753};
3754
3755/// Pepresents a block literal declaration, which is like an
3756/// unnamed FunctionDecl. For example:
3757/// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
3758class BlockDecl : public Decl, public DeclContext {
3759public:
3760 /// A class which contains all the information about a particular
3761 /// captured value.
3762 class Capture {
3763 enum {
3764 flag_isByRef = 0x1,
3765 flag_isNested = 0x2
3766 };
3767
3768 /// The variable being captured.
3769 llvm::PointerIntPair<VarDecl*, 2> VariableAndFlags;
3770
3771 /// The copy expression, expressed in terms of a DeclRef (or
3772 /// BlockDeclRef) to the captured variable. Only required if the
3773 /// variable has a C++ class type.
3774 Expr *CopyExpr;
3775
3776 public:
3777 Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy)
3778 : VariableAndFlags(variable,
3779 (byRef ? flag_isByRef : 0) | (nested ? flag_isNested : 0)),
3780 CopyExpr(copy) {}
3781
3782 /// The variable being captured.
3783 VarDecl *getVariable() const { return VariableAndFlags.getPointer(); }
3784
3785 /// Whether this is a "by ref" capture, i.e. a capture of a __block
3786 /// variable.
3787 bool isByRef() const { return VariableAndFlags.getInt() & flag_isByRef; }
3788
3789 /// Whether this is a nested capture, i.e. the variable captured
3790 /// is not from outside the immediately enclosing function/block.
3791 bool isNested() const { return VariableAndFlags.getInt() & flag_isNested; }
3792
3793 bool hasCopyExpr() const { return CopyExpr != nullptr; }
3794 Expr *getCopyExpr() const { return CopyExpr; }
3795 void setCopyExpr(Expr *e) { CopyExpr = e; }
3796 };
3797
3798private:
3799 // FIXME: This can be packed into the bitfields in Decl.
3800 bool IsVariadic : 1;
3801 bool CapturesCXXThis : 1;
3802 bool BlockMissingReturnType : 1;
3803 bool IsConversionFromLambda : 1;
3804
3805 /// A new[]'d array of pointers to ParmVarDecls for the formal
3806 /// parameters of this function. This is null if a prototype or if there are
3807 /// no formals.
3808 ParmVarDecl **ParamInfo = nullptr;
3809 unsigned NumParams = 0;
3810
3811 Stmt *Body = nullptr;
3812 TypeSourceInfo *SignatureAsWritten = nullptr;
3813
3814 const Capture *Captures = nullptr;
3815 unsigned NumCaptures = 0;
3816
3817 unsigned ManglingNumber = 0;
3818 Decl *ManglingContextDecl = nullptr;
3819
3820protected:
3821 BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
3822 : Decl(Block, DC, CaretLoc), DeclContext(Block), IsVariadic(false),
3823 CapturesCXXThis(false), BlockMissingReturnType(true),
3824 IsConversionFromLambda(false) {}
3825
3826public:
3827 static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L);
3828 static BlockDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3829
3830 SourceLocation getCaretLocation() const { return getLocation(); }
3831
3832 bool isVariadic() const { return IsVariadic; }
3833 void setIsVariadic(bool value) { IsVariadic = value; }
3834
3835 CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; }
3836 Stmt *getBody() const override { return (Stmt*) Body; }
3837 void setBody(CompoundStmt *B) { Body = (Stmt*) B; }
3838
3839 void setSignatureAsWritten(TypeSourceInfo *Sig) { SignatureAsWritten = Sig; }
3840 TypeSourceInfo *getSignatureAsWritten() const { return SignatureAsWritten; }
3841
3842 // ArrayRef access to formal parameters.
3843 ArrayRef<ParmVarDecl *> parameters() const {
3844 return {ParamInfo, getNumParams()};
3845 }
3846 MutableArrayRef<ParmVarDecl *> parameters() {
3847 return {ParamInfo, getNumParams()};
3848 }
3849
3850 // Iterator access to formal parameters.
3851 using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator;
3852 using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator;
3853
3854 bool param_empty() const { return parameters().empty(); }
3855 param_iterator param_begin() { return parameters().begin(); }
3856 param_iterator param_end() { return parameters().end(); }
3857 param_const_iterator param_begin() const { return parameters().begin(); }
3858 param_const_iterator param_end() const { return parameters().end(); }
3859 size_t param_size() const { return parameters().size(); }
3860
3861 unsigned getNumParams() const { return NumParams; }
3862
3863 const ParmVarDecl *getParamDecl(unsigned i) const {
3864 assert(i < getNumParams() && "Illegal param #")(static_cast <bool> (i < getNumParams() && "Illegal param #"
) ? void (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 3864, __extension__ __PRETTY_FUNCTION__))
;
3865 return ParamInfo[i];
3866 }
3867 ParmVarDecl *getParamDecl(unsigned i) {
3868 assert(i < getNumParams() && "Illegal param #")(static_cast <bool> (i < getNumParams() && "Illegal param #"
) ? void (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 3868, __extension__ __PRETTY_FUNCTION__))
;
3869 return ParamInfo[i];
3870 }
3871
3872 void setParams(ArrayRef<ParmVarDecl *> NewParamInfo);
3873
3874 /// True if this block (or its nested blocks) captures
3875 /// anything of local storage from its enclosing scopes.
3876 bool hasCaptures() const { return NumCaptures != 0 || CapturesCXXThis; }
3877
3878 /// Returns the number of captured variables.
3879 /// Does not include an entry for 'this'.
3880 unsigned getNumCaptures() const { return NumCaptures; }
3881
3882 using capture_const_iterator = ArrayRef<Capture>::const_iterator;
3883
3884 ArrayRef<Capture> captures() const { return {Captures, NumCaptures}; }
3885
3886 capture_const_iterator capture_begin() const { return captures().begin(); }
3887 capture_const_iterator capture_end() const { return captures().end(); }
3888
3889 bool capturesCXXThis() const { return CapturesCXXThis; }
3890 bool blockMissingReturnType() const { return BlockMissingReturnType; }
3891 void setBlockMissingReturnType(bool val) { BlockMissingReturnType = val; }
3892
3893 bool isConversionFromLambda() const { return IsConversionFromLambda; }
3894 void setIsConversionFromLambda(bool val) { IsConversionFromLambda = val; }
3895
3896 bool capturesVariable(const VarDecl *var) const;
3897
3898 void setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
3899 bool CapturesCXXThis);
3900
3901 unsigned getBlockManglingNumber() const {
3902 return ManglingNumber;
3903 }
3904
3905 Decl *getBlockManglingContextDecl() const {
3906 return ManglingContextDecl;
3907 }
3908
3909 void setBlockMangling(unsigned Number, Decl *Ctx) {
3910 ManglingNumber = Number;
3911 ManglingContextDecl = Ctx;
3912 }
3913
3914 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
3915
3916 // Implement isa/cast/dyncast/etc.
3917 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3918 static bool classofKind(Kind K) { return K == Block; }
3919 static DeclContext *castToDeclContext(const BlockDecl *D) {
3920 return static_cast<DeclContext *>(const_cast<BlockDecl*>(D));
3921 }
3922 static BlockDecl *castFromDeclContext(const DeclContext *DC) {
3923 return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC));
3924 }
3925};
3926
3927/// Represents the body of a CapturedStmt, and serves as its DeclContext.
3928class CapturedDecl final
3929 : public Decl,
3930 public DeclContext,
3931 private llvm::TrailingObjects<CapturedDecl, ImplicitParamDecl *> {
3932protected:
3933 size_t numTrailingObjects(OverloadToken<ImplicitParamDecl>) {
3934 return NumParams;
3935 }
3936
3937private:
3938 /// \brief The number of parameters to the outlined function.
3939 unsigned NumParams;
3940
3941 /// \brief The position of context parameter in list of parameters.
3942 unsigned ContextParam;
3943
3944 /// \brief The body of the outlined function.
3945 llvm::PointerIntPair<Stmt *, 1, bool> BodyAndNothrow;
3946
3947 explicit CapturedDecl(DeclContext *DC, unsigned NumParams);
3948
3949 ImplicitParamDecl *const *getParams() const {
3950 return getTrailingObjects<ImplicitParamDecl *>();
3951 }
3952
3953 ImplicitParamDecl **getParams() {
3954 return getTrailingObjects<ImplicitParamDecl *>();
3955 }
3956
3957public:
3958 friend class ASTDeclReader;
3959 friend class ASTDeclWriter;
3960 friend TrailingObjects;
3961
3962 static CapturedDecl *Create(ASTContext &C, DeclContext *DC,
3963 unsigned NumParams);
3964 static CapturedDecl *CreateDeserialized(ASTContext &C, unsigned ID,
3965 unsigned NumParams);
3966
3967 Stmt *getBody() const override;
3968 void setBody(Stmt *B);
3969
3970 bool isNothrow() const;
3971 void setNothrow(bool Nothrow = true);
3972
3973 unsigned getNumParams() const { return NumParams; }
3974
3975 ImplicitParamDecl *getParam(unsigned i) const {
3976 assert(i < NumParams)(static_cast <bool> (i < NumParams) ? void (0) : __assert_fail
("i < NumParams", "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 3976, __extension__ __PRETTY_FUNCTION__))
;
3977 return getParams()[i];
3978 }
3979 void setParam(unsigned i, ImplicitParamDecl *P) {
3980 assert(i < NumParams)(static_cast <bool> (i < NumParams) ? void (0) : __assert_fail
("i < NumParams", "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 3980, __extension__ __PRETTY_FUNCTION__))
;
3981 getParams()[i] = P;
3982 }
3983
3984 // ArrayRef interface to parameters.
3985 ArrayRef<ImplicitParamDecl *> parameters() const {
3986 return {getParams(), getNumParams()};
3987 }
3988 MutableArrayRef<ImplicitParamDecl *> parameters() {
3989 return {getParams(), getNumParams()};
3990 }
3991
3992 /// \brief Retrieve the parameter containing captured variables.
3993 ImplicitParamDecl *getContextParam() const {
3994 assert(ContextParam < NumParams)(static_cast <bool> (ContextParam < NumParams) ? void
(0) : __assert_fail ("ContextParam < NumParams", "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 3994, __extension__ __PRETTY_FUNCTION__))
;
3995 return getParam(ContextParam);
3996 }
3997 void setContextParam(unsigned i, ImplicitParamDecl *P) {
3998 assert(i < NumParams)(static_cast <bool> (i < NumParams) ? void (0) : __assert_fail
("i < NumParams", "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 3998, __extension__ __PRETTY_FUNCTION__))
;
3999 ContextParam = i;
4000 setParam(i, P);
4001 }
4002 unsigned getContextParamPosition() const { return ContextParam; }
4003
4004 using param_iterator = ImplicitParamDecl *const *;
4005 using param_range = llvm::iterator_range<param_iterator>;
4006
4007 /// \brief Retrieve an iterator pointing to the first parameter decl.
4008 param_iterator param_begin() const { return getParams(); }
4009 /// \brief Retrieve an iterator one past the last parameter decl.
4010 param_iterator param_end() const { return getParams() + NumParams; }
4011
4012 // Implement isa/cast/dyncast/etc.
4013 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4014 static bool classofKind(Kind K) { return K == Captured; }
4015 static DeclContext *castToDeclContext(const CapturedDecl *D) {
4016 return static_cast<DeclContext *>(const_cast<CapturedDecl *>(D));
4017 }
4018 static CapturedDecl *castFromDeclContext(const DeclContext *DC) {
4019 return static_cast<CapturedDecl *>(const_cast<DeclContext *>(DC));
4020 }
4021};
4022
4023/// \brief Describes a module import declaration, which makes the contents
4024/// of the named module visible in the current translation unit.
4025///
4026/// An import declaration imports the named module (or submodule). For example:
4027/// \code
4028/// @import std.vector;
4029/// \endcode
4030///
4031/// Import declarations can also be implicitly generated from
4032/// \#include/\#import directives.
4033class ImportDecl final : public Decl,
4034 llvm::TrailingObjects<ImportDecl, SourceLocation> {
4035 friend class ASTContext;
4036 friend class ASTDeclReader;
4037 friend class ASTReader;
4038 friend TrailingObjects;
4039
4040 /// \brief The imported module, along with a bit that indicates whether
4041 /// we have source-location information for each identifier in the module
4042 /// name.
4043 ///
4044 /// When the bit is false, we only have a single source location for the
4045 /// end of the import declaration.
4046 llvm::PointerIntPair<Module *, 1, bool> ImportedAndComplete;
4047
4048 /// \brief The next import in the list of imports local to the translation
4049 /// unit being parsed (not loaded from an AST file).
4050 ImportDecl *NextLocalImport = nullptr;
4051
4052 ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
4053 ArrayRef<SourceLocation> IdentifierLocs);
4054
4055 ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
4056 SourceLocation EndLoc);
4057
4058 ImportDecl(EmptyShell Empty) : Decl(Import, Empty) {}
4059
4060public:
4061 /// \brief Create a new module import declaration.
4062 static ImportDecl *Create(ASTContext &C, DeclContext *DC,
4063 SourceLocation StartLoc, Module *Imported,
4064 ArrayRef<SourceLocation> IdentifierLocs);
4065
4066 /// \brief Create a new module import declaration for an implicitly-generated
4067 /// import.
4068 static ImportDecl *CreateImplicit(ASTContext &C, DeclContext *DC,
4069 SourceLocation StartLoc, Module *Imported,
4070 SourceLocation EndLoc);
4071
4072 /// \brief Create a new, deserialized module import declaration.
4073 static ImportDecl *CreateDeserialized(ASTContext &C, unsigned ID,
4074 unsigned NumLocations);
4075
4076 /// \brief Retrieve the module that was imported by the import declaration.
4077 Module *getImportedModule() const { return ImportedAndComplete.getPointer(); }
4078
4079 /// \brief Retrieves the locations of each of the identifiers that make up
4080 /// the complete module name in the import declaration.
4081 ///
4082 /// This will return an empty array if the locations of the individual
4083 /// identifiers aren't available.
4084 ArrayRef<SourceLocation> getIdentifierLocs() const;
4085
4086 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
4087
4088 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4089 static bool classofKind(Kind K) { return K == Import; }
4090};
4091
4092/// \brief Represents a C++ Modules TS module export declaration.
4093///
4094/// For example:
4095/// \code
4096/// export void foo();
4097/// \endcode
4098class ExportDecl final : public Decl, public DeclContext {
4099 virtual void anchor();
4100
4101private:
4102 friend class ASTDeclReader;
4103
4104 /// \brief The source location for the right brace (if valid).
4105 SourceLocation RBraceLoc;
4106
4107 ExportDecl(DeclContext *DC, SourceLocation ExportLoc)
4108 : Decl(Export, DC, ExportLoc), DeclContext(Export),
4109 RBraceLoc(SourceLocation()) {}
4110
4111public:
4112 static ExportDecl *Create(ASTContext &C, DeclContext *DC,
4113 SourceLocation ExportLoc);
4114 static ExportDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4115
4116 SourceLocation getExportLoc() const { return getLocation(); }
4117 SourceLocation getRBraceLoc() const { return RBraceLoc; }
4118 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
4119
4120 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) {
4121 if (RBraceLoc.isValid())
4122 return RBraceLoc;
4123 // No braces: get the end location of the (only) declaration in context
4124 // (if present).
4125 return decls_empty() ? getLocation() : decls_begin()->getLocEnd();
4126 }
4127
4128 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
4129 return SourceRange(getLocation(), getLocEnd());
4130 }
4131
4132 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4133 static bool classofKind(Kind K) { return K == Export; }
4134 static DeclContext *castToDeclContext(const ExportDecl *D) {
4135 return static_cast<DeclContext *>(const_cast<ExportDecl*>(D));
4136 }
4137 static ExportDecl *castFromDeclContext(const DeclContext *DC) {
4138 return static_cast<ExportDecl *>(const_cast<DeclContext*>(DC));
4139 }
4140};
4141
4142/// Represents an empty-declaration.
4143class EmptyDecl : public Decl {
4144 EmptyDecl(DeclContext *DC, SourceLocation L) : Decl(Empty, DC, L) {}
4145
4146 virtual void anchor();
4147
4148public:
4149 static EmptyDecl *Create(ASTContext &C, DeclContext *DC,
4150 SourceLocation L);
4151 static EmptyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4152
4153 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4154 static bool classofKind(Kind K) { return K == Empty; }
4155};
4156
4157/// Insertion operator for diagnostics. This allows sending NamedDecl's
4158/// into a diagnostic with <<.
4159inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
4160 const NamedDecl* ND) {
4161 DB.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
4162 DiagnosticsEngine::ak_nameddecl);
4163 return DB;
4164}
4165inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
4166 const NamedDecl* ND) {
4167 PD.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
16
Calling 'PartialDiagnostic::AddTaggedVal'
25
Returned allocated memory
4168 DiagnosticsEngine::ak_nameddecl);
4169 return PD;
4170}
4171
4172template<typename decl_type>
4173void Redeclarable<decl_type>::setPreviousDecl(decl_type *PrevDecl) {
4174 // Note: This routine is implemented here because we need both NamedDecl
4175 // and Redeclarable to be defined.
4176 assert(RedeclLink.NextIsLatest() &&(static_cast <bool> (RedeclLink.NextIsLatest() &&
"setPreviousDecl on a decl already in a redeclaration chain"
) ? void (0) : __assert_fail ("RedeclLink.NextIsLatest() && \"setPreviousDecl on a decl already in a redeclaration chain\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 4177, __extension__ __PRETTY_FUNCTION__))
4177 "setPreviousDecl on a decl already in a redeclaration chain")(static_cast <bool> (RedeclLink.NextIsLatest() &&
"setPreviousDecl on a decl already in a redeclaration chain"
) ? void (0) : __assert_fail ("RedeclLink.NextIsLatest() && \"setPreviousDecl on a decl already in a redeclaration chain\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 4177, __extension__ __PRETTY_FUNCTION__))
;
4178
4179 if (PrevDecl) {
4180 // Point to previous. Make sure that this is actually the most recent
4181 // redeclaration, or we can build invalid chains. If the most recent
4182 // redeclaration is invalid, it won't be PrevDecl, but we want it anyway.
4183 First = PrevDecl->getFirstDecl();
4184 assert(First->RedeclLink.NextIsLatest() && "Expected first")(static_cast <bool> (First->RedeclLink.NextIsLatest(
) && "Expected first") ? void (0) : __assert_fail ("First->RedeclLink.NextIsLatest() && \"Expected first\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 4184, __extension__ __PRETTY_FUNCTION__))
;
4185 decl_type *MostRecent = First->getNextRedeclaration();
4186 RedeclLink = PreviousDeclLink(cast<decl_type>(MostRecent));
4187
4188 // If the declaration was previously visible, a redeclaration of it remains
4189 // visible even if it wouldn't be visible by itself.
4190 static_cast<decl_type*>(this)->IdentifierNamespace |=
4191 MostRecent->getIdentifierNamespace() &
4192 (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
4193 } else {
4194 // Make this first.
4195 First = static_cast<decl_type*>(this);
4196 }
4197
4198 // First one will point to this one as latest.
4199 First->RedeclLink.setLatest(static_cast<decl_type*>(this));
4200
4201 assert(!isa<NamedDecl>(static_cast<decl_type*>(this)) ||(static_cast <bool> (!isa<NamedDecl>(static_cast<
decl_type*>(this)) || cast<NamedDecl>(static_cast<
decl_type*>(this))->isLinkageValid()) ? void (0) : __assert_fail
("!isa<NamedDecl>(static_cast<decl_type*>(this)) || cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid()"
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 4202, __extension__ __PRETTY_FUNCTION__))
4202 cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid())(static_cast <bool> (!isa<NamedDecl>(static_cast<
decl_type*>(this)) || cast<NamedDecl>(static_cast<
decl_type*>(this))->isLinkageValid()) ? void (0) : __assert_fail
("!isa<NamedDecl>(static_cast<decl_type*>(this)) || cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid()"
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/AST/Decl.h"
, 4202, __extension__ __PRETTY_FUNCTION__))
;
4203}
4204
4205// Inline function definitions.
4206
4207/// Check if the given decl is complete.
4208///
4209/// We use this function to break a cycle between the inline definitions in
4210/// Type.h and Decl.h.
4211inline bool IsEnumDeclComplete(EnumDecl *ED) {
4212 return ED->isComplete();
4213}
4214
4215/// Check if the given decl is scoped.
4216///
4217/// We use this function to break a cycle between the inline definitions in
4218/// Type.h and Decl.h.
4219inline bool IsEnumDeclScoped(EnumDecl *ED) {
4220 return ED->isScoped();
4221}
4222
4223} // namespace clang
4224
4225#endif // LLVM_CLANG_AST_DECL_H

/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/Basic/PartialDiagnostic.h

1//===- PartialDiagnostic.h - Diagnostic "closures" --------------*- 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/// \file
11/// \brief Implements a partial diagnostic that can be emitted anwyhere
12/// in a DiagnosticBuilder stream.
13//
14//===----------------------------------------------------------------------===//
15
16#ifndef LLVM_CLANG_BASIC_PARTIALDIAGNOSTIC_H
17#define LLVM_CLANG_BASIC_PARTIALDIAGNOSTIC_H
18
19#include "clang/Basic/Diagnostic.h"
20#include "clang/Basic/LLVM.h"
21#include "clang/Basic/SourceLocation.h"
22#include "llvm/ADT/SmallVector.h"
23#include "llvm/ADT/StringRef.h"
24#include <cassert>
25#include <cstdint>
26#include <string>
27#include <type_traits>
28#include <utility>
29
30namespace clang {
31
32class DeclContext;
33class IdentifierInfo;
34
35class PartialDiagnostic {
36public:
37 enum {
38 // The MaxArguments and MaxFixItHints member enum values from
39 // DiagnosticsEngine are private but DiagnosticsEngine declares
40 // PartialDiagnostic a friend. These enum values are redeclared
41 // here so that the nested Storage class below can access them.
42 MaxArguments = DiagnosticsEngine::MaxArguments
43 };
44
45 struct Storage {
46 enum {
47 /// \brief The maximum number of arguments we can hold. We
48 /// currently only support up to 10 arguments (%0-%9).
49 ///
50 /// A single diagnostic with more than that almost certainly has to
51 /// be simplified anyway.
52 MaxArguments = PartialDiagnostic::MaxArguments
53 };
54
55 /// \brief The number of entries in Arguments.
56 unsigned char NumDiagArgs = 0;
57
58 /// \brief Specifies for each argument whether it is in DiagArgumentsStr
59 /// or in DiagArguments.
60 unsigned char DiagArgumentsKind[MaxArguments];
61
62 /// \brief The values for the various substitution positions.
63 ///
64 /// This is used when the argument is not an std::string. The specific value
65 /// is mangled into an intptr_t and the interpretation depends on exactly
66 /// what sort of argument kind it is.
67 intptr_t DiagArgumentsVal[MaxArguments];
68
69 /// \brief The values for the various substitution positions that have
70 /// string arguments.
71 std::string DiagArgumentsStr[MaxArguments];
72
73 /// \brief The list of ranges added to this diagnostic.
74 SmallVector<CharSourceRange, 8> DiagRanges;
75
76 /// \brief If valid, provides a hint with some code to insert, remove, or
77 /// modify at a particular position.
78 SmallVector<FixItHint, 6> FixItHints;
79
80 Storage() = default;
81 };
82
83 /// \brief An allocator for Storage objects, which uses a small cache to
84 /// objects, used to reduce malloc()/free() traffic for partial diagnostics.
85 class StorageAllocator {
86 static const unsigned NumCached = 16;
87 Storage Cached[NumCached];
88 Storage *FreeList[NumCached];
89 unsigned NumFreeListEntries;
90
91 public:
92 StorageAllocator();
93 ~StorageAllocator();
94
95 /// \brief Allocate new storage.
96 Storage *Allocate() {
97 if (NumFreeListEntries == 0)
98 return new Storage;
99
100 Storage *Result = FreeList[--NumFreeListEntries];
101 Result->NumDiagArgs = 0;
102 Result->DiagRanges.clear();
103 Result->FixItHints.clear();
104 return Result;
105 }
106
107 /// \brief Free the given storage object.
108 void Deallocate(Storage *S) {
109 if (S >= Cached && S <= Cached + NumCached) {
110 FreeList[NumFreeListEntries++] = S;
111 return;
112 }
113
114 delete S;
115 }
116 };
117
118private:
119 // NOTE: Sema assumes that PartialDiagnostic is location-invariant
120 // in the sense that its bits can be safely memcpy'ed and destructed
121 // in the new location.
122
123 /// \brief The diagnostic ID.
124 mutable unsigned DiagID = 0;
125
126 /// \brief Storage for args and ranges.
127 mutable Storage *DiagStorage = nullptr;
128
129 /// \brief Allocator used to allocate storage for this diagnostic.
130 StorageAllocator *Allocator = nullptr;
131
132 /// \brief Retrieve storage for this particular diagnostic.
133 Storage *getStorage() const {
134 if (DiagStorage)
20
Taking false branch
135 return DiagStorage;
136
137 if (Allocator)
21
Assuming the condition is false
22
Taking false branch
138 DiagStorage = Allocator->Allocate();
139 else {
140 assert(Allocator != reinterpret_cast<StorageAllocator *>(~uintptr_t(0)))(static_cast <bool> (Allocator != reinterpret_cast<StorageAllocator
*>(~uintptr_t(0))) ? void (0) : __assert_fail ("Allocator != reinterpret_cast<StorageAllocator *>(~uintptr_t(0))"
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/Basic/PartialDiagnostic.h"
, 140, __extension__ __PRETTY_FUNCTION__))
;
141 DiagStorage = new Storage;
23
Memory is allocated
142 }
143 return DiagStorage;
144 }
145
146 void freeStorage() {
147 if (!DiagStorage)
148 return;
149
150 // The hot path for PartialDiagnostic is when we just used it to wrap an ID
151 // (typically so we have the flexibility of passing a more complex
152 // diagnostic into the callee, but that does not commonly occur).
153 //
154 // Split this out into a slow function for silly compilers (*cough*) which
155 // can't do decent partial inlining.
156 freeStorageSlow();
157 }
158
159 void freeStorageSlow() {
160 if (Allocator)
161 Allocator->Deallocate(DiagStorage);
162 else if (Allocator != reinterpret_cast<StorageAllocator *>(~uintptr_t(0)))
163 delete DiagStorage;
164 DiagStorage = nullptr;
165 }
166
167 void AddSourceRange(const CharSourceRange &R) const {
168 if (!DiagStorage)
169 DiagStorage = getStorage();
170
171 DiagStorage->DiagRanges.push_back(R);
172 }
173
174 void AddFixItHint(const FixItHint &Hint) const {
175 if (Hint.isNull())
176 return;
177
178 if (!DiagStorage)
179 DiagStorage = getStorage();
180
181 DiagStorage->FixItHints.push_back(Hint);
182 }
183
184public:
185 struct NullDiagnostic {};
186
187 /// \brief Create a null partial diagnostic, which cannot carry a payload,
188 /// and only exists to be swapped with a real partial diagnostic.
189 PartialDiagnostic(NullDiagnostic) {}
190
191 PartialDiagnostic(unsigned DiagID, StorageAllocator &Allocator)
192 : DiagID(DiagID), Allocator(&Allocator) {}
193
194 PartialDiagnostic(const PartialDiagnostic &Other)
195 : DiagID(Other.DiagID), Allocator(Other.Allocator) {
196 if (Other.DiagStorage) {
197 DiagStorage = getStorage();
198 *DiagStorage = *Other.DiagStorage;
199 }
200 }
201
202 PartialDiagnostic(PartialDiagnostic &&Other)
203 : DiagID(Other.DiagID), DiagStorage(Other.DiagStorage),
204 Allocator(Other.Allocator) {
205 Other.DiagStorage = nullptr;
206 }
207
208 PartialDiagnostic(const PartialDiagnostic &Other, Storage *DiagStorage)
209 : DiagID(Other.DiagID), DiagStorage(DiagStorage),
210 Allocator(reinterpret_cast<StorageAllocator *>(~uintptr_t(0))) {
211 if (Other.DiagStorage)
212 *this->DiagStorage = *Other.DiagStorage;
213 }
214
215 PartialDiagnostic(const Diagnostic &Other, StorageAllocator &Allocator)
216 : DiagID(Other.getID()), Allocator(&Allocator) {
217 // Copy arguments.
218 for (unsigned I = 0, N = Other.getNumArgs(); I != N; ++I) {
219 if (Other.getArgKind(I) == DiagnosticsEngine::ak_std_string)
220 AddString(Other.getArgStdStr(I));
221 else
222 AddTaggedVal(Other.getRawArg(I), Other.getArgKind(I));
223 }
224
225 // Copy source ranges.
226 for (unsigned I = 0, N = Other.getNumRanges(); I != N; ++I)
227 AddSourceRange(Other.getRange(I));
228
229 // Copy fix-its.
230 for (unsigned I = 0, N = Other.getNumFixItHints(); I != N; ++I)
231 AddFixItHint(Other.getFixItHint(I));
232 }
233
234 PartialDiagnostic &operator=(const PartialDiagnostic &Other) {
235 DiagID = Other.DiagID;
236 if (Other.DiagStorage) {
237 if (!DiagStorage)
238 DiagStorage = getStorage();
239
240 *DiagStorage = *Other.DiagStorage;
241 } else {
242 freeStorage();
243 }
244
245 return *this;
246 }
247
248 PartialDiagnostic &operator=(PartialDiagnostic &&Other) {
249 freeStorage();
250
251 DiagID = Other.DiagID;
252 DiagStorage = Other.DiagStorage;
253 Allocator = Other.Allocator;
254
255 Other.DiagStorage = nullptr;
256 return *this;
257 }
258
259 ~PartialDiagnostic() {
260 freeStorage();
261 }
262
263 void swap(PartialDiagnostic &PD) {
264 std::swap(DiagID, PD.DiagID);
265 std::swap(DiagStorage, PD.DiagStorage);
266 std::swap(Allocator, PD.Allocator);
267 }
268
269 unsigned getDiagID() const { return DiagID; }
270
271 void AddTaggedVal(intptr_t V, DiagnosticsEngine::ArgumentKind Kind) const {
272 if (!DiagStorage)
17
Assuming the condition is true
18
Taking true branch
273 DiagStorage = getStorage();
19
Calling 'PartialDiagnostic::getStorage'
24
Returned allocated memory
274
275 assert(DiagStorage->NumDiagArgs < Storage::MaxArguments &&(static_cast <bool> (DiagStorage->NumDiagArgs < Storage
::MaxArguments && "Too many arguments to diagnostic!"
) ? void (0) : __assert_fail ("DiagStorage->NumDiagArgs < Storage::MaxArguments && \"Too many arguments to diagnostic!\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/Basic/PartialDiagnostic.h"
, 276, __extension__ __PRETTY_FUNCTION__))
276 "Too many arguments to diagnostic!")(static_cast <bool> (DiagStorage->NumDiagArgs < Storage
::MaxArguments && "Too many arguments to diagnostic!"
) ? void (0) : __assert_fail ("DiagStorage->NumDiagArgs < Storage::MaxArguments && \"Too many arguments to diagnostic!\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/Basic/PartialDiagnostic.h"
, 276, __extension__ __PRETTY_FUNCTION__))
;
277 DiagStorage->DiagArgumentsKind[DiagStorage->NumDiagArgs] = Kind;
278 DiagStorage->DiagArgumentsVal[DiagStorage->NumDiagArgs++] = V;
279 }
280
281 void AddString(StringRef V) const {
282 if (!DiagStorage)
283 DiagStorage = getStorage();
284
285 assert(DiagStorage->NumDiagArgs < Storage::MaxArguments &&(static_cast <bool> (DiagStorage->NumDiagArgs < Storage
::MaxArguments && "Too many arguments to diagnostic!"
) ? void (0) : __assert_fail ("DiagStorage->NumDiagArgs < Storage::MaxArguments && \"Too many arguments to diagnostic!\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/Basic/PartialDiagnostic.h"
, 286, __extension__ __PRETTY_FUNCTION__))
286 "Too many arguments to diagnostic!")(static_cast <bool> (DiagStorage->NumDiagArgs < Storage
::MaxArguments && "Too many arguments to diagnostic!"
) ? void (0) : __assert_fail ("DiagStorage->NumDiagArgs < Storage::MaxArguments && \"Too many arguments to diagnostic!\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/Basic/PartialDiagnostic.h"
, 286, __extension__ __PRETTY_FUNCTION__))
;
287 DiagStorage->DiagArgumentsKind[DiagStorage->NumDiagArgs]
288 = DiagnosticsEngine::ak_std_string;
289 DiagStorage->DiagArgumentsStr[DiagStorage->NumDiagArgs++] = V;
290 }
291
292 void Emit(const DiagnosticBuilder &DB) const {
293 if (!DiagStorage)
294 return;
295
296 // Add all arguments.
297 for (unsigned i = 0, e = DiagStorage->NumDiagArgs; i != e; ++i) {
298 if ((DiagnosticsEngine::ArgumentKind)DiagStorage->DiagArgumentsKind[i]
299 == DiagnosticsEngine::ak_std_string)
300 DB.AddString(DiagStorage->DiagArgumentsStr[i]);
301 else
302 DB.AddTaggedVal(DiagStorage->DiagArgumentsVal[i],
303 (DiagnosticsEngine::ArgumentKind)DiagStorage->DiagArgumentsKind[i]);
304 }
305
306 // Add all ranges.
307 for (const CharSourceRange &Range : DiagStorage->DiagRanges)
308 DB.AddSourceRange(Range);
309
310 // Add all fix-its.
311 for (const FixItHint &Fix : DiagStorage->FixItHints)
312 DB.AddFixItHint(Fix);
313 }
314
315 void EmitToString(DiagnosticsEngine &Diags,
316 SmallVectorImpl<char> &Buf) const {
317 // FIXME: It should be possible to render a diagnostic to a string without
318 // messing with the state of the diagnostics engine.
319 DiagnosticBuilder DB(Diags.Report(getDiagID()));
320 Emit(DB);
321 DB.FlushCounts();
322 Diagnostic(&Diags).FormatDiagnostic(Buf);
323 DB.Clear();
324 Diags.Clear();
325 }
326
327 /// \brief Clear out this partial diagnostic, giving it a new diagnostic ID
328 /// and removing all of its arguments, ranges, and fix-it hints.
329 void Reset(unsigned DiagID = 0) {
330 this->DiagID = DiagID;
331 freeStorage();
332 }
333
334 bool hasStorage() const { return DiagStorage != nullptr; }
335
336 /// Retrieve the string argument at the given index.
337 StringRef getStringArg(unsigned I) {
338 assert(DiagStorage && "No diagnostic storage?")(static_cast <bool> (DiagStorage && "No diagnostic storage?"
) ? void (0) : __assert_fail ("DiagStorage && \"No diagnostic storage?\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/Basic/PartialDiagnostic.h"
, 338, __extension__ __PRETTY_FUNCTION__))
;
339 assert(I < DiagStorage->NumDiagArgs && "Not enough diagnostic args")(static_cast <bool> (I < DiagStorage->NumDiagArgs
&& "Not enough diagnostic args") ? void (0) : __assert_fail
("I < DiagStorage->NumDiagArgs && \"Not enough diagnostic args\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/Basic/PartialDiagnostic.h"
, 339, __extension__ __PRETTY_FUNCTION__))
;
340 assert(DiagStorage->DiagArgumentsKind[I](static_cast <bool> (DiagStorage->DiagArgumentsKind[
I] == DiagnosticsEngine::ak_std_string && "Not a string arg"
) ? void (0) : __assert_fail ("DiagStorage->DiagArgumentsKind[I] == DiagnosticsEngine::ak_std_string && \"Not a string arg\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/Basic/PartialDiagnostic.h"
, 341, __extension__ __PRETTY_FUNCTION__))
341 == DiagnosticsEngine::ak_std_string && "Not a string arg")(static_cast <bool> (DiagStorage->DiagArgumentsKind[
I] == DiagnosticsEngine::ak_std_string && "Not a string arg"
) ? void (0) : __assert_fail ("DiagStorage->DiagArgumentsKind[I] == DiagnosticsEngine::ak_std_string && \"Not a string arg\""
, "/build/llvm-toolchain-snapshot-7~svn326425/tools/clang/include/clang/Basic/PartialDiagnostic.h"
, 341, __extension__ __PRETTY_FUNCTION__))
;
342 return DiagStorage->DiagArgumentsStr[I];
343 }
344
345 friend const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
346 unsigned I) {
347 PD.AddTaggedVal(I, DiagnosticsEngine::ak_uint);
348 return PD;
349 }
350
351 friend const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
352 int I) {
353 PD.AddTaggedVal(I, DiagnosticsEngine::ak_sint);
354 return PD;
355 }
356
357 friend inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
358 const char *S) {
359 PD.AddTaggedVal(reinterpret_cast<intptr_t>(S),
360 DiagnosticsEngine::ak_c_string);
361 return PD;
362 }
363
364 friend inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
365 StringRef S) {
366
367 PD.AddString(S);
368 return PD;
369 }
370
371 friend inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
372 const IdentifierInfo *II) {
373 PD.AddTaggedVal(reinterpret_cast<intptr_t>(II),
374 DiagnosticsEngine::ak_identifierinfo);
375 return PD;
376 }
377
378 // Adds a DeclContext to the diagnostic. The enable_if template magic is here
379 // so that we only match those arguments that are (statically) DeclContexts;
380 // other arguments that derive from DeclContext (e.g., RecordDecls) will not
381 // match.
382 template<typename T>
383 friend inline
384 typename std::enable_if<std::is_same<T, DeclContext>::value,
385 const PartialDiagnostic &>::type
386 operator<<(const PartialDiagnostic &PD, T *DC) {
387 PD.AddTaggedVal(reinterpret_cast<intptr_t>(DC),
388 DiagnosticsEngine::ak_declcontext);
389 return PD;
390 }
391
392 friend inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
393 SourceRange R) {
394 PD.AddSourceRange(CharSourceRange::getTokenRange(R));
395 return PD;
396 }
397
398 friend inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
399 const CharSourceRange &R) {
400 PD.AddSourceRange(R);
401 return PD;
402 }
403
404 friend const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
405 const FixItHint &Hint) {
406 PD.AddFixItHint(Hint);
407 return PD;
408 }
409};
410
411inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
412 const PartialDiagnostic &PD) {
413 PD.Emit(DB);
414 return DB;
415}
416
417/// \brief A partial diagnostic along with the source location where this
418/// diagnostic occurs.
419using PartialDiagnosticAt = std::pair<SourceLocation, PartialDiagnostic>;
420
421} // namespace clang
422
423#endif // LLVM_CLANG_BASIC_PARTIALDIAGNOSTIC_H