Bug Summary

File:tools/clang/lib/Sema/SemaTemplateDeduction.cpp
Warning:line 3973, column 41
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaTemplateDeduction.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/include -I /build/llvm-toolchain-snapshot-10~svn374877/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.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++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~svn374877=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2019-10-15-233810-7101-1 -x c++ /build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp

/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp

1//===- SemaTemplateDeduction.cpp - Template Argument Deduction ------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements C++ template argument deduction.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/Sema/TemplateDeduction.h"
14#include "TreeTransform.h"
15#include "TypeLocBuilder.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/ASTLambda.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclAccessPair.h"
20#include "clang/AST/DeclBase.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclTemplate.h"
23#include "clang/AST/DeclarationName.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/NestedNameSpecifier.h"
27#include "clang/AST/TemplateBase.h"
28#include "clang/AST/TemplateName.h"
29#include "clang/AST/Type.h"
30#include "clang/AST/TypeLoc.h"
31#include "clang/AST/UnresolvedSet.h"
32#include "clang/Basic/AddressSpaces.h"
33#include "clang/Basic/ExceptionSpecificationType.h"
34#include "clang/Basic/LLVM.h"
35#include "clang/Basic/LangOptions.h"
36#include "clang/Basic/PartialDiagnostic.h"
37#include "clang/Basic/SourceLocation.h"
38#include "clang/Basic/Specifiers.h"
39#include "clang/Sema/Ownership.h"
40#include "clang/Sema/Sema.h"
41#include "clang/Sema/Template.h"
42#include "llvm/ADT/APInt.h"
43#include "llvm/ADT/APSInt.h"
44#include "llvm/ADT/ArrayRef.h"
45#include "llvm/ADT/DenseMap.h"
46#include "llvm/ADT/FoldingSet.h"
47#include "llvm/ADT/Optional.h"
48#include "llvm/ADT/SmallBitVector.h"
49#include "llvm/ADT/SmallPtrSet.h"
50#include "llvm/ADT/SmallVector.h"
51#include "llvm/Support/Casting.h"
52#include "llvm/Support/Compiler.h"
53#include "llvm/Support/ErrorHandling.h"
54#include <algorithm>
55#include <cassert>
56#include <tuple>
57#include <utility>
58
59namespace clang {
60
61 /// Various flags that control template argument deduction.
62 ///
63 /// These flags can be bitwise-OR'd together.
64 enum TemplateDeductionFlags {
65 /// No template argument deduction flags, which indicates the
66 /// strictest results for template argument deduction (as used for, e.g.,
67 /// matching class template partial specializations).
68 TDF_None = 0,
69
70 /// Within template argument deduction from a function call, we are
71 /// matching with a parameter type for which the original parameter was
72 /// a reference.
73 TDF_ParamWithReferenceType = 0x1,
74
75 /// Within template argument deduction from a function call, we
76 /// are matching in a case where we ignore cv-qualifiers.
77 TDF_IgnoreQualifiers = 0x02,
78
79 /// Within template argument deduction from a function call,
80 /// we are matching in a case where we can perform template argument
81 /// deduction from a template-id of a derived class of the argument type.
82 TDF_DerivedClass = 0x04,
83
84 /// Allow non-dependent types to differ, e.g., when performing
85 /// template argument deduction from a function call where conversions
86 /// may apply.
87 TDF_SkipNonDependent = 0x08,
88
89 /// Whether we are performing template argument deduction for
90 /// parameters and arguments in a top-level template argument
91 TDF_TopLevelParameterTypeList = 0x10,
92
93 /// Within template argument deduction from overload resolution per
94 /// C++ [over.over] allow matching function types that are compatible in
95 /// terms of noreturn and default calling convention adjustments, or
96 /// similarly matching a declared template specialization against a
97 /// possible template, per C++ [temp.deduct.decl]. In either case, permit
98 /// deduction where the parameter is a function type that can be converted
99 /// to the argument type.
100 TDF_AllowCompatibleFunctionType = 0x20,
101
102 /// Within template argument deduction for a conversion function, we are
103 /// matching with an argument type for which the original argument was
104 /// a reference.
105 TDF_ArgWithReferenceType = 0x40,
106 };
107}
108
109using namespace clang;
110using namespace sema;
111
112/// Compare two APSInts, extending and switching the sign as
113/// necessary to compare their values regardless of underlying type.
114static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
115 if (Y.getBitWidth() > X.getBitWidth())
116 X = X.extend(Y.getBitWidth());
117 else if (Y.getBitWidth() < X.getBitWidth())
118 Y = Y.extend(X.getBitWidth());
119
120 // If there is a signedness mismatch, correct it.
121 if (X.isSigned() != Y.isSigned()) {
122 // If the signed value is negative, then the values cannot be the same.
123 if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
124 return false;
125
126 Y.setIsSigned(true);
127 X.setIsSigned(true);
128 }
129
130 return X == Y;
131}
132
133static Sema::TemplateDeductionResult
134DeduceTemplateArguments(Sema &S,
135 TemplateParameterList *TemplateParams,
136 const TemplateArgument &Param,
137 TemplateArgument Arg,
138 TemplateDeductionInfo &Info,
139 SmallVectorImpl<DeducedTemplateArgument> &Deduced);
140
141static Sema::TemplateDeductionResult
142DeduceTemplateArgumentsByTypeMatch(Sema &S,
143 TemplateParameterList *TemplateParams,
144 QualType Param,
145 QualType Arg,
146 TemplateDeductionInfo &Info,
147 SmallVectorImpl<DeducedTemplateArgument> &
148 Deduced,
149 unsigned TDF,
150 bool PartialOrdering = false,
151 bool DeducedFromArrayBound = false);
152
153static Sema::TemplateDeductionResult
154DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
155 ArrayRef<TemplateArgument> Params,
156 ArrayRef<TemplateArgument> Args,
157 TemplateDeductionInfo &Info,
158 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
159 bool NumberOfArgumentsMustMatch);
160
161static void MarkUsedTemplateParameters(ASTContext &Ctx,
162 const TemplateArgument &TemplateArg,
163 bool OnlyDeduced, unsigned Depth,
164 llvm::SmallBitVector &Used);
165
166static void MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
167 bool OnlyDeduced, unsigned Level,
168 llvm::SmallBitVector &Deduced);
169
170/// If the given expression is of a form that permits the deduction
171/// of a non-type template parameter, return the declaration of that
172/// non-type template parameter.
173static NonTypeTemplateParmDecl *
174getDeducedParameterFromExpr(TemplateDeductionInfo &Info, Expr *E) {
175 // If we are within an alias template, the expression may have undergone
176 // any number of parameter substitutions already.
177 while (true) {
178 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
179 E = IC->getSubExpr();
180 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(E))
181 E = CE->getSubExpr();
182 else if (SubstNonTypeTemplateParmExpr *Subst =
183 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
184 E = Subst->getReplacement();
185 else
186 break;
187 }
188
189 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
190 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()))
191 if (NTTP->getDepth() == Info.getDeducedDepth())
192 return NTTP;
193
194 return nullptr;
195}
196
197/// Determine whether two declaration pointers refer to the same
198/// declaration.
199static bool isSameDeclaration(Decl *X, Decl *Y) {
200 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
201 X = NX->getUnderlyingDecl();
202 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
203 Y = NY->getUnderlyingDecl();
204
205 return X->getCanonicalDecl() == Y->getCanonicalDecl();
206}
207
208/// Verify that the given, deduced template arguments are compatible.
209///
210/// \returns The deduced template argument, or a NULL template argument if
211/// the deduced template arguments were incompatible.
212static DeducedTemplateArgument
213checkDeducedTemplateArguments(ASTContext &Context,
214 const DeducedTemplateArgument &X,
215 const DeducedTemplateArgument &Y) {
216 // We have no deduction for one or both of the arguments; they're compatible.
217 if (X.isNull())
218 return Y;
219 if (Y.isNull())
220 return X;
221
222 // If we have two non-type template argument values deduced for the same
223 // parameter, they must both match the type of the parameter, and thus must
224 // match each other's type. As we're only keeping one of them, we must check
225 // for that now. The exception is that if either was deduced from an array
226 // bound, the type is permitted to differ.
227 if (!X.wasDeducedFromArrayBound() && !Y.wasDeducedFromArrayBound()) {
228 QualType XType = X.getNonTypeTemplateArgumentType();
229 if (!XType.isNull()) {
230 QualType YType = Y.getNonTypeTemplateArgumentType();
231 if (YType.isNull() || !Context.hasSameType(XType, YType))
232 return DeducedTemplateArgument();
233 }
234 }
235
236 switch (X.getKind()) {
237 case TemplateArgument::Null:
238 llvm_unreachable("Non-deduced template arguments handled above")::llvm::llvm_unreachable_internal("Non-deduced template arguments handled above"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 238)
;
239
240 case TemplateArgument::Type:
241 // If two template type arguments have the same type, they're compatible.
242 if (Y.getKind() == TemplateArgument::Type &&
243 Context.hasSameType(X.getAsType(), Y.getAsType()))
244 return X;
245
246 // If one of the two arguments was deduced from an array bound, the other
247 // supersedes it.
248 if (X.wasDeducedFromArrayBound() != Y.wasDeducedFromArrayBound())
249 return X.wasDeducedFromArrayBound() ? Y : X;
250
251 // The arguments are not compatible.
252 return DeducedTemplateArgument();
253
254 case TemplateArgument::Integral:
255 // If we deduced a constant in one case and either a dependent expression or
256 // declaration in another case, keep the integral constant.
257 // If both are integral constants with the same value, keep that value.
258 if (Y.getKind() == TemplateArgument::Expression ||
259 Y.getKind() == TemplateArgument::Declaration ||
260 (Y.getKind() == TemplateArgument::Integral &&
261 hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral())))
262 return X.wasDeducedFromArrayBound() ? Y : X;
263
264 // All other combinations are incompatible.
265 return DeducedTemplateArgument();
266
267 case TemplateArgument::Template:
268 if (Y.getKind() == TemplateArgument::Template &&
269 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
270 return X;
271
272 // All other combinations are incompatible.
273 return DeducedTemplateArgument();
274
275 case TemplateArgument::TemplateExpansion:
276 if (Y.getKind() == TemplateArgument::TemplateExpansion &&
277 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
278 Y.getAsTemplateOrTemplatePattern()))
279 return X;
280
281 // All other combinations are incompatible.
282 return DeducedTemplateArgument();
283
284 case TemplateArgument::Expression: {
285 if (Y.getKind() != TemplateArgument::Expression)
286 return checkDeducedTemplateArguments(Context, Y, X);
287
288 // Compare the expressions for equality
289 llvm::FoldingSetNodeID ID1, ID2;
290 X.getAsExpr()->Profile(ID1, Context, true);
291 Y.getAsExpr()->Profile(ID2, Context, true);
292 if (ID1 == ID2)
293 return X.wasDeducedFromArrayBound() ? Y : X;
294
295 // Differing dependent expressions are incompatible.
296 return DeducedTemplateArgument();
297 }
298
299 case TemplateArgument::Declaration:
300 assert(!X.wasDeducedFromArrayBound())((!X.wasDeducedFromArrayBound()) ? static_cast<void> (0
) : __assert_fail ("!X.wasDeducedFromArrayBound()", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 300, __PRETTY_FUNCTION__))
;
301
302 // If we deduced a declaration and a dependent expression, keep the
303 // declaration.
304 if (Y.getKind() == TemplateArgument::Expression)
305 return X;
306
307 // If we deduced a declaration and an integral constant, keep the
308 // integral constant and whichever type did not come from an array
309 // bound.
310 if (Y.getKind() == TemplateArgument::Integral) {
311 if (Y.wasDeducedFromArrayBound())
312 return TemplateArgument(Context, Y.getAsIntegral(),
313 X.getParamTypeForDecl());
314 return Y;
315 }
316
317 // If we deduced two declarations, make sure that they refer to the
318 // same declaration.
319 if (Y.getKind() == TemplateArgument::Declaration &&
320 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
321 return X;
322
323 // All other combinations are incompatible.
324 return DeducedTemplateArgument();
325
326 case TemplateArgument::NullPtr:
327 // If we deduced a null pointer and a dependent expression, keep the
328 // null pointer.
329 if (Y.getKind() == TemplateArgument::Expression)
330 return X;
331
332 // If we deduced a null pointer and an integral constant, keep the
333 // integral constant.
334 if (Y.getKind() == TemplateArgument::Integral)
335 return Y;
336
337 // If we deduced two null pointers, they are the same.
338 if (Y.getKind() == TemplateArgument::NullPtr)
339 return X;
340
341 // All other combinations are incompatible.
342 return DeducedTemplateArgument();
343
344 case TemplateArgument::Pack: {
345 if (Y.getKind() != TemplateArgument::Pack ||
346 X.pack_size() != Y.pack_size())
347 return DeducedTemplateArgument();
348
349 llvm::SmallVector<TemplateArgument, 8> NewPack;
350 for (TemplateArgument::pack_iterator XA = X.pack_begin(),
351 XAEnd = X.pack_end(),
352 YA = Y.pack_begin();
353 XA != XAEnd; ++XA, ++YA) {
354 TemplateArgument Merged = checkDeducedTemplateArguments(
355 Context, DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
356 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()));
357 if (Merged.isNull())
358 return DeducedTemplateArgument();
359 NewPack.push_back(Merged);
360 }
361
362 return DeducedTemplateArgument(
363 TemplateArgument::CreatePackCopy(Context, NewPack),
364 X.wasDeducedFromArrayBound() && Y.wasDeducedFromArrayBound());
365 }
366 }
367
368 llvm_unreachable("Invalid TemplateArgument Kind!")::llvm::llvm_unreachable_internal("Invalid TemplateArgument Kind!"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 368)
;
369}
370
371/// Deduce the value of the given non-type template parameter
372/// as the given deduced template argument. All non-type template parameter
373/// deduction is funneled through here.
374static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
375 Sema &S, TemplateParameterList *TemplateParams,
376 NonTypeTemplateParmDecl *NTTP, const DeducedTemplateArgument &NewDeduced,
377 QualType ValueType, TemplateDeductionInfo &Info,
378 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
379 assert(NTTP->getDepth() == Info.getDeducedDepth() &&((NTTP->getDepth() == Info.getDeducedDepth() && "deducing non-type template argument with wrong depth"
) ? static_cast<void> (0) : __assert_fail ("NTTP->getDepth() == Info.getDeducedDepth() && \"deducing non-type template argument with wrong depth\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 380, __PRETTY_FUNCTION__))
380 "deducing non-type template argument with wrong depth")((NTTP->getDepth() == Info.getDeducedDepth() && "deducing non-type template argument with wrong depth"
) ? static_cast<void> (0) : __assert_fail ("NTTP->getDepth() == Info.getDeducedDepth() && \"deducing non-type template argument with wrong depth\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 380, __PRETTY_FUNCTION__))
;
381
382 DeducedTemplateArgument Result = checkDeducedTemplateArguments(
383 S.Context, Deduced[NTTP->getIndex()], NewDeduced);
384 if (Result.isNull()) {
385 Info.Param = NTTP;
386 Info.FirstArg = Deduced[NTTP->getIndex()];
387 Info.SecondArg = NewDeduced;
388 return Sema::TDK_Inconsistent;
389 }
390
391 Deduced[NTTP->getIndex()] = Result;
392 if (!S.getLangOpts().CPlusPlus17)
393 return Sema::TDK_Success;
394
395 if (NTTP->isExpandedParameterPack())
396 // FIXME: We may still need to deduce parts of the type here! But we
397 // don't have any way to find which slice of the type to use, and the
398 // type stored on the NTTP itself is nonsense. Perhaps the type of an
399 // expanded NTTP should be a pack expansion type?
400 return Sema::TDK_Success;
401
402 // Get the type of the parameter for deduction. If it's a (dependent) array
403 // or function type, we will not have decayed it yet, so do that now.
404 QualType ParamType = S.Context.getAdjustedParameterType(NTTP->getType());
405 if (auto *Expansion = dyn_cast<PackExpansionType>(ParamType))
406 ParamType = Expansion->getPattern();
407
408 // FIXME: It's not clear how deduction of a parameter of reference
409 // type from an argument (of non-reference type) should be performed.
410 // For now, we just remove reference types from both sides and let
411 // the final check for matching types sort out the mess.
412 return DeduceTemplateArgumentsByTypeMatch(
413 S, TemplateParams, ParamType.getNonReferenceType(),
414 ValueType.getNonReferenceType(), Info, Deduced, TDF_SkipNonDependent,
415 /*PartialOrdering=*/false,
416 /*ArrayBound=*/NewDeduced.wasDeducedFromArrayBound());
417}
418
419/// Deduce the value of the given non-type template parameter
420/// from the given integral constant.
421static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
422 Sema &S, TemplateParameterList *TemplateParams,
423 NonTypeTemplateParmDecl *NTTP, const llvm::APSInt &Value,
424 QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info,
425 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
426 return DeduceNonTypeTemplateArgument(
427 S, TemplateParams, NTTP,
428 DeducedTemplateArgument(S.Context, Value, ValueType,
429 DeducedFromArrayBound),
430 ValueType, Info, Deduced);
431}
432
433/// Deduce the value of the given non-type template parameter
434/// from the given null pointer template argument type.
435static Sema::TemplateDeductionResult DeduceNullPtrTemplateArgument(
436 Sema &S, TemplateParameterList *TemplateParams,
437 NonTypeTemplateParmDecl *NTTP, QualType NullPtrType,
438 TemplateDeductionInfo &Info,
439 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
440 Expr *Value =
441 S.ImpCastExprToType(new (S.Context) CXXNullPtrLiteralExpr(
442 S.Context.NullPtrTy, NTTP->getLocation()),
443 NullPtrType, CK_NullToPointer)
444 .get();
445 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
446 DeducedTemplateArgument(Value),
447 Value->getType(), Info, Deduced);
448}
449
450/// Deduce the value of the given non-type template parameter
451/// from the given type- or value-dependent expression.
452///
453/// \returns true if deduction succeeded, false otherwise.
454static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
455 Sema &S, TemplateParameterList *TemplateParams,
456 NonTypeTemplateParmDecl *NTTP, Expr *Value, TemplateDeductionInfo &Info,
457 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
458 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
459 DeducedTemplateArgument(Value),
460 Value->getType(), Info, Deduced);
461}
462
463/// Deduce the value of the given non-type template parameter
464/// from the given declaration.
465///
466/// \returns true if deduction succeeded, false otherwise.
467static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
468 Sema &S, TemplateParameterList *TemplateParams,
469 NonTypeTemplateParmDecl *NTTP, ValueDecl *D, QualType T,
470 TemplateDeductionInfo &Info,
471 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
472 D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
473 TemplateArgument New(D, T);
474 return DeduceNonTypeTemplateArgument(
475 S, TemplateParams, NTTP, DeducedTemplateArgument(New), T, Info, Deduced);
476}
477
478static Sema::TemplateDeductionResult
479DeduceTemplateArguments(Sema &S,
480 TemplateParameterList *TemplateParams,
481 TemplateName Param,
482 TemplateName Arg,
483 TemplateDeductionInfo &Info,
484 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
485 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
486 if (!ParamDecl) {
487 // The parameter type is dependent and is not a template template parameter,
488 // so there is nothing that we can deduce.
489 return Sema::TDK_Success;
490 }
491
492 if (TemplateTemplateParmDecl *TempParam
493 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
494 // If we're not deducing at this depth, there's nothing to deduce.
495 if (TempParam->getDepth() != Info.getDeducedDepth())
496 return Sema::TDK_Success;
497
498 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
499 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
500 Deduced[TempParam->getIndex()],
501 NewDeduced);
502 if (Result.isNull()) {
503 Info.Param = TempParam;
504 Info.FirstArg = Deduced[TempParam->getIndex()];
505 Info.SecondArg = NewDeduced;
506 return Sema::TDK_Inconsistent;
507 }
508
509 Deduced[TempParam->getIndex()] = Result;
510 return Sema::TDK_Success;
511 }
512
513 // Verify that the two template names are equivalent.
514 if (S.Context.hasSameTemplateName(Param, Arg))
515 return Sema::TDK_Success;
516
517 // Mismatch of non-dependent template parameter to argument.
518 Info.FirstArg = TemplateArgument(Param);
519 Info.SecondArg = TemplateArgument(Arg);
520 return Sema::TDK_NonDeducedMismatch;
521}
522
523/// Deduce the template arguments by comparing the template parameter
524/// type (which is a template-id) with the template argument type.
525///
526/// \param S the Sema
527///
528/// \param TemplateParams the template parameters that we are deducing
529///
530/// \param Param the parameter type
531///
532/// \param Arg the argument type
533///
534/// \param Info information about the template argument deduction itself
535///
536/// \param Deduced the deduced template arguments
537///
538/// \returns the result of template argument deduction so far. Note that a
539/// "success" result means that template argument deduction has not yet failed,
540/// but it may still fail, later, for other reasons.
541static Sema::TemplateDeductionResult
542DeduceTemplateArguments(Sema &S,
543 TemplateParameterList *TemplateParams,
544 const TemplateSpecializationType *Param,
545 QualType Arg,
546 TemplateDeductionInfo &Info,
547 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
548 assert(Arg.isCanonical() && "Argument type must be canonical")((Arg.isCanonical() && "Argument type must be canonical"
) ? static_cast<void> (0) : __assert_fail ("Arg.isCanonical() && \"Argument type must be canonical\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 548, __PRETTY_FUNCTION__))
;
549
550 // Treat an injected-class-name as its underlying template-id.
551 if (auto *Injected = dyn_cast<InjectedClassNameType>(Arg))
552 Arg = Injected->getInjectedSpecializationType();
553
554 // Check whether the template argument is a dependent template-id.
555 if (const TemplateSpecializationType *SpecArg
556 = dyn_cast<TemplateSpecializationType>(Arg)) {
557 // Perform template argument deduction for the template name.
558 if (Sema::TemplateDeductionResult Result
559 = DeduceTemplateArguments(S, TemplateParams,
560 Param->getTemplateName(),
561 SpecArg->getTemplateName(),
562 Info, Deduced))
563 return Result;
564
565
566 // Perform template argument deduction on each template
567 // argument. Ignore any missing/extra arguments, since they could be
568 // filled in by default arguments.
569 return DeduceTemplateArguments(S, TemplateParams,
570 Param->template_arguments(),
571 SpecArg->template_arguments(), Info, Deduced,
572 /*NumberOfArgumentsMustMatch=*/false);
573 }
574
575 // If the argument type is a class template specialization, we
576 // perform template argument deduction using its template
577 // arguments.
578 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
579 if (!RecordArg) {
580 Info.FirstArg = TemplateArgument(QualType(Param, 0));
581 Info.SecondArg = TemplateArgument(Arg);
582 return Sema::TDK_NonDeducedMismatch;
583 }
584
585 ClassTemplateSpecializationDecl *SpecArg
586 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
587 if (!SpecArg) {
588 Info.FirstArg = TemplateArgument(QualType(Param, 0));
589 Info.SecondArg = TemplateArgument(Arg);
590 return Sema::TDK_NonDeducedMismatch;
591 }
592
593 // Perform template argument deduction for the template name.
594 if (Sema::TemplateDeductionResult Result
595 = DeduceTemplateArguments(S,
596 TemplateParams,
597 Param->getTemplateName(),
598 TemplateName(SpecArg->getSpecializedTemplate()),
599 Info, Deduced))
600 return Result;
601
602 // Perform template argument deduction for the template arguments.
603 return DeduceTemplateArguments(S, TemplateParams, Param->template_arguments(),
604 SpecArg->getTemplateArgs().asArray(), Info,
605 Deduced, /*NumberOfArgumentsMustMatch=*/true);
606}
607
608/// Determines whether the given type is an opaque type that
609/// might be more qualified when instantiated.
610static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
611 switch (T->getTypeClass()) {
612 case Type::TypeOfExpr:
613 case Type::TypeOf:
614 case Type::DependentName:
615 case Type::Decltype:
616 case Type::UnresolvedUsing:
617 case Type::TemplateTypeParm:
618 return true;
619
620 case Type::ConstantArray:
621 case Type::IncompleteArray:
622 case Type::VariableArray:
623 case Type::DependentSizedArray:
624 return IsPossiblyOpaquelyQualifiedType(
625 cast<ArrayType>(T)->getElementType());
626
627 default:
628 return false;
629 }
630}
631
632/// Helper function to build a TemplateParameter when we don't
633/// know its type statically.
634static TemplateParameter makeTemplateParameter(Decl *D) {
635 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
636 return TemplateParameter(TTP);
637 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
638 return TemplateParameter(NTTP);
639
640 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
641}
642
643/// If \p Param is an expanded parameter pack, get the number of expansions.
644static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
645 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param))
646 if (NTTP->isExpandedParameterPack())
647 return NTTP->getNumExpansionTypes();
648
649 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param))
650 if (TTP->isExpandedParameterPack())
651 return TTP->getNumExpansionTemplateParameters();
652
653 return None;
654}
655
656/// A pack that we're currently deducing.
657struct clang::DeducedPack {
658 // The index of the pack.
659 unsigned Index;
660
661 // The old value of the pack before we started deducing it.
662 DeducedTemplateArgument Saved;
663
664 // A deferred value of this pack from an inner deduction, that couldn't be
665 // deduced because this deduction hadn't happened yet.
666 DeducedTemplateArgument DeferredDeduction;
667
668 // The new value of the pack.
669 SmallVector<DeducedTemplateArgument, 4> New;
670
671 // The outer deduction for this pack, if any.
672 DeducedPack *Outer = nullptr;
673
674 DeducedPack(unsigned Index) : Index(Index) {}
675};
676
677namespace {
678
679/// A scope in which we're performing pack deduction.
680class PackDeductionScope {
681public:
682 /// Prepare to deduce the packs named within Pattern.
683 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
684 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
685 TemplateDeductionInfo &Info, TemplateArgument Pattern)
686 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
687 unsigned NumNamedPacks = addPacks(Pattern);
688 finishConstruction(NumNamedPacks);
689 }
690
691 /// Prepare to directly deduce arguments of the parameter with index \p Index.
692 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
693 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
694 TemplateDeductionInfo &Info, unsigned Index)
695 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
696 addPack(Index);
697 finishConstruction(1);
698 }
699
700private:
701 void addPack(unsigned Index) {
702 // Save the deduced template argument for the parameter pack expanded
703 // by this pack expansion, then clear out the deduction.
704 DeducedPack Pack(Index);
705 Pack.Saved = Deduced[Index];
706 Deduced[Index] = TemplateArgument();
707
708 // FIXME: What if we encounter multiple packs with different numbers of
709 // pre-expanded expansions? (This should already have been diagnosed
710 // during substitution.)
711 if (Optional<unsigned> ExpandedPackExpansions =
712 getExpandedPackSize(TemplateParams->getParam(Index)))
713 FixedNumExpansions = ExpandedPackExpansions;
714
715 Packs.push_back(Pack);
716 }
717
718 unsigned addPacks(TemplateArgument Pattern) {
719 // Compute the set of template parameter indices that correspond to
720 // parameter packs expanded by the pack expansion.
721 llvm::SmallBitVector SawIndices(TemplateParams->size());
722
723 auto AddPack = [&](unsigned Index) {
724 if (SawIndices[Index])
725 return;
726 SawIndices[Index] = true;
727 addPack(Index);
728 };
729
730 // First look for unexpanded packs in the pattern.
731 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
732 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
733 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
734 unsigned Depth, Index;
735 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
736 if (Depth == Info.getDeducedDepth())
737 AddPack(Index);
738 }
739 assert(!Packs.empty() && "Pack expansion without unexpanded packs?")((!Packs.empty() && "Pack expansion without unexpanded packs?"
) ? static_cast<void> (0) : __assert_fail ("!Packs.empty() && \"Pack expansion without unexpanded packs?\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 739, __PRETTY_FUNCTION__))
;
740
741 unsigned NumNamedPacks = Packs.size();
742
743 // We can also have deduced template parameters that do not actually
744 // appear in the pattern, but can be deduced by it (the type of a non-type
745 // template parameter pack, in particular). These won't have prevented us
746 // from partially expanding the pack.
747 llvm::SmallBitVector Used(TemplateParams->size());
748 MarkUsedTemplateParameters(S.Context, Pattern, /*OnlyDeduced*/true,
749 Info.getDeducedDepth(), Used);
750 for (int Index = Used.find_first(); Index != -1;
751 Index = Used.find_next(Index))
752 if (TemplateParams->getParam(Index)->isParameterPack())
753 AddPack(Index);
754
755 return NumNamedPacks;
756 }
757
758 void finishConstruction(unsigned NumNamedPacks) {
759 // Dig out the partially-substituted pack, if there is one.
760 const TemplateArgument *PartialPackArgs = nullptr;
761 unsigned NumPartialPackArgs = 0;
762 std::pair<unsigned, unsigned> PartialPackDepthIndex(-1u, -1u);
763 if (auto *Scope = S.CurrentInstantiationScope)
764 if (auto *Partial = Scope->getPartiallySubstitutedPack(
765 &PartialPackArgs, &NumPartialPackArgs))
766 PartialPackDepthIndex = getDepthAndIndex(Partial);
767
768 // This pack expansion will have been partially or fully expanded if
769 // it only names explicitly-specified parameter packs (including the
770 // partially-substituted one, if any).
771 bool IsExpanded = true;
772 for (unsigned I = 0; I != NumNamedPacks; ++I) {
773 if (Packs[I].Index >= Info.getNumExplicitArgs()) {
774 IsExpanded = false;
775 IsPartiallyExpanded = false;
776 break;
777 }
778 if (PartialPackDepthIndex ==
779 std::make_pair(Info.getDeducedDepth(), Packs[I].Index)) {
780 IsPartiallyExpanded = true;
781 }
782 }
783
784 // Skip over the pack elements that were expanded into separate arguments.
785 // If we partially expanded, this is the number of partial arguments.
786 if (IsPartiallyExpanded)
787 PackElements += NumPartialPackArgs;
788 else if (IsExpanded)
789 PackElements += *FixedNumExpansions;
790
791 for (auto &Pack : Packs) {
792 if (Info.PendingDeducedPacks.size() > Pack.Index)
793 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
794 else
795 Info.PendingDeducedPacks.resize(Pack.Index + 1);
796 Info.PendingDeducedPacks[Pack.Index] = &Pack;
797
798 if (PartialPackDepthIndex ==
799 std::make_pair(Info.getDeducedDepth(), Pack.Index)) {
800 Pack.New.append(PartialPackArgs, PartialPackArgs + NumPartialPackArgs);
801 // We pre-populate the deduced value of the partially-substituted
802 // pack with the specified value. This is not entirely correct: the
803 // value is supposed to have been substituted, not deduced, but the
804 // cases where this is observable require an exact type match anyway.
805 //
806 // FIXME: If we could represent a "depth i, index j, pack elem k"
807 // parameter, we could substitute the partially-substituted pack
808 // everywhere and avoid this.
809 if (!IsPartiallyExpanded)
810 Deduced[Pack.Index] = Pack.New[PackElements];
811 }
812 }
813 }
814
815public:
816 ~PackDeductionScope() {
817 for (auto &Pack : Packs)
818 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
819 }
820
821 /// Determine whether this pack has already been partially expanded into a
822 /// sequence of (prior) function parameters / template arguments.
823 bool isPartiallyExpanded() { return IsPartiallyExpanded; }
824
825 /// Determine whether this pack expansion scope has a known, fixed arity.
826 /// This happens if it involves a pack from an outer template that has
827 /// (notionally) already been expanded.
828 bool hasFixedArity() { return FixedNumExpansions.hasValue(); }
829
830 /// Determine whether the next element of the argument is still part of this
831 /// pack. This is the case unless the pack is already expanded to a fixed
832 /// length.
833 bool hasNextElement() {
834 return !FixedNumExpansions || *FixedNumExpansions > PackElements;
835 }
836
837 /// Move to deducing the next element in each pack that is being deduced.
838 void nextPackElement() {
839 // Capture the deduced template arguments for each parameter pack expanded
840 // by this pack expansion, add them to the list of arguments we've deduced
841 // for that pack, then clear out the deduced argument.
842 for (auto &Pack : Packs) {
843 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
844 if (!Pack.New.empty() || !DeducedArg.isNull()) {
845 while (Pack.New.size() < PackElements)
846 Pack.New.push_back(DeducedTemplateArgument());
847 if (Pack.New.size() == PackElements)
848 Pack.New.push_back(DeducedArg);
849 else
850 Pack.New[PackElements] = DeducedArg;
851 DeducedArg = Pack.New.size() > PackElements + 1
852 ? Pack.New[PackElements + 1]
853 : DeducedTemplateArgument();
854 }
855 }
856 ++PackElements;
857 }
858
859 /// Finish template argument deduction for a set of argument packs,
860 /// producing the argument packs and checking for consistency with prior
861 /// deductions.
862 Sema::TemplateDeductionResult
863 finish(bool TreatNoDeductionsAsNonDeduced = true) {
864 // Build argument packs for each of the parameter packs expanded by this
865 // pack expansion.
866 for (auto &Pack : Packs) {
867 // Put back the old value for this pack.
868 Deduced[Pack.Index] = Pack.Saved;
869
870 // If we are deducing the size of this pack even if we didn't deduce any
871 // values for it, then make sure we build a pack of the right size.
872 // FIXME: Should we always deduce the size, even if the pack appears in
873 // a non-deduced context?
874 if (!TreatNoDeductionsAsNonDeduced)
875 Pack.New.resize(PackElements);
876
877 // Build or find a new value for this pack.
878 DeducedTemplateArgument NewPack;
879 if (PackElements && Pack.New.empty()) {
880 if (Pack.DeferredDeduction.isNull()) {
881 // We were not able to deduce anything for this parameter pack
882 // (because it only appeared in non-deduced contexts), so just
883 // restore the saved argument pack.
884 continue;
885 }
886
887 NewPack = Pack.DeferredDeduction;
888 Pack.DeferredDeduction = TemplateArgument();
889 } else if (Pack.New.empty()) {
890 // If we deduced an empty argument pack, create it now.
891 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
892 } else {
893 TemplateArgument *ArgumentPack =
894 new (S.Context) TemplateArgument[Pack.New.size()];
895 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
896 NewPack = DeducedTemplateArgument(
897 TemplateArgument(llvm::makeArrayRef(ArgumentPack, Pack.New.size())),
898 // FIXME: This is wrong, it's possible that some pack elements are
899 // deduced from an array bound and others are not:
900 // template<typename ...T, T ...V> void g(const T (&...p)[V]);
901 // g({1, 2, 3}, {{}, {}});
902 // ... should deduce T = {int, size_t (from array bound)}.
903 Pack.New[0].wasDeducedFromArrayBound());
904 }
905
906 // Pick where we're going to put the merged pack.
907 DeducedTemplateArgument *Loc;
908 if (Pack.Outer) {
909 if (Pack.Outer->DeferredDeduction.isNull()) {
910 // Defer checking this pack until we have a complete pack to compare
911 // it against.
912 Pack.Outer->DeferredDeduction = NewPack;
913 continue;
914 }
915 Loc = &Pack.Outer->DeferredDeduction;
916 } else {
917 Loc = &Deduced[Pack.Index];
918 }
919
920 // Check the new pack matches any previous value.
921 DeducedTemplateArgument OldPack = *Loc;
922 DeducedTemplateArgument Result =
923 checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
924
925 // If we deferred a deduction of this pack, check that one now too.
926 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
927 OldPack = Result;
928 NewPack = Pack.DeferredDeduction;
929 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
930 }
931
932 NamedDecl *Param = TemplateParams->getParam(Pack.Index);
933 if (Result.isNull()) {
934 Info.Param = makeTemplateParameter(Param);
935 Info.FirstArg = OldPack;
936 Info.SecondArg = NewPack;
937 return Sema::TDK_Inconsistent;
938 }
939
940 // If we have a pre-expanded pack and we didn't deduce enough elements
941 // for it, fail deduction.
942 if (Optional<unsigned> Expansions = getExpandedPackSize(Param)) {
943 if (*Expansions != PackElements) {
944 Info.Param = makeTemplateParameter(Param);
945 Info.FirstArg = Result;
946 return Sema::TDK_IncompletePack;
947 }
948 }
949
950 *Loc = Result;
951 }
952
953 return Sema::TDK_Success;
954 }
955
956private:
957 Sema &S;
958 TemplateParameterList *TemplateParams;
959 SmallVectorImpl<DeducedTemplateArgument> &Deduced;
960 TemplateDeductionInfo &Info;
961 unsigned PackElements = 0;
962 bool IsPartiallyExpanded = false;
963 /// The number of expansions, if we have a fully-expanded pack in this scope.
964 Optional<unsigned> FixedNumExpansions;
965
966 SmallVector<DeducedPack, 2> Packs;
967};
968
969} // namespace
970
971/// Deduce the template arguments by comparing the list of parameter
972/// types to the list of argument types, as in the parameter-type-lists of
973/// function types (C++ [temp.deduct.type]p10).
974///
975/// \param S The semantic analysis object within which we are deducing
976///
977/// \param TemplateParams The template parameters that we are deducing
978///
979/// \param Params The list of parameter types
980///
981/// \param NumParams The number of types in \c Params
982///
983/// \param Args The list of argument types
984///
985/// \param NumArgs The number of types in \c Args
986///
987/// \param Info information about the template argument deduction itself
988///
989/// \param Deduced the deduced template arguments
990///
991/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
992/// how template argument deduction is performed.
993///
994/// \param PartialOrdering If true, we are performing template argument
995/// deduction for during partial ordering for a call
996/// (C++0x [temp.deduct.partial]).
997///
998/// \returns the result of template argument deduction so far. Note that a
999/// "success" result means that template argument deduction has not yet failed,
1000/// but it may still fail, later, for other reasons.
1001static Sema::TemplateDeductionResult
1002DeduceTemplateArguments(Sema &S,
1003 TemplateParameterList *TemplateParams,
1004 const QualType *Params, unsigned NumParams,
1005 const QualType *Args, unsigned NumArgs,
1006 TemplateDeductionInfo &Info,
1007 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1008 unsigned TDF,
1009 bool PartialOrdering = false) {
1010 // C++0x [temp.deduct.type]p10:
1011 // Similarly, if P has a form that contains (T), then each parameter type
1012 // Pi of the respective parameter-type- list of P is compared with the
1013 // corresponding parameter type Ai of the corresponding parameter-type-list
1014 // of A. [...]
1015 unsigned ArgIdx = 0, ParamIdx = 0;
1016 for (; ParamIdx != NumParams; ++ParamIdx) {
1017 // Check argument types.
1018 const PackExpansionType *Expansion
1019 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
1020 if (!Expansion) {
1021 // Simple case: compare the parameter and argument types at this point.
1022
1023 // Make sure we have an argument.
1024 if (ArgIdx >= NumArgs)
1025 return Sema::TDK_MiscellaneousDeductionFailure;
1026
1027 if (isa<PackExpansionType>(Args[ArgIdx])) {
1028 // C++0x [temp.deduct.type]p22:
1029 // If the original function parameter associated with A is a function
1030 // parameter pack and the function parameter associated with P is not
1031 // a function parameter pack, then template argument deduction fails.
1032 return Sema::TDK_MiscellaneousDeductionFailure;
1033 }
1034
1035 if (Sema::TemplateDeductionResult Result
1036 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1037 Params[ParamIdx], Args[ArgIdx],
1038 Info, Deduced, TDF,
1039 PartialOrdering))
1040 return Result;
1041
1042 ++ArgIdx;
1043 continue;
1044 }
1045
1046 // C++0x [temp.deduct.type]p10:
1047 // If the parameter-declaration corresponding to Pi is a function
1048 // parameter pack, then the type of its declarator- id is compared with
1049 // each remaining parameter type in the parameter-type-list of A. Each
1050 // comparison deduces template arguments for subsequent positions in the
1051 // template parameter packs expanded by the function parameter pack.
1052
1053 QualType Pattern = Expansion->getPattern();
1054 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
1055
1056 // A pack scope with fixed arity is not really a pack any more, so is not
1057 // a non-deduced context.
1058 if (ParamIdx + 1 == NumParams || PackScope.hasFixedArity()) {
1059 for (; ArgIdx < NumArgs && PackScope.hasNextElement(); ++ArgIdx) {
1060 // Deduce template arguments from the pattern.
1061 if (Sema::TemplateDeductionResult Result
1062 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern,
1063 Args[ArgIdx], Info, Deduced,
1064 TDF, PartialOrdering))
1065 return Result;
1066
1067 PackScope.nextPackElement();
1068 }
1069 } else {
1070 // C++0x [temp.deduct.type]p5:
1071 // The non-deduced contexts are:
1072 // - A function parameter pack that does not occur at the end of the
1073 // parameter-declaration-clause.
1074 //
1075 // FIXME: There is no wording to say what we should do in this case. We
1076 // choose to resolve this by applying the same rule that is applied for a
1077 // function call: that is, deduce all contained packs to their
1078 // explicitly-specified values (or to <> if there is no such value).
1079 //
1080 // This is seemingly-arbitrarily different from the case of a template-id
1081 // with a non-trailing pack-expansion in its arguments, which renders the
1082 // entire template-argument-list a non-deduced context.
1083
1084 // If the parameter type contains an explicitly-specified pack that we
1085 // could not expand, skip the number of parameters notionally created
1086 // by the expansion.
1087 Optional<unsigned> NumExpansions = Expansion->getNumExpansions();
1088 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
1089 for (unsigned I = 0; I != *NumExpansions && ArgIdx < NumArgs;
1090 ++I, ++ArgIdx)
1091 PackScope.nextPackElement();
1092 }
1093 }
1094
1095 // Build argument packs for each of the parameter packs expanded by this
1096 // pack expansion.
1097 if (auto Result = PackScope.finish())
1098 return Result;
1099 }
1100
1101 // Make sure we don't have any extra arguments.
1102 if (ArgIdx < NumArgs)
1103 return Sema::TDK_MiscellaneousDeductionFailure;
1104
1105 return Sema::TDK_Success;
1106}
1107
1108/// Determine whether the parameter has qualifiers that the argument
1109/// lacks. Put another way, determine whether there is no way to add
1110/// a deduced set of qualifiers to the ParamType that would result in
1111/// its qualifiers matching those of the ArgType.
1112static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
1113 QualType ArgType) {
1114 Qualifiers ParamQs = ParamType.getQualifiers();
1115 Qualifiers ArgQs = ArgType.getQualifiers();
1116
1117 if (ParamQs == ArgQs)
1118 return false;
1119
1120 // Mismatched (but not missing) Objective-C GC attributes.
1121 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
1122 ParamQs.hasObjCGCAttr())
1123 return true;
1124
1125 // Mismatched (but not missing) address spaces.
1126 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
1127 ParamQs.hasAddressSpace())
1128 return true;
1129
1130 // Mismatched (but not missing) Objective-C lifetime qualifiers.
1131 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
1132 ParamQs.hasObjCLifetime())
1133 return true;
1134
1135 // CVR qualifiers inconsistent or a superset.
1136 return (ParamQs.getCVRQualifiers() & ~ArgQs.getCVRQualifiers()) != 0;
1137}
1138
1139/// Compare types for equality with respect to possibly compatible
1140/// function types (noreturn adjustment, implicit calling conventions). If any
1141/// of parameter and argument is not a function, just perform type comparison.
1142///
1143/// \param Param the template parameter type.
1144///
1145/// \param Arg the argument type.
1146bool Sema::isSameOrCompatibleFunctionType(CanQualType Param,
1147 CanQualType Arg) {
1148 const FunctionType *ParamFunction = Param->getAs<FunctionType>(),
1149 *ArgFunction = Arg->getAs<FunctionType>();
1150
1151 // Just compare if not functions.
1152 if (!ParamFunction || !ArgFunction)
1153 return Param == Arg;
1154
1155 // Noreturn and noexcept adjustment.
1156 QualType AdjustedParam;
1157 if (IsFunctionConversion(Param, Arg, AdjustedParam))
1158 return Arg == Context.getCanonicalType(AdjustedParam);
1159
1160 // FIXME: Compatible calling conventions.
1161
1162 return Param == Arg;
1163}
1164
1165/// Get the index of the first template parameter that was originally from the
1166/// innermost template-parameter-list. This is 0 except when we concatenate
1167/// the template parameter lists of a class template and a constructor template
1168/// when forming an implicit deduction guide.
1169static unsigned getFirstInnerIndex(FunctionTemplateDecl *FTD) {
1170 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
1171 if (!Guide || !Guide->isImplicit())
1172 return 0;
1173 return Guide->getDeducedTemplate()->getTemplateParameters()->size();
1174}
1175
1176/// Determine whether a type denotes a forwarding reference.
1177static bool isForwardingReference(QualType Param, unsigned FirstInnerIndex) {
1178 // C++1z [temp.deduct.call]p3:
1179 // A forwarding reference is an rvalue reference to a cv-unqualified
1180 // template parameter that does not represent a template parameter of a
1181 // class template.
1182 if (auto *ParamRef = Param->getAs<RValueReferenceType>()) {
1183 if (ParamRef->getPointeeType().getQualifiers())
1184 return false;
1185 auto *TypeParm = ParamRef->getPointeeType()->getAs<TemplateTypeParmType>();
1186 return TypeParm && TypeParm->getIndex() >= FirstInnerIndex;
1187 }
1188 return false;
1189}
1190
1191/// Deduce the template arguments by comparing the parameter type and
1192/// the argument type (C++ [temp.deduct.type]).
1193///
1194/// \param S the semantic analysis object within which we are deducing
1195///
1196/// \param TemplateParams the template parameters that we are deducing
1197///
1198/// \param ParamIn the parameter type
1199///
1200/// \param ArgIn the argument type
1201///
1202/// \param Info information about the template argument deduction itself
1203///
1204/// \param Deduced the deduced template arguments
1205///
1206/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
1207/// how template argument deduction is performed.
1208///
1209/// \param PartialOrdering Whether we're performing template argument deduction
1210/// in the context of partial ordering (C++0x [temp.deduct.partial]).
1211///
1212/// \returns the result of template argument deduction so far. Note that a
1213/// "success" result means that template argument deduction has not yet failed,
1214/// but it may still fail, later, for other reasons.
1215static Sema::TemplateDeductionResult
1216DeduceTemplateArgumentsByTypeMatch(Sema &S,
1217 TemplateParameterList *TemplateParams,
1218 QualType ParamIn, QualType ArgIn,
1219 TemplateDeductionInfo &Info,
1220 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1221 unsigned TDF,
1222 bool PartialOrdering,
1223 bool DeducedFromArrayBound) {
1224 // We only want to look at the canonical types, since typedefs and
1225 // sugar are not part of template argument deduction.
1226 QualType Param = S.Context.getCanonicalType(ParamIn);
1227 QualType Arg = S.Context.getCanonicalType(ArgIn);
1228
1229 // If the argument type is a pack expansion, look at its pattern.
1230 // This isn't explicitly called out
1231 if (const PackExpansionType *ArgExpansion
1232 = dyn_cast<PackExpansionType>(Arg))
1233 Arg = ArgExpansion->getPattern();
1234
1235 if (PartialOrdering) {
1236 // C++11 [temp.deduct.partial]p5:
1237 // Before the partial ordering is done, certain transformations are
1238 // performed on the types used for partial ordering:
1239 // - If P is a reference type, P is replaced by the type referred to.
1240 const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
1241 if (ParamRef)
1242 Param = ParamRef->getPointeeType();
1243
1244 // - If A is a reference type, A is replaced by the type referred to.
1245 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
1246 if (ArgRef)
1247 Arg = ArgRef->getPointeeType();
1248
1249 if (ParamRef && ArgRef && S.Context.hasSameUnqualifiedType(Param, Arg)) {
1250 // C++11 [temp.deduct.partial]p9:
1251 // If, for a given type, deduction succeeds in both directions (i.e.,
1252 // the types are identical after the transformations above) and both
1253 // P and A were reference types [...]:
1254 // - if [one type] was an lvalue reference and [the other type] was
1255 // not, [the other type] is not considered to be at least as
1256 // specialized as [the first type]
1257 // - if [one type] is more cv-qualified than [the other type],
1258 // [the other type] is not considered to be at least as specialized
1259 // as [the first type]
1260 // Objective-C ARC adds:
1261 // - [one type] has non-trivial lifetime, [the other type] has
1262 // __unsafe_unretained lifetime, and the types are otherwise
1263 // identical
1264 //
1265 // A is "considered to be at least as specialized" as P iff deduction
1266 // succeeds, so we model this as a deduction failure. Note that
1267 // [the first type] is P and [the other type] is A here; the standard
1268 // gets this backwards.
1269 Qualifiers ParamQuals = Param.getQualifiers();
1270 Qualifiers ArgQuals = Arg.getQualifiers();
1271 if ((ParamRef->isLValueReferenceType() &&
1272 !ArgRef->isLValueReferenceType()) ||
1273 ParamQuals.isStrictSupersetOf(ArgQuals) ||
1274 (ParamQuals.hasNonTrivialObjCLifetime() &&
1275 ArgQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1276 ParamQuals.withoutObjCLifetime() ==
1277 ArgQuals.withoutObjCLifetime())) {
1278 Info.FirstArg = TemplateArgument(ParamIn);
1279 Info.SecondArg = TemplateArgument(ArgIn);
1280 return Sema::TDK_NonDeducedMismatch;
1281 }
1282 }
1283
1284 // C++11 [temp.deduct.partial]p7:
1285 // Remove any top-level cv-qualifiers:
1286 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
1287 // version of P.
1288 Param = Param.getUnqualifiedType();
1289 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
1290 // version of A.
1291 Arg = Arg.getUnqualifiedType();
1292 } else {
1293 // C++0x [temp.deduct.call]p4 bullet 1:
1294 // - If the original P is a reference type, the deduced A (i.e., the type
1295 // referred to by the reference) can be more cv-qualified than the
1296 // transformed A.
1297 if (TDF & TDF_ParamWithReferenceType) {
1298 Qualifiers Quals;
1299 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
1300 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
1301 Arg.getCVRQualifiers());
1302 Param = S.Context.getQualifiedType(UnqualParam, Quals);
1303 }
1304
1305 if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) {
1306 // C++0x [temp.deduct.type]p10:
1307 // If P and A are function types that originated from deduction when
1308 // taking the address of a function template (14.8.2.2) or when deducing
1309 // template arguments from a function declaration (14.8.2.6) and Pi and
1310 // Ai are parameters of the top-level parameter-type-list of P and A,
1311 // respectively, Pi is adjusted if it is a forwarding reference and Ai
1312 // is an lvalue reference, in
1313 // which case the type of Pi is changed to be the template parameter
1314 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1315 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
1316 // deduced as X&. - end note ]
1317 TDF &= ~TDF_TopLevelParameterTypeList;
1318 if (isForwardingReference(Param, 0) && Arg->isLValueReferenceType())
1319 Param = Param->getPointeeType();
1320 }
1321 }
1322
1323 // C++ [temp.deduct.type]p9:
1324 // A template type argument T, a template template argument TT or a
1325 // template non-type argument i can be deduced if P and A have one of
1326 // the following forms:
1327 //
1328 // T
1329 // cv-list T
1330 if (const TemplateTypeParmType *TemplateTypeParm
1331 = Param->getAs<TemplateTypeParmType>()) {
1332 // Just skip any attempts to deduce from a placeholder type or a parameter
1333 // at a different depth.
1334 if (Arg->isPlaceholderType() ||
1335 Info.getDeducedDepth() != TemplateTypeParm->getDepth())
1336 return Sema::TDK_Success;
1337
1338 unsigned Index = TemplateTypeParm->getIndex();
1339 bool RecanonicalizeArg = false;
1340
1341 // If the argument type is an array type, move the qualifiers up to the
1342 // top level, so they can be matched with the qualifiers on the parameter.
1343 if (isa<ArrayType>(Arg)) {
1344 Qualifiers Quals;
1345 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
1346 if (Quals) {
1347 Arg = S.Context.getQualifiedType(Arg, Quals);
1348 RecanonicalizeArg = true;
1349 }
1350 }
1351
1352 // The argument type can not be less qualified than the parameter
1353 // type.
1354 if (!(TDF & TDF_IgnoreQualifiers) &&
1355 hasInconsistentOrSupersetQualifiersOf(Param, Arg)) {
1356 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1357 Info.FirstArg = TemplateArgument(Param);
1358 Info.SecondArg = TemplateArgument(Arg);
1359 return Sema::TDK_Underqualified;
1360 }
1361
1362 // Do not match a function type with a cv-qualified type.
1363 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1584
1364 if (Arg->isFunctionType() && Param.hasQualifiers()) {
1365 return Sema::TDK_NonDeducedMismatch;
1366 }
1367
1368 assert(TemplateTypeParm->getDepth() == Info.getDeducedDepth() &&((TemplateTypeParm->getDepth() == Info.getDeducedDepth() &&
"saw template type parameter with wrong depth") ? static_cast
<void> (0) : __assert_fail ("TemplateTypeParm->getDepth() == Info.getDeducedDepth() && \"saw template type parameter with wrong depth\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 1369, __PRETTY_FUNCTION__))
1369 "saw template type parameter with wrong depth")((TemplateTypeParm->getDepth() == Info.getDeducedDepth() &&
"saw template type parameter with wrong depth") ? static_cast
<void> (0) : __assert_fail ("TemplateTypeParm->getDepth() == Info.getDeducedDepth() && \"saw template type parameter with wrong depth\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 1369, __PRETTY_FUNCTION__))
;
1370 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function")((Arg != S.Context.OverloadTy && "Unresolved overloaded function"
) ? static_cast<void> (0) : __assert_fail ("Arg != S.Context.OverloadTy && \"Unresolved overloaded function\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 1370, __PRETTY_FUNCTION__))
;
1371 QualType DeducedType = Arg;
1372
1373 // Remove any qualifiers on the parameter from the deduced type.
1374 // We checked the qualifiers for consistency above.
1375 Qualifiers DeducedQs = DeducedType.getQualifiers();
1376 Qualifiers ParamQs = Param.getQualifiers();
1377 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1378 if (ParamQs.hasObjCGCAttr())
1379 DeducedQs.removeObjCGCAttr();
1380 if (ParamQs.hasAddressSpace())
1381 DeducedQs.removeAddressSpace();
1382 if (ParamQs.hasObjCLifetime())
1383 DeducedQs.removeObjCLifetime();
1384
1385 // Objective-C ARC:
1386 // If template deduction would produce a lifetime qualifier on a type
1387 // that is not a lifetime type, template argument deduction fails.
1388 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1389 !DeducedType->isDependentType()) {
1390 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1391 Info.FirstArg = TemplateArgument(Param);
1392 Info.SecondArg = TemplateArgument(Arg);
1393 return Sema::TDK_Underqualified;
1394 }
1395
1396 // Objective-C ARC:
1397 // If template deduction would produce an argument type with lifetime type
1398 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
1399 if (S.getLangOpts().ObjCAutoRefCount &&
1400 DeducedType->isObjCLifetimeType() &&
1401 !DeducedQs.hasObjCLifetime())
1402 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
1403
1404 DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(),
1405 DeducedQs);
1406
1407 if (RecanonicalizeArg)
1408 DeducedType = S.Context.getCanonicalType(DeducedType);
1409
1410 DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
1411 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
1412 Deduced[Index],
1413 NewDeduced);
1414 if (Result.isNull()) {
1415 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1416 Info.FirstArg = Deduced[Index];
1417 Info.SecondArg = NewDeduced;
1418 return Sema::TDK_Inconsistent;
1419 }
1420
1421 Deduced[Index] = Result;
1422 return Sema::TDK_Success;
1423 }
1424
1425 // Set up the template argument deduction information for a failure.
1426 Info.FirstArg = TemplateArgument(ParamIn);
1427 Info.SecondArg = TemplateArgument(ArgIn);
1428
1429 // If the parameter is an already-substituted template parameter
1430 // pack, do nothing: we don't know which of its arguments to look
1431 // at, so we have to wait until all of the parameter packs in this
1432 // expansion have arguments.
1433 if (isa<SubstTemplateTypeParmPackType>(Param))
1434 return Sema::TDK_Success;
1435
1436 // Check the cv-qualifiers on the parameter and argument types.
1437 CanQualType CanParam = S.Context.getCanonicalType(Param);
1438 CanQualType CanArg = S.Context.getCanonicalType(Arg);
1439 if (!(TDF & TDF_IgnoreQualifiers)) {
1440 if (TDF & TDF_ParamWithReferenceType) {
1441 if (hasInconsistentOrSupersetQualifiersOf(Param, Arg))
1442 return Sema::TDK_NonDeducedMismatch;
1443 } else if (TDF & TDF_ArgWithReferenceType) {
1444 // C++ [temp.deduct.conv]p4:
1445 // If the original A is a reference type, A can be more cv-qualified
1446 // than the deduced A
1447 if (!Arg.getQualifiers().compatiblyIncludes(Param.getQualifiers()))
1448 return Sema::TDK_NonDeducedMismatch;
1449
1450 // Strip out all extra qualifiers from the argument to figure out the
1451 // type we're converting to, prior to the qualification conversion.
1452 Qualifiers Quals;
1453 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
1454 Arg = S.Context.getQualifiedType(Arg, Param.getQualifiers());
1455 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
1456 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
1457 return Sema::TDK_NonDeducedMismatch;
1458 }
1459
1460 // If the parameter type is not dependent, there is nothing to deduce.
1461 if (!Param->isDependentType()) {
1462 if (!(TDF & TDF_SkipNonDependent)) {
1463 bool NonDeduced =
1464 (TDF & TDF_AllowCompatibleFunctionType)
1465 ? !S.isSameOrCompatibleFunctionType(CanParam, CanArg)
1466 : Param != Arg;
1467 if (NonDeduced) {
1468 return Sema::TDK_NonDeducedMismatch;
1469 }
1470 }
1471 return Sema::TDK_Success;
1472 }
1473 } else if (!Param->isDependentType()) {
1474 CanQualType ParamUnqualType = CanParam.getUnqualifiedType(),
1475 ArgUnqualType = CanArg.getUnqualifiedType();
1476 bool Success =
1477 (TDF & TDF_AllowCompatibleFunctionType)
1478 ? S.isSameOrCompatibleFunctionType(ParamUnqualType, ArgUnqualType)
1479 : ParamUnqualType == ArgUnqualType;
1480 if (Success)
1481 return Sema::TDK_Success;
1482 }
1483
1484 switch (Param->getTypeClass()) {
1485 // Non-canonical types cannot appear here.
1486#define NON_CANONICAL_TYPE(Class, Base) \
1487 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class)::llvm::llvm_unreachable_internal("deducing non-canonical type: "
#Class, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 1487)
;
1488#define TYPE(Class, Base)
1489#include "clang/AST/TypeNodes.inc"
1490
1491 case Type::TemplateTypeParm:
1492 case Type::SubstTemplateTypeParmPack:
1493 llvm_unreachable("Type nodes handled above")::llvm::llvm_unreachable_internal("Type nodes handled above",
"/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 1493)
;
1494
1495 // These types cannot be dependent, so simply check whether the types are
1496 // the same.
1497 case Type::Builtin:
1498 case Type::VariableArray:
1499 case Type::Vector:
1500 case Type::FunctionNoProto:
1501 case Type::Record:
1502 case Type::Enum:
1503 case Type::ObjCObject:
1504 case Type::ObjCInterface:
1505 case Type::ObjCObjectPointer:
1506 if (TDF & TDF_SkipNonDependent)
1507 return Sema::TDK_Success;
1508
1509 if (TDF & TDF_IgnoreQualifiers) {
1510 Param = Param.getUnqualifiedType();
1511 Arg = Arg.getUnqualifiedType();
1512 }
1513
1514 return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch;
1515
1516 // _Complex T [placeholder extension]
1517 case Type::Complex:
1518 if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>())
1519 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1520 cast<ComplexType>(Param)->getElementType(),
1521 ComplexArg->getElementType(),
1522 Info, Deduced, TDF);
1523
1524 return Sema::TDK_NonDeducedMismatch;
1525
1526 // _Atomic T [extension]
1527 case Type::Atomic:
1528 if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>())
1529 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1530 cast<AtomicType>(Param)->getValueType(),
1531 AtomicArg->getValueType(),
1532 Info, Deduced, TDF);
1533
1534 return Sema::TDK_NonDeducedMismatch;
1535
1536 // T *
1537 case Type::Pointer: {
1538 QualType PointeeType;
1539 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
1540 PointeeType = PointerArg->getPointeeType();
1541 } else if (const ObjCObjectPointerType *PointerArg
1542 = Arg->getAs<ObjCObjectPointerType>()) {
1543 PointeeType = PointerArg->getPointeeType();
1544 } else {
1545 return Sema::TDK_NonDeducedMismatch;
1546 }
1547
1548 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
1549 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1550 cast<PointerType>(Param)->getPointeeType(),
1551 PointeeType,
1552 Info, Deduced, SubTDF);
1553 }
1554
1555 // T &
1556 case Type::LValueReference: {
1557 const LValueReferenceType *ReferenceArg =
1558 Arg->getAs<LValueReferenceType>();
1559 if (!ReferenceArg)
1560 return Sema::TDK_NonDeducedMismatch;
1561
1562 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1563 cast<LValueReferenceType>(Param)->getPointeeType(),
1564 ReferenceArg->getPointeeType(), Info, Deduced, 0);
1565 }
1566
1567 // T && [C++0x]
1568 case Type::RValueReference: {
1569 const RValueReferenceType *ReferenceArg =
1570 Arg->getAs<RValueReferenceType>();
1571 if (!ReferenceArg)
1572 return Sema::TDK_NonDeducedMismatch;
1573
1574 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1575 cast<RValueReferenceType>(Param)->getPointeeType(),
1576 ReferenceArg->getPointeeType(),
1577 Info, Deduced, 0);
1578 }
1579
1580 // T [] (implied, but not stated explicitly)
1581 case Type::IncompleteArray: {
1582 const IncompleteArrayType *IncompleteArrayArg =
1583 S.Context.getAsIncompleteArrayType(Arg);
1584 if (!IncompleteArrayArg)
1585 return Sema::TDK_NonDeducedMismatch;
1586
1587 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1588 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1589 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
1590 IncompleteArrayArg->getElementType(),
1591 Info, Deduced, SubTDF);
1592 }
1593
1594 // T [integer-constant]
1595 case Type::ConstantArray: {
1596 const ConstantArrayType *ConstantArrayArg =
1597 S.Context.getAsConstantArrayType(Arg);
1598 if (!ConstantArrayArg)
1599 return Sema::TDK_NonDeducedMismatch;
1600
1601 const ConstantArrayType *ConstantArrayParm =
1602 S.Context.getAsConstantArrayType(Param);
1603 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
1604 return Sema::TDK_NonDeducedMismatch;
1605
1606 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1607 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1608 ConstantArrayParm->getElementType(),
1609 ConstantArrayArg->getElementType(),
1610 Info, Deduced, SubTDF);
1611 }
1612
1613 // type [i]
1614 case Type::DependentSizedArray: {
1615 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
1616 if (!ArrayArg)
1617 return Sema::TDK_NonDeducedMismatch;
1618
1619 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1620
1621 // Check the element type of the arrays
1622 const DependentSizedArrayType *DependentArrayParm
1623 = S.Context.getAsDependentSizedArrayType(Param);
1624 if (Sema::TemplateDeductionResult Result
1625 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1626 DependentArrayParm->getElementType(),
1627 ArrayArg->getElementType(),
1628 Info, Deduced, SubTDF))
1629 return Result;
1630
1631 // Determine the array bound is something we can deduce.
1632 NonTypeTemplateParmDecl *NTTP
1633 = getDeducedParameterFromExpr(Info, DependentArrayParm->getSizeExpr());
1634 if (!NTTP)
1635 return Sema::TDK_Success;
1636
1637 // We can perform template argument deduction for the given non-type
1638 // template parameter.
1639 assert(NTTP->getDepth() == Info.getDeducedDepth() &&((NTTP->getDepth() == Info.getDeducedDepth() && "saw non-type template parameter with wrong depth"
) ? static_cast<void> (0) : __assert_fail ("NTTP->getDepth() == Info.getDeducedDepth() && \"saw non-type template parameter with wrong depth\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 1640, __PRETTY_FUNCTION__))
1640 "saw non-type template parameter with wrong depth")((NTTP->getDepth() == Info.getDeducedDepth() && "saw non-type template parameter with wrong depth"
) ? static_cast<void> (0) : __assert_fail ("NTTP->getDepth() == Info.getDeducedDepth() && \"saw non-type template parameter with wrong depth\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 1640, __PRETTY_FUNCTION__))
;
1641 if (const ConstantArrayType *ConstantArrayArg
1642 = dyn_cast<ConstantArrayType>(ArrayArg)) {
1643 llvm::APSInt Size(ConstantArrayArg->getSize());
1644 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, Size,
1645 S.Context.getSizeType(),
1646 /*ArrayBound=*/true,
1647 Info, Deduced);
1648 }
1649 if (const DependentSizedArrayType *DependentArrayArg
1650 = dyn_cast<DependentSizedArrayType>(ArrayArg))
1651 if (DependentArrayArg->getSizeExpr())
1652 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1653 DependentArrayArg->getSizeExpr(),
1654 Info, Deduced);
1655
1656 // Incomplete type does not match a dependently-sized array type
1657 return Sema::TDK_NonDeducedMismatch;
1658 }
1659
1660 // type(*)(T)
1661 // T(*)()
1662 // T(*)(T)
1663 case Type::FunctionProto: {
1664 unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
1665 const FunctionProtoType *FunctionProtoArg =
1666 dyn_cast<FunctionProtoType>(Arg);
1667 if (!FunctionProtoArg)
1668 return Sema::TDK_NonDeducedMismatch;
1669
1670 const FunctionProtoType *FunctionProtoParam =
1671 cast<FunctionProtoType>(Param);
1672
1673 if (FunctionProtoParam->getMethodQuals()
1674 != FunctionProtoArg->getMethodQuals() ||
1675 FunctionProtoParam->getRefQualifier()
1676 != FunctionProtoArg->getRefQualifier() ||
1677 FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
1678 return Sema::TDK_NonDeducedMismatch;
1679
1680 // Check return types.
1681 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
1682 S, TemplateParams, FunctionProtoParam->getReturnType(),
1683 FunctionProtoArg->getReturnType(), Info, Deduced, 0))
1684 return Result;
1685
1686 // Check parameter types.
1687 if (auto Result = DeduceTemplateArguments(
1688 S, TemplateParams, FunctionProtoParam->param_type_begin(),
1689 FunctionProtoParam->getNumParams(),
1690 FunctionProtoArg->param_type_begin(),
1691 FunctionProtoArg->getNumParams(), Info, Deduced, SubTDF))
1692 return Result;
1693
1694 if (TDF & TDF_AllowCompatibleFunctionType)
1695 return Sema::TDK_Success;
1696
1697 // FIXME: Per core-2016/10/1019 (no corresponding core issue yet), permit
1698 // deducing through the noexcept-specifier if it's part of the canonical
1699 // type. libstdc++ relies on this.
1700 Expr *NoexceptExpr = FunctionProtoParam->getNoexceptExpr();
1701 if (NonTypeTemplateParmDecl *NTTP =
1702 NoexceptExpr ? getDeducedParameterFromExpr(Info, NoexceptExpr)
1703 : nullptr) {
1704 assert(NTTP->getDepth() == Info.getDeducedDepth() &&((NTTP->getDepth() == Info.getDeducedDepth() && "saw non-type template parameter with wrong depth"
) ? static_cast<void> (0) : __assert_fail ("NTTP->getDepth() == Info.getDeducedDepth() && \"saw non-type template parameter with wrong depth\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 1705, __PRETTY_FUNCTION__))
1705 "saw non-type template parameter with wrong depth")((NTTP->getDepth() == Info.getDeducedDepth() && "saw non-type template parameter with wrong depth"
) ? static_cast<void> (0) : __assert_fail ("NTTP->getDepth() == Info.getDeducedDepth() && \"saw non-type template parameter with wrong depth\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 1705, __PRETTY_FUNCTION__))
;
1706
1707 llvm::APSInt Noexcept(1);
1708 switch (FunctionProtoArg->canThrow()) {
1709 case CT_Cannot:
1710 Noexcept = 1;
1711 LLVM_FALLTHROUGH[[gnu::fallthrough]];
1712
1713 case CT_Can:
1714 // We give E in noexcept(E) the "deduced from array bound" treatment.
1715 // FIXME: Should we?
1716 return DeduceNonTypeTemplateArgument(
1717 S, TemplateParams, NTTP, Noexcept, S.Context.BoolTy,
1718 /*ArrayBound*/true, Info, Deduced);
1719
1720 case CT_Dependent:
1721 if (Expr *ArgNoexceptExpr = FunctionProtoArg->getNoexceptExpr())
1722 return DeduceNonTypeTemplateArgument(
1723 S, TemplateParams, NTTP, ArgNoexceptExpr, Info, Deduced);
1724 // Can't deduce anything from throw(T...).
1725 break;
1726 }
1727 }
1728 // FIXME: Detect non-deduced exception specification mismatches?
1729 //
1730 // Careful about [temp.deduct.call] and [temp.deduct.conv], which allow
1731 // top-level differences in noexcept-specifications.
1732
1733 return Sema::TDK_Success;
1734 }
1735
1736 case Type::InjectedClassName:
1737 // Treat a template's injected-class-name as if the template
1738 // specialization type had been used.
1739 Param = cast<InjectedClassNameType>(Param)
1740 ->getInjectedSpecializationType();
1741 assert(isa<TemplateSpecializationType>(Param) &&((isa<TemplateSpecializationType>(Param) && "injected class name is not a template specialization type"
) ? static_cast<void> (0) : __assert_fail ("isa<TemplateSpecializationType>(Param) && \"injected class name is not a template specialization type\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 1742, __PRETTY_FUNCTION__))
1742 "injected class name is not a template specialization type")((isa<TemplateSpecializationType>(Param) && "injected class name is not a template specialization type"
) ? static_cast<void> (0) : __assert_fail ("isa<TemplateSpecializationType>(Param) && \"injected class name is not a template specialization type\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 1742, __PRETTY_FUNCTION__))
;
1743 LLVM_FALLTHROUGH[[gnu::fallthrough]];
1744
1745 // template-name<T> (where template-name refers to a class template)
1746 // template-name<i>
1747 // TT<T>
1748 // TT<i>
1749 // TT<>
1750 case Type::TemplateSpecialization: {
1751 const TemplateSpecializationType *SpecParam =
1752 cast<TemplateSpecializationType>(Param);
1753
1754 // When Arg cannot be a derived class, we can just try to deduce template
1755 // arguments from the template-id.
1756 const RecordType *RecordT = Arg->getAs<RecordType>();
1757 if (!(TDF & TDF_DerivedClass) || !RecordT)
1758 return DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg, Info,
1759 Deduced);
1760
1761 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
1762 Deduced.end());
1763
1764 Sema::TemplateDeductionResult Result = DeduceTemplateArguments(
1765 S, TemplateParams, SpecParam, Arg, Info, Deduced);
1766
1767 if (Result == Sema::TDK_Success)
1768 return Result;
1769
1770 // We cannot inspect base classes as part of deduction when the type
1771 // is incomplete, so either instantiate any templates necessary to
1772 // complete the type, or skip over it if it cannot be completed.
1773 if (!S.isCompleteType(Info.getLocation(), Arg))
1774 return Result;
1775
1776 // C++14 [temp.deduct.call] p4b3:
1777 // If P is a class and P has the form simple-template-id, then the
1778 // transformed A can be a derived class of the deduced A. Likewise if
1779 // P is a pointer to a class of the form simple-template-id, the
1780 // transformed A can be a pointer to a derived class pointed to by the
1781 // deduced A.
1782 //
1783 // These alternatives are considered only if type deduction would
1784 // otherwise fail. If they yield more than one possible deduced A, the
1785 // type deduction fails.
1786
1787 // Reset the incorrectly deduced argument from above.
1788 Deduced = DeducedOrig;
1789
1790 // Use data recursion to crawl through the list of base classes.
1791 // Visited contains the set of nodes we have already visited, while
1792 // ToVisit is our stack of records that we still need to visit.
1793 llvm::SmallPtrSet<const RecordType *, 8> Visited;
1794 SmallVector<const RecordType *, 8> ToVisit;
1795 ToVisit.push_back(RecordT);
1796 bool Successful = false;
1797 SmallVector<DeducedTemplateArgument, 8> SuccessfulDeduced;
1798 while (!ToVisit.empty()) {
1799 // Retrieve the next class in the inheritance hierarchy.
1800 const RecordType *NextT = ToVisit.pop_back_val();
1801
1802 // If we have already seen this type, skip it.
1803 if (!Visited.insert(NextT).second)
1804 continue;
1805
1806 // If this is a base class, try to perform template argument
1807 // deduction from it.
1808 if (NextT != RecordT) {
1809 TemplateDeductionInfo BaseInfo(Info.getLocation());
1810 Sema::TemplateDeductionResult BaseResult =
1811 DeduceTemplateArguments(S, TemplateParams, SpecParam,
1812 QualType(NextT, 0), BaseInfo, Deduced);
1813
1814 // If template argument deduction for this base was successful,
1815 // note that we had some success. Otherwise, ignore any deductions
1816 // from this base class.
1817 if (BaseResult == Sema::TDK_Success) {
1818 // If we've already seen some success, then deduction fails due to
1819 // an ambiguity (temp.deduct.call p5).
1820 if (Successful)
1821 return Sema::TDK_MiscellaneousDeductionFailure;
1822
1823 Successful = true;
1824 std::swap(SuccessfulDeduced, Deduced);
1825
1826 Info.Param = BaseInfo.Param;
1827 Info.FirstArg = BaseInfo.FirstArg;
1828 Info.SecondArg = BaseInfo.SecondArg;
1829 }
1830
1831 Deduced = DeducedOrig;
1832 }
1833
1834 // Visit base classes
1835 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1836 for (const auto &Base : Next->bases()) {
1837 assert(Base.getType()->isRecordType() &&((Base.getType()->isRecordType() && "Base class that isn't a record?"
) ? static_cast<void> (0) : __assert_fail ("Base.getType()->isRecordType() && \"Base class that isn't a record?\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 1838, __PRETTY_FUNCTION__))
1838 "Base class that isn't a record?")((Base.getType()->isRecordType() && "Base class that isn't a record?"
) ? static_cast<void> (0) : __assert_fail ("Base.getType()->isRecordType() && \"Base class that isn't a record?\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 1838, __PRETTY_FUNCTION__))
;
1839 ToVisit.push_back(Base.getType()->getAs<RecordType>());
1840 }
1841 }
1842
1843 if (Successful) {
1844 std::swap(SuccessfulDeduced, Deduced);
1845 return Sema::TDK_Success;
1846 }
1847
1848 return Result;
1849 }
1850
1851 // T type::*
1852 // T T::*
1853 // T (type::*)()
1854 // type (T::*)()
1855 // type (type::*)(T)
1856 // type (T::*)(T)
1857 // T (type::*)(T)
1858 // T (T::*)()
1859 // T (T::*)(T)
1860 case Type::MemberPointer: {
1861 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1862 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1863 if (!MemPtrArg)
1864 return Sema::TDK_NonDeducedMismatch;
1865
1866 QualType ParamPointeeType = MemPtrParam->getPointeeType();
1867 if (ParamPointeeType->isFunctionType())
1868 S.adjustMemberFunctionCC(ParamPointeeType, /*IsStatic=*/true,
1869 /*IsCtorOrDtor=*/false, Info.getLocation());
1870 QualType ArgPointeeType = MemPtrArg->getPointeeType();
1871 if (ArgPointeeType->isFunctionType())
1872 S.adjustMemberFunctionCC(ArgPointeeType, /*IsStatic=*/true,
1873 /*IsCtorOrDtor=*/false, Info.getLocation());
1874
1875 if (Sema::TemplateDeductionResult Result
1876 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1877 ParamPointeeType,
1878 ArgPointeeType,
1879 Info, Deduced,
1880 TDF & TDF_IgnoreQualifiers))
1881 return Result;
1882
1883 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1884 QualType(MemPtrParam->getClass(), 0),
1885 QualType(MemPtrArg->getClass(), 0),
1886 Info, Deduced,
1887 TDF & TDF_IgnoreQualifiers);
1888 }
1889
1890 // (clang extension)
1891 //
1892 // type(^)(T)
1893 // T(^)()
1894 // T(^)(T)
1895 case Type::BlockPointer: {
1896 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1897 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
1898
1899 if (!BlockPtrArg)
1900 return Sema::TDK_NonDeducedMismatch;
1901
1902 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1903 BlockPtrParam->getPointeeType(),
1904 BlockPtrArg->getPointeeType(),
1905 Info, Deduced, 0);
1906 }
1907
1908 // (clang extension)
1909 //
1910 // T __attribute__(((ext_vector_type(<integral constant>))))
1911 case Type::ExtVector: {
1912 const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1913 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1914 // Make sure that the vectors have the same number of elements.
1915 if (VectorParam->getNumElements() != VectorArg->getNumElements())
1916 return Sema::TDK_NonDeducedMismatch;
1917
1918 // Perform deduction on the element types.
1919 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1920 VectorParam->getElementType(),
1921 VectorArg->getElementType(),
1922 Info, Deduced, TDF);
1923 }
1924
1925 if (const DependentSizedExtVectorType *VectorArg
1926 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1927 // We can't check the number of elements, since the argument has a
1928 // dependent number of elements. This can only occur during partial
1929 // ordering.
1930
1931 // Perform deduction on the element types.
1932 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1933 VectorParam->getElementType(),
1934 VectorArg->getElementType(),
1935 Info, Deduced, TDF);
1936 }
1937
1938 return Sema::TDK_NonDeducedMismatch;
1939 }
1940
1941 case Type::DependentVector: {
1942 const auto *VectorParam = cast<DependentVectorType>(Param);
1943
1944 if (const auto *VectorArg = dyn_cast<VectorType>(Arg)) {
1945 // Perform deduction on the element types.
1946 if (Sema::TemplateDeductionResult Result =
1947 DeduceTemplateArgumentsByTypeMatch(
1948 S, TemplateParams, VectorParam->getElementType(),
1949 VectorArg->getElementType(), Info, Deduced, TDF))
1950 return Result;
1951
1952 // Perform deduction on the vector size, if we can.
1953 NonTypeTemplateParmDecl *NTTP =
1954 getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
1955 if (!NTTP)
1956 return Sema::TDK_Success;
1957
1958 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1959 ArgSize = VectorArg->getNumElements();
1960 // Note that we use the "array bound" rules here; just like in that
1961 // case, we don't have any particular type for the vector size, but
1962 // we can provide one if necessary.
1963 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
1964 S.Context.UnsignedIntTy, true,
1965 Info, Deduced);
1966 }
1967
1968 if (const auto *VectorArg = dyn_cast<DependentVectorType>(Arg)) {
1969 // Perform deduction on the element types.
1970 if (Sema::TemplateDeductionResult Result =
1971 DeduceTemplateArgumentsByTypeMatch(
1972 S, TemplateParams, VectorParam->getElementType(),
1973 VectorArg->getElementType(), Info, Deduced, TDF))
1974 return Result;
1975
1976 // Perform deduction on the vector size, if we can.
1977 NonTypeTemplateParmDecl *NTTP = getDeducedParameterFromExpr(
1978 Info, VectorParam->getSizeExpr());
1979 if (!NTTP)
1980 return Sema::TDK_Success;
1981
1982 return DeduceNonTypeTemplateArgument(
1983 S, TemplateParams, NTTP, VectorArg->getSizeExpr(), Info, Deduced);
1984 }
1985
1986 return Sema::TDK_NonDeducedMismatch;
1987 }
1988
1989 // (clang extension)
1990 //
1991 // T __attribute__(((ext_vector_type(N))))
1992 case Type::DependentSizedExtVector: {
1993 const DependentSizedExtVectorType *VectorParam
1994 = cast<DependentSizedExtVectorType>(Param);
1995
1996 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1997 // Perform deduction on the element types.
1998 if (Sema::TemplateDeductionResult Result
1999 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
2000 VectorParam->getElementType(),
2001 VectorArg->getElementType(),
2002 Info, Deduced, TDF))
2003 return Result;
2004
2005 // Perform deduction on the vector size, if we can.
2006 NonTypeTemplateParmDecl *NTTP
2007 = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
2008 if (!NTTP)
2009 return Sema::TDK_Success;
2010
2011 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2012 ArgSize = VectorArg->getNumElements();
2013 // Note that we use the "array bound" rules here; just like in that
2014 // case, we don't have any particular type for the vector size, but
2015 // we can provide one if necessary.
2016 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
2017 S.Context.IntTy, true, Info,
2018 Deduced);
2019 }
2020
2021 if (const DependentSizedExtVectorType *VectorArg
2022 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
2023 // Perform deduction on the element types.
2024 if (Sema::TemplateDeductionResult Result
2025 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
2026 VectorParam->getElementType(),
2027 VectorArg->getElementType(),
2028 Info, Deduced, TDF))
2029 return Result;
2030
2031 // Perform deduction on the vector size, if we can.
2032 NonTypeTemplateParmDecl *NTTP
2033 = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
2034 if (!NTTP)
2035 return Sema::TDK_Success;
2036
2037 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2038 VectorArg->getSizeExpr(),
2039 Info, Deduced);
2040 }
2041
2042 return Sema::TDK_NonDeducedMismatch;
2043 }
2044
2045 // (clang extension)
2046 //
2047 // T __attribute__(((address_space(N))))
2048 case Type::DependentAddressSpace: {
2049 const DependentAddressSpaceType *AddressSpaceParam =
2050 cast<DependentAddressSpaceType>(Param);
2051
2052 if (const DependentAddressSpaceType *AddressSpaceArg =
2053 dyn_cast<DependentAddressSpaceType>(Arg)) {
2054 // Perform deduction on the pointer type.
2055 if (Sema::TemplateDeductionResult Result =
2056 DeduceTemplateArgumentsByTypeMatch(
2057 S, TemplateParams, AddressSpaceParam->getPointeeType(),
2058 AddressSpaceArg->getPointeeType(), Info, Deduced, TDF))
2059 return Result;
2060
2061 // Perform deduction on the address space, if we can.
2062 NonTypeTemplateParmDecl *NTTP = getDeducedParameterFromExpr(
2063 Info, AddressSpaceParam->getAddrSpaceExpr());
2064 if (!NTTP)
2065 return Sema::TDK_Success;
2066
2067 return DeduceNonTypeTemplateArgument(
2068 S, TemplateParams, NTTP, AddressSpaceArg->getAddrSpaceExpr(), Info,
2069 Deduced);
2070 }
2071
2072 if (isTargetAddressSpace(Arg.getAddressSpace())) {
2073 llvm::APSInt ArgAddressSpace(S.Context.getTypeSize(S.Context.IntTy),
2074 false);
2075 ArgAddressSpace = toTargetAddressSpace(Arg.getAddressSpace());
2076
2077 // Perform deduction on the pointer types.
2078 if (Sema::TemplateDeductionResult Result =
2079 DeduceTemplateArgumentsByTypeMatch(
2080 S, TemplateParams, AddressSpaceParam->getPointeeType(),
2081 S.Context.removeAddrSpaceQualType(Arg), Info, Deduced, TDF))
2082 return Result;
2083
2084 // Perform deduction on the address space, if we can.
2085 NonTypeTemplateParmDecl *NTTP = getDeducedParameterFromExpr(
2086 Info, AddressSpaceParam->getAddrSpaceExpr());
2087 if (!NTTP)
2088 return Sema::TDK_Success;
2089
2090 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2091 ArgAddressSpace, S.Context.IntTy,
2092 true, Info, Deduced);
2093 }
2094
2095 return Sema::TDK_NonDeducedMismatch;
2096 }
2097
2098 case Type::TypeOfExpr:
2099 case Type::TypeOf:
2100 case Type::DependentName:
2101 case Type::UnresolvedUsing:
2102 case Type::Decltype:
2103 case Type::UnaryTransform:
2104 case Type::Auto:
2105 case Type::DeducedTemplateSpecialization:
2106 case Type::DependentTemplateSpecialization:
2107 case Type::PackExpansion:
2108 case Type::Pipe:
2109 // No template argument deduction for these types
2110 return Sema::TDK_Success;
2111 }
2112
2113 llvm_unreachable("Invalid Type Class!")::llvm::llvm_unreachable_internal("Invalid Type Class!", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 2113)
;
2114}
2115
2116static Sema::TemplateDeductionResult
2117DeduceTemplateArguments(Sema &S,
2118 TemplateParameterList *TemplateParams,
2119 const TemplateArgument &Param,
2120 TemplateArgument Arg,
2121 TemplateDeductionInfo &Info,
2122 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
2123 // If the template argument is a pack expansion, perform template argument
2124 // deduction against the pattern of that expansion. This only occurs during
2125 // partial ordering.
2126 if (Arg.isPackExpansion())
2127 Arg = Arg.getPackExpansionPattern();
2128
2129 switch (Param.getKind()) {
2130 case TemplateArgument::Null:
2131 llvm_unreachable("Null template argument in parameter list")::llvm::llvm_unreachable_internal("Null template argument in parameter list"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 2131)
;
2132
2133 case TemplateArgument::Type:
2134 if (Arg.getKind() == TemplateArgument::Type)
2135 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
2136 Param.getAsType(),
2137 Arg.getAsType(),
2138 Info, Deduced, 0);
2139 Info.FirstArg = Param;
2140 Info.SecondArg = Arg;
2141 return Sema::TDK_NonDeducedMismatch;
2142
2143 case TemplateArgument::Template:
2144 if (Arg.getKind() == TemplateArgument::Template)
2145 return DeduceTemplateArguments(S, TemplateParams,
2146 Param.getAsTemplate(),
2147 Arg.getAsTemplate(), Info, Deduced);
2148 Info.FirstArg = Param;
2149 Info.SecondArg = Arg;
2150 return Sema::TDK_NonDeducedMismatch;
2151
2152 case TemplateArgument::TemplateExpansion:
2153 llvm_unreachable("caller should handle pack expansions")::llvm::llvm_unreachable_internal("caller should handle pack expansions"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 2153)
;
2154
2155 case TemplateArgument::Declaration:
2156 if (Arg.getKind() == TemplateArgument::Declaration &&
2157 isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()))
2158 return Sema::TDK_Success;
2159
2160 Info.FirstArg = Param;
2161 Info.SecondArg = Arg;
2162 return Sema::TDK_NonDeducedMismatch;
2163
2164 case TemplateArgument::NullPtr:
2165 if (Arg.getKind() == TemplateArgument::NullPtr &&
2166 S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType()))
2167 return Sema::TDK_Success;
2168
2169 Info.FirstArg = Param;
2170 Info.SecondArg = Arg;
2171 return Sema::TDK_NonDeducedMismatch;
2172
2173 case TemplateArgument::Integral:
2174 if (Arg.getKind() == TemplateArgument::Integral) {
2175 if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral()))
2176 return Sema::TDK_Success;
2177
2178 Info.FirstArg = Param;
2179 Info.SecondArg = Arg;
2180 return Sema::TDK_NonDeducedMismatch;
2181 }
2182
2183 if (Arg.getKind() == TemplateArgument::Expression) {
2184 Info.FirstArg = Param;
2185 Info.SecondArg = Arg;
2186 return Sema::TDK_NonDeducedMismatch;
2187 }
2188
2189 Info.FirstArg = Param;
2190 Info.SecondArg = Arg;
2191 return Sema::TDK_NonDeducedMismatch;
2192
2193 case TemplateArgument::Expression:
2194 if (NonTypeTemplateParmDecl *NTTP
2195 = getDeducedParameterFromExpr(Info, Param.getAsExpr())) {
2196 if (Arg.getKind() == TemplateArgument::Integral)
2197 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2198 Arg.getAsIntegral(),
2199 Arg.getIntegralType(),
2200 /*ArrayBound=*/false,
2201 Info, Deduced);
2202 if (Arg.getKind() == TemplateArgument::NullPtr)
2203 return DeduceNullPtrTemplateArgument(S, TemplateParams, NTTP,
2204 Arg.getNullPtrType(),
2205 Info, Deduced);
2206 if (Arg.getKind() == TemplateArgument::Expression)
2207 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2208 Arg.getAsExpr(), Info, Deduced);
2209 if (Arg.getKind() == TemplateArgument::Declaration)
2210 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2211 Arg.getAsDecl(),
2212 Arg.getParamTypeForDecl(),
2213 Info, Deduced);
2214
2215 Info.FirstArg = Param;
2216 Info.SecondArg = Arg;
2217 return Sema::TDK_NonDeducedMismatch;
2218 }
2219
2220 // Can't deduce anything, but that's okay.
2221 return Sema::TDK_Success;
2222
2223 case TemplateArgument::Pack:
2224 llvm_unreachable("Argument packs should be expanded by the caller!")::llvm::llvm_unreachable_internal("Argument packs should be expanded by the caller!"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 2224)
;
2225 }
2226
2227 llvm_unreachable("Invalid TemplateArgument Kind!")::llvm::llvm_unreachable_internal("Invalid TemplateArgument Kind!"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 2227)
;
2228}
2229
2230/// Determine whether there is a template argument to be used for
2231/// deduction.
2232///
2233/// This routine "expands" argument packs in-place, overriding its input
2234/// parameters so that \c Args[ArgIdx] will be the available template argument.
2235///
2236/// \returns true if there is another template argument (which will be at
2237/// \c Args[ArgIdx]), false otherwise.
2238static bool hasTemplateArgumentForDeduction(ArrayRef<TemplateArgument> &Args,
2239 unsigned &ArgIdx) {
2240 if (ArgIdx == Args.size())
2241 return false;
2242
2243 const TemplateArgument &Arg = Args[ArgIdx];
2244 if (Arg.getKind() != TemplateArgument::Pack)
2245 return true;
2246
2247 assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?")((ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?"
) ? static_cast<void> (0) : __assert_fail ("ArgIdx == Args.size() - 1 && \"Pack not at the end of argument list?\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 2247, __PRETTY_FUNCTION__))
;
2248 Args = Arg.pack_elements();
2249 ArgIdx = 0;
2250 return ArgIdx < Args.size();
2251}
2252
2253/// Determine whether the given set of template arguments has a pack
2254/// expansion that is not the last template argument.
2255static bool hasPackExpansionBeforeEnd(ArrayRef<TemplateArgument> Args) {
2256 bool FoundPackExpansion = false;
2257 for (const auto &A : Args) {
2258 if (FoundPackExpansion)
2259 return true;
2260
2261 if (A.getKind() == TemplateArgument::Pack)
2262 return hasPackExpansionBeforeEnd(A.pack_elements());
2263
2264 // FIXME: If this is a fixed-arity pack expansion from an outer level of
2265 // templates, it should not be treated as a pack expansion.
2266 if (A.isPackExpansion())
2267 FoundPackExpansion = true;
2268 }
2269
2270 return false;
2271}
2272
2273static Sema::TemplateDeductionResult
2274DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
2275 ArrayRef<TemplateArgument> Params,
2276 ArrayRef<TemplateArgument> Args,
2277 TemplateDeductionInfo &Info,
2278 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2279 bool NumberOfArgumentsMustMatch) {
2280 // C++0x [temp.deduct.type]p9:
2281 // If the template argument list of P contains a pack expansion that is not
2282 // the last template argument, the entire template argument list is a
2283 // non-deduced context.
2284 if (hasPackExpansionBeforeEnd(Params))
2285 return Sema::TDK_Success;
2286
2287 // C++0x [temp.deduct.type]p9:
2288 // If P has a form that contains <T> or <i>, then each argument Pi of the
2289 // respective template argument list P is compared with the corresponding
2290 // argument Ai of the corresponding template argument list of A.
2291 unsigned ArgIdx = 0, ParamIdx = 0;
2292 for (; hasTemplateArgumentForDeduction(Params, ParamIdx); ++ParamIdx) {
2293 if (!Params[ParamIdx].isPackExpansion()) {
2294 // The simple case: deduce template arguments by matching Pi and Ai.
2295
2296 // Check whether we have enough arguments.
2297 if (!hasTemplateArgumentForDeduction(Args, ArgIdx))
2298 return NumberOfArgumentsMustMatch
2299 ? Sema::TDK_MiscellaneousDeductionFailure
2300 : Sema::TDK_Success;
2301
2302 // C++1z [temp.deduct.type]p9:
2303 // During partial ordering, if Ai was originally a pack expansion [and]
2304 // Pi is not a pack expansion, template argument deduction fails.
2305 if (Args[ArgIdx].isPackExpansion())
2306 return Sema::TDK_MiscellaneousDeductionFailure;
2307
2308 // Perform deduction for this Pi/Ai pair.
2309 if (Sema::TemplateDeductionResult Result
2310 = DeduceTemplateArguments(S, TemplateParams,
2311 Params[ParamIdx], Args[ArgIdx],
2312 Info, Deduced))
2313 return Result;
2314
2315 // Move to the next argument.
2316 ++ArgIdx;
2317 continue;
2318 }
2319
2320 // The parameter is a pack expansion.
2321
2322 // C++0x [temp.deduct.type]p9:
2323 // If Pi is a pack expansion, then the pattern of Pi is compared with
2324 // each remaining argument in the template argument list of A. Each
2325 // comparison deduces template arguments for subsequent positions in the
2326 // template parameter packs expanded by Pi.
2327 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
2328
2329 // Prepare to deduce the packs within the pattern.
2330 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
2331
2332 // Keep track of the deduced template arguments for each parameter pack
2333 // expanded by this pack expansion (the outer index) and for each
2334 // template argument (the inner SmallVectors).
2335 for (; hasTemplateArgumentForDeduction(Args, ArgIdx) &&
2336 PackScope.hasNextElement();
2337 ++ArgIdx) {
2338 // Deduce template arguments from the pattern.
2339 if (Sema::TemplateDeductionResult Result
2340 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
2341 Info, Deduced))
2342 return Result;
2343
2344 PackScope.nextPackElement();
2345 }
2346
2347 // Build argument packs for each of the parameter packs expanded by this
2348 // pack expansion.
2349 if (auto Result = PackScope.finish())
2350 return Result;
2351 }
2352
2353 return Sema::TDK_Success;
2354}
2355
2356static Sema::TemplateDeductionResult
2357DeduceTemplateArguments(Sema &S,
2358 TemplateParameterList *TemplateParams,
2359 const TemplateArgumentList &ParamList,
2360 const TemplateArgumentList &ArgList,
2361 TemplateDeductionInfo &Info,
2362 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
2363 return DeduceTemplateArguments(S, TemplateParams, ParamList.asArray(),
2364 ArgList.asArray(), Info, Deduced,
2365 /*NumberOfArgumentsMustMatch*/false);
2366}
2367
2368/// Determine whether two template arguments are the same.
2369static bool isSameTemplateArg(ASTContext &Context,
2370 TemplateArgument X,
2371 const TemplateArgument &Y,
2372 bool PackExpansionMatchesPack = false) {
2373 // If we're checking deduced arguments (X) against original arguments (Y),
2374 // we will have flattened packs to non-expansions in X.
2375 if (PackExpansionMatchesPack && X.isPackExpansion() && !Y.isPackExpansion())
2376 X = X.getPackExpansionPattern();
2377
2378 if (X.getKind() != Y.getKind())
2379 return false;
2380
2381 switch (X.getKind()) {
2382 case TemplateArgument::Null:
2383 llvm_unreachable("Comparing NULL template argument")::llvm::llvm_unreachable_internal("Comparing NULL template argument"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 2383)
;
2384
2385 case TemplateArgument::Type:
2386 return Context.getCanonicalType(X.getAsType()) ==
2387 Context.getCanonicalType(Y.getAsType());
2388
2389 case TemplateArgument::Declaration:
2390 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
2391
2392 case TemplateArgument::NullPtr:
2393 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
2394
2395 case TemplateArgument::Template:
2396 case TemplateArgument::TemplateExpansion:
2397 return Context.getCanonicalTemplateName(
2398 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
2399 Context.getCanonicalTemplateName(
2400 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
2401
2402 case TemplateArgument::Integral:
2403 return hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral());
2404
2405 case TemplateArgument::Expression: {
2406 llvm::FoldingSetNodeID XID, YID;
2407 X.getAsExpr()->Profile(XID, Context, true);
2408 Y.getAsExpr()->Profile(YID, Context, true);
2409 return XID == YID;
2410 }
2411
2412 case TemplateArgument::Pack:
2413 if (X.pack_size() != Y.pack_size())
2414 return false;
2415
2416 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
2417 XPEnd = X.pack_end(),
2418 YP = Y.pack_begin();
2419 XP != XPEnd; ++XP, ++YP)
2420 if (!isSameTemplateArg(Context, *XP, *YP, PackExpansionMatchesPack))
2421 return false;
2422
2423 return true;
2424 }
2425
2426 llvm_unreachable("Invalid TemplateArgument Kind!")::llvm::llvm_unreachable_internal("Invalid TemplateArgument Kind!"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 2426)
;
2427}
2428
2429/// Allocate a TemplateArgumentLoc where all locations have
2430/// been initialized to the given location.
2431///
2432/// \param Arg The template argument we are producing template argument
2433/// location information for.
2434///
2435/// \param NTTPType For a declaration template argument, the type of
2436/// the non-type template parameter that corresponds to this template
2437/// argument. Can be null if no type sugar is available to add to the
2438/// type from the template argument.
2439///
2440/// \param Loc The source location to use for the resulting template
2441/// argument.
2442TemplateArgumentLoc
2443Sema::getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
2444 QualType NTTPType, SourceLocation Loc) {
2445 switch (Arg.getKind()) {
2446 case TemplateArgument::Null:
2447 llvm_unreachable("Can't get a NULL template argument here")::llvm::llvm_unreachable_internal("Can't get a NULL template argument here"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 2447)
;
2448
2449 case TemplateArgument::Type:
2450 return TemplateArgumentLoc(
2451 Arg, Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
2452
2453 case TemplateArgument::Declaration: {
2454 if (NTTPType.isNull())
2455 NTTPType = Arg.getParamTypeForDecl();
2456 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2457 .getAs<Expr>();
2458 return TemplateArgumentLoc(TemplateArgument(E), E);
2459 }
2460
2461 case TemplateArgument::NullPtr: {
2462 if (NTTPType.isNull())
2463 NTTPType = Arg.getNullPtrType();
2464 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2465 .getAs<Expr>();
2466 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2467 E);
2468 }
2469
2470 case TemplateArgument::Integral: {
2471 Expr *E =
2472 BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>();
2473 return TemplateArgumentLoc(TemplateArgument(E), E);
2474 }
2475
2476 case TemplateArgument::Template:
2477 case TemplateArgument::TemplateExpansion: {
2478 NestedNameSpecifierLocBuilder Builder;
2479 TemplateName Template = Arg.getAsTemplate();
2480 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
2481 Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
2482 else if (QualifiedTemplateName *QTN =
2483 Template.getAsQualifiedTemplateName())
2484 Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
2485
2486 if (Arg.getKind() == TemplateArgument::Template)
2487 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
2488 Loc);
2489
2490 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
2491 Loc, Loc);
2492 }
2493
2494 case TemplateArgument::Expression:
2495 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
2496
2497 case TemplateArgument::Pack:
2498 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
2499 }
2500
2501 llvm_unreachable("Invalid TemplateArgument Kind!")::llvm::llvm_unreachable_internal("Invalid TemplateArgument Kind!"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 2501)
;
2502}
2503
2504/// Convert the given deduced template argument and add it to the set of
2505/// fully-converted template arguments.
2506static bool
2507ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
2508 DeducedTemplateArgument Arg,
2509 NamedDecl *Template,
2510 TemplateDeductionInfo &Info,
2511 bool IsDeduced,
2512 SmallVectorImpl<TemplateArgument> &Output) {
2513 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2514 unsigned ArgumentPackIndex) {
2515 // Convert the deduced template argument into a template
2516 // argument that we can check, almost as if the user had written
2517 // the template argument explicitly.
2518 TemplateArgumentLoc ArgLoc =
2519 S.getTrivialTemplateArgumentLoc(Arg, QualType(), Info.getLocation());
2520
2521 // Check the template argument, converting it as necessary.
2522 return S.CheckTemplateArgument(
2523 Param, ArgLoc, Template, Template->getLocation(),
2524 Template->getSourceRange().getEnd(), ArgumentPackIndex, Output,
2525 IsDeduced
2526 ? (Arg.wasDeducedFromArrayBound() ? Sema::CTAK_DeducedFromArrayBound
2527 : Sema::CTAK_Deduced)
2528 : Sema::CTAK_Specified);
2529 };
2530
2531 if (Arg.getKind() == TemplateArgument::Pack) {
2532 // This is a template argument pack, so check each of its arguments against
2533 // the template parameter.
2534 SmallVector<TemplateArgument, 2> PackedArgsBuilder;
2535 for (const auto &P : Arg.pack_elements()) {
2536 // When converting the deduced template argument, append it to the
2537 // general output list. We need to do this so that the template argument
2538 // checking logic has all of the prior template arguments available.
2539 DeducedTemplateArgument InnerArg(P);
2540 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
2541 assert(InnerArg.getKind() != TemplateArgument::Pack &&((InnerArg.getKind() != TemplateArgument::Pack && "deduced nested pack"
) ? static_cast<void> (0) : __assert_fail ("InnerArg.getKind() != TemplateArgument::Pack && \"deduced nested pack\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 2542, __PRETTY_FUNCTION__))
2542 "deduced nested pack")((InnerArg.getKind() != TemplateArgument::Pack && "deduced nested pack"
) ? static_cast<void> (0) : __assert_fail ("InnerArg.getKind() != TemplateArgument::Pack && \"deduced nested pack\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 2542, __PRETTY_FUNCTION__))
;
2543 if (P.isNull()) {
2544 // We deduced arguments for some elements of this pack, but not for
2545 // all of them. This happens if we get a conditionally-non-deduced
2546 // context in a pack expansion (such as an overload set in one of the
2547 // arguments).
2548 S.Diag(Param->getLocation(),
2549 diag::err_template_arg_deduced_incomplete_pack)
2550 << Arg << Param;
2551 return true;
2552 }
2553 if (ConvertArg(InnerArg, PackedArgsBuilder.size()))
2554 return true;
2555
2556 // Move the converted template argument into our argument pack.
2557 PackedArgsBuilder.push_back(Output.pop_back_val());
2558 }
2559
2560 // If the pack is empty, we still need to substitute into the parameter
2561 // itself, in case that substitution fails.
2562 if (PackedArgsBuilder.empty()) {
2563 LocalInstantiationScope Scope(S);
2564 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Output);
2565 MultiLevelTemplateArgumentList Args(TemplateArgs);
2566
2567 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2568 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2569 NTTP, Output,
2570 Template->getSourceRange());
2571 if (Inst.isInvalid() ||
2572 S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
2573 NTTP->getDeclName()).isNull())
2574 return true;
2575 } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
2576 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2577 TTP, Output,
2578 Template->getSourceRange());
2579 if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
2580 return true;
2581 }
2582 // For type parameters, no substitution is ever required.
2583 }
2584
2585 // Create the resulting argument pack.
2586 Output.push_back(
2587 TemplateArgument::CreatePackCopy(S.Context, PackedArgsBuilder));
2588 return false;
2589 }
2590
2591 return ConvertArg(Arg, 0);
2592}
2593
2594// FIXME: This should not be a template, but
2595// ClassTemplatePartialSpecializationDecl sadly does not derive from
2596// TemplateDecl.
2597template<typename TemplateDeclT>
2598static Sema::TemplateDeductionResult ConvertDeducedTemplateArguments(
2599 Sema &S, TemplateDeclT *Template, bool IsDeduced,
2600 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2601 TemplateDeductionInfo &Info, SmallVectorImpl<TemplateArgument> &Builder,
2602 LocalInstantiationScope *CurrentInstantiationScope = nullptr,
2603 unsigned NumAlreadyConverted = 0, bool PartialOverloading = false) {
2604 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2605
2606 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2607 NamedDecl *Param = TemplateParams->getParam(I);
2608
2609 // C++0x [temp.arg.explicit]p3:
2610 // A trailing template parameter pack (14.5.3) not otherwise deduced will
2611 // be deduced to an empty sequence of template arguments.
2612 // FIXME: Where did the word "trailing" come from?
2613 if (Deduced[I].isNull() && Param->isTemplateParameterPack()) {
2614 if (auto Result = PackDeductionScope(S, TemplateParams, Deduced, Info, I)
2615 .finish(/*TreatNoDeductionsAsNonDeduced*/false))
2616 return Result;
2617 }
2618
2619 if (!Deduced[I].isNull()) {
2620 if (I < NumAlreadyConverted) {
2621 // We may have had explicitly-specified template arguments for a
2622 // template parameter pack (that may or may not have been extended
2623 // via additional deduced arguments).
2624 if (Param->isParameterPack() && CurrentInstantiationScope &&
2625 CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) {
2626 // Forget the partially-substituted pack; its substitution is now
2627 // complete.
2628 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2629 // We still need to check the argument in case it was extended by
2630 // deduction.
2631 } else {
2632 // We have already fully type-checked and converted this
2633 // argument, because it was explicitly-specified. Just record the
2634 // presence of this argument.
2635 Builder.push_back(Deduced[I]);
2636 continue;
2637 }
2638 }
2639
2640 // We may have deduced this argument, so it still needs to be
2641 // checked and converted.
2642 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
2643 IsDeduced, Builder)) {
2644 Info.Param = makeTemplateParameter(Param);
2645 // FIXME: These template arguments are temporary. Free them!
2646 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2647 return Sema::TDK_SubstitutionFailure;
2648 }
2649
2650 continue;
2651 }
2652
2653 // Substitute into the default template argument, if available.
2654 bool HasDefaultArg = false;
2655 TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
2656 if (!TD) {
2657 assert(isa<ClassTemplatePartialSpecializationDecl>(Template) ||((isa<ClassTemplatePartialSpecializationDecl>(Template)
|| isa<VarTemplatePartialSpecializationDecl>(Template)
) ? static_cast<void> (0) : __assert_fail ("isa<ClassTemplatePartialSpecializationDecl>(Template) || isa<VarTemplatePartialSpecializationDecl>(Template)"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 2658, __PRETTY_FUNCTION__))
2658 isa<VarTemplatePartialSpecializationDecl>(Template))((isa<ClassTemplatePartialSpecializationDecl>(Template)
|| isa<VarTemplatePartialSpecializationDecl>(Template)
) ? static_cast<void> (0) : __assert_fail ("isa<ClassTemplatePartialSpecializationDecl>(Template) || isa<VarTemplatePartialSpecializationDecl>(Template)"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 2658, __PRETTY_FUNCTION__))
;
2659 return Sema::TDK_Incomplete;
2660 }
2661
2662 TemplateArgumentLoc DefArg = S.SubstDefaultTemplateArgumentIfAvailable(
2663 TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param, Builder,
2664 HasDefaultArg);
2665
2666 // If there was no default argument, deduction is incomplete.
2667 if (DefArg.getArgument().isNull()) {
2668 Info.Param = makeTemplateParameter(
2669 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2670 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2671 if (PartialOverloading) break;
2672
2673 return HasDefaultArg ? Sema::TDK_SubstitutionFailure
2674 : Sema::TDK_Incomplete;
2675 }
2676
2677 // Check whether we can actually use the default argument.
2678 if (S.CheckTemplateArgument(Param, DefArg, TD, TD->getLocation(),
2679 TD->getSourceRange().getEnd(), 0, Builder,
2680 Sema::CTAK_Specified)) {
2681 Info.Param = makeTemplateParameter(
2682 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2683 // FIXME: These template arguments are temporary. Free them!
2684 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2685 return Sema::TDK_SubstitutionFailure;
2686 }
2687
2688 // If we get here, we successfully used the default template argument.
2689 }
2690
2691 return Sema::TDK_Success;
2692}
2693
2694static DeclContext *getAsDeclContextOrEnclosing(Decl *D) {
2695 if (auto *DC = dyn_cast<DeclContext>(D))
2696 return DC;
2697 return D->getDeclContext();
2698}
2699
2700template<typename T> struct IsPartialSpecialization {
2701 static constexpr bool value = false;
2702};
2703template<>
2704struct IsPartialSpecialization<ClassTemplatePartialSpecializationDecl> {
2705 static constexpr bool value = true;
2706};
2707template<>
2708struct IsPartialSpecialization<VarTemplatePartialSpecializationDecl> {
2709 static constexpr bool value = true;
2710};
2711
2712/// Complete template argument deduction for a partial specialization.
2713template <typename T>
2714static typename std::enable_if<IsPartialSpecialization<T>::value,
2715 Sema::TemplateDeductionResult>::type
2716FinishTemplateArgumentDeduction(
2717 Sema &S, T *Partial, bool IsPartialOrdering,
2718 const TemplateArgumentList &TemplateArgs,
2719 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2720 TemplateDeductionInfo &Info) {
2721 // Unevaluated SFINAE context.
2722 EnterExpressionEvaluationContext Unevaluated(
2723 S, Sema::ExpressionEvaluationContext::Unevaluated);
2724 Sema::SFINAETrap Trap(S);
2725
2726 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Partial));
2727
2728 // C++ [temp.deduct.type]p2:
2729 // [...] or if any template argument remains neither deduced nor
2730 // explicitly specified, template argument deduction fails.
2731 SmallVector<TemplateArgument, 4> Builder;
2732 if (auto Result = ConvertDeducedTemplateArguments(
2733 S, Partial, IsPartialOrdering, Deduced, Info, Builder))
2734 return Result;
2735
2736 // Form the template argument list from the deduced template arguments.
2737 TemplateArgumentList *DeducedArgumentList
2738 = TemplateArgumentList::CreateCopy(S.Context, Builder);
2739
2740 Info.reset(DeducedArgumentList);
2741
2742 // Substitute the deduced template arguments into the template
2743 // arguments of the class template partial specialization, and
2744 // verify that the instantiated template arguments are both valid
2745 // and are equivalent to the template arguments originally provided
2746 // to the class template.
2747 LocalInstantiationScope InstScope(S);
2748 auto *Template = Partial->getSpecializedTemplate();
2749 const ASTTemplateArgumentListInfo *PartialTemplArgInfo =
2750 Partial->getTemplateArgsAsWritten();
2751 const TemplateArgumentLoc *PartialTemplateArgs =
2752 PartialTemplArgInfo->getTemplateArgs();
2753
2754 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2755 PartialTemplArgInfo->RAngleLoc);
2756
2757 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
2758 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2759 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2760 if (ParamIdx >= Partial->getTemplateParameters()->size())
2761 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2762
2763 Decl *Param = const_cast<NamedDecl *>(
2764 Partial->getTemplateParameters()->getParam(ParamIdx));
2765 Info.Param = makeTemplateParameter(Param);
2766 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2767 return Sema::TDK_SubstitutionFailure;
2768 }
2769
2770 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
2771 if (S.CheckTemplateArgumentList(Template, Partial->getLocation(), InstArgs,
2772 false, ConvertedInstArgs))
2773 return Sema::TDK_SubstitutionFailure;
2774
2775 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2776 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2777 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
2778 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
2779 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2780 Info.FirstArg = TemplateArgs[I];
2781 Info.SecondArg = InstArg;
2782 return Sema::TDK_NonDeducedMismatch;
2783 }
2784 }
2785
2786 if (Trap.hasErrorOccurred())
2787 return Sema::TDK_SubstitutionFailure;
2788
2789 return Sema::TDK_Success;
2790}
2791
2792/// Complete template argument deduction for a class or variable template,
2793/// when partial ordering against a partial specialization.
2794// FIXME: Factor out duplication with partial specialization version above.
2795static Sema::TemplateDeductionResult FinishTemplateArgumentDeduction(
2796 Sema &S, TemplateDecl *Template, bool PartialOrdering,
2797 const TemplateArgumentList &TemplateArgs,
2798 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2799 TemplateDeductionInfo &Info) {
2800 // Unevaluated SFINAE context.
2801 EnterExpressionEvaluationContext Unevaluated(
2802 S, Sema::ExpressionEvaluationContext::Unevaluated);
2803 Sema::SFINAETrap Trap(S);
2804
2805 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Template));
2806
2807 // C++ [temp.deduct.type]p2:
2808 // [...] or if any template argument remains neither deduced nor
2809 // explicitly specified, template argument deduction fails.
2810 SmallVector<TemplateArgument, 4> Builder;
2811 if (auto Result = ConvertDeducedTemplateArguments(
2812 S, Template, /*IsDeduced*/PartialOrdering, Deduced, Info, Builder))
2813 return Result;
2814
2815 // Check that we produced the correct argument list.
2816 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2817 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2818 TemplateArgument InstArg = Builder[I];
2819 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg,
2820 /*PackExpansionMatchesPack*/true)) {
2821 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2822 Info.FirstArg = TemplateArgs[I];
2823 Info.SecondArg = InstArg;
2824 return Sema::TDK_NonDeducedMismatch;
2825 }
2826 }
2827
2828 if (Trap.hasErrorOccurred())
2829 return Sema::TDK_SubstitutionFailure;
2830
2831 return Sema::TDK_Success;
2832}
2833
2834
2835/// Perform template argument deduction to determine whether
2836/// the given template arguments match the given class template
2837/// partial specialization per C++ [temp.class.spec.match].
2838Sema::TemplateDeductionResult
2839Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
2840 const TemplateArgumentList &TemplateArgs,
2841 TemplateDeductionInfo &Info) {
2842 if (Partial->isInvalidDecl())
2843 return TDK_Invalid;
2844
2845 // C++ [temp.class.spec.match]p2:
2846 // A partial specialization matches a given actual template
2847 // argument list if the template arguments of the partial
2848 // specialization can be deduced from the actual template argument
2849 // list (14.8.2).
2850
2851 // Unevaluated SFINAE context.
2852 EnterExpressionEvaluationContext Unevaluated(
2853 *this, Sema::ExpressionEvaluationContext::Unevaluated);
2854 SFINAETrap Trap(*this);
2855
2856 SmallVector<DeducedTemplateArgument, 4> Deduced;
2857 Deduced.resize(Partial->getTemplateParameters()->size());
2858 if (TemplateDeductionResult Result
2859 = ::DeduceTemplateArguments(*this,
2860 Partial->getTemplateParameters(),
2861 Partial->getTemplateArgs(),
2862 TemplateArgs, Info, Deduced))
2863 return Result;
2864
2865 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
2866 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2867 Info);
2868 if (Inst.isInvalid())
2869 return TDK_InstantiationDepth;
2870
2871 if (Trap.hasErrorOccurred())
2872 return Sema::TDK_SubstitutionFailure;
2873
2874 return ::FinishTemplateArgumentDeduction(
2875 *this, Partial, /*IsPartialOrdering=*/false, TemplateArgs, Deduced, Info);
2876}
2877
2878/// Perform template argument deduction to determine whether
2879/// the given template arguments match the given variable template
2880/// partial specialization per C++ [temp.class.spec.match].
2881Sema::TemplateDeductionResult
2882Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
2883 const TemplateArgumentList &TemplateArgs,
2884 TemplateDeductionInfo &Info) {
2885 if (Partial->isInvalidDecl())
2886 return TDK_Invalid;
2887
2888 // C++ [temp.class.spec.match]p2:
2889 // A partial specialization matches a given actual template
2890 // argument list if the template arguments of the partial
2891 // specialization can be deduced from the actual template argument
2892 // list (14.8.2).
2893
2894 // Unevaluated SFINAE context.
2895 EnterExpressionEvaluationContext Unevaluated(
2896 *this, Sema::ExpressionEvaluationContext::Unevaluated);
2897 SFINAETrap Trap(*this);
2898
2899 SmallVector<DeducedTemplateArgument, 4> Deduced;
2900 Deduced.resize(Partial->getTemplateParameters()->size());
2901 if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
2902 *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
2903 TemplateArgs, Info, Deduced))
2904 return Result;
2905
2906 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
2907 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2908 Info);
2909 if (Inst.isInvalid())
2910 return TDK_InstantiationDepth;
2911
2912 if (Trap.hasErrorOccurred())
2913 return Sema::TDK_SubstitutionFailure;
2914
2915 return ::FinishTemplateArgumentDeduction(
2916 *this, Partial, /*IsPartialOrdering=*/false, TemplateArgs, Deduced, Info);
2917}
2918
2919/// Determine whether the given type T is a simple-template-id type.
2920static bool isSimpleTemplateIdType(QualType T) {
2921 if (const TemplateSpecializationType *Spec
2922 = T->getAs<TemplateSpecializationType>())
2923 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
2924
2925 // C++17 [temp.local]p2:
2926 // the injected-class-name [...] is equivalent to the template-name followed
2927 // by the template-arguments of the class template specialization or partial
2928 // specialization enclosed in <>
2929 // ... which means it's equivalent to a simple-template-id.
2930 //
2931 // This only arises during class template argument deduction for a copy
2932 // deduction candidate, where it permits slicing.
2933 if (T->getAs<InjectedClassNameType>())
2934 return true;
2935
2936 return false;
2937}
2938
2939/// Substitute the explicitly-provided template arguments into the
2940/// given function template according to C++ [temp.arg.explicit].
2941///
2942/// \param FunctionTemplate the function template into which the explicit
2943/// template arguments will be substituted.
2944///
2945/// \param ExplicitTemplateArgs the explicitly-specified template
2946/// arguments.
2947///
2948/// \param Deduced the deduced template arguments, which will be populated
2949/// with the converted and checked explicit template arguments.
2950///
2951/// \param ParamTypes will be populated with the instantiated function
2952/// parameters.
2953///
2954/// \param FunctionType if non-NULL, the result type of the function template
2955/// will also be instantiated and the pointed-to value will be updated with
2956/// the instantiated function type.
2957///
2958/// \param Info if substitution fails for any reason, this object will be
2959/// populated with more information about the failure.
2960///
2961/// \returns TDK_Success if substitution was successful, or some failure
2962/// condition.
2963Sema::TemplateDeductionResult
2964Sema::SubstituteExplicitTemplateArguments(
2965 FunctionTemplateDecl *FunctionTemplate,
2966 TemplateArgumentListInfo &ExplicitTemplateArgs,
2967 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2968 SmallVectorImpl<QualType> &ParamTypes,
2969 QualType *FunctionType,
2970 TemplateDeductionInfo &Info) {
2971 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2972 TemplateParameterList *TemplateParams
2973 = FunctionTemplate->getTemplateParameters();
2974
2975 if (ExplicitTemplateArgs.size() == 0) {
2976 // No arguments to substitute; just copy over the parameter types and
2977 // fill in the function type.
2978 for (auto P : Function->parameters())
2979 ParamTypes.push_back(P->getType());
2980
2981 if (FunctionType)
2982 *FunctionType = Function->getType();
2983 return TDK_Success;
2984 }
2985
2986 // Unevaluated SFINAE context.
2987 EnterExpressionEvaluationContext Unevaluated(
2988 *this, Sema::ExpressionEvaluationContext::Unevaluated);
2989 SFINAETrap Trap(*this);
2990
2991 // C++ [temp.arg.explicit]p3:
2992 // Template arguments that are present shall be specified in the
2993 // declaration order of their corresponding template-parameters. The
2994 // template argument list shall not specify more template-arguments than
2995 // there are corresponding template-parameters.
2996 SmallVector<TemplateArgument, 4> Builder;
2997
2998 // Enter a new template instantiation context where we check the
2999 // explicitly-specified template arguments against this function template,
3000 // and then substitute them into the function parameter types.
3001 SmallVector<TemplateArgument, 4> DeducedArgs;
3002 InstantiatingTemplate Inst(
3003 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3004 CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info);
3005 if (Inst.isInvalid())
3006 return TDK_InstantiationDepth;
3007
3008 if (CheckTemplateArgumentList(FunctionTemplate, SourceLocation(),
3009 ExplicitTemplateArgs, true, Builder, false) ||
3010 Trap.hasErrorOccurred()) {
3011 unsigned Index = Builder.size();
3012 if (Index >= TemplateParams->size())
3013 return TDK_SubstitutionFailure;
3014 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
3015 return TDK_InvalidExplicitArguments;
3016 }
3017
3018 // Form the template argument list from the explicitly-specified
3019 // template arguments.
3020 TemplateArgumentList *ExplicitArgumentList
3021 = TemplateArgumentList::CreateCopy(Context, Builder);
3022 Info.setExplicitArgs(ExplicitArgumentList);
3023
3024 // Template argument deduction and the final substitution should be
3025 // done in the context of the templated declaration. Explicit
3026 // argument substitution, on the other hand, needs to happen in the
3027 // calling context.
3028 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
3029
3030 // If we deduced template arguments for a template parameter pack,
3031 // note that the template argument pack is partially substituted and record
3032 // the explicit template arguments. They'll be used as part of deduction
3033 // for this template parameter pack.
3034 unsigned PartiallySubstitutedPackIndex = -1u;
3035 if (!Builder.empty()) {
3036 const TemplateArgument &Arg = Builder.back();
3037 if (Arg.getKind() == TemplateArgument::Pack) {
3038 auto *Param = TemplateParams->getParam(Builder.size() - 1);
3039 // If this is a fully-saturated fixed-size pack, it should be
3040 // fully-substituted, not partially-substituted.
3041 Optional<unsigned> Expansions = getExpandedPackSize(Param);
3042 if (!Expansions || Arg.pack_size() < *Expansions) {
3043 PartiallySubstitutedPackIndex = Builder.size() - 1;
3044 CurrentInstantiationScope->SetPartiallySubstitutedPack(
3045 Param, Arg.pack_begin(), Arg.pack_size());
3046 }
3047 }
3048 }
3049
3050 const FunctionProtoType *Proto
3051 = Function->getType()->getAs<FunctionProtoType>();
3052 assert(Proto && "Function template does not have a prototype?")((Proto && "Function template does not have a prototype?"
) ? static_cast<void> (0) : __assert_fail ("Proto && \"Function template does not have a prototype?\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 3052, __PRETTY_FUNCTION__))
;
3053
3054 // Isolate our substituted parameters from our caller.
3055 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
3056
3057 ExtParameterInfoBuilder ExtParamInfos;
3058
3059 // Instantiate the types of each of the function parameters given the
3060 // explicitly-specified template arguments. If the function has a trailing
3061 // return type, substitute it after the arguments to ensure we substitute
3062 // in lexical order.
3063 if (Proto->hasTrailingReturn()) {
3064 if (SubstParmTypes(Function->getLocation(), Function->parameters(),
3065 Proto->getExtParameterInfosOrNull(),
3066 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
3067 ParamTypes, /*params*/ nullptr, ExtParamInfos))
3068 return TDK_SubstitutionFailure;
3069 }
3070
3071 // Instantiate the return type.
3072 QualType ResultType;
3073 {
3074 // C++11 [expr.prim.general]p3:
3075 // If a declaration declares a member function or member function
3076 // template of a class X, the expression this is a prvalue of type
3077 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
3078 // and the end of the function-definition, member-declarator, or
3079 // declarator.
3080 Qualifiers ThisTypeQuals;
3081 CXXRecordDecl *ThisContext = nullptr;
3082 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
3083 ThisContext = Method->getParent();
3084 ThisTypeQuals = Method->getMethodQualifiers();
3085 }
3086
3087 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
3088 getLangOpts().CPlusPlus11);
3089
3090 ResultType =
3091 SubstType(Proto->getReturnType(),
3092 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
3093 Function->getTypeSpecStartLoc(), Function->getDeclName());
3094 if (ResultType.isNull() || Trap.hasErrorOccurred())
3095 return TDK_SubstitutionFailure;
3096 // CUDA: Kernel function must have 'void' return type.
3097 if (getLangOpts().CUDA)
3098 if (Function->hasAttr<CUDAGlobalAttr>() && !ResultType->isVoidType()) {
3099 Diag(Function->getLocation(), diag::err_kern_type_not_void_return)
3100 << Function->getType() << Function->getSourceRange();
3101 return TDK_SubstitutionFailure;
3102 }
3103 }
3104
3105 // Instantiate the types of each of the function parameters given the
3106 // explicitly-specified template arguments if we didn't do so earlier.
3107 if (!Proto->hasTrailingReturn() &&
3108 SubstParmTypes(Function->getLocation(), Function->parameters(),
3109 Proto->getExtParameterInfosOrNull(),
3110 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
3111 ParamTypes, /*params*/ nullptr, ExtParamInfos))
3112 return TDK_SubstitutionFailure;
3113
3114 if (FunctionType) {
3115 auto EPI = Proto->getExtProtoInfo();
3116 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
3117
3118 // In C++1z onwards, exception specifications are part of the function type,
3119 // so substitution into the type must also substitute into the exception
3120 // specification.
3121 SmallVector<QualType, 4> ExceptionStorage;
3122 if (getLangOpts().CPlusPlus17 &&
3123 SubstExceptionSpec(
3124 Function->getLocation(), EPI.ExceptionSpec, ExceptionStorage,
3125 MultiLevelTemplateArgumentList(*ExplicitArgumentList)))
3126 return TDK_SubstitutionFailure;
3127
3128 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
3129 Function->getLocation(),
3130 Function->getDeclName(),
3131 EPI);
3132 if (FunctionType->isNull() || Trap.hasErrorOccurred())
3133 return TDK_SubstitutionFailure;
3134 }
3135
3136 // C++ [temp.arg.explicit]p2:
3137 // Trailing template arguments that can be deduced (14.8.2) may be
3138 // omitted from the list of explicit template-arguments. If all of the
3139 // template arguments can be deduced, they may all be omitted; in this
3140 // case, the empty template argument list <> itself may also be omitted.
3141 //
3142 // Take all of the explicitly-specified arguments and put them into
3143 // the set of deduced template arguments. The partially-substituted
3144 // parameter pack, however, will be set to NULL since the deduction
3145 // mechanism handles the partially-substituted argument pack directly.
3146 Deduced.reserve(TemplateParams->size());
3147 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
3148 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
3149 if (I == PartiallySubstitutedPackIndex)
3150 Deduced.push_back(DeducedTemplateArgument());
3151 else
3152 Deduced.push_back(Arg);
3153 }
3154
3155 return TDK_Success;
3156}
3157
3158/// Check whether the deduced argument type for a call to a function
3159/// template matches the actual argument type per C++ [temp.deduct.call]p4.
3160static Sema::TemplateDeductionResult
3161CheckOriginalCallArgDeduction(Sema &S, TemplateDeductionInfo &Info,
3162 Sema::OriginalCallArg OriginalArg,
3163 QualType DeducedA) {
3164 ASTContext &Context = S.Context;
3165
3166 auto Failed = [&]() -> Sema::TemplateDeductionResult {
3167 Info.FirstArg = TemplateArgument(DeducedA);
3168 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
3169 Info.CallArgIndex = OriginalArg.ArgIdx;
3170 return OriginalArg.DecomposedParam ? Sema::TDK_DeducedMismatchNested
3171 : Sema::TDK_DeducedMismatch;
3172 };
3173
3174 QualType A = OriginalArg.OriginalArgType;
3175 QualType OriginalParamType = OriginalArg.OriginalParamType;
3176
3177 // Check for type equality (top-level cv-qualifiers are ignored).
3178 if (Context.hasSameUnqualifiedType(A, DeducedA))
3179 return Sema::TDK_Success;
3180
3181 // Strip off references on the argument types; they aren't needed for
3182 // the following checks.
3183 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
3184 DeducedA = DeducedARef->getPointeeType();
3185 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
3186 A = ARef->getPointeeType();
3187
3188 // C++ [temp.deduct.call]p4:
3189 // [...] However, there are three cases that allow a difference:
3190 // - If the original P is a reference type, the deduced A (i.e., the
3191 // type referred to by the reference) can be more cv-qualified than
3192 // the transformed A.
3193 if (const ReferenceType *OriginalParamRef
3194 = OriginalParamType->getAs<ReferenceType>()) {
3195 // We don't want to keep the reference around any more.
3196 OriginalParamType = OriginalParamRef->getPointeeType();
3197
3198 // FIXME: Resolve core issue (no number yet): if the original P is a
3199 // reference type and the transformed A is function type "noexcept F",
3200 // the deduced A can be F.
3201 QualType Tmp;
3202 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA, Tmp))
3203 return Sema::TDK_Success;
3204
3205 Qualifiers AQuals = A.getQualifiers();
3206 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
3207
3208 // Under Objective-C++ ARC, the deduced type may have implicitly
3209 // been given strong or (when dealing with a const reference)
3210 // unsafe_unretained lifetime. If so, update the original
3211 // qualifiers to include this lifetime.
3212 if (S.getLangOpts().ObjCAutoRefCount &&
3213 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
3214 AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
3215 (DeducedAQuals.hasConst() &&
3216 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
3217 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
3218 }
3219
3220 if (AQuals == DeducedAQuals) {
3221 // Qualifiers match; there's nothing to do.
3222 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
3223 return Failed();
3224 } else {
3225 // Qualifiers are compatible, so have the argument type adopt the
3226 // deduced argument type's qualifiers as if we had performed the
3227 // qualification conversion.
3228 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
3229 }
3230 }
3231
3232 // - The transformed A can be another pointer or pointer to member
3233 // type that can be converted to the deduced A via a function pointer
3234 // conversion and/or a qualification conversion.
3235 //
3236 // Also allow conversions which merely strip __attribute__((noreturn)) from
3237 // function types (recursively).
3238 bool ObjCLifetimeConversion = false;
3239 QualType ResultTy;
3240 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
3241 (S.IsQualificationConversion(A, DeducedA, false,
3242 ObjCLifetimeConversion) ||
3243 S.IsFunctionConversion(A, DeducedA, ResultTy)))
3244 return Sema::TDK_Success;
3245
3246 // - If P is a class and P has the form simple-template-id, then the
3247 // transformed A can be a derived class of the deduced A. [...]
3248 // [...] Likewise, if P is a pointer to a class of the form
3249 // simple-template-id, the transformed A can be a pointer to a
3250 // derived class pointed to by the deduced A.
3251 if (const PointerType *OriginalParamPtr
3252 = OriginalParamType->getAs<PointerType>()) {
3253 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
3254 if (const PointerType *APtr = A->getAs<PointerType>()) {
3255 if (A->getPointeeType()->isRecordType()) {
3256 OriginalParamType = OriginalParamPtr->getPointeeType();
3257 DeducedA = DeducedAPtr->getPointeeType();
3258 A = APtr->getPointeeType();
3259 }
3260 }
3261 }
3262 }
3263
3264 if (Context.hasSameUnqualifiedType(A, DeducedA))
3265 return Sema::TDK_Success;
3266
3267 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
3268 S.IsDerivedFrom(Info.getLocation(), A, DeducedA))
3269 return Sema::TDK_Success;
3270
3271 return Failed();
3272}
3273
3274/// Find the pack index for a particular parameter index in an instantiation of
3275/// a function template with specific arguments.
3276///
3277/// \return The pack index for whichever pack produced this parameter, or -1
3278/// if this was not produced by a parameter. Intended to be used as the
3279/// ArgumentPackSubstitutionIndex for further substitutions.
3280// FIXME: We should track this in OriginalCallArgs so we don't need to
3281// reconstruct it here.
3282static unsigned getPackIndexForParam(Sema &S,
3283 FunctionTemplateDecl *FunctionTemplate,
3284 const MultiLevelTemplateArgumentList &Args,
3285 unsigned ParamIdx) {
3286 unsigned Idx = 0;
3287 for (auto *PD : FunctionTemplate->getTemplatedDecl()->parameters()) {
3288 if (PD->isParameterPack()) {
3289 unsigned NumExpansions =
3290 S.getNumArgumentsInExpansion(PD->getType(), Args).getValueOr(1);
3291 if (Idx + NumExpansions > ParamIdx)
3292 return ParamIdx - Idx;
3293 Idx += NumExpansions;
3294 } else {
3295 if (Idx == ParamIdx)
3296 return -1; // Not a pack expansion
3297 ++Idx;
3298 }
3299 }
3300
3301 llvm_unreachable("parameter index would not be produced from template")::llvm::llvm_unreachable_internal("parameter index would not be produced from template"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 3301)
;
3302}
3303
3304/// Finish template argument deduction for a function template,
3305/// checking the deduced template arguments for completeness and forming
3306/// the function template specialization.
3307///
3308/// \param OriginalCallArgs If non-NULL, the original call arguments against
3309/// which the deduced argument types should be compared.
3310Sema::TemplateDeductionResult Sema::FinishTemplateArgumentDeduction(
3311 FunctionTemplateDecl *FunctionTemplate,
3312 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3313 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
3314 TemplateDeductionInfo &Info,
3315 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
3316 bool PartialOverloading, llvm::function_ref<bool()> CheckNonDependent) {
3317 // Unevaluated SFINAE context.
3318 EnterExpressionEvaluationContext Unevaluated(
3319 *this, Sema::ExpressionEvaluationContext::Unevaluated);
3320 SFINAETrap Trap(*this);
3321
3322 // Enter a new template instantiation context while we instantiate the
3323 // actual function declaration.
3324 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3325 InstantiatingTemplate Inst(
3326 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3327 CodeSynthesisContext::DeducedTemplateArgumentSubstitution, Info);
3328 if (Inst.isInvalid())
3329 return TDK_InstantiationDepth;
3330
3331 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
3332
3333 // C++ [temp.deduct.type]p2:
3334 // [...] or if any template argument remains neither deduced nor
3335 // explicitly specified, template argument deduction fails.
3336 SmallVector<TemplateArgument, 4> Builder;
3337 if (auto Result = ConvertDeducedTemplateArguments(
3338 *this, FunctionTemplate, /*IsDeduced*/true, Deduced, Info, Builder,
3339 CurrentInstantiationScope, NumExplicitlySpecified,
3340 PartialOverloading))
3341 return Result;
3342
3343 // C++ [temp.deduct.call]p10: [DR1391]
3344 // If deduction succeeds for all parameters that contain
3345 // template-parameters that participate in template argument deduction,
3346 // and all template arguments are explicitly specified, deduced, or
3347 // obtained from default template arguments, remaining parameters are then
3348 // compared with the corresponding arguments. For each remaining parameter
3349 // P with a type that was non-dependent before substitution of any
3350 // explicitly-specified template arguments, if the corresponding argument
3351 // A cannot be implicitly converted to P, deduction fails.
3352 if (CheckNonDependent())
3353 return TDK_NonDependentConversionFailure;
3354
3355 // Form the template argument list from the deduced template arguments.
3356 TemplateArgumentList *DeducedArgumentList
3357 = TemplateArgumentList::CreateCopy(Context, Builder);
3358 Info.reset(DeducedArgumentList);
3359
3360 // Substitute the deduced template arguments into the function template
3361 // declaration to produce the function template specialization.
3362 DeclContext *Owner = FunctionTemplate->getDeclContext();
3363 if (FunctionTemplate->getFriendObjectKind())
3364 Owner = FunctionTemplate->getLexicalDeclContext();
3365 MultiLevelTemplateArgumentList SubstArgs(*DeducedArgumentList);
3366 Specialization = cast_or_null<FunctionDecl>(
3367 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner, SubstArgs));
3368 if (!Specialization || Specialization->isInvalidDecl())
3369 return TDK_SubstitutionFailure;
3370
3371 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==((Specialization->getPrimaryTemplate()->getCanonicalDecl
() == FunctionTemplate->getCanonicalDecl()) ? static_cast<
void> (0) : __assert_fail ("Specialization->getPrimaryTemplate()->getCanonicalDecl() == FunctionTemplate->getCanonicalDecl()"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 3372, __PRETTY_FUNCTION__))
3372 FunctionTemplate->getCanonicalDecl())((Specialization->getPrimaryTemplate()->getCanonicalDecl
() == FunctionTemplate->getCanonicalDecl()) ? static_cast<
void> (0) : __assert_fail ("Specialization->getPrimaryTemplate()->getCanonicalDecl() == FunctionTemplate->getCanonicalDecl()"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 3372, __PRETTY_FUNCTION__))
;
3373
3374 // If the template argument list is owned by the function template
3375 // specialization, release it.
3376 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
3377 !Trap.hasErrorOccurred())
3378 Info.take();
3379
3380 // There may have been an error that did not prevent us from constructing a
3381 // declaration. Mark the declaration invalid and return with a substitution
3382 // failure.
3383 if (Trap.hasErrorOccurred()) {
3384 Specialization->setInvalidDecl(true);
3385 return TDK_SubstitutionFailure;
3386 }
3387
3388 if (OriginalCallArgs) {
3389 // C++ [temp.deduct.call]p4:
3390 // In general, the deduction process attempts to find template argument
3391 // values that will make the deduced A identical to A (after the type A
3392 // is transformed as described above). [...]
3393 llvm::SmallDenseMap<std::pair<unsigned, QualType>, QualType> DeducedATypes;
3394 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
3395 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
3396
3397 auto ParamIdx = OriginalArg.ArgIdx;
3398 if (ParamIdx >= Specialization->getNumParams())
3399 // FIXME: This presumably means a pack ended up smaller than we
3400 // expected while deducing. Should this not result in deduction
3401 // failure? Can it even happen?
3402 continue;
3403
3404 QualType DeducedA;
3405 if (!OriginalArg.DecomposedParam) {
3406 // P is one of the function parameters, just look up its substituted
3407 // type.
3408 DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
3409 } else {
3410 // P is a decomposed element of a parameter corresponding to a
3411 // braced-init-list argument. Substitute back into P to find the
3412 // deduced A.
3413 QualType &CacheEntry =
3414 DeducedATypes[{ParamIdx, OriginalArg.OriginalParamType}];
3415 if (CacheEntry.isNull()) {
3416 ArgumentPackSubstitutionIndexRAII PackIndex(
3417 *this, getPackIndexForParam(*this, FunctionTemplate, SubstArgs,
3418 ParamIdx));
3419 CacheEntry =
3420 SubstType(OriginalArg.OriginalParamType, SubstArgs,
3421 Specialization->getTypeSpecStartLoc(),
3422 Specialization->getDeclName());
3423 }
3424 DeducedA = CacheEntry;
3425 }
3426
3427 if (auto TDK =
3428 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA))
3429 return TDK;
3430 }
3431 }
3432
3433 // If we suppressed any diagnostics while performing template argument
3434 // deduction, and if we haven't already instantiated this declaration,
3435 // keep track of these diagnostics. They'll be emitted if this specialization
3436 // is actually used.
3437 if (Info.diag_begin() != Info.diag_end()) {
3438 SuppressedDiagnosticsMap::iterator
3439 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
3440 if (Pos == SuppressedDiagnostics.end())
3441 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
3442 .append(Info.diag_begin(), Info.diag_end());
3443 }
3444
3445 return TDK_Success;
3446}
3447
3448/// Gets the type of a function for template-argument-deducton
3449/// purposes when it's considered as part of an overload set.
3450static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
3451 FunctionDecl *Fn) {
3452 // We may need to deduce the return type of the function now.
3453 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
3454 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
3455 return {};
3456
3457 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
3458 if (Method->isInstance()) {
3459 // An instance method that's referenced in a form that doesn't
3460 // look like a member pointer is just invalid.
3461 if (!R.HasFormOfMemberPointer)
3462 return {};
3463
3464 return S.Context.getMemberPointerType(Fn->getType(),
3465 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
3466 }
3467
3468 if (!R.IsAddressOfOperand) return Fn->getType();
3469 return S.Context.getPointerType(Fn->getType());
3470}
3471
3472/// Apply the deduction rules for overload sets.
3473///
3474/// \return the null type if this argument should be treated as an
3475/// undeduced context
3476static QualType
3477ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
3478 Expr *Arg, QualType ParamType,
3479 bool ParamWasReference) {
3480
3481 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
3482
3483 OverloadExpr *Ovl = R.Expression;
3484
3485 // C++0x [temp.deduct.call]p4
3486 unsigned TDF = 0;
3487 if (ParamWasReference)
3488 TDF |= TDF_ParamWithReferenceType;
3489 if (R.IsAddressOfOperand)
3490 TDF |= TDF_IgnoreQualifiers;
3491
3492 // C++0x [temp.deduct.call]p6:
3493 // When P is a function type, pointer to function type, or pointer
3494 // to member function type:
3495
3496 if (!ParamType->isFunctionType() &&
3497 !ParamType->isFunctionPointerType() &&
3498 !ParamType->isMemberFunctionPointerType()) {
3499 if (Ovl->hasExplicitTemplateArgs()) {
3500 // But we can still look for an explicit specialization.
3501 if (FunctionDecl *ExplicitSpec
3502 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
3503 return GetTypeOfFunction(S, R, ExplicitSpec);
3504 }
3505
3506 DeclAccessPair DAP;
3507 if (FunctionDecl *Viable =
3508 S.resolveAddressOfOnlyViableOverloadCandidate(Arg, DAP))
3509 return GetTypeOfFunction(S, R, Viable);
3510
3511 return {};
3512 }
3513
3514 // Gather the explicit template arguments, if any.
3515 TemplateArgumentListInfo ExplicitTemplateArgs;
3516 if (Ovl->hasExplicitTemplateArgs())
3517 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
3518 QualType Match;
3519 for (UnresolvedSetIterator I = Ovl->decls_begin(),
3520 E = Ovl->decls_end(); I != E; ++I) {
3521 NamedDecl *D = (*I)->getUnderlyingDecl();
3522
3523 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
3524 // - If the argument is an overload set containing one or more
3525 // function templates, the parameter is treated as a
3526 // non-deduced context.
3527 if (!Ovl->hasExplicitTemplateArgs())
3528 return {};
3529
3530 // Otherwise, see if we can resolve a function type
3531 FunctionDecl *Specialization = nullptr;
3532 TemplateDeductionInfo Info(Ovl->getNameLoc());
3533 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
3534 Specialization, Info))
3535 continue;
3536
3537 D = Specialization;
3538 }
3539
3540 FunctionDecl *Fn = cast<FunctionDecl>(D);
3541 QualType ArgType = GetTypeOfFunction(S, R, Fn);
3542 if (ArgType.isNull()) continue;
3543
3544 // Function-to-pointer conversion.
3545 if (!ParamWasReference && ParamType->isPointerType() &&
3546 ArgType->isFunctionType())
3547 ArgType = S.Context.getPointerType(ArgType);
3548
3549 // - If the argument is an overload set (not containing function
3550 // templates), trial argument deduction is attempted using each
3551 // of the members of the set. If deduction succeeds for only one
3552 // of the overload set members, that member is used as the
3553 // argument value for the deduction. If deduction succeeds for
3554 // more than one member of the overload set the parameter is
3555 // treated as a non-deduced context.
3556
3557 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
3558 // Type deduction is done independently for each P/A pair, and
3559 // the deduced template argument values are then combined.
3560 // So we do not reject deductions which were made elsewhere.
3561 SmallVector<DeducedTemplateArgument, 8>
3562 Deduced(TemplateParams->size());
3563 TemplateDeductionInfo Info(Ovl->getNameLoc());
3564 Sema::TemplateDeductionResult Result
3565 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3566 ArgType, Info, Deduced, TDF);
3567 if (Result) continue;
3568 if (!Match.isNull())
3569 return {};
3570 Match = ArgType;
3571 }
3572
3573 return Match;
3574}
3575
3576/// Perform the adjustments to the parameter and argument types
3577/// described in C++ [temp.deduct.call].
3578///
3579/// \returns true if the caller should not attempt to perform any template
3580/// argument deduction based on this P/A pair because the argument is an
3581/// overloaded function set that could not be resolved.
3582static bool AdjustFunctionParmAndArgTypesForDeduction(
3583 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
3584 QualType &ParamType, QualType &ArgType, Expr *Arg, unsigned &TDF) {
3585 // C++0x [temp.deduct.call]p3:
3586 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
3587 // are ignored for type deduction.
3588 if (ParamType.hasQualifiers())
3589 ParamType = ParamType.getUnqualifiedType();
3590
3591 // [...] If P is a reference type, the type referred to by P is
3592 // used for type deduction.
3593 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
3594 if (ParamRefType)
3595 ParamType = ParamRefType->getPointeeType();
3596
3597 // Overload sets usually make this parameter an undeduced context,
3598 // but there are sometimes special circumstances. Typically
3599 // involving a template-id-expr.
3600 if (ArgType == S.Context.OverloadTy) {
3601 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
3602 Arg, ParamType,
3603 ParamRefType != nullptr);
3604 if (ArgType.isNull())
3605 return true;
3606 }
3607
3608 if (ParamRefType) {
3609 // If the argument has incomplete array type, try to complete its type.
3610 if (ArgType->isIncompleteArrayType()) {
3611 S.completeExprArrayBound(Arg);
3612 ArgType = Arg->getType();
3613 }
3614
3615 // C++1z [temp.deduct.call]p3:
3616 // If P is a forwarding reference and the argument is an lvalue, the type
3617 // "lvalue reference to A" is used in place of A for type deduction.
3618 if (isForwardingReference(QualType(ParamRefType, 0), FirstInnerIndex) &&
3619 Arg->isLValue())
3620 ArgType = S.Context.getLValueReferenceType(ArgType);
3621 } else {
3622 // C++ [temp.deduct.call]p2:
3623 // If P is not a reference type:
3624 // - If A is an array type, the pointer type produced by the
3625 // array-to-pointer standard conversion (4.2) is used in place of
3626 // A for type deduction; otherwise,
3627 if (ArgType->isArrayType())
3628 ArgType = S.Context.getArrayDecayedType(ArgType);
3629 // - If A is a function type, the pointer type produced by the
3630 // function-to-pointer standard conversion (4.3) is used in place
3631 // of A for type deduction; otherwise,
3632 else if (ArgType->isFunctionType())
3633 ArgType = S.Context.getPointerType(ArgType);
3634 else {
3635 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
3636 // type are ignored for type deduction.
3637 ArgType = ArgType.getUnqualifiedType();
3638 }
3639 }
3640
3641 // C++0x [temp.deduct.call]p4:
3642 // In general, the deduction process attempts to find template argument
3643 // values that will make the deduced A identical to A (after the type A
3644 // is transformed as described above). [...]
3645 TDF = TDF_SkipNonDependent;
3646
3647 // - If the original P is a reference type, the deduced A (i.e., the
3648 // type referred to by the reference) can be more cv-qualified than
3649 // the transformed A.
3650 if (ParamRefType)
3651 TDF |= TDF_ParamWithReferenceType;
3652 // - The transformed A can be another pointer or pointer to member
3653 // type that can be converted to the deduced A via a qualification
3654 // conversion (4.4).
3655 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
3656 ArgType->isObjCObjectPointerType())
3657 TDF |= TDF_IgnoreQualifiers;
3658 // - If P is a class and P has the form simple-template-id, then the
3659 // transformed A can be a derived class of the deduced A. Likewise,
3660 // if P is a pointer to a class of the form simple-template-id, the
3661 // transformed A can be a pointer to a derived class pointed to by
3662 // the deduced A.
3663 if (isSimpleTemplateIdType(ParamType) ||
3664 (isa<PointerType>(ParamType) &&
3665 isSimpleTemplateIdType(
3666 ParamType->getAs<PointerType>()->getPointeeType())))
3667 TDF |= TDF_DerivedClass;
3668
3669 return false;
3670}
3671
3672static bool
3673hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
3674 QualType T);
3675
3676static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
3677 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
3678 QualType ParamType, Expr *Arg, TemplateDeductionInfo &Info,
3679 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3680 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
3681 bool DecomposedParam, unsigned ArgIdx, unsigned TDF);
3682
3683/// Attempt template argument deduction from an initializer list
3684/// deemed to be an argument in a function call.
3685static Sema::TemplateDeductionResult DeduceFromInitializerList(
3686 Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType,
3687 InitListExpr *ILE, TemplateDeductionInfo &Info,
3688 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3689 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, unsigned ArgIdx,
3690 unsigned TDF) {
3691 // C++ [temp.deduct.call]p1: (CWG 1591)
3692 // If removing references and cv-qualifiers from P gives
3693 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is
3694 // a non-empty initializer list, then deduction is performed instead for
3695 // each element of the initializer list, taking P0 as a function template
3696 // parameter type and the initializer element as its argument
3697 //
3698 // We've already removed references and cv-qualifiers here.
3699 if (!ILE->getNumInits())
3700 return Sema::TDK_Success;
3701
3702 QualType ElTy;
3703 auto *ArrTy = S.Context.getAsArrayType(AdjustedParamType);
3704 if (ArrTy)
3705 ElTy = ArrTy->getElementType();
3706 else if (!S.isStdInitializerList(AdjustedParamType, &ElTy)) {
3707 // Otherwise, an initializer list argument causes the parameter to be
3708 // considered a non-deduced context
3709 return Sema::TDK_Success;
3710 }
3711
3712 // Resolving a core issue: a braced-init-list containing any designators is
3713 // a non-deduced context.
3714 for (Expr *E : ILE->inits())
3715 if (isa<DesignatedInitExpr>(E))
3716 return Sema::TDK_Success;
3717
3718 // Deduction only needs to be done for dependent types.
3719 if (ElTy->isDependentType()) {
3720 for (Expr *E : ILE->inits()) {
3721 if (auto Result = DeduceTemplateArgumentsFromCallArgument(
3722 S, TemplateParams, 0, ElTy, E, Info, Deduced, OriginalCallArgs, true,
3723 ArgIdx, TDF))
3724 return Result;
3725 }
3726 }
3727
3728 // in the P0[N] case, if N is a non-type template parameter, N is deduced
3729 // from the length of the initializer list.
3730 if (auto *DependentArrTy = dyn_cast_or_null<DependentSizedArrayType>(ArrTy)) {
3731 // Determine the array bound is something we can deduce.
3732 if (NonTypeTemplateParmDecl *NTTP =
3733 getDeducedParameterFromExpr(Info, DependentArrTy->getSizeExpr())) {
3734 // We can perform template argument deduction for the given non-type
3735 // template parameter.
3736 // C++ [temp.deduct.type]p13:
3737 // The type of N in the type T[N] is std::size_t.
3738 QualType T = S.Context.getSizeType();
3739 llvm::APInt Size(S.Context.getIntWidth(T), ILE->getNumInits());
3740 if (auto Result = DeduceNonTypeTemplateArgument(
3741 S, TemplateParams, NTTP, llvm::APSInt(Size), T,
3742 /*ArrayBound=*/true, Info, Deduced))
3743 return Result;
3744 }
3745 }
3746
3747 return Sema::TDK_Success;
3748}
3749
3750/// Perform template argument deduction per [temp.deduct.call] for a
3751/// single parameter / argument pair.
3752static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
3753 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
3754 QualType ParamType, Expr *Arg, TemplateDeductionInfo &Info,
3755 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3756 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
3757 bool DecomposedParam, unsigned ArgIdx, unsigned TDF) {
3758 QualType ArgType = Arg->getType();
3759 QualType OrigParamType = ParamType;
3760
3761 // If P is a reference type [...]
3762 // If P is a cv-qualified type [...]
3763 if (AdjustFunctionParmAndArgTypesForDeduction(
3764 S, TemplateParams, FirstInnerIndex, ParamType, ArgType, Arg, TDF))
3765 return Sema::TDK_Success;
3766
3767 // If [...] the argument is a non-empty initializer list [...]
3768 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg))
3769 return DeduceFromInitializerList(S, TemplateParams, ParamType, ILE, Info,
3770 Deduced, OriginalCallArgs, ArgIdx, TDF);
3771
3772 // [...] the deduction process attempts to find template argument values
3773 // that will make the deduced A identical to A
3774 //
3775 // Keep track of the argument type and corresponding parameter index,
3776 // so we can check for compatibility between the deduced A and A.
3777 OriginalCallArgs.push_back(
3778 Sema::OriginalCallArg(OrigParamType, DecomposedParam, ArgIdx, ArgType));
3779 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3780 ArgType, Info, Deduced, TDF);
3781}
3782
3783/// Perform template argument deduction from a function call
3784/// (C++ [temp.deduct.call]).
3785///
3786/// \param FunctionTemplate the function template for which we are performing
3787/// template argument deduction.
3788///
3789/// \param ExplicitTemplateArgs the explicit template arguments provided
3790/// for this call.
3791///
3792/// \param Args the function call arguments
3793///
3794/// \param Specialization if template argument deduction was successful,
3795/// this will be set to the function template specialization produced by
3796/// template argument deduction.
3797///
3798/// \param Info the argument will be updated to provide additional information
3799/// about template argument deduction.
3800///
3801/// \param CheckNonDependent A callback to invoke to check conversions for
3802/// non-dependent parameters, between deduction and substitution, per DR1391.
3803/// If this returns true, substitution will be skipped and we return
3804/// TDK_NonDependentConversionFailure. The callback is passed the parameter
3805/// types (after substituting explicit template arguments).
3806///
3807/// \returns the result of template argument deduction.
3808Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3809 FunctionTemplateDecl *FunctionTemplate,
3810 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
3811 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3812 bool PartialOverloading,
3813 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent) {
3814 if (FunctionTemplate->isInvalidDecl())
3815 return TDK_Invalid;
3816
3817 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3818 unsigned NumParams = Function->getNumParams();
3819
3820 unsigned FirstInnerIndex = getFirstInnerIndex(FunctionTemplate);
3821
3822 // C++ [temp.deduct.call]p1:
3823 // Template argument deduction is done by comparing each function template
3824 // parameter type (call it P) with the type of the corresponding argument
3825 // of the call (call it A) as described below.
3826 if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading)
3827 return TDK_TooFewArguments;
3828 else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
3829 const FunctionProtoType *Proto
3830 = Function->getType()->getAs<FunctionProtoType>();
3831 if (Proto->isTemplateVariadic())
3832 /* Do nothing */;
3833 else if (!Proto->isVariadic())
3834 return TDK_TooManyArguments;
3835 }
3836
3837 // The types of the parameters from which we will perform template argument
3838 // deduction.
3839 LocalInstantiationScope InstScope(*this);
3840 TemplateParameterList *TemplateParams
3841 = FunctionTemplate->getTemplateParameters();
3842 SmallVector<DeducedTemplateArgument, 4> Deduced;
3843 SmallVector<QualType, 8> ParamTypes;
3844 unsigned NumExplicitlySpecified = 0;
3845 if (ExplicitTemplateArgs) {
3846 TemplateDeductionResult Result =
3847 SubstituteExplicitTemplateArguments(FunctionTemplate,
3848 *ExplicitTemplateArgs,
3849 Deduced,
3850 ParamTypes,
3851 nullptr,
3852 Info);
3853 if (Result)
3854 return Result;
3855
3856 NumExplicitlySpecified = Deduced.size();
3857 } else {
3858 // Just fill in the parameter types from the function declaration.
3859 for (unsigned I = 0; I != NumParams; ++I)
3860 ParamTypes.push_back(Function->getParamDecl(I)->getType());
3861 }
3862
3863 SmallVector<OriginalCallArg, 8> OriginalCallArgs;
3864
3865 // Deduce an argument of type ParamType from an expression with index ArgIdx.
3866 auto DeduceCallArgument = [&](QualType ParamType, unsigned ArgIdx) {
3867 // C++ [demp.deduct.call]p1: (DR1391)
3868 // Template argument deduction is done by comparing each function template
3869 // parameter that contains template-parameters that participate in
3870 // template argument deduction ...
3871 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3872 return Sema::TDK_Success;
3873
3874 // ... with the type of the corresponding argument
3875 return DeduceTemplateArgumentsFromCallArgument(
3876 *this, TemplateParams, FirstInnerIndex, ParamType, Args[ArgIdx], Info, Deduced,
3877 OriginalCallArgs, /*Decomposed*/false, ArgIdx, /*TDF*/ 0);
3878 };
3879
3880 // Deduce template arguments from the function parameters.
3881 Deduced.resize(TemplateParams->size());
3882 SmallVector<QualType, 8> ParamTypesForArgChecking;
3883 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(), ArgIdx = 0;
3884 ParamIdx != NumParamTypes; ++ParamIdx) {
3885 QualType ParamType = ParamTypes[ParamIdx];
3886
3887 const PackExpansionType *ParamExpansion =
3888 dyn_cast<PackExpansionType>(ParamType);
3889 if (!ParamExpansion) {
3890 // Simple case: matching a function parameter to a function argument.
3891 if (ArgIdx >= Args.size())
3892 break;
3893
3894 ParamTypesForArgChecking.push_back(ParamType);
3895 if (auto Result = DeduceCallArgument(ParamType, ArgIdx++))
3896 return Result;
3897
3898 continue;
3899 }
3900
3901 QualType ParamPattern = ParamExpansion->getPattern();
3902 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
3903 ParamPattern);
3904
3905 // C++0x [temp.deduct.call]p1:
3906 // For a function parameter pack that occurs at the end of the
3907 // parameter-declaration-list, the type A of each remaining argument of
3908 // the call is compared with the type P of the declarator-id of the
3909 // function parameter pack. Each comparison deduces template arguments
3910 // for subsequent positions in the template parameter packs expanded by
3911 // the function parameter pack. When a function parameter pack appears
3912 // in a non-deduced context [not at the end of the list], the type of
3913 // that parameter pack is never deduced.
3914 //
3915 // FIXME: The above rule allows the size of the parameter pack to change
3916 // after we skip it (in the non-deduced case). That makes no sense, so
3917 // we instead notionally deduce the pack against N arguments, where N is
3918 // the length of the explicitly-specified pack if it's expanded by the
3919 // parameter pack and 0 otherwise, and we treat each deduction as a
3920 // non-deduced context.
3921 if (ParamIdx + 1 == NumParamTypes || PackScope.hasFixedArity()) {
3922 for (; ArgIdx < Args.size() && PackScope.hasNextElement();
3923 PackScope.nextPackElement(), ++ArgIdx) {
3924 ParamTypesForArgChecking.push_back(ParamPattern);
3925 if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx))
3926 return Result;
3927 }
3928 } else {
3929 // If the parameter type contains an explicitly-specified pack that we
3930 // could not expand, skip the number of parameters notionally created
3931 // by the expansion.
3932 Optional<unsigned> NumExpansions = ParamExpansion->getNumExpansions();
3933 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
3934 for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
3935 ++I, ++ArgIdx) {
3936 ParamTypesForArgChecking.push_back(ParamPattern);
3937 // FIXME: Should we add OriginalCallArgs for these? What if the
3938 // corresponding argument is a list?
3939 PackScope.nextPackElement();
3940 }
3941 }
3942 }
3943
3944 // Build argument packs for each of the parameter packs expanded by this
3945 // pack expansion.
3946 if (auto Result = PackScope.finish())
3947 return Result;
3948 }
3949
3950 // Capture the context in which the function call is made. This is the context
3951 // that is needed when the accessibility of template arguments is checked.
3952 DeclContext *CallingCtx = CurContext;
3953
3954 return FinishTemplateArgumentDeduction(
3955 FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
3956 &OriginalCallArgs, PartialOverloading, [&, CallingCtx]() {
3957 ContextRAII SavedContext(*this, CallingCtx);
3958 return CheckNonDependent(ParamTypesForArgChecking);
3959 });
3960}
3961
3962QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
3963 QualType FunctionType,
3964 bool AdjustExceptionSpec) {
3965 if (ArgFunctionType.isNull())
8
Calling 'QualType::isNull'
14
Returning from 'QualType::isNull'
15
Taking false branch
3966 return ArgFunctionType;
3967
3968 const FunctionProtoType *FunctionTypeP =
3969 FunctionType->castAs<FunctionProtoType>();
16
The object is a 'FunctionProtoType'
3970 const FunctionProtoType *ArgFunctionTypeP =
18
'ArgFunctionTypeP' initialized to a null pointer value
3971 ArgFunctionType->getAs<FunctionProtoType>();
17
Assuming the object is not a 'FunctionProtoType'
3972
3973 FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
19
Called C++ object pointer is null
3974 bool Rebuild = false;
3975
3976 CallingConv CC = FunctionTypeP->getCallConv();
3977 if (EPI.ExtInfo.getCC() != CC) {
3978 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
3979 Rebuild = true;
3980 }
3981
3982 bool NoReturn = FunctionTypeP->getNoReturnAttr();
3983 if (EPI.ExtInfo.getNoReturn() != NoReturn) {
3984 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
3985 Rebuild = true;
3986 }
3987
3988 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
3989 ArgFunctionTypeP->hasExceptionSpec())) {
3990 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
3991 Rebuild = true;
3992 }
3993
3994 if (!Rebuild)
3995 return ArgFunctionType;
3996
3997 return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
3998 ArgFunctionTypeP->getParamTypes(), EPI);
3999}
4000
4001/// Deduce template arguments when taking the address of a function
4002/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
4003/// a template.
4004///
4005/// \param FunctionTemplate the function template for which we are performing
4006/// template argument deduction.
4007///
4008/// \param ExplicitTemplateArgs the explicitly-specified template
4009/// arguments.
4010///
4011/// \param ArgFunctionType the function type that will be used as the
4012/// "argument" type (A) when performing template argument deduction from the
4013/// function template's function type. This type may be NULL, if there is no
4014/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
4015///
4016/// \param Specialization if template argument deduction was successful,
4017/// this will be set to the function template specialization produced by
4018/// template argument deduction.
4019///
4020/// \param Info the argument will be updated to provide additional information
4021/// about template argument deduction.
4022///
4023/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
4024/// the address of a function template per [temp.deduct.funcaddr] and
4025/// [over.over]. If \c false, we are looking up a function template
4026/// specialization based on its signature, per [temp.deduct.decl].
4027///
4028/// \returns the result of template argument deduction.
4029Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
4030 FunctionTemplateDecl *FunctionTemplate,
4031 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
4032 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
4033 bool IsAddressOfFunction) {
4034 if (FunctionTemplate->isInvalidDecl())
1
Assuming the condition is false
2
Taking false branch
4035 return TDK_Invalid;
4036
4037 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4038 TemplateParameterList *TemplateParams
4039 = FunctionTemplate->getTemplateParameters();
4040 QualType FunctionType = Function->getType();
4041
4042 // Substitute any explicit template arguments.
4043 LocalInstantiationScope InstScope(*this);
4044 SmallVector<DeducedTemplateArgument, 4> Deduced;
4045 unsigned NumExplicitlySpecified = 0;
4046 SmallVector<QualType, 4> ParamTypes;
4047 if (ExplicitTemplateArgs) {
3
Assuming 'ExplicitTemplateArgs' is null
4
Taking false branch
4048 if (TemplateDeductionResult Result
4049 = SubstituteExplicitTemplateArguments(FunctionTemplate,
4050 *ExplicitTemplateArgs,
4051 Deduced, ParamTypes,
4052 &FunctionType, Info))
4053 return Result;
4054
4055 NumExplicitlySpecified = Deduced.size();
4056 }
4057
4058 // When taking the address of a function, we require convertibility of
4059 // the resulting function type. Otherwise, we allow arbitrary mismatches
4060 // of calling convention and noreturn.
4061 if (!IsAddressOfFunction)
5
Assuming 'IsAddressOfFunction' is false
6
Taking true branch
4062 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
7
Calling 'Sema::adjustCCAndNoReturn'
4063 /*AdjustExceptionSpec*/false);
4064
4065 // Unevaluated SFINAE context.
4066 EnterExpressionEvaluationContext Unevaluated(
4067 *this, Sema::ExpressionEvaluationContext::Unevaluated);
4068 SFINAETrap Trap(*this);
4069
4070 Deduced.resize(TemplateParams->size());
4071
4072 // If the function has a deduced return type, substitute it for a dependent
4073 // type so that we treat it as a non-deduced context in what follows. If we
4074 // are looking up by signature, the signature type should also have a deduced
4075 // return type, which we instead expect to exactly match.
4076 bool HasDeducedReturnType = false;
4077 if (getLangOpts().CPlusPlus14 && IsAddressOfFunction &&
4078 Function->getReturnType()->getContainedAutoType()) {
4079 FunctionType = SubstAutoType(FunctionType, Context.DependentTy);
4080 HasDeducedReturnType = true;
4081 }
4082
4083 if (!ArgFunctionType.isNull()) {
4084 unsigned TDF =
4085 TDF_TopLevelParameterTypeList | TDF_AllowCompatibleFunctionType;
4086 // Deduce template arguments from the function type.
4087 if (TemplateDeductionResult Result
4088 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
4089 FunctionType, ArgFunctionType,
4090 Info, Deduced, TDF))
4091 return Result;
4092 }
4093
4094 if (TemplateDeductionResult Result
4095 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
4096 NumExplicitlySpecified,
4097 Specialization, Info))
4098 return Result;
4099
4100 // If the function has a deduced return type, deduce it now, so we can check
4101 // that the deduced function type matches the requested type.
4102 if (HasDeducedReturnType &&
4103 Specialization->getReturnType()->isUndeducedType() &&
4104 DeduceReturnType(Specialization, Info.getLocation(), false))
4105 return TDK_MiscellaneousDeductionFailure;
4106
4107 // If the function has a dependent exception specification, resolve it now,
4108 // so we can check that the exception specification matches.
4109 auto *SpecializationFPT =
4110 Specialization->getType()->castAs<FunctionProtoType>();
4111 if (getLangOpts().CPlusPlus17 &&
4112 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
4113 !ResolveExceptionSpec(Info.getLocation(), SpecializationFPT))
4114 return TDK_MiscellaneousDeductionFailure;
4115
4116 // Adjust the exception specification of the argument to match the
4117 // substituted and resolved type we just formed. (Calling convention and
4118 // noreturn can't be dependent, so we don't actually need this for them
4119 // right now.)
4120 QualType SpecializationType = Specialization->getType();
4121 if (!IsAddressOfFunction)
4122 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
4123 /*AdjustExceptionSpec*/true);
4124
4125 // If the requested function type does not match the actual type of the
4126 // specialization with respect to arguments of compatible pointer to function
4127 // types, template argument deduction fails.
4128 if (!ArgFunctionType.isNull()) {
4129 if (IsAddressOfFunction &&
4130 !isSameOrCompatibleFunctionType(
4131 Context.getCanonicalType(SpecializationType),
4132 Context.getCanonicalType(ArgFunctionType)))
4133 return TDK_MiscellaneousDeductionFailure;
4134
4135 if (!IsAddressOfFunction &&
4136 !Context.hasSameType(SpecializationType, ArgFunctionType))
4137 return TDK_MiscellaneousDeductionFailure;
4138 }
4139
4140 return TDK_Success;
4141}
4142
4143/// Deduce template arguments for a templated conversion
4144/// function (C++ [temp.deduct.conv]) and, if successful, produce a
4145/// conversion function template specialization.
4146Sema::TemplateDeductionResult
4147Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
4148 QualType ToType,
4149 CXXConversionDecl *&Specialization,
4150 TemplateDeductionInfo &Info) {
4151 if (ConversionTemplate->isInvalidDecl())
4152 return TDK_Invalid;
4153
4154 CXXConversionDecl *ConversionGeneric
4155 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
4156
4157 QualType FromType = ConversionGeneric->getConversionType();
4158
4159 // Canonicalize the types for deduction.
4160 QualType P = Context.getCanonicalType(FromType);
4161 QualType A = Context.getCanonicalType(ToType);
4162
4163 // C++0x [temp.deduct.conv]p2:
4164 // If P is a reference type, the type referred to by P is used for
4165 // type deduction.
4166 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
4167 P = PRef->getPointeeType();
4168
4169 // C++0x [temp.deduct.conv]p4:
4170 // [...] If A is a reference type, the type referred to by A is used
4171 // for type deduction.
4172 if (const ReferenceType *ARef = A->getAs<ReferenceType>()) {
4173 A = ARef->getPointeeType();
4174 // We work around a defect in the standard here: cv-qualifiers are also
4175 // removed from P and A in this case, unless P was a reference type. This
4176 // seems to mostly match what other compilers are doing.
4177 if (!FromType->getAs<ReferenceType>()) {
4178 A = A.getUnqualifiedType();
4179 P = P.getUnqualifiedType();
4180 }
4181
4182 // C++ [temp.deduct.conv]p3:
4183 //
4184 // If A is not a reference type:
4185 } else {
4186 assert(!A->isReferenceType() && "Reference types were handled above")((!A->isReferenceType() && "Reference types were handled above"
) ? static_cast<void> (0) : __assert_fail ("!A->isReferenceType() && \"Reference types were handled above\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 4186, __PRETTY_FUNCTION__))
;
4187
4188 // - If P is an array type, the pointer type produced by the
4189 // array-to-pointer standard conversion (4.2) is used in place
4190 // of P for type deduction; otherwise,
4191 if (P->isArrayType())
4192 P = Context.getArrayDecayedType(P);
4193 // - If P is a function type, the pointer type produced by the
4194 // function-to-pointer standard conversion (4.3) is used in
4195 // place of P for type deduction; otherwise,
4196 else if (P->isFunctionType())
4197 P = Context.getPointerType(P);
4198 // - If P is a cv-qualified type, the top level cv-qualifiers of
4199 // P's type are ignored for type deduction.
4200 else
4201 P = P.getUnqualifiedType();
4202
4203 // C++0x [temp.deduct.conv]p4:
4204 // If A is a cv-qualified type, the top level cv-qualifiers of A's
4205 // type are ignored for type deduction. If A is a reference type, the type
4206 // referred to by A is used for type deduction.
4207 A = A.getUnqualifiedType();
4208 }
4209
4210 // Unevaluated SFINAE context.
4211 EnterExpressionEvaluationContext Unevaluated(
4212 *this, Sema::ExpressionEvaluationContext::Unevaluated);
4213 SFINAETrap Trap(*this);
4214
4215 // C++ [temp.deduct.conv]p1:
4216 // Template argument deduction is done by comparing the return
4217 // type of the template conversion function (call it P) with the
4218 // type that is required as the result of the conversion (call it
4219 // A) as described in 14.8.2.4.
4220 TemplateParameterList *TemplateParams
4221 = ConversionTemplate->getTemplateParameters();
4222 SmallVector<DeducedTemplateArgument, 4> Deduced;
4223 Deduced.resize(TemplateParams->size());
4224
4225 // C++0x [temp.deduct.conv]p4:
4226 // In general, the deduction process attempts to find template
4227 // argument values that will make the deduced A identical to
4228 // A. However, there are two cases that allow a difference:
4229 unsigned TDF = 0;
4230 // - If the original A is a reference type, A can be more
4231 // cv-qualified than the deduced A (i.e., the type referred to
4232 // by the reference)
4233 if (ToType->isReferenceType())
4234 TDF |= TDF_ArgWithReferenceType;
4235 // - The deduced A can be another pointer or pointer to member
4236 // type that can be converted to A via a qualification
4237 // conversion.
4238 //
4239 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
4240 // both P and A are pointers or member pointers. In this case, we
4241 // just ignore cv-qualifiers completely).
4242 if ((P->isPointerType() && A->isPointerType()) ||
4243 (P->isMemberPointerType() && A->isMemberPointerType()))
4244 TDF |= TDF_IgnoreQualifiers;
4245 if (TemplateDeductionResult Result
4246 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
4247 P, A, Info, Deduced, TDF))
4248 return Result;
4249
4250 // Create an Instantiation Scope for finalizing the operator.
4251 LocalInstantiationScope InstScope(*this);
4252 // Finish template argument deduction.
4253 FunctionDecl *ConversionSpecialized = nullptr;
4254 TemplateDeductionResult Result
4255 = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
4256 ConversionSpecialized, Info);
4257 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
4258 return Result;
4259}
4260
4261/// Deduce template arguments for a function template when there is
4262/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
4263///
4264/// \param FunctionTemplate the function template for which we are performing
4265/// template argument deduction.
4266///
4267/// \param ExplicitTemplateArgs the explicitly-specified template
4268/// arguments.
4269///
4270/// \param Specialization if template argument deduction was successful,
4271/// this will be set to the function template specialization produced by
4272/// template argument deduction.
4273///
4274/// \param Info the argument will be updated to provide additional information
4275/// about template argument deduction.
4276///
4277/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
4278/// the address of a function template in a context where we do not have a
4279/// target type, per [over.over]. If \c false, we are looking up a function
4280/// template specialization based on its signature, which only happens when
4281/// deducing a function parameter type from an argument that is a template-id
4282/// naming a function template specialization.
4283///
4284/// \returns the result of template argument deduction.
4285Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
4286 FunctionTemplateDecl *FunctionTemplate,
4287 TemplateArgumentListInfo *ExplicitTemplateArgs,
4288 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
4289 bool IsAddressOfFunction) {
4290 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
4291 QualType(), Specialization, Info,
4292 IsAddressOfFunction);
4293}
4294
4295namespace {
4296 struct DependentAuto { bool IsPack; };
4297
4298 /// Substitute the 'auto' specifier or deduced template specialization type
4299 /// specifier within a type for a given replacement type.
4300 class SubstituteDeducedTypeTransform :
4301 public TreeTransform<SubstituteDeducedTypeTransform> {
4302 QualType Replacement;
4303 bool ReplacementIsPack;
4304 bool UseTypeSugar;
4305
4306 public:
4307 SubstituteDeducedTypeTransform(Sema &SemaRef, DependentAuto DA)
4308 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef), Replacement(),
4309 ReplacementIsPack(DA.IsPack), UseTypeSugar(true) {}
4310
4311 SubstituteDeducedTypeTransform(Sema &SemaRef, QualType Replacement,
4312 bool UseTypeSugar = true)
4313 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
4314 Replacement(Replacement), ReplacementIsPack(false),
4315 UseTypeSugar(UseTypeSugar) {}
4316
4317 QualType TransformDesugared(TypeLocBuilder &TLB, DeducedTypeLoc TL) {
4318 assert(isa<TemplateTypeParmType>(Replacement) &&((isa<TemplateTypeParmType>(Replacement) && "unexpected unsugared replacement kind"
) ? static_cast<void> (0) : __assert_fail ("isa<TemplateTypeParmType>(Replacement) && \"unexpected unsugared replacement kind\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 4319, __PRETTY_FUNCTION__))
4319 "unexpected unsugared replacement kind")((isa<TemplateTypeParmType>(Replacement) && "unexpected unsugared replacement kind"
) ? static_cast<void> (0) : __assert_fail ("isa<TemplateTypeParmType>(Replacement) && \"unexpected unsugared replacement kind\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 4319, __PRETTY_FUNCTION__))
;
4320 QualType Result = Replacement;
4321 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
4322 NewTL.setNameLoc(TL.getNameLoc());
4323 return Result;
4324 }
4325
4326 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
4327 // If we're building the type pattern to deduce against, don't wrap the
4328 // substituted type in an AutoType. Certain template deduction rules
4329 // apply only when a template type parameter appears directly (and not if
4330 // the parameter is found through desugaring). For instance:
4331 // auto &&lref = lvalue;
4332 // must transform into "rvalue reference to T" not "rvalue reference to
4333 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
4334 //
4335 // FIXME: Is this still necessary?
4336 if (!UseTypeSugar)
4337 return TransformDesugared(TLB, TL);
4338
4339 QualType Result = SemaRef.Context.getAutoType(
4340 Replacement, TL.getTypePtr()->getKeyword(), Replacement.isNull(),
4341 ReplacementIsPack);
4342 auto NewTL = TLB.push<AutoTypeLoc>(Result);
4343 NewTL.setNameLoc(TL.getNameLoc());
4344 return Result;
4345 }
4346
4347 QualType TransformDeducedTemplateSpecializationType(
4348 TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
4349 if (!UseTypeSugar)
4350 return TransformDesugared(TLB, TL);
4351
4352 QualType Result = SemaRef.Context.getDeducedTemplateSpecializationType(
4353 TL.getTypePtr()->getTemplateName(),
4354 Replacement, Replacement.isNull());
4355 auto NewTL = TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
4356 NewTL.setNameLoc(TL.getNameLoc());
4357 return Result;
4358 }
4359
4360 ExprResult TransformLambdaExpr(LambdaExpr *E) {
4361 // Lambdas never need to be transformed.
4362 return E;
4363 }
4364
4365 QualType Apply(TypeLoc TL) {
4366 // Create some scratch storage for the transformed type locations.
4367 // FIXME: We're just going to throw this information away. Don't build it.
4368 TypeLocBuilder TLB;
4369 TLB.reserve(TL.getFullDataSize());
4370 return TransformType(TLB, TL);
4371 }
4372 };
4373
4374} // namespace
4375
4376Sema::DeduceAutoResult
4377Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result,
4378 Optional<unsigned> DependentDeductionDepth) {
4379 return DeduceAutoType(Type->getTypeLoc(), Init, Result,
4380 DependentDeductionDepth);
4381}
4382
4383/// Attempt to produce an informative diagostic explaining why auto deduction
4384/// failed.
4385/// \return \c true if diagnosed, \c false if not.
4386static bool diagnoseAutoDeductionFailure(Sema &S,
4387 Sema::TemplateDeductionResult TDK,
4388 TemplateDeductionInfo &Info,
4389 ArrayRef<SourceRange> Ranges) {
4390 switch (TDK) {
4391 case Sema::TDK_Inconsistent: {
4392 // Inconsistent deduction means we were deducing from an initializer list.
4393 auto D = S.Diag(Info.getLocation(), diag::err_auto_inconsistent_deduction);
4394 D << Info.FirstArg << Info.SecondArg;
4395 for (auto R : Ranges)
4396 D << R;
4397 return true;
4398 }
4399
4400 // FIXME: Are there other cases for which a custom diagnostic is more useful
4401 // than the basic "types don't match" diagnostic?
4402
4403 default:
4404 return false;
4405 }
4406}
4407
4408/// Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
4409///
4410/// Note that this is done even if the initializer is dependent. (This is
4411/// necessary to support partial ordering of templates using 'auto'.)
4412/// A dependent type will be produced when deducing from a dependent type.
4413///
4414/// \param Type the type pattern using the auto type-specifier.
4415/// \param Init the initializer for the variable whose type is to be deduced.
4416/// \param Result if type deduction was successful, this will be set to the
4417/// deduced type.
4418/// \param DependentDeductionDepth Set if we should permit deduction in
4419/// dependent cases. This is necessary for template partial ordering with
4420/// 'auto' template parameters. The value specified is the template
4421/// parameter depth at which we should perform 'auto' deduction.
4422Sema::DeduceAutoResult
4423Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result,
4424 Optional<unsigned> DependentDeductionDepth) {
4425 if (Init->getType()->isNonOverloadPlaceholderType()) {
4426 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
4427 if (NonPlaceholder.isInvalid())
4428 return DAR_FailedAlreadyDiagnosed;
4429 Init = NonPlaceholder.get();
4430 }
4431
4432 DependentAuto DependentResult = {
4433 /*.IsPack = */ (bool)Type.getAs<PackExpansionTypeLoc>()};
4434
4435 if (!DependentDeductionDepth &&
4436 (Type.getType()->isDependentType() || Init->isTypeDependent())) {
4437 Result = SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type);
4438 assert(!Result.isNull() && "substituting DependentTy can't fail")((!Result.isNull() && "substituting DependentTy can't fail"
) ? static_cast<void> (0) : __assert_fail ("!Result.isNull() && \"substituting DependentTy can't fail\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 4438, __PRETTY_FUNCTION__))
;
4439 return DAR_Succeeded;
4440 }
4441
4442 // Find the depth of template parameter to synthesize.
4443 unsigned Depth = DependentDeductionDepth.getValueOr(0);
4444
4445 // If this is a 'decltype(auto)' specifier, do the decltype dance.
4446 // Since 'decltype(auto)' can only occur at the top of the type, we
4447 // don't need to go digging for it.
4448 if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
4449 if (AT->isDecltypeAuto()) {
4450 if (isa<InitListExpr>(Init)) {
4451 Diag(Init->getBeginLoc(), diag::err_decltype_auto_initializer_list);
4452 return DAR_FailedAlreadyDiagnosed;
4453 }
4454
4455 ExprResult ER = CheckPlaceholderExpr(Init);
4456 if (ER.isInvalid())
4457 return DAR_FailedAlreadyDiagnosed;
4458 Init = ER.get();
4459 QualType Deduced = BuildDecltypeType(Init, Init->getBeginLoc(), false);
4460 if (Deduced.isNull())
4461 return DAR_FailedAlreadyDiagnosed;
4462 // FIXME: Support a non-canonical deduced type for 'auto'.
4463 Deduced = Context.getCanonicalType(Deduced);
4464 Result = SubstituteDeducedTypeTransform(*this, Deduced).Apply(Type);
4465 if (Result.isNull())
4466 return DAR_FailedAlreadyDiagnosed;
4467 return DAR_Succeeded;
4468 } else if (!getLangOpts().CPlusPlus) {
4469 if (isa<InitListExpr>(Init)) {
4470 Diag(Init->getBeginLoc(), diag::err_auto_init_list_from_c);
4471 return DAR_FailedAlreadyDiagnosed;
4472 }
4473 }
4474 }
4475
4476 SourceLocation Loc = Init->getExprLoc();
4477
4478 LocalInstantiationScope InstScope(*this);
4479
4480 // Build template<class TemplParam> void Func(FuncParam);
4481 TemplateTypeParmDecl *TemplParam = TemplateTypeParmDecl::Create(
4482 Context, nullptr, SourceLocation(), Loc, Depth, 0, nullptr, false, false);
4483 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
4484 NamedDecl *TemplParamPtr = TemplParam;
4485 FixedSizeTemplateParameterListStorage<1, false> TemplateParamsSt(
4486 Loc, Loc, TemplParamPtr, Loc, nullptr);
4487
4488 QualType FuncParam =
4489 SubstituteDeducedTypeTransform(*this, TemplArg, /*UseTypeSugar*/false)
4490 .Apply(Type);
4491 assert(!FuncParam.isNull() &&((!FuncParam.isNull() && "substituting template parameter for 'auto' failed"
) ? static_cast<void> (0) : __assert_fail ("!FuncParam.isNull() && \"substituting template parameter for 'auto' failed\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 4492, __PRETTY_FUNCTION__))
4492 "substituting template parameter for 'auto' failed")((!FuncParam.isNull() && "substituting template parameter for 'auto' failed"
) ? static_cast<void> (0) : __assert_fail ("!FuncParam.isNull() && \"substituting template parameter for 'auto' failed\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 4492, __PRETTY_FUNCTION__))
;
4493
4494 // Deduce type of TemplParam in Func(Init)
4495 SmallVector<DeducedTemplateArgument, 1> Deduced;
4496 Deduced.resize(1);
4497
4498 TemplateDeductionInfo Info(Loc, Depth);
4499
4500 // If deduction failed, don't diagnose if the initializer is dependent; it
4501 // might acquire a matching type in the instantiation.
4502 auto DeductionFailed = [&](TemplateDeductionResult TDK,
4503 ArrayRef<SourceRange> Ranges) -> DeduceAutoResult {
4504 if (Init->isTypeDependent()) {
4505 Result =
4506 SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type);
4507 assert(!Result.isNull() && "substituting DependentTy can't fail")((!Result.isNull() && "substituting DependentTy can't fail"
) ? static_cast<void> (0) : __assert_fail ("!Result.isNull() && \"substituting DependentTy can't fail\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 4507, __PRETTY_FUNCTION__))
;
4508 return DAR_Succeeded;
4509 }
4510 if (diagnoseAutoDeductionFailure(*this, TDK, Info, Ranges))
4511 return DAR_FailedAlreadyDiagnosed;
4512 return DAR_Failed;
4513 };
4514
4515 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
4516
4517 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
4518 if (InitList) {
4519 // Notionally, we substitute std::initializer_list<T> for 'auto' and deduce
4520 // against that. Such deduction only succeeds if removing cv-qualifiers and
4521 // references results in std::initializer_list<T>.
4522 if (!Type.getType().getNonReferenceType()->getAs<AutoType>())
4523 return DAR_Failed;
4524
4525 // Resolving a core issue: a braced-init-list containing any designators is
4526 // a non-deduced context.
4527 for (Expr *E : InitList->inits())
4528 if (isa<DesignatedInitExpr>(E))
4529 return DAR_Failed;
4530
4531 SourceRange DeducedFromInitRange;
4532 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
4533 Expr *Init = InitList->getInit(i);
4534
4535 if (auto TDK = DeduceTemplateArgumentsFromCallArgument(
4536 *this, TemplateParamsSt.get(), 0, TemplArg, Init,
4537 Info, Deduced, OriginalCallArgs, /*Decomposed*/ true,
4538 /*ArgIdx*/ 0, /*TDF*/ 0))
4539 return DeductionFailed(TDK, {DeducedFromInitRange,
4540 Init->getSourceRange()});
4541
4542 if (DeducedFromInitRange.isInvalid() &&
4543 Deduced[0].getKind() != TemplateArgument::Null)
4544 DeducedFromInitRange = Init->getSourceRange();
4545 }
4546 } else {
4547 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
4548 Diag(Loc, diag::err_auto_bitfield);
4549 return DAR_FailedAlreadyDiagnosed;
4550 }
4551
4552 if (auto TDK = DeduceTemplateArgumentsFromCallArgument(
4553 *this, TemplateParamsSt.get(), 0, FuncParam, Init, Info, Deduced,
4554 OriginalCallArgs, /*Decomposed*/ false, /*ArgIdx*/ 0, /*TDF*/ 0))
4555 return DeductionFailed(TDK, {});
4556 }
4557
4558 // Could be null if somehow 'auto' appears in a non-deduced context.
4559 if (Deduced[0].getKind() != TemplateArgument::Type)
4560 return DeductionFailed(TDK_Incomplete, {});
4561
4562 QualType DeducedType = Deduced[0].getAsType();
4563
4564 if (InitList) {
4565 DeducedType = BuildStdInitializerList(DeducedType, Loc);
4566 if (DeducedType.isNull())
4567 return DAR_FailedAlreadyDiagnosed;
4568 }
4569
4570 Result = SubstituteDeducedTypeTransform(*this, DeducedType).Apply(Type);
4571 if (Result.isNull())
4572 return DAR_FailedAlreadyDiagnosed;
4573
4574 // Check that the deduced argument type is compatible with the original
4575 // argument type per C++ [temp.deduct.call]p4.
4576 QualType DeducedA = InitList ? Deduced[0].getAsType() : Result;
4577 for (const OriginalCallArg &OriginalArg : OriginalCallArgs) {
4578 assert((bool)InitList == OriginalArg.DecomposedParam &&(((bool)InitList == OriginalArg.DecomposedParam && "decomposed non-init-list in auto deduction?"
) ? static_cast<void> (0) : __assert_fail ("(bool)InitList == OriginalArg.DecomposedParam && \"decomposed non-init-list in auto deduction?\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 4579, __PRETTY_FUNCTION__))
4579 "decomposed non-init-list in auto deduction?")(((bool)InitList == OriginalArg.DecomposedParam && "decomposed non-init-list in auto deduction?"
) ? static_cast<void> (0) : __assert_fail ("(bool)InitList == OriginalArg.DecomposedParam && \"decomposed non-init-list in auto deduction?\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 4579, __PRETTY_FUNCTION__))
;
4580 if (auto TDK =
4581 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA)) {
4582 Result = QualType();
4583 return DeductionFailed(TDK, {});
4584 }
4585 }
4586
4587 return DAR_Succeeded;
4588}
4589
4590QualType Sema::SubstAutoType(QualType TypeWithAuto,
4591 QualType TypeToReplaceAuto) {
4592 if (TypeToReplaceAuto->isDependentType())
4593 return SubstituteDeducedTypeTransform(
4594 *this, DependentAuto{
4595 TypeToReplaceAuto->containsUnexpandedParameterPack()})
4596 .TransformType(TypeWithAuto);
4597 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
4598 .TransformType(TypeWithAuto);
4599}
4600
4601TypeSourceInfo *Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
4602 QualType TypeToReplaceAuto) {
4603 if (TypeToReplaceAuto->isDependentType())
4604 return SubstituteDeducedTypeTransform(
4605 *this,
4606 DependentAuto{
4607 TypeToReplaceAuto->containsUnexpandedParameterPack()})
4608 .TransformType(TypeWithAuto);
4609 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
4610 .TransformType(TypeWithAuto);
4611}
4612
4613QualType Sema::ReplaceAutoType(QualType TypeWithAuto,
4614 QualType TypeToReplaceAuto) {
4615 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
4616 /*UseTypeSugar*/ false)
4617 .TransformType(TypeWithAuto);
4618}
4619
4620void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
4621 if (isa<InitListExpr>(Init))
4622 Diag(VDecl->getLocation(),
4623 VDecl->isInitCapture()
4624 ? diag::err_init_capture_deduction_failure_from_init_list
4625 : diag::err_auto_var_deduction_failure_from_init_list)
4626 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
4627 else
4628 Diag(VDecl->getLocation(),
4629 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
4630 : diag::err_auto_var_deduction_failure)
4631 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4632 << Init->getSourceRange();
4633}
4634
4635bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
4636 bool Diagnose) {
4637 assert(FD->getReturnType()->isUndeducedType())((FD->getReturnType()->isUndeducedType()) ? static_cast
<void> (0) : __assert_fail ("FD->getReturnType()->isUndeducedType()"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 4637, __PRETTY_FUNCTION__))
;
4638
4639 // For a lambda's conversion operator, deduce any 'auto' or 'decltype(auto)'
4640 // within the return type from the call operator's type.
4641 if (isLambdaConversionOperator(FD)) {
4642 CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent();
4643 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
4644
4645 // For a generic lambda, instantiate the call operator if needed.
4646 if (auto *Args = FD->getTemplateSpecializationArgs()) {
4647 CallOp = InstantiateFunctionDeclaration(
4648 CallOp->getDescribedFunctionTemplate(), Args, Loc);
4649 if (!CallOp || CallOp->isInvalidDecl())
4650 return true;
4651
4652 // We might need to deduce the return type by instantiating the definition
4653 // of the operator() function.
4654 if (CallOp->getReturnType()->isUndeducedType()) {
4655 runWithSufficientStackSpace(Loc, [&] {
4656 InstantiateFunctionDefinition(Loc, CallOp);
4657 });
4658 }
4659 }
4660
4661 if (CallOp->isInvalidDecl())
4662 return true;
4663 assert(!CallOp->getReturnType()->isUndeducedType() &&((!CallOp->getReturnType()->isUndeducedType() &&
"failed to deduce lambda return type") ? static_cast<void
> (0) : __assert_fail ("!CallOp->getReturnType()->isUndeducedType() && \"failed to deduce lambda return type\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 4664, __PRETTY_FUNCTION__))
4664 "failed to deduce lambda return type")((!CallOp->getReturnType()->isUndeducedType() &&
"failed to deduce lambda return type") ? static_cast<void
> (0) : __assert_fail ("!CallOp->getReturnType()->isUndeducedType() && \"failed to deduce lambda return type\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 4664, __PRETTY_FUNCTION__))
;
4665
4666 // Build the new return type from scratch.
4667 QualType RetType = getLambdaConversionFunctionResultType(
4668 CallOp->getType()->castAs<FunctionProtoType>());
4669 if (FD->getReturnType()->getAs<PointerType>())
4670 RetType = Context.getPointerType(RetType);
4671 else {
4672 assert(FD->getReturnType()->getAs<BlockPointerType>())((FD->getReturnType()->getAs<BlockPointerType>())
? static_cast<void> (0) : __assert_fail ("FD->getReturnType()->getAs<BlockPointerType>()"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 4672, __PRETTY_FUNCTION__))
;
4673 RetType = Context.getBlockPointerType(RetType);
4674 }
4675 Context.adjustDeducedFunctionResultType(FD, RetType);
4676 return false;
4677 }
4678
4679 if (FD->getTemplateInstantiationPattern()) {
4680 runWithSufficientStackSpace(Loc, [&] {
4681 InstantiateFunctionDefinition(Loc, FD);
4682 });
4683 }
4684
4685 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
4686 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
4687 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
4688 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
4689 }
4690
4691 return StillUndeduced;
4692}
4693
4694/// If this is a non-static member function,
4695static void
4696AddImplicitObjectParameterType(ASTContext &Context,
4697 CXXMethodDecl *Method,
4698 SmallVectorImpl<QualType> &ArgTypes) {
4699 // C++11 [temp.func.order]p3:
4700 // [...] The new parameter is of type "reference to cv A," where cv are
4701 // the cv-qualifiers of the function template (if any) and A is
4702 // the class of which the function template is a member.
4703 //
4704 // The standard doesn't say explicitly, but we pick the appropriate kind of
4705 // reference type based on [over.match.funcs]p4.
4706 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
4707 ArgTy = Context.getQualifiedType(ArgTy, Method->getMethodQualifiers());
4708 if (Method->getRefQualifier() == RQ_RValue)
4709 ArgTy = Context.getRValueReferenceType(ArgTy);
4710 else
4711 ArgTy = Context.getLValueReferenceType(ArgTy);
4712 ArgTypes.push_back(ArgTy);
4713}
4714
4715/// Determine whether the function template \p FT1 is at least as
4716/// specialized as \p FT2.
4717static bool isAtLeastAsSpecializedAs(Sema &S,
4718 SourceLocation Loc,
4719 FunctionTemplateDecl *FT1,
4720 FunctionTemplateDecl *FT2,
4721 TemplatePartialOrderingContext TPOC,
4722 unsigned NumCallArguments1) {
4723 FunctionDecl *FD1 = FT1->getTemplatedDecl();
4724 FunctionDecl *FD2 = FT2->getTemplatedDecl();
4725 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
4726 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
4727
4728 assert(Proto1 && Proto2 && "Function templates must have prototypes")((Proto1 && Proto2 && "Function templates must have prototypes"
) ? static_cast<void> (0) : __assert_fail ("Proto1 && Proto2 && \"Function templates must have prototypes\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 4728, __PRETTY_FUNCTION__))
;
4729 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
4730 SmallVector<DeducedTemplateArgument, 4> Deduced;
4731 Deduced.resize(TemplateParams->size());
4732
4733 // C++0x [temp.deduct.partial]p3:
4734 // The types used to determine the ordering depend on the context in which
4735 // the partial ordering is done:
4736 TemplateDeductionInfo Info(Loc);
4737 SmallVector<QualType, 4> Args2;
4738 switch (TPOC) {
4739 case TPOC_Call: {
4740 // - In the context of a function call, the function parameter types are
4741 // used.
4742 CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
4743 CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
4744
4745 // C++11 [temp.func.order]p3:
4746 // [...] If only one of the function templates is a non-static
4747 // member, that function template is considered to have a new
4748 // first parameter inserted in its function parameter list. The
4749 // new parameter is of type "reference to cv A," where cv are
4750 // the cv-qualifiers of the function template (if any) and A is
4751 // the class of which the function template is a member.
4752 //
4753 // Note that we interpret this to mean "if one of the function
4754 // templates is a non-static member and the other is a non-member";
4755 // otherwise, the ordering rules for static functions against non-static
4756 // functions don't make any sense.
4757 //
4758 // C++98/03 doesn't have this provision but we've extended DR532 to cover
4759 // it as wording was broken prior to it.
4760 SmallVector<QualType, 4> Args1;
4761
4762 unsigned NumComparedArguments = NumCallArguments1;
4763
4764 if (!Method2 && Method1 && !Method1->isStatic()) {
4765 // Compare 'this' from Method1 against first parameter from Method2.
4766 AddImplicitObjectParameterType(S.Context, Method1, Args1);
4767 ++NumComparedArguments;
4768 } else if (!Method1 && Method2 && !Method2->isStatic()) {
4769 // Compare 'this' from Method2 against first parameter from Method1.
4770 AddImplicitObjectParameterType(S.Context, Method2, Args2);
4771 }
4772
4773 Args1.insert(Args1.end(), Proto1->param_type_begin(),
4774 Proto1->param_type_end());
4775 Args2.insert(Args2.end(), Proto2->param_type_begin(),
4776 Proto2->param_type_end());
4777
4778 // C++ [temp.func.order]p5:
4779 // The presence of unused ellipsis and default arguments has no effect on
4780 // the partial ordering of function templates.
4781 if (Args1.size() > NumComparedArguments)
4782 Args1.resize(NumComparedArguments);
4783 if (Args2.size() > NumComparedArguments)
4784 Args2.resize(NumComparedArguments);
4785 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
4786 Args1.data(), Args1.size(), Info, Deduced,
4787 TDF_None, /*PartialOrdering=*/true))
4788 return false;
4789
4790 break;
4791 }
4792
4793 case TPOC_Conversion:
4794 // - In the context of a call to a conversion operator, the return types
4795 // of the conversion function templates are used.
4796 if (DeduceTemplateArgumentsByTypeMatch(
4797 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
4798 Info, Deduced, TDF_None,
4799 /*PartialOrdering=*/true))
4800 return false;
4801 break;
4802
4803 case TPOC_Other:
4804 // - In other contexts (14.6.6.2) the function template's function type
4805 // is used.
4806 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
4807 FD2->getType(), FD1->getType(),
4808 Info, Deduced, TDF_None,
4809 /*PartialOrdering=*/true))
4810 return false;
4811 break;
4812 }
4813
4814 // C++0x [temp.deduct.partial]p11:
4815 // In most cases, all template parameters must have values in order for
4816 // deduction to succeed, but for partial ordering purposes a template
4817 // parameter may remain without a value provided it is not used in the
4818 // types being used for partial ordering. [ Note: a template parameter used
4819 // in a non-deduced context is considered used. -end note]
4820 unsigned ArgIdx = 0, NumArgs = Deduced.size();
4821 for (; ArgIdx != NumArgs; ++ArgIdx)
4822 if (Deduced[ArgIdx].isNull())
4823 break;
4824
4825 // FIXME: We fail to implement [temp.deduct.type]p1 along this path. We need
4826 // to substitute the deduced arguments back into the template and check that
4827 // we get the right type.
4828
4829 if (ArgIdx == NumArgs) {
4830 // All template arguments were deduced. FT1 is at least as specialized
4831 // as FT2.
4832 return true;
4833 }
4834
4835 // Figure out which template parameters were used.
4836 llvm::SmallBitVector UsedParameters(TemplateParams->size());
4837 switch (TPOC) {
4838 case TPOC_Call:
4839 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
4840 ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
4841 TemplateParams->getDepth(),
4842 UsedParameters);
4843 break;
4844
4845 case TPOC_Conversion:
4846 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
4847 TemplateParams->getDepth(), UsedParameters);
4848 break;
4849
4850 case TPOC_Other:
4851 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
4852 TemplateParams->getDepth(),
4853 UsedParameters);
4854 break;
4855 }
4856
4857 for (; ArgIdx != NumArgs; ++ArgIdx)
4858 // If this argument had no value deduced but was used in one of the types
4859 // used for partial ordering, then deduction fails.
4860 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
4861 return false;
4862
4863 return true;
4864}
4865
4866/// Determine whether this a function template whose parameter-type-list
4867/// ends with a function parameter pack.
4868static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
4869 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
4870 unsigned NumParams = Function->getNumParams();
4871 if (NumParams == 0)
4872 return false;
4873
4874 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
4875 if (!Last->isParameterPack())
4876 return false;
4877
4878 // Make sure that no previous parameter is a parameter pack.
4879 while (--NumParams > 0) {
4880 if (Function->getParamDecl(NumParams - 1)->isParameterPack())
4881 return false;
4882 }
4883
4884 return true;
4885}
4886
4887/// Returns the more specialized function template according
4888/// to the rules of function template partial ordering (C++ [temp.func.order]).
4889///
4890/// \param FT1 the first function template
4891///
4892/// \param FT2 the second function template
4893///
4894/// \param TPOC the context in which we are performing partial ordering of
4895/// function templates.
4896///
4897/// \param NumCallArguments1 The number of arguments in the call to FT1, used
4898/// only when \c TPOC is \c TPOC_Call.
4899///
4900/// \param NumCallArguments2 The number of arguments in the call to FT2, used
4901/// only when \c TPOC is \c TPOC_Call.
4902///
4903/// \returns the more specialized function template. If neither
4904/// template is more specialized, returns NULL.
4905FunctionTemplateDecl *
4906Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4907 FunctionTemplateDecl *FT2,
4908 SourceLocation Loc,
4909 TemplatePartialOrderingContext TPOC,
4910 unsigned NumCallArguments1,
4911 unsigned NumCallArguments2) {
4912 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
4913 NumCallArguments1);
4914 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
4915 NumCallArguments2);
4916
4917 if (Better1 != Better2) // We have a clear winner
4918 return Better1 ? FT1 : FT2;
4919
4920 if (!Better1 && !Better2) // Neither is better than the other
4921 return nullptr;
4922
4923 // FIXME: This mimics what GCC implements, but doesn't match up with the
4924 // proposed resolution for core issue 692. This area needs to be sorted out,
4925 // but for now we attempt to maintain compatibility.
4926 bool Variadic1 = isVariadicFunctionTemplate(FT1);
4927 bool Variadic2 = isVariadicFunctionTemplate(FT2);
4928 if (Variadic1 != Variadic2)
4929 return Variadic1? FT2 : FT1;
4930
4931 return nullptr;
4932}
4933
4934/// Determine if the two templates are equivalent.
4935static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
4936 if (T1 == T2)
4937 return true;
4938
4939 if (!T1 || !T2)
4940 return false;
4941
4942 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
4943}
4944
4945/// Retrieve the most specialized of the given function template
4946/// specializations.
4947///
4948/// \param SpecBegin the start iterator of the function template
4949/// specializations that we will be comparing.
4950///
4951/// \param SpecEnd the end iterator of the function template
4952/// specializations, paired with \p SpecBegin.
4953///
4954/// \param Loc the location where the ambiguity or no-specializations
4955/// diagnostic should occur.
4956///
4957/// \param NoneDiag partial diagnostic used to diagnose cases where there are
4958/// no matching candidates.
4959///
4960/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
4961/// occurs.
4962///
4963/// \param CandidateDiag partial diagnostic used for each function template
4964/// specialization that is a candidate in the ambiguous ordering. One parameter
4965/// in this diagnostic should be unbound, which will correspond to the string
4966/// describing the template arguments for the function template specialization.
4967///
4968/// \returns the most specialized function template specialization, if
4969/// found. Otherwise, returns SpecEnd.
4970UnresolvedSetIterator Sema::getMostSpecialized(
4971 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
4972 TemplateSpecCandidateSet &FailedCandidates,
4973 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
4974 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
4975 bool Complain, QualType TargetType) {
4976 if (SpecBegin == SpecEnd) {
4977 if (Complain) {
4978 Diag(Loc, NoneDiag);
4979 FailedCandidates.NoteCandidates(*this, Loc);
4980 }
4981 return SpecEnd;
4982 }
4983
4984 if (SpecBegin + 1 == SpecEnd)
4985 return SpecBegin;
4986
4987 // Find the function template that is better than all of the templates it
4988 // has been compared to.
4989 UnresolvedSetIterator Best = SpecBegin;
4990 FunctionTemplateDecl *BestTemplate
4991 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
4992 assert(BestTemplate && "Not a function template specialization?")((BestTemplate && "Not a function template specialization?"
) ? static_cast<void> (0) : __assert_fail ("BestTemplate && \"Not a function template specialization?\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 4992, __PRETTY_FUNCTION__))
;
4993 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
4994 FunctionTemplateDecl *Challenger
4995 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
4996 assert(Challenger && "Not a function template specialization?")((Challenger && "Not a function template specialization?"
) ? static_cast<void> (0) : __assert_fail ("Challenger && \"Not a function template specialization?\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 4996, __PRETTY_FUNCTION__))
;
4997 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
4998 Loc, TPOC_Other, 0, 0),
4999 Challenger)) {
5000 Best = I;
5001 BestTemplate = Challenger;
5002 }
5003 }
5004
5005 // Make sure that the "best" function template is more specialized than all
5006 // of the others.
5007 bool Ambiguous = false;
5008 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
5009 FunctionTemplateDecl *Challenger
5010 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
5011 if (I != Best &&
5012 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
5013 Loc, TPOC_Other, 0, 0),
5014 BestTemplate)) {
5015 Ambiguous = true;
5016 break;
5017 }
5018 }
5019
5020 if (!Ambiguous) {
5021 // We found an answer. Return it.
5022 return Best;
5023 }
5024
5025 // Diagnose the ambiguity.
5026 if (Complain) {
5027 Diag(Loc, AmbigDiag);
5028
5029 // FIXME: Can we order the candidates in some sane way?
5030 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
5031 PartialDiagnostic PD = CandidateDiag;
5032 const auto *FD = cast<FunctionDecl>(*I);
5033 PD << FD << getTemplateArgumentBindingsText(
5034 FD->getPrimaryTemplate()->getTemplateParameters(),
5035 *FD->getTemplateSpecializationArgs());
5036 if (!TargetType.isNull())
5037 HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
5038 Diag((*I)->getLocation(), PD);
5039 }
5040 }
5041
5042 return SpecEnd;
5043}
5044
5045/// Determine whether one partial specialization, P1, is at least as
5046/// specialized than another, P2.
5047///
5048/// \tparam TemplateLikeDecl The kind of P2, which must be a
5049/// TemplateDecl or {Class,Var}TemplatePartialSpecializationDecl.
5050/// \param T1 The injected-class-name of P1 (faked for a variable template).
5051/// \param T2 The injected-class-name of P2 (faked for a variable template).
5052template<typename TemplateLikeDecl>
5053static bool isAtLeastAsSpecializedAs(Sema &S, QualType T1, QualType T2,
5054 TemplateLikeDecl *P2,
5055 TemplateDeductionInfo &Info) {
5056 // C++ [temp.class.order]p1:
5057 // For two class template partial specializations, the first is at least as
5058 // specialized as the second if, given the following rewrite to two
5059 // function templates, the first function template is at least as
5060 // specialized as the second according to the ordering rules for function
5061 // templates (14.6.6.2):
5062 // - the first function template has the same template parameters as the
5063 // first partial specialization and has a single function parameter
5064 // whose type is a class template specialization with the template
5065 // arguments of the first partial specialization, and
5066 // - the second function template has the same template parameters as the
5067 // second partial specialization and has a single function parameter
5068 // whose type is a class template specialization with the template
5069 // arguments of the second partial specialization.
5070 //
5071 // Rather than synthesize function templates, we merely perform the
5072 // equivalent partial ordering by performing deduction directly on
5073 // the template arguments of the class template partial
5074 // specializations. This computation is slightly simpler than the
5075 // general problem of function template partial ordering, because
5076 // class template partial specializations are more constrained. We
5077 // know that every template parameter is deducible from the class
5078 // template partial specialization's template arguments, for
5079 // example.
5080 SmallVector<DeducedTemplateArgument, 4> Deduced;
5081
5082 // Determine whether P1 is at least as specialized as P2.
5083 Deduced.resize(P2->getTemplateParameters()->size());
5084 if (DeduceTemplateArgumentsByTypeMatch(S, P2->getTemplateParameters(),
5085 T2, T1, Info, Deduced, TDF_None,
5086 /*PartialOrdering=*/true))
5087 return false;
5088
5089 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
5090 Deduced.end());
5091 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs,
5092 Info);
5093 auto *TST1 = T1->castAs<TemplateSpecializationType>();
5094 if (FinishTemplateArgumentDeduction(
5095 S, P2, /*IsPartialOrdering=*/true,
5096 TemplateArgumentList(TemplateArgumentList::OnStack,
5097 TST1->template_arguments()),
5098 Deduced, Info))
5099 return false;
5100
5101 return true;
5102}
5103
5104/// Returns the more specialized class template partial specialization
5105/// according to the rules of partial ordering of class template partial
5106/// specializations (C++ [temp.class.order]).
5107///
5108/// \param PS1 the first class template partial specialization
5109///
5110/// \param PS2 the second class template partial specialization
5111///
5112/// \returns the more specialized class template partial specialization. If
5113/// neither partial specialization is more specialized, returns NULL.
5114ClassTemplatePartialSpecializationDecl *
5115Sema::getMoreSpecializedPartialSpecialization(
5116 ClassTemplatePartialSpecializationDecl *PS1,
5117 ClassTemplatePartialSpecializationDecl *PS2,
5118 SourceLocation Loc) {
5119 QualType PT1 = PS1->getInjectedSpecializationType();
5120 QualType PT2 = PS2->getInjectedSpecializationType();
5121
5122 TemplateDeductionInfo Info(Loc);
5123 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info);
5124 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info);
5125
5126 if (Better1 == Better2)
5127 return nullptr;
5128
5129 return Better1 ? PS1 : PS2;
5130}
5131
5132bool Sema::isMoreSpecializedThanPrimary(
5133 ClassTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
5134 ClassTemplateDecl *Primary = Spec->getSpecializedTemplate();
5135 QualType PrimaryT = Primary->getInjectedClassNameSpecialization();
5136 QualType PartialT = Spec->getInjectedSpecializationType();
5137 if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info))
5138 return false;
5139 if (isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info)) {
5140 Info.clearSFINAEDiagnostic();
5141 return false;
5142 }
5143 return true;
5144}
5145
5146VarTemplatePartialSpecializationDecl *
5147Sema::getMoreSpecializedPartialSpecialization(
5148 VarTemplatePartialSpecializationDecl *PS1,
5149 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
5150 // Pretend the variable template specializations are class template
5151 // specializations and form a fake injected class name type for comparison.
5152 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&((PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate
() && "the partial specializations being compared should specialize"
" the same template.") ? static_cast<void> (0) : __assert_fail
("PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() && \"the partial specializations being compared should specialize\" \" the same template.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 5154, __PRETTY_FUNCTION__))
5153 "the partial specializations being compared should specialize"((PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate
() && "the partial specializations being compared should specialize"
" the same template.") ? static_cast<void> (0) : __assert_fail
("PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() && \"the partial specializations being compared should specialize\" \" the same template.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 5154, __PRETTY_FUNCTION__))
5154 " the same template.")((PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate
() && "the partial specializations being compared should specialize"
" the same template.") ? static_cast<void> (0) : __assert_fail
("PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() && \"the partial specializations being compared should specialize\" \" the same template.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 5154, __PRETTY_FUNCTION__))
;
5155 TemplateName Name(PS1->getSpecializedTemplate());
5156 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
5157 QualType PT1 = Context.getTemplateSpecializationType(
5158 CanonTemplate, PS1->getTemplateArgs().asArray());
5159 QualType PT2 = Context.getTemplateSpecializationType(
5160 CanonTemplate, PS2->getTemplateArgs().asArray());
5161
5162 TemplateDeductionInfo Info(Loc);
5163 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info);
5164 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info);
5165
5166 if (Better1 == Better2)
5167 return nullptr;
5168
5169 return Better1 ? PS1 : PS2;
5170}
5171
5172bool Sema::isMoreSpecializedThanPrimary(
5173 VarTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
5174 TemplateDecl *Primary = Spec->getSpecializedTemplate();
5175 // FIXME: Cache the injected template arguments rather than recomputing
5176 // them for each partial specialization.
5177 SmallVector<TemplateArgument, 8> PrimaryArgs;
5178 Context.getInjectedTemplateArgs(Primary->getTemplateParameters(),
5179 PrimaryArgs);
5180
5181 TemplateName CanonTemplate =
5182 Context.getCanonicalTemplateName(TemplateName(Primary));
5183 QualType PrimaryT = Context.getTemplateSpecializationType(
5184 CanonTemplate, PrimaryArgs);
5185 QualType PartialT = Context.getTemplateSpecializationType(
5186 CanonTemplate, Spec->getTemplateArgs().asArray());
5187 if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info))
5188 return false;
5189 if (isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info)) {
5190 Info.clearSFINAEDiagnostic();
5191 return false;
5192 }
5193 return true;
5194}
5195
5196bool Sema::isTemplateTemplateParameterAtLeastAsSpecializedAs(
5197 TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc) {
5198 // C++1z [temp.arg.template]p4: (DR 150)
5199 // A template template-parameter P is at least as specialized as a
5200 // template template-argument A if, given the following rewrite to two
5201 // function templates...
5202
5203 // Rather than synthesize function templates, we merely perform the
5204 // equivalent partial ordering by performing deduction directly on
5205 // the template parameter lists of the template template parameters.
5206 //
5207 // Given an invented class template X with the template parameter list of
5208 // A (including default arguments):
5209 TemplateName X = Context.getCanonicalTemplateName(TemplateName(AArg));
5210 TemplateParameterList *A = AArg->getTemplateParameters();
5211
5212 // - Each function template has a single function parameter whose type is
5213 // a specialization of X with template arguments corresponding to the
5214 // template parameters from the respective function template
5215 SmallVector<TemplateArgument, 8> AArgs;
5216 Context.getInjectedTemplateArgs(A, AArgs);
5217
5218 // Check P's arguments against A's parameter list. This will fill in default
5219 // template arguments as needed. AArgs are already correct by construction.
5220 // We can't just use CheckTemplateIdType because that will expand alias
5221 // templates.
5222 SmallVector<TemplateArgument, 4> PArgs;
5223 {
5224 SFINAETrap Trap(*this);
5225
5226 Context.getInjectedTemplateArgs(P, PArgs);
5227 TemplateArgumentListInfo PArgList(P->getLAngleLoc(), P->getRAngleLoc());
5228 for (unsigned I = 0, N = P->size(); I != N; ++I) {
5229 // Unwrap packs that getInjectedTemplateArgs wrapped around pack
5230 // expansions, to form an "as written" argument list.
5231 TemplateArgument Arg = PArgs[I];
5232 if (Arg.getKind() == TemplateArgument::Pack) {
5233 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion())((Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion
()) ? static_cast<void> (0) : __assert_fail ("Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion()"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 5233, __PRETTY_FUNCTION__))
;
5234 Arg = *Arg.pack_begin();
5235 }
5236 PArgList.addArgument(getTrivialTemplateArgumentLoc(
5237 Arg, QualType(), P->getParam(I)->getLocation()));
5238 }
5239 PArgs.clear();
5240
5241 // C++1z [temp.arg.template]p3:
5242 // If the rewrite produces an invalid type, then P is not at least as
5243 // specialized as A.
5244 if (CheckTemplateArgumentList(AArg, Loc, PArgList, false, PArgs) ||
5245 Trap.hasErrorOccurred())
5246 return false;
5247 }
5248
5249 QualType AType = Context.getTemplateSpecializationType(X, AArgs);
5250 QualType PType = Context.getTemplateSpecializationType(X, PArgs);
5251
5252 // ... the function template corresponding to P is at least as specialized
5253 // as the function template corresponding to A according to the partial
5254 // ordering rules for function templates.
5255 TemplateDeductionInfo Info(Loc, A->getDepth());
5256 return isAtLeastAsSpecializedAs(*this, PType, AType, AArg, Info);
5257}
5258
5259/// Mark the template parameters that are used by the given
5260/// expression.
5261static void
5262MarkUsedTemplateParameters(ASTContext &Ctx,
5263 const Expr *E,
5264 bool OnlyDeduced,
5265 unsigned Depth,
5266 llvm::SmallBitVector &Used) {
5267 // We can deduce from a pack expansion.
5268 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
5269 E = Expansion->getPattern();
5270
5271 // Skip through any implicit casts we added while type-checking, and any
5272 // substitutions performed by template alias expansion.
5273 while (true) {
5274 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
5275 E = ICE->getSubExpr();
5276 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(E))
5277 E = CE->getSubExpr();
5278 else if (const SubstNonTypeTemplateParmExpr *Subst =
5279 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
5280 E = Subst->getReplacement();
5281 else
5282 break;
5283 }
5284
5285 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
5286 // find other occurrences of template parameters.
5287 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
5288 if (!DRE)
5289 return;
5290
5291 const NonTypeTemplateParmDecl *NTTP
5292 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
5293 if (!NTTP)
5294 return;
5295
5296 if (NTTP->getDepth() == Depth)
5297 Used[NTTP->getIndex()] = true;
5298
5299 // In C++17 mode, additional arguments may be deduced from the type of a
5300 // non-type argument.
5301 if (Ctx.getLangOpts().CPlusPlus17)
5302 MarkUsedTemplateParameters(Ctx, NTTP->getType(), OnlyDeduced, Depth, Used);
5303}
5304
5305/// Mark the template parameters that are used by the given
5306/// nested name specifier.
5307static void
5308MarkUsedTemplateParameters(ASTContext &Ctx,
5309 NestedNameSpecifier *NNS,
5310 bool OnlyDeduced,
5311 unsigned Depth,
5312 llvm::SmallBitVector &Used) {
5313 if (!NNS)
5314 return;
5315
5316 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
5317 Used);
5318 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
5319 OnlyDeduced, Depth, Used);
5320}
5321
5322/// Mark the template parameters that are used by the given
5323/// template name.
5324static void
5325MarkUsedTemplateParameters(ASTContext &Ctx,
5326 TemplateName Name,
5327 bool OnlyDeduced,
5328 unsigned Depth,
5329 llvm::SmallBitVector &Used) {
5330 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
5331 if (TemplateTemplateParmDecl *TTP
5332 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
5333 if (TTP->getDepth() == Depth)
5334 Used[TTP->getIndex()] = true;
5335 }
5336 return;
5337 }
5338
5339 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
5340 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
5341 Depth, Used);
5342 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
5343 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
5344 Depth, Used);
5345}
5346
5347/// Mark the template parameters that are used by the given
5348/// type.
5349static void
5350MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
5351 bool OnlyDeduced,
5352 unsigned Depth,
5353 llvm::SmallBitVector &Used) {
5354 if (T.isNull())
5355 return;
5356
5357 // Non-dependent types have nothing deducible
5358 if (!T->isDependentType())
5359 return;
5360
5361 T = Ctx.getCanonicalType(T);
5362 switch (T->getTypeClass()) {
5363 case Type::Pointer:
5364 MarkUsedTemplateParameters(Ctx,
5365 cast<PointerType>(T)->getPointeeType(),
5366 OnlyDeduced,
5367 Depth,
5368 Used);
5369 break;
5370
5371 case Type::BlockPointer:
5372 MarkUsedTemplateParameters(Ctx,
5373 cast<BlockPointerType>(T)->getPointeeType(),
5374 OnlyDeduced,
5375 Depth,
5376 Used);
5377 break;
5378
5379 case Type::LValueReference:
5380 case Type::RValueReference:
5381 MarkUsedTemplateParameters(Ctx,
5382 cast<ReferenceType>(T)->getPointeeType(),
5383 OnlyDeduced,
5384 Depth,
5385 Used);
5386 break;
5387
5388 case Type::MemberPointer: {
5389 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
5390 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
5391 Depth, Used);
5392 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
5393 OnlyDeduced, Depth, Used);
5394 break;
5395 }
5396
5397 case Type::DependentSizedArray:
5398 MarkUsedTemplateParameters(Ctx,
5399 cast<DependentSizedArrayType>(T)->getSizeExpr(),
5400 OnlyDeduced, Depth, Used);
5401 // Fall through to check the element type
5402 LLVM_FALLTHROUGH[[gnu::fallthrough]];
5403
5404 case Type::ConstantArray:
5405 case Type::IncompleteArray:
5406 MarkUsedTemplateParameters(Ctx,
5407 cast<ArrayType>(T)->getElementType(),
5408 OnlyDeduced, Depth, Used);
5409 break;
5410
5411 case Type::Vector:
5412 case Type::ExtVector:
5413 MarkUsedTemplateParameters(Ctx,
5414 cast<VectorType>(T)->getElementType(),
5415 OnlyDeduced, Depth, Used);
5416 break;
5417
5418 case Type::DependentVector: {
5419 const auto *VecType = cast<DependentVectorType>(T);
5420 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
5421 Depth, Used);
5422 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced, Depth,
5423 Used);
5424 break;
5425 }
5426 case Type::DependentSizedExtVector: {
5427 const DependentSizedExtVectorType *VecType
5428 = cast<DependentSizedExtVectorType>(T);
5429 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
5430 Depth, Used);
5431 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
5432 Depth, Used);
5433 break;
5434 }
5435
5436 case Type::DependentAddressSpace: {
5437 const DependentAddressSpaceType *DependentASType =
5438 cast<DependentAddressSpaceType>(T);
5439 MarkUsedTemplateParameters(Ctx, DependentASType->getPointeeType(),
5440 OnlyDeduced, Depth, Used);
5441 MarkUsedTemplateParameters(Ctx,
5442 DependentASType->getAddrSpaceExpr(),
5443 OnlyDeduced, Depth, Used);
5444 break;
5445 }
5446
5447 case Type::FunctionProto: {
5448 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
5449 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
5450 Used);
5451 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I) {
5452 // C++17 [temp.deduct.type]p5:
5453 // The non-deduced contexts are: [...]
5454 // -- A function parameter pack that does not occur at the end of the
5455 // parameter-declaration-list.
5456 if (!OnlyDeduced || I + 1 == N ||
5457 !Proto->getParamType(I)->getAs<PackExpansionType>()) {
5458 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
5459 Depth, Used);
5460 } else {
5461 // FIXME: C++17 [temp.deduct.call]p1:
5462 // When a function parameter pack appears in a non-deduced context,
5463 // the type of that pack is never deduced.
5464 //
5465 // We should also track a set of "never deduced" parameters, and
5466 // subtract that from the list of deduced parameters after marking.
5467 }
5468 }
5469 if (auto *E = Proto->getNoexceptExpr())
5470 MarkUsedTemplateParameters(Ctx, E, OnlyDeduced, Depth, Used);
5471 break;
5472 }
5473
5474 case Type::TemplateTypeParm: {
5475 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
5476 if (TTP->getDepth() == Depth)
5477 Used[TTP->getIndex()] = true;
5478 break;
5479 }
5480
5481 case Type::SubstTemplateTypeParmPack: {
5482 const SubstTemplateTypeParmPackType *Subst
5483 = cast<SubstTemplateTypeParmPackType>(T);
5484 MarkUsedTemplateParameters(Ctx,
5485 QualType(Subst->getReplacedParameter(), 0),
5486 OnlyDeduced, Depth, Used);
5487 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
5488 OnlyDeduced, Depth, Used);
5489 break;
5490 }
5491
5492 case Type::InjectedClassName:
5493 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
5494 LLVM_FALLTHROUGH[[gnu::fallthrough]];
5495
5496 case Type::TemplateSpecialization: {
5497 const TemplateSpecializationType *Spec
5498 = cast<TemplateSpecializationType>(T);
5499 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
5500 Depth, Used);
5501
5502 // C++0x [temp.deduct.type]p9:
5503 // If the template argument list of P contains a pack expansion that is
5504 // not the last template argument, the entire template argument list is a
5505 // non-deduced context.
5506 if (OnlyDeduced &&
5507 hasPackExpansionBeforeEnd(Spec->template_arguments()))
5508 break;
5509
5510 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
5511 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
5512 Used);
5513 break;
5514 }
5515
5516 case Type::Complex:
5517 if (!OnlyDeduced)
5518 MarkUsedTemplateParameters(Ctx,
5519 cast<ComplexType>(T)->getElementType(),
5520 OnlyDeduced, Depth, Used);
5521 break;
5522
5523 case Type::Atomic:
5524 if (!OnlyDeduced)
5525 MarkUsedTemplateParameters(Ctx,
5526 cast<AtomicType>(T)->getValueType(),
5527 OnlyDeduced, Depth, Used);
5528 break;
5529
5530 case Type::DependentName:
5531 if (!OnlyDeduced)
5532 MarkUsedTemplateParameters(Ctx,
5533 cast<DependentNameType>(T)->getQualifier(),
5534 OnlyDeduced, Depth, Used);
5535 break;
5536
5537 case Type::DependentTemplateSpecialization: {
5538 // C++14 [temp.deduct.type]p5:
5539 // The non-deduced contexts are:
5540 // -- The nested-name-specifier of a type that was specified using a
5541 // qualified-id
5542 //
5543 // C++14 [temp.deduct.type]p6:
5544 // When a type name is specified in a way that includes a non-deduced
5545 // context, all of the types that comprise that type name are also
5546 // non-deduced.
5547 if (OnlyDeduced)
5548 break;
5549
5550 const DependentTemplateSpecializationType *Spec
5551 = cast<DependentTemplateSpecializationType>(T);
5552
5553 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
5554 OnlyDeduced, Depth, Used);
5555
5556 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
5557 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
5558 Used);
5559 break;
5560 }
5561
5562 case Type::TypeOf:
5563 if (!OnlyDeduced)
5564 MarkUsedTemplateParameters(Ctx,
5565 cast<TypeOfType>(T)->getUnderlyingType(),
5566 OnlyDeduced, Depth, Used);
5567 break;
5568
5569 case Type::TypeOfExpr:
5570 if (!OnlyDeduced)
5571 MarkUsedTemplateParameters(Ctx,
5572 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
5573 OnlyDeduced, Depth, Used);
5574 break;
5575
5576 case Type::Decltype:
5577 if (!OnlyDeduced)
5578 MarkUsedTemplateParameters(Ctx,
5579 cast<DecltypeType>(T)->getUnderlyingExpr(),
5580 OnlyDeduced, Depth, Used);
5581 break;
5582
5583 case Type::UnaryTransform:
5584 if (!OnlyDeduced)
5585 MarkUsedTemplateParameters(Ctx,
5586 cast<UnaryTransformType>(T)->getUnderlyingType(),
5587 OnlyDeduced, Depth, Used);
5588 break;
5589
5590 case Type::PackExpansion:
5591 MarkUsedTemplateParameters(Ctx,
5592 cast<PackExpansionType>(T)->getPattern(),
5593 OnlyDeduced, Depth, Used);
5594 break;
5595
5596 case Type::Auto:
5597 case Type::DeducedTemplateSpecialization:
5598 MarkUsedTemplateParameters(Ctx,
5599 cast<DeducedType>(T)->getDeducedType(),
5600 OnlyDeduced, Depth, Used);
5601 break;
5602
5603 // None of these types have any template parameters in them.
5604 case Type::Builtin:
5605 case Type::VariableArray:
5606 case Type::FunctionNoProto:
5607 case Type::Record:
5608 case Type::Enum:
5609 case Type::ObjCInterface:
5610 case Type::ObjCObject:
5611 case Type::ObjCObjectPointer:
5612 case Type::UnresolvedUsing:
5613 case Type::Pipe:
5614#define TYPE(Class, Base)
5615#define ABSTRACT_TYPE(Class, Base)
5616#define DEPENDENT_TYPE(Class, Base)
5617#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5618#include "clang/AST/TypeNodes.inc"
5619 break;
5620 }
5621}
5622
5623/// Mark the template parameters that are used by this
5624/// template argument.
5625static void
5626MarkUsedTemplateParameters(ASTContext &Ctx,
5627 const TemplateArgument &TemplateArg,
5628 bool OnlyDeduced,
5629 unsigned Depth,
5630 llvm::SmallBitVector &Used) {
5631 switch (TemplateArg.getKind()) {
5632 case TemplateArgument::Null:
5633 case TemplateArgument::Integral:
5634 case TemplateArgument::Declaration:
5635 break;
5636
5637 case TemplateArgument::NullPtr:
5638 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
5639 Depth, Used);
5640 break;
5641
5642 case TemplateArgument::Type:
5643 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
5644 Depth, Used);
5645 break;
5646
5647 case TemplateArgument::Template:
5648 case TemplateArgument::TemplateExpansion:
5649 MarkUsedTemplateParameters(Ctx,
5650 TemplateArg.getAsTemplateOrTemplatePattern(),
5651 OnlyDeduced, Depth, Used);
5652 break;
5653
5654 case TemplateArgument::Expression:
5655 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
5656 Depth, Used);
5657 break;
5658
5659 case TemplateArgument::Pack:
5660 for (const auto &P : TemplateArg.pack_elements())
5661 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
5662 break;
5663 }
5664}
5665
5666/// Mark which template parameters can be deduced from a given
5667/// template argument list.
5668///
5669/// \param TemplateArgs the template argument list from which template
5670/// parameters will be deduced.
5671///
5672/// \param Used a bit vector whose elements will be set to \c true
5673/// to indicate when the corresponding template parameter will be
5674/// deduced.
5675void
5676Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
5677 bool OnlyDeduced, unsigned Depth,
5678 llvm::SmallBitVector &Used) {
5679 // C++0x [temp.deduct.type]p9:
5680 // If the template argument list of P contains a pack expansion that is not
5681 // the last template argument, the entire template argument list is a
5682 // non-deduced context.
5683 if (OnlyDeduced &&
5684 hasPackExpansionBeforeEnd(TemplateArgs.asArray()))
5685 return;
5686
5687 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
5688 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
5689 Depth, Used);
5690}
5691
5692/// Marks all of the template parameters that will be deduced by a
5693/// call to the given function template.
5694void Sema::MarkDeducedTemplateParameters(
5695 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
5696 llvm::SmallBitVector &Deduced) {
5697 TemplateParameterList *TemplateParams
5698 = FunctionTemplate->getTemplateParameters();
5699 Deduced.clear();
5700 Deduced.resize(TemplateParams->size());
5701
5702 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
5703 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
5704 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
5705 true, TemplateParams->getDepth(), Deduced);
5706}
5707
5708bool hasDeducibleTemplateParameters(Sema &S,
5709 FunctionTemplateDecl *FunctionTemplate,
5710 QualType T) {
5711 if (!T->isDependentType())
5712 return false;
5713
5714 TemplateParameterList *TemplateParams
5715 = FunctionTemplate->getTemplateParameters();
5716 llvm::SmallBitVector Deduced(TemplateParams->size());
5717 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
5718 Deduced);
5719
5720 return Deduced.any();
5721}

/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h

1//===- Type.h - C Language Family Type Representation -----------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// C Language Family Type Representation
11///
12/// This file defines the clang::Type interface and subclasses, used to
13/// represent types for languages in the C family.
14//
15//===----------------------------------------------------------------------===//
16
17#ifndef LLVM_CLANG_AST_TYPE_H
18#define LLVM_CLANG_AST_TYPE_H
19
20#include "clang/AST/NestedNameSpecifier.h"
21#include "clang/AST/TemplateName.h"
22#include "clang/Basic/AddressSpaces.h"
23#include "clang/Basic/AttrKinds.h"
24#include "clang/Basic/Diagnostic.h"
25#include "clang/Basic/ExceptionSpecificationType.h"
26#include "clang/Basic/LLVM.h"
27#include "clang/Basic/Linkage.h"
28#include "clang/Basic/PartialDiagnostic.h"
29#include "clang/Basic/SourceLocation.h"
30#include "clang/Basic/Specifiers.h"
31#include "clang/Basic/Visibility.h"
32#include "llvm/ADT/APInt.h"
33#include "llvm/ADT/APSInt.h"
34#include "llvm/ADT/ArrayRef.h"
35#include "llvm/ADT/FoldingSet.h"
36#include "llvm/ADT/None.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/Twine.h"
42#include "llvm/ADT/iterator_range.h"
43#include "llvm/Support/Casting.h"
44#include "llvm/Support/Compiler.h"
45#include "llvm/Support/ErrorHandling.h"
46#include "llvm/Support/PointerLikeTypeTraits.h"
47#include "llvm/Support/type_traits.h"
48#include "llvm/Support/TrailingObjects.h"
49#include <cassert>
50#include <cstddef>
51#include <cstdint>
52#include <cstring>
53#include <string>
54#include <type_traits>
55#include <utility>
56
57namespace clang {
58
59class ExtQuals;
60class QualType;
61class TagDecl;
62class Type;
63
64enum {
65 TypeAlignmentInBits = 4,
66 TypeAlignment = 1 << TypeAlignmentInBits
67};
68
69} // namespace clang
70
71namespace llvm {
72
73 template <typename T>
74 struct PointerLikeTypeTraits;
75 template<>
76 struct PointerLikeTypeTraits< ::clang::Type*> {
77 static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
78
79 static inline ::clang::Type *getFromVoidPointer(void *P) {
80 return static_cast< ::clang::Type*>(P);
81 }
82
83 enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
84 };
85
86 template<>
87 struct PointerLikeTypeTraits< ::clang::ExtQuals*> {
88 static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; }
89
90 static inline ::clang::ExtQuals *getFromVoidPointer(void *P) {
91 return static_cast< ::clang::ExtQuals*>(P);
92 }
93
94 enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
95 };
96
97} // namespace llvm
98
99namespace clang {
100
101class ASTContext;
102template <typename> class CanQual;
103class CXXRecordDecl;
104class DeclContext;
105class EnumDecl;
106class Expr;
107class ExtQualsTypeCommonBase;
108class FunctionDecl;
109class IdentifierInfo;
110class NamedDecl;
111class ObjCInterfaceDecl;
112class ObjCProtocolDecl;
113class ObjCTypeParamDecl;
114struct PrintingPolicy;
115class RecordDecl;
116class Stmt;
117class TagDecl;
118class TemplateArgument;
119class TemplateArgumentListInfo;
120class TemplateArgumentLoc;
121class TemplateTypeParmDecl;
122class TypedefNameDecl;
123class UnresolvedUsingTypenameDecl;
124
125using CanQualType = CanQual<Type>;
126
127// Provide forward declarations for all of the *Type classes.
128#define TYPE(Class, Base) class Class##Type;
129#include "clang/AST/TypeNodes.inc"
130
131/// The collection of all-type qualifiers we support.
132/// Clang supports five independent qualifiers:
133/// * C99: const, volatile, and restrict
134/// * MS: __unaligned
135/// * Embedded C (TR18037): address spaces
136/// * Objective C: the GC attributes (none, weak, or strong)
137class Qualifiers {
138public:
139 enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ.
140 Const = 0x1,
141 Restrict = 0x2,
142 Volatile = 0x4,
143 CVRMask = Const | Volatile | Restrict
144 };
145
146 enum GC {
147 GCNone = 0,
148 Weak,
149 Strong
150 };
151
152 enum ObjCLifetime {
153 /// There is no lifetime qualification on this type.
154 OCL_None,
155
156 /// This object can be modified without requiring retains or
157 /// releases.
158 OCL_ExplicitNone,
159
160 /// Assigning into this object requires the old value to be
161 /// released and the new value to be retained. The timing of the
162 /// release of the old value is inexact: it may be moved to
163 /// immediately after the last known point where the value is
164 /// live.
165 OCL_Strong,
166
167 /// Reading or writing from this object requires a barrier call.
168 OCL_Weak,
169
170 /// Assigning into this object requires a lifetime extension.
171 OCL_Autoreleasing
172 };
173
174 enum {
175 /// The maximum supported address space number.
176 /// 23 bits should be enough for anyone.
177 MaxAddressSpace = 0x7fffffu,
178
179 /// The width of the "fast" qualifier mask.
180 FastWidth = 3,
181
182 /// The fast qualifier mask.
183 FastMask = (1 << FastWidth) - 1
184 };
185
186 /// Returns the common set of qualifiers while removing them from
187 /// the given sets.
188 static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) {
189 // If both are only CVR-qualified, bit operations are sufficient.
190 if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) {
191 Qualifiers Q;
192 Q.Mask = L.Mask & R.Mask;
193 L.Mask &= ~Q.Mask;
194 R.Mask &= ~Q.Mask;
195 return Q;
196 }
197
198 Qualifiers Q;
199 unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers();
200 Q.addCVRQualifiers(CommonCRV);
201 L.removeCVRQualifiers(CommonCRV);
202 R.removeCVRQualifiers(CommonCRV);
203
204 if (L.getObjCGCAttr() == R.getObjCGCAttr()) {
205 Q.setObjCGCAttr(L.getObjCGCAttr());
206 L.removeObjCGCAttr();
207 R.removeObjCGCAttr();
208 }
209
210 if (L.getObjCLifetime() == R.getObjCLifetime()) {
211 Q.setObjCLifetime(L.getObjCLifetime());
212 L.removeObjCLifetime();
213 R.removeObjCLifetime();
214 }
215
216 if (L.getAddressSpace() == R.getAddressSpace()) {
217 Q.setAddressSpace(L.getAddressSpace());
218 L.removeAddressSpace();
219 R.removeAddressSpace();
220 }
221 return Q;
222 }
223
224 static Qualifiers fromFastMask(unsigned Mask) {
225 Qualifiers Qs;
226 Qs.addFastQualifiers(Mask);
227 return Qs;
228 }
229
230 static Qualifiers fromCVRMask(unsigned CVR) {
231 Qualifiers Qs;
232 Qs.addCVRQualifiers(CVR);
233 return Qs;
234 }
235
236 static Qualifiers fromCVRUMask(unsigned CVRU) {
237 Qualifiers Qs;
238 Qs.addCVRUQualifiers(CVRU);
239 return Qs;
240 }
241
242 // Deserialize qualifiers from an opaque representation.
243 static Qualifiers fromOpaqueValue(unsigned opaque) {
244 Qualifiers Qs;
245 Qs.Mask = opaque;
246 return Qs;
247 }
248
249 // Serialize these qualifiers into an opaque representation.
250 unsigned getAsOpaqueValue() const {
251 return Mask;
252 }
253
254 bool hasConst() const { return Mask & Const; }
255 bool hasOnlyConst() const { return Mask == Const; }
256 void removeConst() { Mask &= ~Const; }
257 void addConst() { Mask |= Const; }
258
259 bool hasVolatile() const { return Mask & Volatile; }
260 bool hasOnlyVolatile() const { return Mask == Volatile; }
261 void removeVolatile() { Mask &= ~Volatile; }
262 void addVolatile() { Mask |= Volatile; }
263
264 bool hasRestrict() const { return Mask & Restrict; }
265 bool hasOnlyRestrict() const { return Mask == Restrict; }
266 void removeRestrict() { Mask &= ~Restrict; }
267 void addRestrict() { Mask |= Restrict; }
268
269 bool hasCVRQualifiers() const { return getCVRQualifiers(); }
270 unsigned getCVRQualifiers() const { return Mask & CVRMask; }
271 unsigned getCVRUQualifiers() const { return Mask & (CVRMask | UMask); }
272
273 void setCVRQualifiers(unsigned mask) {
274 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 274, __PRETTY_FUNCTION__))
;
275 Mask = (Mask & ~CVRMask) | mask;
276 }
277 void removeCVRQualifiers(unsigned mask) {
278 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 278, __PRETTY_FUNCTION__))
;
279 Mask &= ~mask;
280 }
281 void removeCVRQualifiers() {
282 removeCVRQualifiers(CVRMask);
283 }
284 void addCVRQualifiers(unsigned mask) {
285 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 285, __PRETTY_FUNCTION__))
;
286 Mask |= mask;
287 }
288 void addCVRUQualifiers(unsigned mask) {
289 assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits")((!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask & ~UMask) && \"bitmask contains non-CVRU bits\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 289, __PRETTY_FUNCTION__))
;
290 Mask |= mask;
291 }
292
293 bool hasUnaligned() const { return Mask & UMask; }
294 void setUnaligned(bool flag) {
295 Mask = (Mask & ~UMask) | (flag ? UMask : 0);
296 }
297 void removeUnaligned() { Mask &= ~UMask; }
298 void addUnaligned() { Mask |= UMask; }
299
300 bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
301 GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
302 void setObjCGCAttr(GC type) {
303 Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
304 }
305 void removeObjCGCAttr() { setObjCGCAttr(GCNone); }
306 void addObjCGCAttr(GC type) {
307 assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 307, __PRETTY_FUNCTION__))
;
308 setObjCGCAttr(type);
309 }
310 Qualifiers withoutObjCGCAttr() const {
311 Qualifiers qs = *this;
312 qs.removeObjCGCAttr();
313 return qs;
314 }
315 Qualifiers withoutObjCLifetime() const {
316 Qualifiers qs = *this;
317 qs.removeObjCLifetime();
318 return qs;
319 }
320 Qualifiers withoutAddressSpace() const {
321 Qualifiers qs = *this;
322 qs.removeAddressSpace();
323 return qs;
324 }
325
326 bool hasObjCLifetime() const { return Mask & LifetimeMask; }
327 ObjCLifetime getObjCLifetime() const {
328 return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift);
329 }
330 void setObjCLifetime(ObjCLifetime type) {
331 Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift);
332 }
333 void removeObjCLifetime() { setObjCLifetime(OCL_None); }
334 void addObjCLifetime(ObjCLifetime type) {
335 assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 335, __PRETTY_FUNCTION__))
;
336 assert(!hasObjCLifetime())((!hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("!hasObjCLifetime()", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 336, __PRETTY_FUNCTION__))
;
337 Mask |= (type << LifetimeShift);
338 }
339
340 /// True if the lifetime is neither None or ExplicitNone.
341 bool hasNonTrivialObjCLifetime() const {
342 ObjCLifetime lifetime = getObjCLifetime();
343 return (lifetime > OCL_ExplicitNone);
344 }
345
346 /// True if the lifetime is either strong or weak.
347 bool hasStrongOrWeakObjCLifetime() const {
348 ObjCLifetime lifetime = getObjCLifetime();
349 return (lifetime == OCL_Strong || lifetime == OCL_Weak);
350 }
351
352 bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
353 LangAS getAddressSpace() const {
354 return static_cast<LangAS>(Mask >> AddressSpaceShift);
355 }
356 bool hasTargetSpecificAddressSpace() const {
357 return isTargetAddressSpace(getAddressSpace());
358 }
359 /// Get the address space attribute value to be printed by diagnostics.
360 unsigned getAddressSpaceAttributePrintValue() const {
361 auto Addr = getAddressSpace();
362 // This function is not supposed to be used with language specific
363 // address spaces. If that happens, the diagnostic message should consider
364 // printing the QualType instead of the address space value.
365 assert(Addr == LangAS::Default || hasTargetSpecificAddressSpace())((Addr == LangAS::Default || hasTargetSpecificAddressSpace())
? static_cast<void> (0) : __assert_fail ("Addr == LangAS::Default || hasTargetSpecificAddressSpace()"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 365, __PRETTY_FUNCTION__))
;
366 if (Addr != LangAS::Default)
367 return toTargetAddressSpace(Addr);
368 // TODO: The diagnostic messages where Addr may be 0 should be fixed
369 // since it cannot differentiate the situation where 0 denotes the default
370 // address space or user specified __attribute__((address_space(0))).
371 return 0;
372 }
373 void setAddressSpace(LangAS space) {
374 assert((unsigned)space <= MaxAddressSpace)(((unsigned)space <= MaxAddressSpace) ? static_cast<void
> (0) : __assert_fail ("(unsigned)space <= MaxAddressSpace"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 374, __PRETTY_FUNCTION__))
;
375 Mask = (Mask & ~AddressSpaceMask)
376 | (((uint32_t) space) << AddressSpaceShift);
377 }
378 void removeAddressSpace() { setAddressSpace(LangAS::Default); }
379 void addAddressSpace(LangAS space) {
380 assert(space != LangAS::Default)((space != LangAS::Default) ? static_cast<void> (0) : __assert_fail
("space != LangAS::Default", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 380, __PRETTY_FUNCTION__))
;
381 setAddressSpace(space);
382 }
383
384 // Fast qualifiers are those that can be allocated directly
385 // on a QualType object.
386 bool hasFastQualifiers() const { return getFastQualifiers(); }
387 unsigned getFastQualifiers() const { return Mask & FastMask; }
388 void setFastQualifiers(unsigned mask) {
389 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 389, __PRETTY_FUNCTION__))
;
390 Mask = (Mask & ~FastMask) | mask;
391 }
392 void removeFastQualifiers(unsigned mask) {
393 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 393, __PRETTY_FUNCTION__))
;
394 Mask &= ~mask;
395 }
396 void removeFastQualifiers() {
397 removeFastQualifiers(FastMask);
398 }
399 void addFastQualifiers(unsigned mask) {
400 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 400, __PRETTY_FUNCTION__))
;
401 Mask |= mask;
402 }
403
404 /// Return true if the set contains any qualifiers which require an ExtQuals
405 /// node to be allocated.
406 bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
407 Qualifiers getNonFastQualifiers() const {
408 Qualifiers Quals = *this;
409 Quals.setFastQualifiers(0);
410 return Quals;
411 }
412
413 /// Return true if the set contains any qualifiers.
414 bool hasQualifiers() const { return Mask; }
415 bool empty() const { return !Mask; }
416
417 /// Add the qualifiers from the given set to this set.
418 void addQualifiers(Qualifiers Q) {
419 // If the other set doesn't have any non-boolean qualifiers, just
420 // bit-or it in.
421 if (!(Q.Mask & ~CVRMask))
422 Mask |= Q.Mask;
423 else {
424 Mask |= (Q.Mask & CVRMask);
425 if (Q.hasAddressSpace())
426 addAddressSpace(Q.getAddressSpace());
427 if (Q.hasObjCGCAttr())
428 addObjCGCAttr(Q.getObjCGCAttr());
429 if (Q.hasObjCLifetime())
430 addObjCLifetime(Q.getObjCLifetime());
431 }
432 }
433
434 /// Remove the qualifiers from the given set from this set.
435 void removeQualifiers(Qualifiers Q) {
436 // If the other set doesn't have any non-boolean qualifiers, just
437 // bit-and the inverse in.
438 if (!(Q.Mask & ~CVRMask))
439 Mask &= ~Q.Mask;
440 else {
441 Mask &= ~(Q.Mask & CVRMask);
442 if (getObjCGCAttr() == Q.getObjCGCAttr())
443 removeObjCGCAttr();
444 if (getObjCLifetime() == Q.getObjCLifetime())
445 removeObjCLifetime();
446 if (getAddressSpace() == Q.getAddressSpace())
447 removeAddressSpace();
448 }
449 }
450
451 /// Add the qualifiers from the given set to this set, given that
452 /// they don't conflict.
453 void addConsistentQualifiers(Qualifiers qs) {
454 assert(getAddressSpace() == qs.getAddressSpace() ||((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace
() || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail
("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 455, __PRETTY_FUNCTION__))
455 !hasAddressSpace() || !qs.hasAddressSpace())((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace
() || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail
("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 455, __PRETTY_FUNCTION__))
;
456 assert(getObjCGCAttr() == qs.getObjCGCAttr() ||((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() ||
!qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail
("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 457, __PRETTY_FUNCTION__))
457 !hasObjCGCAttr() || !qs.hasObjCGCAttr())((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() ||
!qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail
("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 457, __PRETTY_FUNCTION__))
;
458 assert(getObjCLifetime() == qs.getObjCLifetime() ||((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime
() || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 459, __PRETTY_FUNCTION__))
459 !hasObjCLifetime() || !qs.hasObjCLifetime())((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime
() || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 459, __PRETTY_FUNCTION__))
;
460 Mask |= qs.Mask;
461 }
462
463 /// Returns true if address space A is equal to or a superset of B.
464 /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of
465 /// overlapping address spaces.
466 /// CL1.1 or CL1.2:
467 /// every address space is a superset of itself.
468 /// CL2.0 adds:
469 /// __generic is a superset of any address space except for __constant.
470 static bool isAddressSpaceSupersetOf(LangAS A, LangAS B) {
471 // Address spaces must match exactly.
472 return A == B ||
473 // Otherwise in OpenCLC v2.0 s6.5.5: every address space except
474 // for __constant can be used as __generic.
475 (A == LangAS::opencl_generic && B != LangAS::opencl_constant);
476 }
477
478 /// Returns true if the address space in these qualifiers is equal to or
479 /// a superset of the address space in the argument qualifiers.
480 bool isAddressSpaceSupersetOf(Qualifiers other) const {
481 return isAddressSpaceSupersetOf(getAddressSpace(), other.getAddressSpace());
482 }
483
484 /// Determines if these qualifiers compatibly include another set.
485 /// Generally this answers the question of whether an object with the other
486 /// qualifiers can be safely used as an object with these qualifiers.
487 bool compatiblyIncludes(Qualifiers other) const {
488 return isAddressSpaceSupersetOf(other) &&
489 // ObjC GC qualifiers can match, be added, or be removed, but can't
490 // be changed.
491 (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() ||
492 !other.hasObjCGCAttr()) &&
493 // ObjC lifetime qualifiers must match exactly.
494 getObjCLifetime() == other.getObjCLifetime() &&
495 // CVR qualifiers may subset.
496 (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) &&
497 // U qualifier may superset.
498 (!other.hasUnaligned() || hasUnaligned());
499 }
500
501 /// Determines if these qualifiers compatibly include another set of
502 /// qualifiers from the narrow perspective of Objective-C ARC lifetime.
503 ///
504 /// One set of Objective-C lifetime qualifiers compatibly includes the other
505 /// if the lifetime qualifiers match, or if both are non-__weak and the
506 /// including set also contains the 'const' qualifier, or both are non-__weak
507 /// and one is None (which can only happen in non-ARC modes).
508 bool compatiblyIncludesObjCLifetime(Qualifiers other) const {
509 if (getObjCLifetime() == other.getObjCLifetime())
510 return true;
511
512 if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak)
513 return false;
514
515 if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None)
516 return true;
517
518 return hasConst();
519 }
520
521 /// Determine whether this set of qualifiers is a strict superset of
522 /// another set of qualifiers, not considering qualifier compatibility.
523 bool isStrictSupersetOf(Qualifiers Other) const;
524
525 bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
526 bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
527
528 explicit operator bool() const { return hasQualifiers(); }
529
530 Qualifiers &operator+=(Qualifiers R) {
531 addQualifiers(R);
532 return *this;
533 }
534
535 // Union two qualifier sets. If an enumerated qualifier appears
536 // in both sets, use the one from the right.
537 friend Qualifiers operator+(Qualifiers L, Qualifiers R) {
538 L += R;
539 return L;
540 }
541
542 Qualifiers &operator-=(Qualifiers R) {
543 removeQualifiers(R);
544 return *this;
545 }
546
547 /// Compute the difference between two qualifier sets.
548 friend Qualifiers operator-(Qualifiers L, Qualifiers R) {
549 L -= R;
550 return L;
551 }
552
553 std::string getAsString() const;
554 std::string getAsString(const PrintingPolicy &Policy) const;
555
556 bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const;
557 void print(raw_ostream &OS, const PrintingPolicy &Policy,
558 bool appendSpaceIfNonEmpty = false) const;
559
560 void Profile(llvm::FoldingSetNodeID &ID) const {
561 ID.AddInteger(Mask);
562 }
563
564private:
565 // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31|
566 // |C R V|U|GCAttr|Lifetime|AddressSpace|
567 uint32_t Mask = 0;
568
569 static const uint32_t UMask = 0x8;
570 static const uint32_t UShift = 3;
571 static const uint32_t GCAttrMask = 0x30;
572 static const uint32_t GCAttrShift = 4;
573 static const uint32_t LifetimeMask = 0x1C0;
574 static const uint32_t LifetimeShift = 6;
575 static const uint32_t AddressSpaceMask =
576 ~(CVRMask | UMask | GCAttrMask | LifetimeMask);
577 static const uint32_t AddressSpaceShift = 9;
578};
579
580/// A std::pair-like structure for storing a qualified type split
581/// into its local qualifiers and its locally-unqualified type.
582struct SplitQualType {
583 /// The locally-unqualified type.
584 const Type *Ty = nullptr;
585
586 /// The local qualifiers.
587 Qualifiers Quals;
588
589 SplitQualType() = default;
590 SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {}
591
592 SplitQualType getSingleStepDesugaredType() const; // end of this file
593
594 // Make std::tie work.
595 std::pair<const Type *,Qualifiers> asPair() const {
596 return std::pair<const Type *, Qualifiers>(Ty, Quals);
597 }
598
599 friend bool operator==(SplitQualType a, SplitQualType b) {
600 return a.Ty == b.Ty && a.Quals == b.Quals;
601 }
602 friend bool operator!=(SplitQualType a, SplitQualType b) {
603 return a.Ty != b.Ty || a.Quals != b.Quals;
604 }
605};
606
607/// The kind of type we are substituting Objective-C type arguments into.
608///
609/// The kind of substitution affects the replacement of type parameters when
610/// no concrete type information is provided, e.g., when dealing with an
611/// unspecialized type.
612enum class ObjCSubstitutionContext {
613 /// An ordinary type.
614 Ordinary,
615
616 /// The result type of a method or function.
617 Result,
618
619 /// The parameter type of a method or function.
620 Parameter,
621
622 /// The type of a property.
623 Property,
624
625 /// The superclass of a type.
626 Superclass,
627};
628
629/// A (possibly-)qualified type.
630///
631/// For efficiency, we don't store CV-qualified types as nodes on their
632/// own: instead each reference to a type stores the qualifiers. This
633/// greatly reduces the number of nodes we need to allocate for types (for
634/// example we only need one for 'int', 'const int', 'volatile int',
635/// 'const volatile int', etc).
636///
637/// As an added efficiency bonus, instead of making this a pair, we
638/// just store the two bits we care about in the low bits of the
639/// pointer. To handle the packing/unpacking, we make QualType be a
640/// simple wrapper class that acts like a smart pointer. A third bit
641/// indicates whether there are extended qualifiers present, in which
642/// case the pointer points to a special structure.
643class QualType {
644 friend class QualifierCollector;
645
646 // Thankfully, these are efficiently composable.
647 llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>,
648 Qualifiers::FastWidth> Value;
649
650 const ExtQuals *getExtQualsUnsafe() const {
651 return Value.getPointer().get<const ExtQuals*>();
652 }
653
654 const Type *getTypePtrUnsafe() const {
655 return Value.getPointer().get<const Type*>();
656 }
657
658 const ExtQualsTypeCommonBase *getCommonPtr() const {
659 assert(!isNull() && "Cannot retrieve a NULL type pointer")((!isNull() && "Cannot retrieve a NULL type pointer")
? static_cast<void> (0) : __assert_fail ("!isNull() && \"Cannot retrieve a NULL type pointer\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 659, __PRETTY_FUNCTION__))
;
660 auto CommonPtrVal = reinterpret_cast<uintptr_t>(Value.getOpaqueValue());
661 CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1);
662 return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal);
663 }
664
665public:
666 QualType() = default;
667 QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
668 QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
669
670 unsigned getLocalFastQualifiers() const { return Value.getInt(); }
671 void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
672
673 /// Retrieves a pointer to the underlying (unqualified) type.
674 ///
675 /// This function requires that the type not be NULL. If the type might be
676 /// NULL, use the (slightly less efficient) \c getTypePtrOrNull().
677 const Type *getTypePtr() const;
678
679 const Type *getTypePtrOrNull() const;
680
681 /// Retrieves a pointer to the name of the base type.
682 const IdentifierInfo *getBaseTypeIdentifier() const;
683
684 /// Divides a QualType into its unqualified type and a set of local
685 /// qualifiers.
686 SplitQualType split() const;
687
688 void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
689
690 static QualType getFromOpaquePtr(const void *Ptr) {
691 QualType T;
692 T.Value.setFromOpaqueValue(const_cast<void*>(Ptr));
693 return T;
694 }
695
696 const Type &operator*() const {
697 return *getTypePtr();
698 }
699
700 const Type *operator->() const {
701 return getTypePtr();
702 }
703
704 bool isCanonical() const;
705 bool isCanonicalAsParam() const;
706
707 /// Return true if this QualType doesn't point to a type yet.
708 bool isNull() const {
709 return Value.getPointer().isNull();
9
Calling 'PointerUnion::isNull'
12
Returning from 'PointerUnion::isNull'
13
Returning zero, which participates in a condition later
710 }
711
712 /// Determine whether this particular QualType instance has the
713 /// "const" qualifier set, without looking through typedefs that may have
714 /// added "const" at a different level.
715 bool isLocalConstQualified() const {
716 return (getLocalFastQualifiers() & Qualifiers::Const);
717 }
718
719 /// Determine whether this type is const-qualified.
720 bool isConstQualified() const;
721
722 /// Determine whether this particular QualType instance has the
723 /// "restrict" qualifier set, without looking through typedefs that may have
724 /// added "restrict" at a different level.
725 bool isLocalRestrictQualified() const {
726 return (getLocalFastQualifiers() & Qualifiers::Restrict);
727 }
728
729 /// Determine whether this type is restrict-qualified.
730 bool isRestrictQualified() const;
731
732 /// Determine whether this particular QualType instance has the
733 /// "volatile" qualifier set, without looking through typedefs that may have
734 /// added "volatile" at a different level.
735 bool isLocalVolatileQualified() const {
736 return (getLocalFastQualifiers() & Qualifiers::Volatile);
737 }
738
739 /// Determine whether this type is volatile-qualified.
740 bool isVolatileQualified() const;
741
742 /// Determine whether this particular QualType instance has any
743 /// qualifiers, without looking through any typedefs that might add
744 /// qualifiers at a different level.
745 bool hasLocalQualifiers() const {
746 return getLocalFastQualifiers() || hasLocalNonFastQualifiers();
747 }
748
749 /// Determine whether this type has any qualifiers.
750 bool hasQualifiers() const;
751
752 /// Determine whether this particular QualType instance has any
753 /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
754 /// instance.
755 bool hasLocalNonFastQualifiers() const {
756 return Value.getPointer().is<const ExtQuals*>();
757 }
758
759 /// Retrieve the set of qualifiers local to this particular QualType
760 /// instance, not including any qualifiers acquired through typedefs or
761 /// other sugar.
762 Qualifiers getLocalQualifiers() const;
763
764 /// Retrieve the set of qualifiers applied to this type.
765 Qualifiers getQualifiers() const;
766
767 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
768 /// local to this particular QualType instance, not including any qualifiers
769 /// acquired through typedefs or other sugar.
770 unsigned getLocalCVRQualifiers() const {
771 return getLocalFastQualifiers();
772 }
773
774 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
775 /// applied to this type.
776 unsigned getCVRQualifiers() const;
777
778 bool isConstant(const ASTContext& Ctx) const {
779 return QualType::isConstant(*this, Ctx);
780 }
781
782 /// Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
783 bool isPODType(const ASTContext &Context) const;
784
785 /// Return true if this is a POD type according to the rules of the C++98
786 /// standard, regardless of the current compilation's language.
787 bool isCXX98PODType(const ASTContext &Context) const;
788
789 /// Return true if this is a POD type according to the more relaxed rules
790 /// of the C++11 standard, regardless of the current compilation's language.
791 /// (C++0x [basic.types]p9). Note that, unlike
792 /// CXXRecordDecl::isCXX11StandardLayout, this takes DRs into account.
793 bool isCXX11PODType(const ASTContext &Context) const;
794
795 /// Return true if this is a trivial type per (C++0x [basic.types]p9)
796 bool isTrivialType(const ASTContext &Context) const;
797
798 /// Return true if this is a trivially copyable type (C++0x [basic.types]p9)
799 bool isTriviallyCopyableType(const ASTContext &Context) const;
800
801
802 /// Returns true if it is a class and it might be dynamic.
803 bool mayBeDynamicClass() const;
804
805 /// Returns true if it is not a class or if the class might not be dynamic.
806 bool mayBeNotDynamicClass() const;
807
808 // Don't promise in the API that anything besides 'const' can be
809 // easily added.
810
811 /// Add the `const` type qualifier to this QualType.
812 void addConst() {
813 addFastQualifiers(Qualifiers::Const);
814 }
815 QualType withConst() const {
816 return withFastQualifiers(Qualifiers::Const);
817 }
818
819 /// Add the `volatile` type qualifier to this QualType.
820 void addVolatile() {
821 addFastQualifiers(Qualifiers::Volatile);
822 }
823 QualType withVolatile() const {
824 return withFastQualifiers(Qualifiers::Volatile);
825 }
826
827 /// Add the `restrict` qualifier to this QualType.
828 void addRestrict() {
829 addFastQualifiers(Qualifiers::Restrict);
830 }
831 QualType withRestrict() const {
832 return withFastQualifiers(Qualifiers::Restrict);
833 }
834
835 QualType withCVRQualifiers(unsigned CVR) const {
836 return withFastQualifiers(CVR);
837 }
838
839 void addFastQualifiers(unsigned TQs) {
840 assert(!(TQs & ~Qualifiers::FastMask)((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!"
) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 841, __PRETTY_FUNCTION__))
841 && "non-fast qualifier bits set in mask!")((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!"
) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 841, __PRETTY_FUNCTION__))
;
842 Value.setInt(Value.getInt() | TQs);
843 }
844
845 void removeLocalConst();
846 void removeLocalVolatile();
847 void removeLocalRestrict();
848 void removeLocalCVRQualifiers(unsigned Mask);
849
850 void removeLocalFastQualifiers() { Value.setInt(0); }
851 void removeLocalFastQualifiers(unsigned Mask) {
852 assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers")((!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!(Mask & ~Qualifiers::FastMask) && \"mask has non-fast qualifiers\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 852, __PRETTY_FUNCTION__))
;
853 Value.setInt(Value.getInt() & ~Mask);
854 }
855
856 // Creates a type with the given qualifiers in addition to any
857 // qualifiers already on this type.
858 QualType withFastQualifiers(unsigned TQs) const {
859 QualType T = *this;
860 T.addFastQualifiers(TQs);
861 return T;
862 }
863
864 // Creates a type with exactly the given fast qualifiers, removing
865 // any existing fast qualifiers.
866 QualType withExactLocalFastQualifiers(unsigned TQs) const {
867 return withoutLocalFastQualifiers().withFastQualifiers(TQs);
868 }
869
870 // Removes fast qualifiers, but leaves any extended qualifiers in place.
871 QualType withoutLocalFastQualifiers() const {
872 QualType T = *this;
873 T.removeLocalFastQualifiers();
874 return T;
875 }
876
877 QualType getCanonicalType() const;
878
879 /// Return this type with all of the instance-specific qualifiers
880 /// removed, but without removing any qualifiers that may have been applied
881 /// through typedefs.
882 QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); }
883
884 /// Retrieve the unqualified variant of the given type,
885 /// removing as little sugar as possible.
886 ///
887 /// This routine looks through various kinds of sugar to find the
888 /// least-desugared type that is unqualified. For example, given:
889 ///
890 /// \code
891 /// typedef int Integer;
892 /// typedef const Integer CInteger;
893 /// typedef CInteger DifferenceType;
894 /// \endcode
895 ///
896 /// Executing \c getUnqualifiedType() on the type \c DifferenceType will
897 /// desugar until we hit the type \c Integer, which has no qualifiers on it.
898 ///
899 /// The resulting type might still be qualified if it's sugar for an array
900 /// type. To strip qualifiers even from within a sugared array type, use
901 /// ASTContext::getUnqualifiedArrayType.
902 inline QualType getUnqualifiedType() const;
903
904 /// Retrieve the unqualified variant of the given type, removing as little
905 /// sugar as possible.
906 ///
907 /// Like getUnqualifiedType(), but also returns the set of
908 /// qualifiers that were built up.
909 ///
910 /// The resulting type might still be qualified if it's sugar for an array
911 /// type. To strip qualifiers even from within a sugared array type, use
912 /// ASTContext::getUnqualifiedArrayType.
913 inline SplitQualType getSplitUnqualifiedType() const;
914
915 /// Determine whether this type is more qualified than the other
916 /// given type, requiring exact equality for non-CVR qualifiers.
917 bool isMoreQualifiedThan(QualType Other) const;
918
919 /// Determine whether this type is at least as qualified as the other
920 /// given type, requiring exact equality for non-CVR qualifiers.
921 bool isAtLeastAsQualifiedAs(QualType Other) const;
922
923 QualType getNonReferenceType() const;
924
925 /// Determine the type of a (typically non-lvalue) expression with the
926 /// specified result type.
927 ///
928 /// This routine should be used for expressions for which the return type is
929 /// explicitly specified (e.g., in a cast or call) and isn't necessarily
930 /// an lvalue. It removes a top-level reference (since there are no
931 /// expressions of reference type) and deletes top-level cvr-qualifiers
932 /// from non-class types (in C++) or all types (in C).
933 QualType getNonLValueExprType(const ASTContext &Context) const;
934
935 /// Return the specified type with any "sugar" removed from
936 /// the type. This takes off typedefs, typeof's etc. If the outer level of
937 /// the type is already concrete, it returns it unmodified. This is similar
938 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
939 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
940 /// concrete.
941 ///
942 /// Qualifiers are left in place.
943 QualType getDesugaredType(const ASTContext &Context) const {
944 return getDesugaredType(*this, Context);
945 }
946
947 SplitQualType getSplitDesugaredType() const {
948 return getSplitDesugaredType(*this);
949 }
950
951 /// Return the specified type with one level of "sugar" removed from
952 /// the type.
953 ///
954 /// This routine takes off the first typedef, typeof, etc. If the outer level
955 /// of the type is already concrete, it returns it unmodified.
956 QualType getSingleStepDesugaredType(const ASTContext &Context) const {
957 return getSingleStepDesugaredTypeImpl(*this, Context);
958 }
959
960 /// Returns the specified type after dropping any
961 /// outer-level parentheses.
962 QualType IgnoreParens() const {
963 if (isa<ParenType>(*this))
964 return QualType::IgnoreParens(*this);
965 return *this;
966 }
967
968 /// Indicate whether the specified types and qualifiers are identical.
969 friend bool operator==(const QualType &LHS, const QualType &RHS) {
970 return LHS.Value == RHS.Value;
971 }
972 friend bool operator!=(const QualType &LHS, const QualType &RHS) {
973 return LHS.Value != RHS.Value;
974 }
975 friend bool operator<(const QualType &LHS, const QualType &RHS) {
976 return LHS.Value < RHS.Value;
977 }
978
979 static std::string getAsString(SplitQualType split,
980 const PrintingPolicy &Policy) {
981 return getAsString(split.Ty, split.Quals, Policy);
982 }
983 static std::string getAsString(const Type *ty, Qualifiers qs,
984 const PrintingPolicy &Policy);
985
986 std::string getAsString() const;
987 std::string getAsString(const PrintingPolicy &Policy) const;
988
989 void print(raw_ostream &OS, const PrintingPolicy &Policy,
990 const Twine &PlaceHolder = Twine(),
991 unsigned Indentation = 0) const;
992
993 static void print(SplitQualType split, raw_ostream &OS,
994 const PrintingPolicy &policy, const Twine &PlaceHolder,
995 unsigned Indentation = 0) {
996 return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation);
997 }
998
999 static void print(const Type *ty, Qualifiers qs,
1000 raw_ostream &OS, const PrintingPolicy &policy,
1001 const Twine &PlaceHolder,
1002 unsigned Indentation = 0);
1003
1004 void getAsStringInternal(std::string &Str,
1005 const PrintingPolicy &Policy) const;
1006
1007 static void getAsStringInternal(SplitQualType split, std::string &out,
1008 const PrintingPolicy &policy) {
1009 return getAsStringInternal(split.Ty, split.Quals, out, policy);
1010 }
1011
1012 static void getAsStringInternal(const Type *ty, Qualifiers qs,
1013 std::string &out,
1014 const PrintingPolicy &policy);
1015
1016 class StreamedQualTypeHelper {
1017 const QualType &T;
1018 const PrintingPolicy &Policy;
1019 const Twine &PlaceHolder;
1020 unsigned Indentation;
1021
1022 public:
1023 StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy,
1024 const Twine &PlaceHolder, unsigned Indentation)
1025 : T(T), Policy(Policy), PlaceHolder(PlaceHolder),
1026 Indentation(Indentation) {}
1027
1028 friend raw_ostream &operator<<(raw_ostream &OS,
1029 const StreamedQualTypeHelper &SQT) {
1030 SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation);
1031 return OS;
1032 }
1033 };
1034
1035 StreamedQualTypeHelper stream(const PrintingPolicy &Policy,
1036 const Twine &PlaceHolder = Twine(),
1037 unsigned Indentation = 0) const {
1038 return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation);
1039 }
1040
1041 void dump(const char *s) const;
1042 void dump() const;
1043 void dump(llvm::raw_ostream &OS) const;
1044
1045 void Profile(llvm::FoldingSetNodeID &ID) const {
1046 ID.AddPointer(getAsOpaquePtr());
1047 }
1048
1049 /// Return the address space of this type.
1050 inline LangAS getAddressSpace() const;
1051
1052 /// Returns gc attribute of this type.
1053 inline Qualifiers::GC getObjCGCAttr() const;
1054
1055 /// true when Type is objc's weak.
1056 bool isObjCGCWeak() const {
1057 return getObjCGCAttr() == Qualifiers::Weak;
1058 }
1059
1060 /// true when Type is objc's strong.
1061 bool isObjCGCStrong() const {
1062 return getObjCGCAttr() == Qualifiers::Strong;
1063 }
1064
1065 /// Returns lifetime attribute of this type.
1066 Qualifiers::ObjCLifetime getObjCLifetime() const {
1067 return getQualifiers().getObjCLifetime();
1068 }
1069
1070 bool hasNonTrivialObjCLifetime() const {
1071 return getQualifiers().hasNonTrivialObjCLifetime();
1072 }
1073
1074 bool hasStrongOrWeakObjCLifetime() const {
1075 return getQualifiers().hasStrongOrWeakObjCLifetime();
1076 }
1077
1078 // true when Type is objc's weak and weak is enabled but ARC isn't.
1079 bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const;
1080
1081 enum PrimitiveDefaultInitializeKind {
1082 /// The type does not fall into any of the following categories. Note that
1083 /// this case is zero-valued so that values of this enum can be used as a
1084 /// boolean condition for non-triviality.
1085 PDIK_Trivial,
1086
1087 /// The type is an Objective-C retainable pointer type that is qualified
1088 /// with the ARC __strong qualifier.
1089 PDIK_ARCStrong,
1090
1091 /// The type is an Objective-C retainable pointer type that is qualified
1092 /// with the ARC __weak qualifier.
1093 PDIK_ARCWeak,
1094
1095 /// The type is a struct containing a field whose type is not PCK_Trivial.
1096 PDIK_Struct
1097 };
1098
1099 /// Functions to query basic properties of non-trivial C struct types.
1100
1101 /// Check if this is a non-trivial type that would cause a C struct
1102 /// transitively containing this type to be non-trivial to default initialize
1103 /// and return the kind.
1104 PrimitiveDefaultInitializeKind
1105 isNonTrivialToPrimitiveDefaultInitialize() const;
1106
1107 enum PrimitiveCopyKind {
1108 /// The type does not fall into any of the following categories. Note that
1109 /// this case is zero-valued so that values of this enum can be used as a
1110 /// boolean condition for non-triviality.
1111 PCK_Trivial,
1112
1113 /// The type would be trivial except that it is volatile-qualified. Types
1114 /// that fall into one of the other non-trivial cases may additionally be
1115 /// volatile-qualified.
1116 PCK_VolatileTrivial,
1117
1118 /// The type is an Objective-C retainable pointer type that is qualified
1119 /// with the ARC __strong qualifier.
1120 PCK_ARCStrong,
1121
1122 /// The type is an Objective-C retainable pointer type that is qualified
1123 /// with the ARC __weak qualifier.
1124 PCK_ARCWeak,
1125
1126 /// The type is a struct containing a field whose type is neither
1127 /// PCK_Trivial nor PCK_VolatileTrivial.
1128 /// Note that a C++ struct type does not necessarily match this; C++ copying
1129 /// semantics are too complex to express here, in part because they depend
1130 /// on the exact constructor or assignment operator that is chosen by
1131 /// overload resolution to do the copy.
1132 PCK_Struct
1133 };
1134
1135 /// Check if this is a non-trivial type that would cause a C struct
1136 /// transitively containing this type to be non-trivial to copy and return the
1137 /// kind.
1138 PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const;
1139
1140 /// Check if this is a non-trivial type that would cause a C struct
1141 /// transitively containing this type to be non-trivial to destructively
1142 /// move and return the kind. Destructive move in this context is a C++-style
1143 /// move in which the source object is placed in a valid but unspecified state
1144 /// after it is moved, as opposed to a truly destructive move in which the
1145 /// source object is placed in an uninitialized state.
1146 PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const;
1147
1148 enum DestructionKind {
1149 DK_none,
1150 DK_cxx_destructor,
1151 DK_objc_strong_lifetime,
1152 DK_objc_weak_lifetime,
1153 DK_nontrivial_c_struct
1154 };
1155
1156 /// Returns a nonzero value if objects of this type require
1157 /// non-trivial work to clean up after. Non-zero because it's
1158 /// conceivable that qualifiers (objc_gc(weak)?) could make
1159 /// something require destruction.
1160 DestructionKind isDestructedType() const {
1161 return isDestructedTypeImpl(*this);
1162 }
1163
1164 /// Check if this is or contains a C union that is non-trivial to
1165 /// default-initialize, which is a union that has a member that is non-trivial
1166 /// to default-initialize. If this returns true,
1167 /// isNonTrivialToPrimitiveDefaultInitialize returns PDIK_Struct.
1168 bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const;
1169
1170 /// Check if this is or contains a C union that is non-trivial to destruct,
1171 /// which is a union that has a member that is non-trivial to destruct. If
1172 /// this returns true, isDestructedType returns DK_nontrivial_c_struct.
1173 bool hasNonTrivialToPrimitiveDestructCUnion() const;
1174
1175 /// Check if this is or contains a C union that is non-trivial to copy, which
1176 /// is a union that has a member that is non-trivial to copy. If this returns
1177 /// true, isNonTrivialToPrimitiveCopy returns PCK_Struct.
1178 bool hasNonTrivialToPrimitiveCopyCUnion() const;
1179
1180 /// Determine whether expressions of the given type are forbidden
1181 /// from being lvalues in C.
1182 ///
1183 /// The expression types that are forbidden to be lvalues are:
1184 /// - 'void', but not qualified void
1185 /// - function types
1186 ///
1187 /// The exact rule here is C99 6.3.2.1:
1188 /// An lvalue is an expression with an object type or an incomplete
1189 /// type other than void.
1190 bool isCForbiddenLValueType() const;
1191
1192 /// Substitute type arguments for the Objective-C type parameters used in the
1193 /// subject type.
1194 ///
1195 /// \param ctx ASTContext in which the type exists.
1196 ///
1197 /// \param typeArgs The type arguments that will be substituted for the
1198 /// Objective-C type parameters in the subject type, which are generally
1199 /// computed via \c Type::getObjCSubstitutions. If empty, the type
1200 /// parameters will be replaced with their bounds or id/Class, as appropriate
1201 /// for the context.
1202 ///
1203 /// \param context The context in which the subject type was written.
1204 ///
1205 /// \returns the resulting type.
1206 QualType substObjCTypeArgs(ASTContext &ctx,
1207 ArrayRef<QualType> typeArgs,
1208 ObjCSubstitutionContext context) const;
1209
1210 /// Substitute type arguments from an object type for the Objective-C type
1211 /// parameters used in the subject type.
1212 ///
1213 /// This operation combines the computation of type arguments for
1214 /// substitution (\c Type::getObjCSubstitutions) with the actual process of
1215 /// substitution (\c QualType::substObjCTypeArgs) for the convenience of
1216 /// callers that need to perform a single substitution in isolation.
1217 ///
1218 /// \param objectType The type of the object whose member type we're
1219 /// substituting into. For example, this might be the receiver of a message
1220 /// or the base of a property access.
1221 ///
1222 /// \param dc The declaration context from which the subject type was
1223 /// retrieved, which indicates (for example) which type parameters should
1224 /// be substituted.
1225 ///
1226 /// \param context The context in which the subject type was written.
1227 ///
1228 /// \returns the subject type after replacing all of the Objective-C type
1229 /// parameters with their corresponding arguments.
1230 QualType substObjCMemberType(QualType objectType,
1231 const DeclContext *dc,
1232 ObjCSubstitutionContext context) const;
1233
1234 /// Strip Objective-C "__kindof" types from the given type.
1235 QualType stripObjCKindOfType(const ASTContext &ctx) const;
1236
1237 /// Remove all qualifiers including _Atomic.
1238 QualType getAtomicUnqualifiedType() const;
1239
1240private:
1241 // These methods are implemented in a separate translation unit;
1242 // "static"-ize them to avoid creating temporary QualTypes in the
1243 // caller.
1244 static bool isConstant(QualType T, const ASTContext& Ctx);
1245 static QualType getDesugaredType(QualType T, const ASTContext &Context);
1246 static SplitQualType getSplitDesugaredType(QualType T);
1247 static SplitQualType getSplitUnqualifiedTypeImpl(QualType type);
1248 static QualType getSingleStepDesugaredTypeImpl(QualType type,
1249 const ASTContext &C);
1250 static QualType IgnoreParens(QualType T);
1251 static DestructionKind isDestructedTypeImpl(QualType type);
1252
1253 /// Check if \param RD is or contains a non-trivial C union.
1254 static bool hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD);
1255 static bool hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD);
1256 static bool hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD);
1257};
1258
1259} // namespace clang
1260
1261namespace llvm {
1262
1263/// Implement simplify_type for QualType, so that we can dyn_cast from QualType
1264/// to a specific Type class.
1265template<> struct simplify_type< ::clang::QualType> {
1266 using SimpleType = const ::clang::Type *;
1267
1268 static SimpleType getSimplifiedValue(::clang::QualType Val) {
1269 return Val.getTypePtr();
1270 }
1271};
1272
1273// Teach SmallPtrSet that QualType is "basically a pointer".
1274template<>
1275struct PointerLikeTypeTraits<clang::QualType> {
1276 static inline void *getAsVoidPointer(clang::QualType P) {
1277 return P.getAsOpaquePtr();
1278 }
1279
1280 static inline clang::QualType getFromVoidPointer(void *P) {
1281 return clang::QualType::getFromOpaquePtr(P);
1282 }
1283
1284 // Various qualifiers go in low bits.
1285 enum { NumLowBitsAvailable = 0 };
1286};
1287
1288} // namespace llvm
1289
1290namespace clang {
1291
1292/// Base class that is common to both the \c ExtQuals and \c Type
1293/// classes, which allows \c QualType to access the common fields between the
1294/// two.
1295class ExtQualsTypeCommonBase {
1296 friend class ExtQuals;
1297 friend class QualType;
1298 friend class Type;
1299
1300 /// The "base" type of an extended qualifiers type (\c ExtQuals) or
1301 /// a self-referential pointer (for \c Type).
1302 ///
1303 /// This pointer allows an efficient mapping from a QualType to its
1304 /// underlying type pointer.
1305 const Type *const BaseType;
1306
1307 /// The canonical type of this type. A QualType.
1308 QualType CanonicalType;
1309
1310 ExtQualsTypeCommonBase(const Type *baseType, QualType canon)
1311 : BaseType(baseType), CanonicalType(canon) {}
1312};
1313
1314/// We can encode up to four bits in the low bits of a
1315/// type pointer, but there are many more type qualifiers that we want
1316/// to be able to apply to an arbitrary type. Therefore we have this
1317/// struct, intended to be heap-allocated and used by QualType to
1318/// store qualifiers.
1319///
1320/// The current design tags the 'const', 'restrict', and 'volatile' qualifiers
1321/// in three low bits on the QualType pointer; a fourth bit records whether
1322/// the pointer is an ExtQuals node. The extended qualifiers (address spaces,
1323/// Objective-C GC attributes) are much more rare.
1324class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode {
1325 // NOTE: changing the fast qualifiers should be straightforward as
1326 // long as you don't make 'const' non-fast.
1327 // 1. Qualifiers:
1328 // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
1329 // Fast qualifiers must occupy the low-order bits.
1330 // b) Update Qualifiers::FastWidth and FastMask.
1331 // 2. QualType:
1332 // a) Update is{Volatile,Restrict}Qualified(), defined inline.
1333 // b) Update remove{Volatile,Restrict}, defined near the end of
1334 // this header.
1335 // 3. ASTContext:
1336 // a) Update get{Volatile,Restrict}Type.
1337
1338 /// The immutable set of qualifiers applied by this node. Always contains
1339 /// extended qualifiers.
1340 Qualifiers Quals;
1341
1342 ExtQuals *this_() { return this; }
1343
1344public:
1345 ExtQuals(const Type *baseType, QualType canon, Qualifiers quals)
1346 : ExtQualsTypeCommonBase(baseType,
1347 canon.isNull() ? QualType(this_(), 0) : canon),
1348 Quals(quals) {
1349 assert(Quals.hasNonFastQualifiers()((Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 1350, __PRETTY_FUNCTION__))
1350 && "ExtQuals created with no fast qualifiers")((Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 1350, __PRETTY_FUNCTION__))
;
1351 assert(!Quals.hasFastQualifiers()((!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 1352, __PRETTY_FUNCTION__))
1352 && "ExtQuals created with fast qualifiers")((!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 1352, __PRETTY_FUNCTION__))
;
1353 }
1354
1355 Qualifiers getQualifiers() const { return Quals; }
1356
1357 bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
1358 Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
1359
1360 bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); }
1361 Qualifiers::ObjCLifetime getObjCLifetime() const {
1362 return Quals.getObjCLifetime();
1363 }
1364
1365 bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
1366 LangAS getAddressSpace() const { return Quals.getAddressSpace(); }
1367
1368 const Type *getBaseType() const { return BaseType; }
1369
1370public:
1371 void Profile(llvm::FoldingSetNodeID &ID) const {
1372 Profile(ID, getBaseType(), Quals);
1373 }
1374
1375 static void Profile(llvm::FoldingSetNodeID &ID,
1376 const Type *BaseType,
1377 Qualifiers Quals) {
1378 assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!")((!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"fast qualifiers in ExtQuals hash!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 1378, __PRETTY_FUNCTION__))
;
1379 ID.AddPointer(BaseType);
1380 Quals.Profile(ID);
1381 }
1382};
1383
1384/// The kind of C++11 ref-qualifier associated with a function type.
1385/// This determines whether a member function's "this" object can be an
1386/// lvalue, rvalue, or neither.
1387enum RefQualifierKind {
1388 /// No ref-qualifier was provided.
1389 RQ_None = 0,
1390
1391 /// An lvalue ref-qualifier was provided (\c &).
1392 RQ_LValue,
1393
1394 /// An rvalue ref-qualifier was provided (\c &&).
1395 RQ_RValue
1396};
1397
1398/// Which keyword(s) were used to create an AutoType.
1399enum class AutoTypeKeyword {
1400 /// auto
1401 Auto,
1402
1403 /// decltype(auto)
1404 DecltypeAuto,
1405
1406 /// __auto_type (GNU extension)
1407 GNUAutoType
1408};
1409
1410/// The base class of the type hierarchy.
1411///
1412/// A central concept with types is that each type always has a canonical
1413/// type. A canonical type is the type with any typedef names stripped out
1414/// of it or the types it references. For example, consider:
1415///
1416/// typedef int foo;
1417/// typedef foo* bar;
1418/// 'int *' 'foo *' 'bar'
1419///
1420/// There will be a Type object created for 'int'. Since int is canonical, its
1421/// CanonicalType pointer points to itself. There is also a Type for 'foo' (a
1422/// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next
1423/// there is a PointerType that represents 'int*', which, like 'int', is
1424/// canonical. Finally, there is a PointerType type for 'foo*' whose canonical
1425/// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
1426/// is also 'int*'.
1427///
1428/// Non-canonical types are useful for emitting diagnostics, without losing
1429/// information about typedefs being used. Canonical types are useful for type
1430/// comparisons (they allow by-pointer equality tests) and useful for reasoning
1431/// about whether something has a particular form (e.g. is a function type),
1432/// because they implicitly, recursively, strip all typedefs out of a type.
1433///
1434/// Types, once created, are immutable.
1435///
1436class alignas(8) Type : public ExtQualsTypeCommonBase {
1437public:
1438 enum TypeClass {
1439#define TYPE(Class, Base) Class,
1440#define LAST_TYPE(Class) TypeLast = Class
1441#define ABSTRACT_TYPE(Class, Base)
1442#include "clang/AST/TypeNodes.inc"
1443 };
1444
1445private:
1446 /// Bitfields required by the Type class.
1447 class TypeBitfields {
1448 friend class Type;
1449 template <class T> friend class TypePropertyCache;
1450
1451 /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
1452 unsigned TC : 8;
1453
1454 /// Whether this type is a dependent type (C++ [temp.dep.type]).
1455 unsigned Dependent : 1;
1456
1457 /// Whether this type somehow involves a template parameter, even
1458 /// if the resolution of the type does not depend on a template parameter.
1459 unsigned InstantiationDependent : 1;
1460
1461 /// Whether this type is a variably-modified type (C99 6.7.5).
1462 unsigned VariablyModified : 1;
1463
1464 /// Whether this type contains an unexpanded parameter pack
1465 /// (for C++11 variadic templates).
1466 unsigned ContainsUnexpandedParameterPack : 1;
1467
1468 /// True if the cache (i.e. the bitfields here starting with
1469 /// 'Cache') is valid.
1470 mutable unsigned CacheValid : 1;
1471
1472 /// Linkage of this type.
1473 mutable unsigned CachedLinkage : 3;
1474
1475 /// Whether this type involves and local or unnamed types.
1476 mutable unsigned CachedLocalOrUnnamed : 1;
1477
1478 /// Whether this type comes from an AST file.
1479 mutable unsigned FromAST : 1;
1480
1481 bool isCacheValid() const {
1482 return CacheValid;
1483 }
1484
1485 Linkage getLinkage() const {
1486 assert(isCacheValid() && "getting linkage from invalid cache")((isCacheValid() && "getting linkage from invalid cache"
) ? static_cast<void> (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 1486, __PRETTY_FUNCTION__))
;
1487 return static_cast<Linkage>(CachedLinkage);
1488 }
1489
1490 bool hasLocalOrUnnamedType() const {
1491 assert(isCacheValid() && "getting linkage from invalid cache")((isCacheValid() && "getting linkage from invalid cache"
) ? static_cast<void> (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 1491, __PRETTY_FUNCTION__))
;
1492 return CachedLocalOrUnnamed;
1493 }
1494 };
1495 enum { NumTypeBits = 18 };
1496
1497protected:
1498 // These classes allow subclasses to somewhat cleanly pack bitfields
1499 // into Type.
1500
1501 class ArrayTypeBitfields {
1502 friend class ArrayType;
1503
1504 unsigned : NumTypeBits;
1505
1506 /// CVR qualifiers from declarations like
1507 /// 'int X[static restrict 4]'. For function parameters only.
1508 unsigned IndexTypeQuals : 3;
1509
1510 /// Storage class qualifiers from declarations like
1511 /// 'int X[static restrict 4]'. For function parameters only.
1512 /// Actually an ArrayType::ArraySizeModifier.
1513 unsigned SizeModifier : 3;
1514 };
1515
1516 class ConstantArrayTypeBitfields {
1517 friend class ConstantArrayType;
1518
1519 unsigned : NumTypeBits + 3 + 3;
1520
1521 /// Whether we have a stored size expression.
1522 unsigned HasStoredSizeExpr : 1;
1523 };
1524
1525 class BuiltinTypeBitfields {
1526 friend class BuiltinType;
1527
1528 unsigned : NumTypeBits;
1529
1530 /// The kind (BuiltinType::Kind) of builtin type this is.
1531 unsigned Kind : 8;
1532 };
1533
1534 /// FunctionTypeBitfields store various bits belonging to FunctionProtoType.
1535 /// Only common bits are stored here. Additional uncommon bits are stored
1536 /// in a trailing object after FunctionProtoType.
1537 class FunctionTypeBitfields {
1538 friend class FunctionProtoType;
1539 friend class FunctionType;
1540
1541 unsigned : NumTypeBits;
1542
1543 /// Extra information which affects how the function is called, like
1544 /// regparm and the calling convention.
1545 unsigned ExtInfo : 12;
1546
1547 /// The ref-qualifier associated with a \c FunctionProtoType.
1548 ///
1549 /// This is a value of type \c RefQualifierKind.
1550 unsigned RefQualifier : 2;
1551
1552 /// Used only by FunctionProtoType, put here to pack with the
1553 /// other bitfields.
1554 /// The qualifiers are part of FunctionProtoType because...
1555 ///
1556 /// C++ 8.3.5p4: The return type, the parameter type list and the
1557 /// cv-qualifier-seq, [...], are part of the function type.
1558 unsigned FastTypeQuals : Qualifiers::FastWidth;
1559 /// Whether this function has extended Qualifiers.
1560 unsigned HasExtQuals : 1;
1561
1562 /// The number of parameters this function has, not counting '...'.
1563 /// According to [implimits] 8 bits should be enough here but this is
1564 /// somewhat easy to exceed with metaprogramming and so we would like to
1565 /// keep NumParams as wide as reasonably possible.
1566 unsigned NumParams : 16;
1567
1568 /// The type of exception specification this function has.
1569 unsigned ExceptionSpecType : 4;
1570
1571 /// Whether this function has extended parameter information.
1572 unsigned HasExtParameterInfos : 1;
1573
1574 /// Whether the function is variadic.
1575 unsigned Variadic : 1;
1576
1577 /// Whether this function has a trailing return type.
1578 unsigned HasTrailingReturn : 1;
1579 };
1580
1581 class ObjCObjectTypeBitfields {
1582 friend class ObjCObjectType;
1583
1584 unsigned : NumTypeBits;
1585
1586 /// The number of type arguments stored directly on this object type.
1587 unsigned NumTypeArgs : 7;
1588
1589 /// The number of protocols stored directly on this object type.
1590 unsigned NumProtocols : 6;
1591
1592 /// Whether this is a "kindof" type.
1593 unsigned IsKindOf : 1;
1594 };
1595
1596 class ReferenceTypeBitfields {
1597 friend class ReferenceType;
1598
1599 unsigned : NumTypeBits;
1600
1601 /// True if the type was originally spelled with an lvalue sigil.
1602 /// This is never true of rvalue references but can also be false
1603 /// on lvalue references because of C++0x [dcl.typedef]p9,
1604 /// as follows:
1605 ///
1606 /// typedef int &ref; // lvalue, spelled lvalue
1607 /// typedef int &&rvref; // rvalue
1608 /// ref &a; // lvalue, inner ref, spelled lvalue
1609 /// ref &&a; // lvalue, inner ref
1610 /// rvref &a; // lvalue, inner ref, spelled lvalue
1611 /// rvref &&a; // rvalue, inner ref
1612 unsigned SpelledAsLValue : 1;
1613
1614 /// True if the inner type is a reference type. This only happens
1615 /// in non-canonical forms.
1616 unsigned InnerRef : 1;
1617 };
1618
1619 class TypeWithKeywordBitfields {
1620 friend class TypeWithKeyword;
1621
1622 unsigned : NumTypeBits;
1623
1624 /// An ElaboratedTypeKeyword. 8 bits for efficient access.
1625 unsigned Keyword : 8;
1626 };
1627
1628 enum { NumTypeWithKeywordBits = 8 };
1629
1630 class ElaboratedTypeBitfields {
1631 friend class ElaboratedType;
1632
1633 unsigned : NumTypeBits;
1634 unsigned : NumTypeWithKeywordBits;
1635
1636 /// Whether the ElaboratedType has a trailing OwnedTagDecl.
1637 unsigned HasOwnedTagDecl : 1;
1638 };
1639
1640 class VectorTypeBitfields {
1641 friend class VectorType;
1642 friend class DependentVectorType;
1643
1644 unsigned : NumTypeBits;
1645
1646 /// The kind of vector, either a generic vector type or some
1647 /// target-specific vector type such as for AltiVec or Neon.
1648 unsigned VecKind : 3;
1649
1650 /// The number of elements in the vector.
1651 unsigned NumElements : 29 - NumTypeBits;
1652
1653 enum { MaxNumElements = (1 << (29 - NumTypeBits)) - 1 };
1654 };
1655
1656 class AttributedTypeBitfields {
1657 friend class AttributedType;
1658
1659 unsigned : NumTypeBits;
1660
1661 /// An AttributedType::Kind
1662 unsigned AttrKind : 32 - NumTypeBits;
1663 };
1664
1665 class AutoTypeBitfields {
1666 friend class AutoType;
1667
1668 unsigned : NumTypeBits;
1669
1670 /// Was this placeholder type spelled as 'auto', 'decltype(auto)',
1671 /// or '__auto_type'? AutoTypeKeyword value.
1672 unsigned Keyword : 2;
1673 };
1674
1675 class SubstTemplateTypeParmPackTypeBitfields {
1676 friend class SubstTemplateTypeParmPackType;
1677
1678 unsigned : NumTypeBits;
1679
1680 /// The number of template arguments in \c Arguments, which is
1681 /// expected to be able to hold at least 1024 according to [implimits].
1682 /// However as this limit is somewhat easy to hit with template
1683 /// metaprogramming we'd prefer to keep it as large as possible.
1684 /// At the moment it has been left as a non-bitfield since this type
1685 /// safely fits in 64 bits as an unsigned, so there is no reason to
1686 /// introduce the performance impact of a bitfield.
1687 unsigned NumArgs;
1688 };
1689
1690 class TemplateSpecializationTypeBitfields {
1691 friend class TemplateSpecializationType;
1692
1693 unsigned : NumTypeBits;
1694
1695 /// Whether this template specialization type is a substituted type alias.
1696 unsigned TypeAlias : 1;
1697
1698 /// The number of template arguments named in this class template
1699 /// specialization, which is expected to be able to hold at least 1024
1700 /// according to [implimits]. However, as this limit is somewhat easy to
1701 /// hit with template metaprogramming we'd prefer to keep it as large
1702 /// as possible. At the moment it has been left as a non-bitfield since
1703 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1704 /// to introduce the performance impact of a bitfield.
1705 unsigned NumArgs;
1706 };
1707
1708 class DependentTemplateSpecializationTypeBitfields {
1709 friend class DependentTemplateSpecializationType;
1710
1711 unsigned : NumTypeBits;
1712 unsigned : NumTypeWithKeywordBits;
1713
1714 /// The number of template arguments named in this class template
1715 /// specialization, which is expected to be able to hold at least 1024
1716 /// according to [implimits]. However, as this limit is somewhat easy to
1717 /// hit with template metaprogramming we'd prefer to keep it as large
1718 /// as possible. At the moment it has been left as a non-bitfield since
1719 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1720 /// to introduce the performance impact of a bitfield.
1721 unsigned NumArgs;
1722 };
1723
1724 class PackExpansionTypeBitfields {
1725 friend class PackExpansionType;
1726
1727 unsigned : NumTypeBits;
1728
1729 /// The number of expansions that this pack expansion will
1730 /// generate when substituted (+1), which is expected to be able to
1731 /// hold at least 1024 according to [implimits]. However, as this limit
1732 /// is somewhat easy to hit with template metaprogramming we'd prefer to
1733 /// keep it as large as possible. At the moment it has been left as a
1734 /// non-bitfield since this type safely fits in 64 bits as an unsigned, so
1735 /// there is no reason to introduce the performance impact of a bitfield.
1736 ///
1737 /// This field will only have a non-zero value when some of the parameter
1738 /// packs that occur within the pattern have been substituted but others
1739 /// have not.
1740 unsigned NumExpansions;
1741 };
1742
1743 union {
1744 TypeBitfields TypeBits;
1745 ArrayTypeBitfields ArrayTypeBits;
1746 ConstantArrayTypeBitfields ConstantArrayTypeBits;
1747 AttributedTypeBitfields AttributedTypeBits;
1748 AutoTypeBitfields AutoTypeBits;
1749 BuiltinTypeBitfields BuiltinTypeBits;
1750 FunctionTypeBitfields FunctionTypeBits;
1751 ObjCObjectTypeBitfields ObjCObjectTypeBits;
1752 ReferenceTypeBitfields ReferenceTypeBits;
1753 TypeWithKeywordBitfields TypeWithKeywordBits;
1754 ElaboratedTypeBitfields ElaboratedTypeBits;
1755 VectorTypeBitfields VectorTypeBits;
1756 SubstTemplateTypeParmPackTypeBitfields SubstTemplateTypeParmPackTypeBits;
1757 TemplateSpecializationTypeBitfields TemplateSpecializationTypeBits;
1758 DependentTemplateSpecializationTypeBitfields
1759 DependentTemplateSpecializationTypeBits;
1760 PackExpansionTypeBitfields PackExpansionTypeBits;
1761
1762 static_assert(sizeof(TypeBitfields) <= 8,
1763 "TypeBitfields is larger than 8 bytes!");
1764 static_assert(sizeof(ArrayTypeBitfields) <= 8,
1765 "ArrayTypeBitfields is larger than 8 bytes!");
1766 static_assert(sizeof(AttributedTypeBitfields) <= 8,
1767 "AttributedTypeBitfields is larger than 8 bytes!");
1768 static_assert(sizeof(AutoTypeBitfields) <= 8,
1769 "AutoTypeBitfields is larger than 8 bytes!");
1770 static_assert(sizeof(BuiltinTypeBitfields) <= 8,
1771 "BuiltinTypeBitfields is larger than 8 bytes!");
1772 static_assert(sizeof(FunctionTypeBitfields) <= 8,
1773 "FunctionTypeBitfields is larger than 8 bytes!");
1774 static_assert(sizeof(ObjCObjectTypeBitfields) <= 8,
1775 "ObjCObjectTypeBitfields is larger than 8 bytes!");
1776 static_assert(sizeof(ReferenceTypeBitfields) <= 8,
1777 "ReferenceTypeBitfields is larger than 8 bytes!");
1778 static_assert(sizeof(TypeWithKeywordBitfields) <= 8,
1779 "TypeWithKeywordBitfields is larger than 8 bytes!");
1780 static_assert(sizeof(ElaboratedTypeBitfields) <= 8,
1781 "ElaboratedTypeBitfields is larger than 8 bytes!");
1782 static_assert(sizeof(VectorTypeBitfields) <= 8,
1783 "VectorTypeBitfields is larger than 8 bytes!");
1784 static_assert(sizeof(SubstTemplateTypeParmPackTypeBitfields) <= 8,
1785 "SubstTemplateTypeParmPackTypeBitfields is larger"
1786 " than 8 bytes!");
1787 static_assert(sizeof(TemplateSpecializationTypeBitfields) <= 8,
1788 "TemplateSpecializationTypeBitfields is larger"
1789 " than 8 bytes!");
1790 static_assert(sizeof(DependentTemplateSpecializationTypeBitfields) <= 8,
1791 "DependentTemplateSpecializationTypeBitfields is larger"
1792 " than 8 bytes!");
1793 static_assert(sizeof(PackExpansionTypeBitfields) <= 8,
1794 "PackExpansionTypeBitfields is larger than 8 bytes");
1795 };
1796
1797private:
1798 template <class T> friend class TypePropertyCache;
1799
1800 /// Set whether this type comes from an AST file.
1801 void setFromAST(bool V = true) const {
1802 TypeBits.FromAST = V;
1803 }
1804
1805protected:
1806 friend class ASTContext;
1807
1808 Type(TypeClass tc, QualType canon, bool Dependent,
1809 bool InstantiationDependent, bool VariablyModified,
1810 bool ContainsUnexpandedParameterPack)
1811 : ExtQualsTypeCommonBase(this,
1812 canon.isNull() ? QualType(this_(), 0) : canon) {
1813 TypeBits.TC = tc;
1814 TypeBits.Dependent = Dependent;
1815 TypeBits.InstantiationDependent = Dependent || InstantiationDependent;
1816 TypeBits.VariablyModified = VariablyModified;
1817 TypeBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
1818 TypeBits.CacheValid = false;
1819 TypeBits.CachedLocalOrUnnamed = false;
1820 TypeBits.CachedLinkage = NoLinkage;
1821 TypeBits.FromAST = false;
1822 }
1823
1824 // silence VC++ warning C4355: 'this' : used in base member initializer list
1825 Type *this_() { return this; }
1826
1827 void setDependent(bool D = true) {
1828 TypeBits.Dependent = D;
1829 if (D)
1830 TypeBits.InstantiationDependent = true;
1831 }
1832
1833 void setInstantiationDependent(bool D = true) {
1834 TypeBits.InstantiationDependent = D; }
1835
1836 void setVariablyModified(bool VM = true) { TypeBits.VariablyModified = VM; }
1837
1838 void setContainsUnexpandedParameterPack(bool PP = true) {
1839 TypeBits.ContainsUnexpandedParameterPack = PP;
1840 }
1841
1842public:
1843 friend class ASTReader;
1844 friend class ASTWriter;
1845
1846 Type(const Type &) = delete;
1847 Type(Type &&) = delete;
1848 Type &operator=(const Type &) = delete;
1849 Type &operator=(Type &&) = delete;
1850
1851 TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); }
1852
1853 /// Whether this type comes from an AST file.
1854 bool isFromAST() const { return TypeBits.FromAST; }
1855
1856 /// Whether this type is or contains an unexpanded parameter
1857 /// pack, used to support C++0x variadic templates.
1858 ///
1859 /// A type that contains a parameter pack shall be expanded by the
1860 /// ellipsis operator at some point. For example, the typedef in the
1861 /// following example contains an unexpanded parameter pack 'T':
1862 ///
1863 /// \code
1864 /// template<typename ...T>
1865 /// struct X {
1866 /// typedef T* pointer_types; // ill-formed; T is a parameter pack.
1867 /// };
1868 /// \endcode
1869 ///
1870 /// Note that this routine does not specify which
1871 bool containsUnexpandedParameterPack() const {
1872 return TypeBits.ContainsUnexpandedParameterPack;
1873 }
1874
1875 /// Determines if this type would be canonical if it had no further
1876 /// qualification.
1877 bool isCanonicalUnqualified() const {
1878 return CanonicalType == QualType(this, 0);
1879 }
1880
1881 /// Pull a single level of sugar off of this locally-unqualified type.
1882 /// Users should generally prefer SplitQualType::getSingleStepDesugaredType()
1883 /// or QualType::getSingleStepDesugaredType(const ASTContext&).
1884 QualType getLocallyUnqualifiedSingleStepDesugaredType() const;
1885
1886 /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
1887 /// object types, function types, and incomplete types.
1888
1889 /// Return true if this is an incomplete type.
1890 /// A type that can describe objects, but which lacks information needed to
1891 /// determine its size (e.g. void, or a fwd declared struct). Clients of this
1892 /// routine will need to determine if the size is actually required.
1893 ///
1894 /// Def If non-null, and the type refers to some kind of declaration
1895 /// that can be completed (such as a C struct, C++ class, or Objective-C
1896 /// class), will be set to the declaration.
1897 bool isIncompleteType(NamedDecl **Def = nullptr) const;
1898
1899 /// Return true if this is an incomplete or object
1900 /// type, in other words, not a function type.
1901 bool isIncompleteOrObjectType() const {
1902 return !isFunctionType();
1903 }
1904
1905 /// Determine whether this type is an object type.
1906 bool isObjectType() const {
1907 // C++ [basic.types]p8:
1908 // An object type is a (possibly cv-qualified) type that is not a
1909 // function type, not a reference type, and not a void type.
1910 return !isReferenceType() && !isFunctionType() && !isVoidType();
1911 }
1912
1913 /// Return true if this is a literal type
1914 /// (C++11 [basic.types]p10)
1915 bool isLiteralType(const ASTContext &Ctx) const;
1916
1917 /// Test if this type is a standard-layout type.
1918 /// (C++0x [basic.type]p9)
1919 bool isStandardLayoutType() const;
1920
1921 /// Helper methods to distinguish type categories. All type predicates
1922 /// operate on the canonical type, ignoring typedefs and qualifiers.
1923
1924 /// Returns true if the type is a builtin type.
1925 bool isBuiltinType() const;
1926
1927 /// Test for a particular builtin type.
1928 bool isSpecificBuiltinType(unsigned K) const;
1929
1930 /// Test for a type which does not represent an actual type-system type but
1931 /// is instead used as a placeholder for various convenient purposes within
1932 /// Clang. All such types are BuiltinTypes.
1933 bool isPlaceholderType() const;
1934 const BuiltinType *getAsPlaceholderType() const;
1935
1936 /// Test for a specific placeholder type.
1937 bool isSpecificPlaceholderType(unsigned K) const;
1938
1939 /// Test for a placeholder type other than Overload; see
1940 /// BuiltinType::isNonOverloadPlaceholderType.
1941 bool isNonOverloadPlaceholderType() const;
1942
1943 /// isIntegerType() does *not* include complex integers (a GCC extension).
1944 /// isComplexIntegerType() can be used to test for complex integers.
1945 bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum)
1946 bool isEnumeralType() const;
1947
1948 /// Determine whether this type is a scoped enumeration type.
1949 bool isScopedEnumeralType() const;
1950 bool isBooleanType() const;
1951 bool isCharType() const;
1952 bool isWideCharType() const;
1953 bool isChar8Type() const;
1954 bool isChar16Type() const;
1955 bool isChar32Type() const;
1956 bool isAnyCharacterType() const;
1957 bool isIntegralType(const ASTContext &Ctx) const;
1958
1959 /// Determine whether this type is an integral or enumeration type.
1960 bool isIntegralOrEnumerationType() const;
1961
1962 /// Determine whether this type is an integral or unscoped enumeration type.
1963 bool isIntegralOrUnscopedEnumerationType() const;
1964
1965 /// Floating point categories.
1966 bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
1967 /// isComplexType() does *not* include complex integers (a GCC extension).
1968 /// isComplexIntegerType() can be used to test for complex integers.
1969 bool isComplexType() const; // C99 6.2.5p11 (complex)
1970 bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int.
1971 bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex)
1972 bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
1973 bool isFloat16Type() const; // C11 extension ISO/IEC TS 18661
1974 bool isFloat128Type() const;
1975 bool isRealType() const; // C99 6.2.5p17 (real floating + integer)
1976 bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating)
1977 bool isVoidType() const; // C99 6.2.5p19
1978 bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers)
1979 bool isAggregateType() const;
1980 bool isFundamentalType() const;
1981 bool isCompoundType() const;
1982
1983 // Type Predicates: Check to see if this type is structurally the specified
1984 // type, ignoring typedefs and qualifiers.
1985 bool isFunctionType() const;
1986 bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
1987 bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
1988 bool isPointerType() const;
1989 bool isAnyPointerType() const; // Any C pointer or ObjC object pointer
1990 bool isBlockPointerType() const;
1991 bool isVoidPointerType() const;
1992 bool isReferenceType() const;
1993 bool isLValueReferenceType() const;
1994 bool isRValueReferenceType() const;
1995 bool isFunctionPointerType() const;
1996 bool isFunctionReferenceType() const;
1997 bool isMemberPointerType() const;
1998 bool isMemberFunctionPointerType() const;
1999 bool isMemberDataPointerType() const;
2000 bool isArrayType() const;
2001 bool isConstantArrayType() const;
2002 bool isIncompleteArrayType() const;
2003 bool isVariableArrayType() const;
2004 bool isDependentSizedArrayType() const;
2005 bool isRecordType() const;
2006 bool isClassType() const;
2007 bool isStructureType() const;
2008 bool isObjCBoxableRecordType() const;
2009 bool isInterfaceType() const;
2010 bool isStructureOrClassType() const;
2011 bool isUnionType() const;
2012 bool isComplexIntegerType() const; // GCC _Complex integer type.
2013 bool isVectorType() const; // GCC vector type.
2014 bool isExtVectorType() const; // Extended vector type.
2015 bool isDependentAddressSpaceType() const; // value-dependent address space qualifier
2016 bool isObjCObjectPointerType() const; // pointer to ObjC object
2017 bool isObjCRetainableType() const; // ObjC object or block pointer
2018 bool isObjCLifetimeType() const; // (array of)* retainable type
2019 bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type
2020 bool isObjCNSObjectType() const; // __attribute__((NSObject))
2021 bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class))
2022 // FIXME: change this to 'raw' interface type, so we can used 'interface' type
2023 // for the common case.
2024 bool isObjCObjectType() const; // NSString or typeof(*(id)0)
2025 bool isObjCQualifiedInterfaceType() const; // NSString<foo>
2026 bool isObjCQualifiedIdType() const; // id<foo>
2027 bool isObjCQualifiedClassType() const; // Class<foo>
2028 bool isObjCObjectOrInterfaceType() const;
2029 bool isObjCIdType() const; // id
2030 bool isDecltypeType() const;
2031 /// Was this type written with the special inert-in-ARC __unsafe_unretained
2032 /// qualifier?
2033 ///
2034 /// This approximates the answer to the following question: if this
2035 /// translation unit were compiled in ARC, would this type be qualified
2036 /// with __unsafe_unretained?
2037 bool isObjCInertUnsafeUnretainedType() const {
2038 return hasAttr(attr::ObjCInertUnsafeUnretained);
2039 }
2040
2041 /// Whether the type is Objective-C 'id' or a __kindof type of an
2042 /// object type, e.g., __kindof NSView * or __kindof id
2043 /// <NSCopying>.
2044 ///
2045 /// \param bound Will be set to the bound on non-id subtype types,
2046 /// which will be (possibly specialized) Objective-C class type, or
2047 /// null for 'id.
2048 bool isObjCIdOrObjectKindOfType(const ASTContext &ctx,
2049 const ObjCObjectType *&bound) const;
2050
2051 bool isObjCClassType() const; // Class
2052
2053 /// Whether the type is Objective-C 'Class' or a __kindof type of an
2054 /// Class type, e.g., __kindof Class <NSCopying>.
2055 ///
2056 /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound
2057 /// here because Objective-C's type system cannot express "a class
2058 /// object for a subclass of NSFoo".
2059 bool isObjCClassOrClassKindOfType() const;
2060
2061 bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const;
2062 bool isObjCSelType() const; // Class
2063 bool isObjCBuiltinType() const; // 'id' or 'Class'
2064 bool isObjCARCBridgableType() const;
2065 bool isCARCBridgableType() const;
2066 bool isTemplateTypeParmType() const; // C++ template type parameter
2067 bool isNullPtrType() const; // C++11 std::nullptr_t
2068 bool isNothrowT() const; // C++ std::nothrow_t
2069 bool isAlignValT() const; // C++17 std::align_val_t
2070 bool isStdByteType() const; // C++17 std::byte
2071 bool isAtomicType() const; // C11 _Atomic()
2072
2073#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2074 bool is##Id##Type() const;
2075#include "clang/Basic/OpenCLImageTypes.def"
2076
2077 bool isImageType() const; // Any OpenCL image type
2078
2079 bool isSamplerT() const; // OpenCL sampler_t
2080 bool isEventT() const; // OpenCL event_t
2081 bool isClkEventT() const; // OpenCL clk_event_t
2082 bool isQueueT() const; // OpenCL queue_t
2083 bool isReserveIDT() const; // OpenCL reserve_id_t
2084
2085#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2086 bool is##Id##Type() const;
2087#include "clang/Basic/OpenCLExtensionTypes.def"
2088 // Type defined in cl_intel_device_side_avc_motion_estimation OpenCL extension
2089 bool isOCLIntelSubgroupAVCType() const;
2090 bool isOCLExtOpaqueType() const; // Any OpenCL extension type
2091
2092 bool isPipeType() const; // OpenCL pipe type
2093 bool isOpenCLSpecificType() const; // Any OpenCL specific type
2094
2095 /// Determines if this type, which must satisfy
2096 /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather
2097 /// than implicitly __strong.
2098 bool isObjCARCImplicitlyUnretainedType() const;
2099
2100 /// Return the implicit lifetime for this type, which must not be dependent.
2101 Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const;
2102
2103 enum ScalarTypeKind {
2104 STK_CPointer,
2105 STK_BlockPointer,
2106 STK_ObjCObjectPointer,
2107 STK_MemberPointer,
2108 STK_Bool,
2109 STK_Integral,
2110 STK_Floating,
2111 STK_IntegralComplex,
2112 STK_FloatingComplex,
2113 STK_FixedPoint
2114 };
2115
2116 /// Given that this is a scalar type, classify it.
2117 ScalarTypeKind getScalarTypeKind() const;
2118
2119 /// Whether this type is a dependent type, meaning that its definition
2120 /// somehow depends on a template parameter (C++ [temp.dep.type]).
2121 bool isDependentType() const { return TypeBits.Dependent; }
2122
2123 /// Determine whether this type is an instantiation-dependent type,
2124 /// meaning that the type involves a template parameter (even if the
2125 /// definition does not actually depend on the type substituted for that
2126 /// template parameter).
2127 bool isInstantiationDependentType() const {
2128 return TypeBits.InstantiationDependent;
2129 }
2130
2131 /// Determine whether this type is an undeduced type, meaning that
2132 /// it somehow involves a C++11 'auto' type or similar which has not yet been
2133 /// deduced.
2134 bool isUndeducedType() const;
2135
2136 /// Whether this type is a variably-modified type (C99 6.7.5).
2137 bool isVariablyModifiedType() const { return TypeBits.VariablyModified; }
2138
2139 /// Whether this type involves a variable-length array type
2140 /// with a definite size.
2141 bool hasSizedVLAType() const;
2142
2143 /// Whether this type is or contains a local or unnamed type.
2144 bool hasUnnamedOrLocalType() const;
2145
2146 bool isOverloadableType() const;
2147
2148 /// Determine wither this type is a C++ elaborated-type-specifier.
2149 bool isElaboratedTypeSpecifier() const;
2150
2151 bool canDecayToPointerType() const;
2152
2153 /// Whether this type is represented natively as a pointer. This includes
2154 /// pointers, references, block pointers, and Objective-C interface,
2155 /// qualified id, and qualified interface types, as well as nullptr_t.
2156 bool hasPointerRepresentation() const;
2157
2158 /// Whether this type can represent an objective pointer type for the
2159 /// purpose of GC'ability
2160 bool hasObjCPointerRepresentation() const;
2161
2162 /// Determine whether this type has an integer representation
2163 /// of some sort, e.g., it is an integer type or a vector.
2164 bool hasIntegerRepresentation() const;
2165
2166 /// Determine whether this type has an signed integer representation
2167 /// of some sort, e.g., it is an signed integer type or a vector.
2168 bool hasSignedIntegerRepresentation() const;
2169
2170 /// Determine whether this type has an unsigned integer representation
2171 /// of some sort, e.g., it is an unsigned integer type or a vector.
2172 bool hasUnsignedIntegerRepresentation() const;
2173
2174 /// Determine whether this type has a floating-point representation
2175 /// of some sort, e.g., it is a floating-point type or a vector thereof.
2176 bool hasFloatingRepresentation() const;
2177
2178 // Type Checking Functions: Check to see if this type is structurally the
2179 // specified type, ignoring typedefs and qualifiers, and return a pointer to
2180 // the best type we can.
2181 const RecordType *getAsStructureType() const;
2182 /// NOTE: getAs*ArrayType are methods on ASTContext.
2183 const RecordType *getAsUnionType() const;
2184 const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
2185 const ObjCObjectType *getAsObjCInterfaceType() const;
2186
2187 // The following is a convenience method that returns an ObjCObjectPointerType
2188 // for object declared using an interface.
2189 const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
2190 const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
2191 const ObjCObjectPointerType *getAsObjCQualifiedClassType() const;
2192 const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
2193
2194 /// Retrieves the CXXRecordDecl that this type refers to, either
2195 /// because the type is a RecordType or because it is the injected-class-name
2196 /// type of a class template or class template partial specialization.
2197 CXXRecordDecl *getAsCXXRecordDecl() const;
2198
2199 /// Retrieves the RecordDecl this type refers to.
2200 RecordDecl *getAsRecordDecl() const;
2201
2202 /// Retrieves the TagDecl that this type refers to, either
2203 /// because the type is a TagType or because it is the injected-class-name
2204 /// type of a class template or class template partial specialization.
2205 TagDecl *getAsTagDecl() const;
2206
2207 /// If this is a pointer or reference to a RecordType, return the
2208 /// CXXRecordDecl that the type refers to.
2209 ///
2210 /// If this is not a pointer or reference, or the type being pointed to does
2211 /// not refer to a CXXRecordDecl, returns NULL.
2212 const CXXRecordDecl *getPointeeCXXRecordDecl() const;
2213
2214 /// Get the DeducedType whose type will be deduced for a variable with
2215 /// an initializer of this type. This looks through declarators like pointer
2216 /// types, but not through decltype or typedefs.
2217 DeducedType *getContainedDeducedType() const;
2218
2219 /// Get the AutoType whose type will be deduced for a variable with
2220 /// an initializer of this type. This looks through declarators like pointer
2221 /// types, but not through decltype or typedefs.
2222 AutoType *getContainedAutoType() const {
2223 return dyn_cast_or_null<AutoType>(getContainedDeducedType());
2224 }
2225
2226 /// Determine whether this type was written with a leading 'auto'
2227 /// corresponding to a trailing return type (possibly for a nested
2228 /// function type within a pointer to function type or similar).
2229 bool hasAutoForTrailingReturnType() const;
2230
2231 /// Member-template getAs<specific type>'. Look through sugar for
2232 /// an instance of \<specific type>. This scheme will eventually
2233 /// replace the specific getAsXXXX methods above.
2234 ///
2235 /// There are some specializations of this member template listed
2236 /// immediately following this class.
2237 template <typename T> const T *getAs() const;
2238
2239 /// Member-template getAsAdjusted<specific type>. Look through specific kinds
2240 /// of sugar (parens, attributes, etc) for an instance of \<specific type>.
2241 /// This is used when you need to walk over sugar nodes that represent some
2242 /// kind of type adjustment from a type that was written as a \<specific type>
2243 /// to another type that is still canonically a \<specific type>.
2244 template <typename T> const T *getAsAdjusted() const;
2245
2246 /// A variant of getAs<> for array types which silently discards
2247 /// qualifiers from the outermost type.
2248 const ArrayType *getAsArrayTypeUnsafe() const;
2249
2250 /// Member-template castAs<specific type>. Look through sugar for
2251 /// the underlying instance of \<specific type>.
2252 ///
2253 /// This method has the same relationship to getAs<T> as cast<T> has
2254 /// to dyn_cast<T>; which is to say, the underlying type *must*
2255 /// have the intended type, and this method will never return null.
2256 template <typename T> const T *castAs() const;
2257
2258 /// A variant of castAs<> for array type which silently discards
2259 /// qualifiers from the outermost type.
2260 const ArrayType *castAsArrayTypeUnsafe() const;
2261
2262 /// Determine whether this type had the specified attribute applied to it
2263 /// (looking through top-level type sugar).
2264 bool hasAttr(attr::Kind AK) const;
2265
2266 /// Get the base element type of this type, potentially discarding type
2267 /// qualifiers. This should never be used when type qualifiers
2268 /// are meaningful.
2269 const Type *getBaseElementTypeUnsafe() const;
2270
2271 /// If this is an array type, return the element type of the array,
2272 /// potentially with type qualifiers missing.
2273 /// This should never be used when type qualifiers are meaningful.
2274 const Type *getArrayElementTypeNoTypeQual() const;
2275
2276 /// If this is a pointer type, return the pointee type.
2277 /// If this is an array type, return the array element type.
2278 /// This should never be used when type qualifiers are meaningful.
2279 const Type *getPointeeOrArrayElementType() const;
2280
2281 /// If this is a pointer, ObjC object pointer, or block
2282 /// pointer, this returns the respective pointee.
2283 QualType getPointeeType() const;
2284
2285 /// Return the specified type with any "sugar" removed from the type,
2286 /// removing any typedefs, typeofs, etc., as well as any qualifiers.
2287 const Type *getUnqualifiedDesugaredType() const;
2288
2289 /// More type predicates useful for type checking/promotion
2290 bool isPromotableIntegerType() const; // C99 6.3.1.1p2
2291
2292 /// Return true if this is an integer type that is
2293 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
2294 /// or an enum decl which has a signed representation.
2295 bool isSignedIntegerType() const;
2296
2297 /// Return true if this is an integer type that is
2298 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
2299 /// or an enum decl which has an unsigned representation.
2300 bool isUnsignedIntegerType() const;
2301
2302 /// Determines whether this is an integer type that is signed or an
2303 /// enumeration types whose underlying type is a signed integer type.
2304 bool isSignedIntegerOrEnumerationType() const;
2305
2306 /// Determines whether this is an integer type that is unsigned or an
2307 /// enumeration types whose underlying type is a unsigned integer type.
2308 bool isUnsignedIntegerOrEnumerationType() const;
2309
2310 /// Return true if this is a fixed point type according to
2311 /// ISO/IEC JTC1 SC22 WG14 N1169.
2312 bool isFixedPointType() const;
2313
2314 /// Return true if this is a fixed point or integer type.
2315 bool isFixedPointOrIntegerType() const;
2316
2317 /// Return true if this is a saturated fixed point type according to
2318 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2319 bool isSaturatedFixedPointType() const;
2320
2321 /// Return true if this is a saturated fixed point type according to
2322 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2323 bool isUnsaturatedFixedPointType() const;
2324
2325 /// Return true if this is a fixed point type that is signed according
2326 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2327 bool isSignedFixedPointType() const;
2328
2329 /// Return true if this is a fixed point type that is unsigned according
2330 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2331 bool isUnsignedFixedPointType() const;
2332
2333 /// Return true if this is not a variable sized type,
2334 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
2335 /// incomplete types.
2336 bool isConstantSizeType() const;
2337
2338 /// Returns true if this type can be represented by some
2339 /// set of type specifiers.
2340 bool isSpecifierType() const;
2341
2342 /// Determine the linkage of this type.
2343 Linkage getLinkage() const;
2344
2345 /// Determine the visibility of this type.
2346 Visibility getVisibility() const {
2347 return getLinkageAndVisibility().getVisibility();
2348 }
2349
2350 /// Return true if the visibility was explicitly set is the code.
2351 bool isVisibilityExplicit() const {
2352 return getLinkageAndVisibility().isVisibilityExplicit();
2353 }
2354
2355 /// Determine the linkage and visibility of this type.
2356 LinkageInfo getLinkageAndVisibility() const;
2357
2358 /// True if the computed linkage is valid. Used for consistency
2359 /// checking. Should always return true.
2360 bool isLinkageValid() const;
2361
2362 /// Determine the nullability of the given type.
2363 ///
2364 /// Note that nullability is only captured as sugar within the type
2365 /// system, not as part of the canonical type, so nullability will
2366 /// be lost by canonicalization and desugaring.
2367 Optional<NullabilityKind> getNullability(const ASTContext &context) const;
2368
2369 /// Determine whether the given type can have a nullability
2370 /// specifier applied to it, i.e., if it is any kind of pointer type.
2371 ///
2372 /// \param ResultIfUnknown The value to return if we don't yet know whether
2373 /// this type can have nullability because it is dependent.
2374 bool canHaveNullability(bool ResultIfUnknown = true) const;
2375
2376 /// Retrieve the set of substitutions required when accessing a member
2377 /// of the Objective-C receiver type that is declared in the given context.
2378 ///
2379 /// \c *this is the type of the object we're operating on, e.g., the
2380 /// receiver for a message send or the base of a property access, and is
2381 /// expected to be of some object or object pointer type.
2382 ///
2383 /// \param dc The declaration context for which we are building up a
2384 /// substitution mapping, which should be an Objective-C class, extension,
2385 /// category, or method within.
2386 ///
2387 /// \returns an array of type arguments that can be substituted for
2388 /// the type parameters of the given declaration context in any type described
2389 /// within that context, or an empty optional to indicate that no
2390 /// substitution is required.
2391 Optional<ArrayRef<QualType>>
2392 getObjCSubstitutions(const DeclContext *dc) const;
2393
2394 /// Determines if this is an ObjC interface type that may accept type
2395 /// parameters.
2396 bool acceptsObjCTypeParams() const;
2397
2398 const char *getTypeClassName() const;
2399
2400 QualType getCanonicalTypeInternal() const {
2401 return CanonicalType;
2402 }
2403
2404 CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
2405 void dump() const;
2406 void dump(llvm::raw_ostream &OS) const;
2407};
2408
2409/// This will check for a TypedefType by removing any existing sugar
2410/// until it reaches a TypedefType or a non-sugared type.
2411template <> const TypedefType *Type::getAs() const;
2412
2413/// This will check for a TemplateSpecializationType by removing any
2414/// existing sugar until it reaches a TemplateSpecializationType or a
2415/// non-sugared type.
2416template <> const TemplateSpecializationType *Type::getAs() const;
2417
2418/// This will check for an AttributedType by removing any existing sugar
2419/// until it reaches an AttributedType or a non-sugared type.
2420template <> const AttributedType *Type::getAs() const;
2421
2422// We can do canonical leaf types faster, because we don't have to
2423// worry about preserving child type decoration.
2424#define TYPE(Class, Base)
2425#define LEAF_TYPE(Class) \
2426template <> inline const Class##Type *Type::getAs() const { \
2427 return dyn_cast<Class##Type>(CanonicalType); \
2428} \
2429template <> inline const Class##Type *Type::castAs() const { \
2430 return cast<Class##Type>(CanonicalType); \
2431}
2432#include "clang/AST/TypeNodes.inc"
2433
2434/// This class is used for builtin types like 'int'. Builtin
2435/// types are always canonical and have a literal name field.
2436class BuiltinType : public Type {
2437public:
2438 enum Kind {
2439// OpenCL image types
2440#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id,
2441#include "clang/Basic/OpenCLImageTypes.def"
2442// OpenCL extension types
2443#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) Id,
2444#include "clang/Basic/OpenCLExtensionTypes.def"
2445// SVE Types
2446#define SVE_TYPE(Name, Id, SingletonId) Id,
2447#include "clang/Basic/AArch64SVEACLETypes.def"
2448// All other builtin types
2449#define BUILTIN_TYPE(Id, SingletonId) Id,
2450#define LAST_BUILTIN_TYPE(Id) LastKind = Id
2451#include "clang/AST/BuiltinTypes.def"
2452 };
2453
2454private:
2455 friend class ASTContext; // ASTContext creates these.
2456
2457 BuiltinType(Kind K)
2458 : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent),
2459 /*InstantiationDependent=*/(K == Dependent),
2460 /*VariablyModified=*/false,
2461 /*Unexpanded parameter pack=*/false) {
2462 BuiltinTypeBits.Kind = K;
2463 }
2464
2465public:
2466 Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
2467 StringRef getName(const PrintingPolicy &Policy) const;
2468
2469 const char *getNameAsCString(const PrintingPolicy &Policy) const {
2470 // The StringRef is null-terminated.
2471 StringRef str = getName(Policy);
2472 assert(!str.empty() && str.data()[str.size()] == '\0')((!str.empty() && str.data()[str.size()] == '\0') ? static_cast
<void> (0) : __assert_fail ("!str.empty() && str.data()[str.size()] == '\\0'"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 2472, __PRETTY_FUNCTION__))
;
2473 return str.data();
2474 }
2475
2476 bool isSugared() const { return false; }
2477 QualType desugar() const { return QualType(this, 0); }
2478
2479 bool isInteger() const {
2480 return getKind() >= Bool && getKind() <= Int128;
2481 }
2482
2483 bool isSignedInteger() const {
2484 return getKind() >= Char_S && getKind() <= Int128;
2485 }
2486
2487 bool isUnsignedInteger() const {
2488 return getKind() >= Bool && getKind() <= UInt128;
2489 }
2490
2491 bool isFloatingPoint() const {
2492 return getKind() >= Half && getKind() <= Float128;
2493 }
2494
2495 /// Determines whether the given kind corresponds to a placeholder type.
2496 static bool isPlaceholderTypeKind(Kind K) {
2497 return K >= Overload;
2498 }
2499
2500 /// Determines whether this type is a placeholder type, i.e. a type
2501 /// which cannot appear in arbitrary positions in a fully-formed
2502 /// expression.
2503 bool isPlaceholderType() const {
2504 return isPlaceholderTypeKind(getKind());
2505 }
2506
2507 /// Determines whether this type is a placeholder type other than
2508 /// Overload. Most placeholder types require only syntactic
2509 /// information about their context in order to be resolved (e.g.
2510 /// whether it is a call expression), which means they can (and
2511 /// should) be resolved in an earlier "phase" of analysis.
2512 /// Overload expressions sometimes pick up further information
2513 /// from their context, like whether the context expects a
2514 /// specific function-pointer type, and so frequently need
2515 /// special treatment.
2516 bool isNonOverloadPlaceholderType() const {
2517 return getKind() > Overload;
2518 }
2519
2520 static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
2521};
2522
2523/// Complex values, per C99 6.2.5p11. This supports the C99 complex
2524/// types (_Complex float etc) as well as the GCC integer complex extensions.
2525class ComplexType : public Type, public llvm::FoldingSetNode {
2526 friend class ASTContext; // ASTContext creates these.
2527
2528 QualType ElementType;
2529
2530 ComplexType(QualType Element, QualType CanonicalPtr)
2531 : Type(Complex, CanonicalPtr, Element->isDependentType(),
2532 Element->isInstantiationDependentType(),
2533 Element->isVariablyModifiedType(),
2534 Element->containsUnexpandedParameterPack()),
2535 ElementType(Element) {}
2536
2537public:
2538 QualType getElementType() const { return ElementType; }
2539
2540 bool isSugared() const { return false; }
2541 QualType desugar() const { return QualType(this, 0); }
2542
2543 void Profile(llvm::FoldingSetNodeID &ID) {
2544 Profile(ID, getElementType());
2545 }
2546
2547 static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
2548 ID.AddPointer(Element.getAsOpaquePtr());
2549 }
2550
2551 static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
2552};
2553
2554/// Sugar for parentheses used when specifying types.
2555class ParenType : public Type, public llvm::FoldingSetNode {
2556 friend class ASTContext; // ASTContext creates these.
2557
2558 QualType Inner;
2559
2560 ParenType(QualType InnerType, QualType CanonType)
2561 : Type(Paren, CanonType, InnerType->isDependentType(),
2562 InnerType->isInstantiationDependentType(),
2563 InnerType->isVariablyModifiedType(),
2564 InnerType->containsUnexpandedParameterPack()),
2565 Inner(InnerType) {}
2566
2567public:
2568 QualType getInnerType() const { return Inner; }
2569
2570 bool isSugared() const { return true; }
2571 QualType desugar() const { return getInnerType(); }
2572
2573 void Profile(llvm::FoldingSetNodeID &ID) {
2574 Profile(ID, getInnerType());
2575 }
2576
2577 static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
2578 Inner.Profile(ID);
2579 }
2580
2581 static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
2582};
2583
2584/// PointerType - C99 6.7.5.1 - Pointer Declarators.
2585class PointerType : public Type, public llvm::FoldingSetNode {
2586 friend class ASTContext; // ASTContext creates these.
2587
2588 QualType PointeeType;
2589
2590 PointerType(QualType Pointee, QualType CanonicalPtr)
2591 : Type(Pointer, CanonicalPtr, Pointee->isDependentType(),
2592 Pointee->isInstantiationDependentType(),
2593 Pointee->isVariablyModifiedType(),
2594 Pointee->containsUnexpandedParameterPack()),
2595 PointeeType(Pointee) {}
2596
2597public:
2598 QualType getPointeeType() const { return PointeeType; }
2599
2600 /// Returns true if address spaces of pointers overlap.
2601 /// OpenCL v2.0 defines conversion rules for pointers to different
2602 /// address spaces (OpenCLC v2.0 s6.5.5) and notion of overlapping
2603 /// address spaces.
2604 /// CL1.1 or CL1.2:
2605 /// address spaces overlap iff they are they same.
2606 /// CL2.0 adds:
2607 /// __generic overlaps with any address space except for __constant.
2608 bool isAddressSpaceOverlapping(const PointerType &other) const {
2609 Qualifiers thisQuals = PointeeType.getQualifiers();
2610 Qualifiers otherQuals = other.getPointeeType().getQualifiers();
2611 // Address spaces overlap if at least one of them is a superset of another
2612 return thisQuals.isAddressSpaceSupersetOf(otherQuals) ||
2613 otherQuals.isAddressSpaceSupersetOf(thisQuals);
2614 }
2615
2616 bool isSugared() const { return false; }
2617 QualType desugar() const { return QualType(this, 0); }
2618
2619 void Profile(llvm::FoldingSetNodeID &ID) {
2620 Profile(ID, getPointeeType());
2621 }
2622
2623 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2624 ID.AddPointer(Pointee.getAsOpaquePtr());
2625 }
2626
2627 static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
2628};
2629
2630/// Represents a type which was implicitly adjusted by the semantic
2631/// engine for arbitrary reasons. For example, array and function types can
2632/// decay, and function types can have their calling conventions adjusted.
2633class AdjustedType : public Type, public llvm::FoldingSetNode {
2634 QualType OriginalTy;
2635 QualType AdjustedTy;
2636
2637protected:
2638 friend class ASTContext; // ASTContext creates these.
2639
2640 AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy,
2641 QualType CanonicalPtr)
2642 : Type(TC, CanonicalPtr, OriginalTy->isDependentType(),
2643 OriginalTy->isInstantiationDependentType(),
2644 OriginalTy->isVariablyModifiedType(),
2645 OriginalTy->containsUnexpandedParameterPack()),
2646 OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {}
2647
2648public:
2649 QualType getOriginalType() const { return OriginalTy; }
2650 QualType getAdjustedType() const { return AdjustedTy; }
2651
2652 bool isSugared() const { return true; }
2653 QualType desugar() const { return AdjustedTy; }
2654
2655 void Profile(llvm::FoldingSetNodeID &ID) {
2656 Profile(ID, OriginalTy, AdjustedTy);
2657 }
2658
2659 static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) {
2660 ID.AddPointer(Orig.getAsOpaquePtr());
2661 ID.AddPointer(New.getAsOpaquePtr());
2662 }
2663
2664 static bool classof(const Type *T) {
2665 return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed;
2666 }
2667};
2668
2669/// Represents a pointer type decayed from an array or function type.
2670class DecayedType : public AdjustedType {
2671 friend class ASTContext; // ASTContext creates these.
2672
2673 inline
2674 DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical);
2675
2676public:
2677 QualType getDecayedType() const { return getAdjustedType(); }
2678
2679 inline QualType getPointeeType() const;
2680
2681 static bool classof(const Type *T) { return T->getTypeClass() == Decayed; }
2682};
2683
2684/// Pointer to a block type.
2685/// This type is to represent types syntactically represented as
2686/// "void (^)(int)", etc. Pointee is required to always be a function type.
2687class BlockPointerType : public Type, public llvm::FoldingSetNode {
2688 friend class ASTContext; // ASTContext creates these.
2689
2690 // Block is some kind of pointer type
2691 QualType PointeeType;
2692
2693 BlockPointerType(QualType Pointee, QualType CanonicalCls)
2694 : Type(BlockPointer, CanonicalCls, Pointee->isDependentType(),
2695 Pointee->isInstantiationDependentType(),
2696 Pointee->isVariablyModifiedType(),
2697 Pointee->containsUnexpandedParameterPack()),
2698 PointeeType(Pointee) {}
2699
2700public:
2701 // Get the pointee type. Pointee is required to always be a function type.
2702 QualType getPointeeType() const { return PointeeType; }
2703
2704 bool isSugared() const { return false; }
2705 QualType desugar() const { return QualType(this, 0); }
2706
2707 void Profile(llvm::FoldingSetNodeID &ID) {
2708 Profile(ID, getPointeeType());
2709 }
2710
2711 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2712 ID.AddPointer(Pointee.getAsOpaquePtr());
2713 }
2714
2715 static bool classof(const Type *T) {
2716 return T->getTypeClass() == BlockPointer;
2717 }
2718};
2719
2720/// Base for LValueReferenceType and RValueReferenceType
2721class ReferenceType : public Type, public llvm::FoldingSetNode {
2722 QualType PointeeType;
2723
2724protected:
2725 ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
2726 bool SpelledAsLValue)
2727 : Type(tc, CanonicalRef, Referencee->isDependentType(),
2728 Referencee->isInstantiationDependentType(),
2729 Referencee->isVariablyModifiedType(),
2730 Referencee->containsUnexpandedParameterPack()),
2731 PointeeType(Referencee) {
2732 ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
2733 ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
2734 }
2735
2736public:
2737 bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
2738 bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
2739
2740 QualType getPointeeTypeAsWritten() const { return PointeeType; }
2741
2742 QualType getPointeeType() const {
2743 // FIXME: this might strip inner qualifiers; okay?
2744 const ReferenceType *T = this;
2745 while (T->isInnerRef())
2746 T = T->PointeeType->castAs<ReferenceType>();
2747 return T->PointeeType;
2748 }
2749
2750 void Profile(llvm::FoldingSetNodeID &ID) {
2751 Profile(ID, PointeeType, isSpelledAsLValue());
2752 }
2753
2754 static void Profile(llvm::FoldingSetNodeID &ID,
2755 QualType Referencee,
2756 bool SpelledAsLValue) {
2757 ID.AddPointer(Referencee.getAsOpaquePtr());
2758 ID.AddBoolean(SpelledAsLValue);
2759 }
2760
2761 static bool classof(const Type *T) {
2762 return T->getTypeClass() == LValueReference ||
2763 T->getTypeClass() == RValueReference;
2764 }
2765};
2766
2767/// An lvalue reference type, per C++11 [dcl.ref].
2768class LValueReferenceType : public ReferenceType {
2769 friend class ASTContext; // ASTContext creates these
2770
2771 LValueReferenceType(QualType Referencee, QualType CanonicalRef,
2772 bool SpelledAsLValue)
2773 : ReferenceType(LValueReference, Referencee, CanonicalRef,
2774 SpelledAsLValue) {}
2775
2776public:
2777 bool isSugared() const { return false; }
2778 QualType desugar() const { return QualType(this, 0); }
2779
2780 static bool classof(const Type *T) {
2781 return T->getTypeClass() == LValueReference;
2782 }
2783};
2784
2785/// An rvalue reference type, per C++11 [dcl.ref].
2786class RValueReferenceType : public ReferenceType {
2787 friend class ASTContext; // ASTContext creates these
2788
2789 RValueReferenceType(QualType Referencee, QualType CanonicalRef)
2790 : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {}
2791
2792public:
2793 bool isSugared() const { return false; }
2794 QualType desugar() const { return QualType(this, 0); }
2795
2796 static bool classof(const Type *T) {
2797 return T->getTypeClass() == RValueReference;
2798 }
2799};
2800
2801/// A pointer to member type per C++ 8.3.3 - Pointers to members.
2802///
2803/// This includes both pointers to data members and pointer to member functions.
2804class MemberPointerType : public Type, public llvm::FoldingSetNode {
2805 friend class ASTContext; // ASTContext creates these.
2806
2807 QualType PointeeType;
2808
2809 /// The class of which the pointee is a member. Must ultimately be a
2810 /// RecordType, but could be a typedef or a template parameter too.
2811 const Type *Class;
2812
2813 MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr)
2814 : Type(MemberPointer, CanonicalPtr,
2815 Cls->isDependentType() || Pointee->isDependentType(),
2816 (Cls->isInstantiationDependentType() ||
2817 Pointee->isInstantiationDependentType()),
2818 Pointee->isVariablyModifiedType(),
2819 (Cls->containsUnexpandedParameterPack() ||
2820 Pointee->containsUnexpandedParameterPack())),
2821 PointeeType(Pointee), Class(Cls) {}
2822
2823public:
2824 QualType getPointeeType() const { return PointeeType; }
2825
2826 /// Returns true if the member type (i.e. the pointee type) is a
2827 /// function type rather than a data-member type.
2828 bool isMemberFunctionPointer() const {
2829 return PointeeType->isFunctionProtoType();
2830 }
2831
2832 /// Returns true if the member type (i.e. the pointee type) is a
2833 /// data type rather than a function type.
2834 bool isMemberDataPointer() const {
2835 return !PointeeType->isFunctionProtoType();
2836 }
2837
2838 const Type *getClass() const { return Class; }
2839 CXXRecordDecl *getMostRecentCXXRecordDecl() const;
2840
2841 bool isSugared() const { return false; }
2842 QualType desugar() const { return QualType(this, 0); }
2843
2844 void Profile(llvm::FoldingSetNodeID &ID) {
2845 Profile(ID, getPointeeType(), getClass());
2846 }
2847
2848 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
2849 const Type *Class) {
2850 ID.AddPointer(Pointee.getAsOpaquePtr());
2851 ID.AddPointer(Class);
2852 }
2853
2854 static bool classof(const Type *T) {
2855 return T->getTypeClass() == MemberPointer;
2856 }
2857};
2858
2859/// Represents an array type, per C99 6.7.5.2 - Array Declarators.
2860class ArrayType : public Type, public llvm::FoldingSetNode {
2861public:
2862 /// Capture whether this is a normal array (e.g. int X[4])
2863 /// an array with a static size (e.g. int X[static 4]), or an array
2864 /// with a star size (e.g. int X[*]).
2865 /// 'static' is only allowed on function parameters.
2866 enum ArraySizeModifier {
2867 Normal, Static, Star
2868 };
2869
2870private:
2871 /// The element type of the array.
2872 QualType ElementType;
2873
2874protected:
2875 friend class ASTContext; // ASTContext creates these.
2876
2877 ArrayType(TypeClass tc, QualType et, QualType can, ArraySizeModifier sm,
2878 unsigned tq, const Expr *sz = nullptr);
2879
2880public:
2881 QualType getElementType() const { return ElementType; }
2882
2883 ArraySizeModifier getSizeModifier() const {
2884 return ArraySizeModifier(ArrayTypeBits.SizeModifier);
2885 }
2886
2887 Qualifiers getIndexTypeQualifiers() const {
2888 return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers());
2889 }
2890
2891 unsigned getIndexTypeCVRQualifiers() const {
2892 return ArrayTypeBits.IndexTypeQuals;
2893 }
2894
2895 static bool classof(const Type *T) {
2896 return T->getTypeClass() == ConstantArray ||
2897 T->getTypeClass() == VariableArray ||
2898 T->getTypeClass() == IncompleteArray ||
2899 T->getTypeClass() == DependentSizedArray;
2900 }
2901};
2902
2903/// Represents the canonical version of C arrays with a specified constant size.
2904/// For example, the canonical type for 'int A[4 + 4*100]' is a
2905/// ConstantArrayType where the element type is 'int' and the size is 404.
2906class ConstantArrayType final
2907 : public ArrayType,
2908 private llvm::TrailingObjects<ConstantArrayType, const Expr *> {
2909 friend class ASTContext; // ASTContext creates these.
2910 friend TrailingObjects;
2911
2912 llvm::APInt Size; // Allows us to unique the type.
2913
2914 ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
2915 const Expr *sz, ArraySizeModifier sm, unsigned tq)
2916 : ArrayType(ConstantArray, et, can, sm, tq, sz), Size(size) {
2917 ConstantArrayTypeBits.HasStoredSizeExpr = sz != nullptr;
2918 if (ConstantArrayTypeBits.HasStoredSizeExpr) {
2919 assert(!can.isNull() && "canonical constant array should not have size")((!can.isNull() && "canonical constant array should not have size"
) ? static_cast<void> (0) : __assert_fail ("!can.isNull() && \"canonical constant array should not have size\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 2919, __PRETTY_FUNCTION__))
;
2920 *getTrailingObjects<const Expr*>() = sz;
2921 }
2922 }
2923
2924 unsigned numTrailingObjects(OverloadToken<const Expr*>) const {
2925 return ConstantArrayTypeBits.HasStoredSizeExpr;
2926 }
2927
2928public:
2929 const llvm::APInt &getSize() const { return Size; }
2930 const Expr *getSizeExpr() const {
2931 return ConstantArrayTypeBits.HasStoredSizeExpr
2932 ? *getTrailingObjects<const Expr *>()
2933 : nullptr;
2934 }
2935 bool isSugared() const { return false; }
2936 QualType desugar() const { return QualType(this, 0); }
2937
2938 /// Determine the number of bits required to address a member of
2939 // an array with the given element type and number of elements.
2940 static unsigned getNumAddressingBits(const ASTContext &Context,
2941 QualType ElementType,
2942 const llvm::APInt &NumElements);
2943
2944 /// Determine the maximum number of active bits that an array's size
2945 /// can require, which limits the maximum size of the array.
2946 static unsigned getMaxSizeBits(const ASTContext &Context);
2947
2948 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
2949 Profile(ID, Ctx, getElementType(), getSize(), getSizeExpr(),
2950 getSizeModifier(), getIndexTypeCVRQualifiers());
2951 }
2952
2953 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx,
2954 QualType ET, const llvm::APInt &ArraySize,
2955 const Expr *SizeExpr, ArraySizeModifier SizeMod,
2956 unsigned TypeQuals);
2957
2958 static bool classof(const Type *T) {
2959 return T->getTypeClass() == ConstantArray;
2960 }
2961};
2962
2963/// Represents a C array with an unspecified size. For example 'int A[]' has
2964/// an IncompleteArrayType where the element type is 'int' and the size is
2965/// unspecified.
2966class IncompleteArrayType : public ArrayType {
2967 friend class ASTContext; // ASTContext creates these.
2968
2969 IncompleteArrayType(QualType et, QualType can,
2970 ArraySizeModifier sm, unsigned tq)
2971 : ArrayType(IncompleteArray, et, can, sm, tq) {}
2972
2973public:
2974 friend class StmtIteratorBase;
2975
2976 bool isSugared() const { return false; }
2977 QualType desugar() const { return QualType(this, 0); }
2978
2979 static bool classof(const Type *T) {
2980 return T->getTypeClass() == IncompleteArray;
2981 }
2982
2983 void Profile(llvm::FoldingSetNodeID &ID) {
2984 Profile(ID, getElementType(), getSizeModifier(),
2985 getIndexTypeCVRQualifiers());
2986 }
2987
2988 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2989 ArraySizeModifier SizeMod, unsigned TypeQuals) {
2990 ID.AddPointer(ET.getAsOpaquePtr());
2991 ID.AddInteger(SizeMod);
2992 ID.AddInteger(TypeQuals);
2993 }
2994};
2995
2996/// Represents a C array with a specified size that is not an
2997/// integer-constant-expression. For example, 'int s[x+foo()]'.
2998/// Since the size expression is an arbitrary expression, we store it as such.
2999///
3000/// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
3001/// should not be: two lexically equivalent variable array types could mean
3002/// different things, for example, these variables do not have the same type
3003/// dynamically:
3004///
3005/// void foo(int x) {
3006/// int Y[x];
3007/// ++x;
3008/// int Z[x];
3009/// }
3010class VariableArrayType : public ArrayType {
3011 friend class ASTContext; // ASTContext creates these.
3012
3013 /// An assignment-expression. VLA's are only permitted within
3014 /// a function block.
3015 Stmt *SizeExpr;
3016
3017 /// The range spanned by the left and right array brackets.
3018 SourceRange Brackets;
3019
3020 VariableArrayType(QualType et, QualType can, Expr *e,
3021 ArraySizeModifier sm, unsigned tq,
3022 SourceRange brackets)
3023 : ArrayType(VariableArray, et, can, sm, tq, e),
3024 SizeExpr((Stmt*) e), Brackets(brackets) {}
3025
3026public:
3027 friend class StmtIteratorBase;
3028
3029 Expr *getSizeExpr() const {
3030 // We use C-style casts instead of cast<> here because we do not wish
3031 // to have a dependency of Type.h on Stmt.h/Expr.h.
3032 return (Expr*) SizeExpr;
3033 }
3034
3035 SourceRange getBracketsRange() const { return Brackets; }
3036 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3037 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3038
3039 bool isSugared() const { return false; }
3040 QualType desugar() const { return QualType(this, 0); }
3041
3042 static bool classof(const Type *T) {
3043 return T->getTypeClass() == VariableArray;
3044 }
3045
3046 void Profile(llvm::FoldingSetNodeID &ID) {
3047 llvm_unreachable("Cannot unique VariableArrayTypes.")::llvm::llvm_unreachable_internal("Cannot unique VariableArrayTypes."
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 3047)
;
3048 }
3049};
3050
3051/// Represents an array type in C++ whose size is a value-dependent expression.
3052///
3053/// For example:
3054/// \code
3055/// template<typename T, int Size>
3056/// class array {
3057/// T data[Size];
3058/// };
3059/// \endcode
3060///
3061/// For these types, we won't actually know what the array bound is
3062/// until template instantiation occurs, at which point this will
3063/// become either a ConstantArrayType or a VariableArrayType.
3064class DependentSizedArrayType : public ArrayType {
3065 friend class ASTContext; // ASTContext creates these.
3066
3067 const ASTContext &Context;
3068
3069 /// An assignment expression that will instantiate to the
3070 /// size of the array.
3071 ///
3072 /// The expression itself might be null, in which case the array
3073 /// type will have its size deduced from an initializer.
3074 Stmt *SizeExpr;
3075
3076 /// The range spanned by the left and right array brackets.
3077 SourceRange Brackets;
3078
3079 DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can,
3080 Expr *e, ArraySizeModifier sm, unsigned tq,
3081 SourceRange brackets);
3082
3083public:
3084 friend class StmtIteratorBase;
3085
3086 Expr *getSizeExpr() const {
3087 // We use C-style casts instead of cast<> here because we do not wish
3088 // to have a dependency of Type.h on Stmt.h/Expr.h.
3089 return (Expr*) SizeExpr;
3090 }
3091
3092 SourceRange getBracketsRange() const { return Brackets; }
3093 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3094 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3095
3096 bool isSugared() const { return false; }
3097 QualType desugar() const { return QualType(this, 0); }
3098
3099 static bool classof(const Type *T) {
3100 return T->getTypeClass() == DependentSizedArray;
3101 }
3102
3103 void Profile(llvm::FoldingSetNodeID &ID) {
3104 Profile(ID, Context, getElementType(),
3105 getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
3106 }
3107
3108 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3109 QualType ET, ArraySizeModifier SizeMod,
3110 unsigned TypeQuals, Expr *E);
3111};
3112
3113/// Represents an extended address space qualifier where the input address space
3114/// value is dependent. Non-dependent address spaces are not represented with a
3115/// special Type subclass; they are stored on an ExtQuals node as part of a QualType.
3116///
3117/// For example:
3118/// \code
3119/// template<typename T, int AddrSpace>
3120/// class AddressSpace {
3121/// typedef T __attribute__((address_space(AddrSpace))) type;
3122/// }
3123/// \endcode
3124class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode {
3125 friend class ASTContext;
3126
3127 const ASTContext &Context;
3128 Expr *AddrSpaceExpr;
3129 QualType PointeeType;
3130 SourceLocation loc;
3131
3132 DependentAddressSpaceType(const ASTContext &Context, QualType PointeeType,
3133 QualType can, Expr *AddrSpaceExpr,
3134 SourceLocation loc);
3135
3136public:
3137 Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; }
3138 QualType getPointeeType() const { return PointeeType; }
3139 SourceLocation getAttributeLoc() const { return loc; }
3140
3141 bool isSugared() const { return false; }
3142 QualType desugar() const { return QualType(this, 0); }
3143
3144 static bool classof(const Type *T) {
3145 return T->getTypeClass() == DependentAddressSpace;
3146 }
3147
3148 void Profile(llvm::FoldingSetNodeID &ID) {
3149 Profile(ID, Context, getPointeeType(), getAddrSpaceExpr());
3150 }
3151
3152 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3153 QualType PointeeType, Expr *AddrSpaceExpr);
3154};
3155
3156/// Represents an extended vector type where either the type or size is
3157/// dependent.
3158///
3159/// For example:
3160/// \code
3161/// template<typename T, int Size>
3162/// class vector {
3163/// typedef T __attribute__((ext_vector_type(Size))) type;
3164/// }
3165/// \endcode
3166class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
3167 friend class ASTContext;
3168
3169 const ASTContext &Context;
3170 Expr *SizeExpr;
3171
3172 /// The element type of the array.
3173 QualType ElementType;
3174
3175 SourceLocation loc;
3176
3177 DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType,
3178 QualType can, Expr *SizeExpr, SourceLocation loc);
3179
3180public:
3181 Expr *getSizeExpr() const { return SizeExpr; }
3182 QualType getElementType() const { return ElementType; }
3183 SourceLocation getAttributeLoc() const { return loc; }
3184
3185 bool isSugared() const { return false; }
3186 QualType desugar() const { return QualType(this, 0); }
3187
3188 static bool classof(const Type *T) {
3189 return T->getTypeClass() == DependentSizedExtVector;
3190 }
3191
3192 void Profile(llvm::FoldingSetNodeID &ID) {
3193 Profile(ID, Context, getElementType(), getSizeExpr());
3194 }
3195
3196 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3197 QualType ElementType, Expr *SizeExpr);
3198};
3199
3200
3201/// Represents a GCC generic vector type. This type is created using
3202/// __attribute__((vector_size(n)), where "n" specifies the vector size in
3203/// bytes; or from an Altivec __vector or vector declaration.
3204/// Since the constructor takes the number of vector elements, the
3205/// client is responsible for converting the size into the number of elements.
3206class VectorType : public Type, public llvm::FoldingSetNode {
3207public:
3208 enum VectorKind {
3209 /// not a target-specific vector type
3210 GenericVector,
3211
3212 /// is AltiVec vector
3213 AltiVecVector,
3214
3215 /// is AltiVec 'vector Pixel'
3216 AltiVecPixel,
3217
3218 /// is AltiVec 'vector bool ...'
3219 AltiVecBool,
3220
3221 /// is ARM Neon vector
3222 NeonVector,
3223
3224 /// is ARM Neon polynomial vector
3225 NeonPolyVector
3226 };
3227
3228protected:
3229 friend class ASTContext; // ASTContext creates these.
3230
3231 /// The element type of the vector.
3232 QualType ElementType;
3233
3234 VectorType(QualType vecType, unsigned nElements, QualType canonType,
3235 VectorKind vecKind);
3236
3237 VectorType(TypeClass tc, QualType vecType, unsigned nElements,
3238 QualType canonType, VectorKind vecKind);
3239
3240public:
3241 QualType getElementType() const { return ElementType; }
3242 unsigned getNumElements() const { return VectorTypeBits.NumElements; }
3243
3244 static bool isVectorSizeTooLarge(unsigned NumElements) {
3245 return NumElements > VectorTypeBitfields::MaxNumElements;
3246 }
3247
3248 bool isSugared() const { return false; }
3249 QualType desugar() const { return QualType(this, 0); }
3250
3251 VectorKind getVectorKind() const {
3252 return VectorKind(VectorTypeBits.VecKind);
3253 }
3254
3255 void Profile(llvm::FoldingSetNodeID &ID) {
3256 Profile(ID, getElementType(), getNumElements(),
3257 getTypeClass(), getVectorKind());
3258 }
3259
3260 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
3261 unsigned NumElements, TypeClass TypeClass,
3262 VectorKind VecKind) {
3263 ID.AddPointer(ElementType.getAsOpaquePtr());
3264 ID.AddInteger(NumElements);
3265 ID.AddInteger(TypeClass);
3266 ID.AddInteger(VecKind);
3267 }
3268
3269 static bool classof(const Type *T) {
3270 return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
3271 }
3272};
3273
3274/// Represents a vector type where either the type or size is dependent.
3275////
3276/// For example:
3277/// \code
3278/// template<typename T, int Size>
3279/// class vector {
3280/// typedef T __attribute__((vector_size(Size))) type;
3281/// }
3282/// \endcode
3283class DependentVectorType : public Type, public llvm::FoldingSetNode {
3284 friend class ASTContext;
3285
3286 const ASTContext &Context;
3287 QualType ElementType;
3288 Expr *SizeExpr;
3289 SourceLocation Loc;
3290
3291 DependentVectorType(const ASTContext &Context, QualType ElementType,
3292 QualType CanonType, Expr *SizeExpr,
3293 SourceLocation Loc, VectorType::VectorKind vecKind);
3294
3295public:
3296 Expr *getSizeExpr() const { return SizeExpr; }
3297 QualType getElementType() const { return ElementType; }
3298 SourceLocation getAttributeLoc() const { return Loc; }
3299 VectorType::VectorKind getVectorKind() const {
3300 return VectorType::VectorKind(VectorTypeBits.VecKind);
3301 }
3302
3303 bool isSugared() const { return false; }
3304 QualType desugar() const { return QualType(this, 0); }
3305
3306 static bool classof(const Type *T) {
3307 return T->getTypeClass() == DependentVector;
3308 }
3309
3310 void Profile(llvm::FoldingSetNodeID &ID) {
3311 Profile(ID, Context, getElementType(), getSizeExpr(), getVectorKind());
3312 }
3313
3314 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3315 QualType ElementType, const Expr *SizeExpr,
3316 VectorType::VectorKind VecKind);
3317};
3318
3319/// ExtVectorType - Extended vector type. This type is created using
3320/// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
3321/// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
3322/// class enables syntactic extensions, like Vector Components for accessing
3323/// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL
3324/// Shading Language).
3325class ExtVectorType : public VectorType {
3326 friend class ASTContext; // ASTContext creates these.
3327
3328 ExtVectorType(QualType vecType, unsigned nElements, QualType canonType)
3329 : VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {}
3330
3331public:
3332 static int getPointAccessorIdx(char c) {
3333 switch (c) {
3334 default: return -1;
3335 case 'x': case 'r': return 0;
3336 case 'y': case 'g': return 1;
3337 case 'z': case 'b': return 2;
3338 case 'w': case 'a': return 3;
3339 }
3340 }
3341
3342 static int getNumericAccessorIdx(char c) {
3343 switch (c) {
3344 default: return -1;
3345 case '0': return 0;
3346 case '1': return 1;
3347 case '2': return 2;
3348 case '3': return 3;
3349 case '4': return 4;
3350 case '5': return 5;
3351 case '6': return 6;
3352 case '7': return 7;
3353 case '8': return 8;
3354 case '9': return 9;
3355 case 'A':
3356 case 'a': return 10;
3357 case 'B':
3358 case 'b': return 11;
3359 case 'C':
3360 case 'c': return 12;
3361 case 'D':
3362 case 'd': return 13;
3363 case 'E':
3364 case 'e': return 14;
3365 case 'F':
3366 case 'f': return 15;
3367 }
3368 }
3369
3370 static int getAccessorIdx(char c, bool isNumericAccessor) {
3371 if (isNumericAccessor)
3372 return getNumericAccessorIdx(c);
3373 else
3374 return getPointAccessorIdx(c);
3375 }
3376
3377 bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const {
3378 if (int idx = getAccessorIdx(c, isNumericAccessor)+1)
3379 return unsigned(idx-1) < getNumElements();
3380 return false;
3381 }
3382
3383 bool isSugared() const { return false; }
3384 QualType desugar() const { return QualType(this, 0); }
3385
3386 static bool classof(const Type *T) {
3387 return T->getTypeClass() == ExtVector;
3388 }
3389};
3390
3391/// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base
3392/// class of FunctionNoProtoType and FunctionProtoType.
3393class FunctionType : public Type {
3394 // The type returned by the function.
3395 QualType ResultType;
3396
3397public:
3398 /// Interesting information about a specific parameter that can't simply
3399 /// be reflected in parameter's type. This is only used by FunctionProtoType
3400 /// but is in FunctionType to make this class available during the
3401 /// specification of the bases of FunctionProtoType.
3402 ///
3403 /// It makes sense to model language features this way when there's some
3404 /// sort of parameter-specific override (such as an attribute) that
3405 /// affects how the function is called. For example, the ARC ns_consumed
3406 /// attribute changes whether a parameter is passed at +0 (the default)
3407 /// or +1 (ns_consumed). This must be reflected in the function type,
3408 /// but isn't really a change to the parameter type.
3409 ///
3410 /// One serious disadvantage of modelling language features this way is
3411 /// that they generally do not work with language features that attempt
3412 /// to destructure types. For example, template argument deduction will
3413 /// not be able to match a parameter declared as
3414 /// T (*)(U)
3415 /// against an argument of type
3416 /// void (*)(__attribute__((ns_consumed)) id)
3417 /// because the substitution of T=void, U=id into the former will
3418 /// not produce the latter.
3419 class ExtParameterInfo {
3420 enum {
3421 ABIMask = 0x0F,
3422 IsConsumed = 0x10,
3423 HasPassObjSize = 0x20,
3424 IsNoEscape = 0x40,
3425 };
3426 unsigned char Data = 0;
3427
3428 public:
3429 ExtParameterInfo() = default;
3430
3431 /// Return the ABI treatment of this parameter.
3432 ParameterABI getABI() const { return ParameterABI(Data & ABIMask); }
3433 ExtParameterInfo withABI(ParameterABI kind) const {
3434 ExtParameterInfo copy = *this;
3435 copy.Data = (copy.Data & ~ABIMask) | unsigned(kind);
3436 return copy;
3437 }
3438
3439 /// Is this parameter considered "consumed" by Objective-C ARC?
3440 /// Consumed parameters must have retainable object type.
3441 bool isConsumed() const { return (Data & IsConsumed); }
3442 ExtParameterInfo withIsConsumed(bool consumed) const {
3443 ExtParameterInfo copy = *this;
3444 if (consumed)
3445 copy.Data |= IsConsumed;
3446 else
3447 copy.Data &= ~IsConsumed;
3448 return copy;
3449 }
3450
3451 bool hasPassObjectSize() const { return Data & HasPassObjSize; }
3452 ExtParameterInfo withHasPassObjectSize() const {
3453 ExtParameterInfo Copy = *this;
3454 Copy.Data |= HasPassObjSize;
3455 return Copy;
3456 }
3457
3458 bool isNoEscape() const { return Data & IsNoEscape; }
3459 ExtParameterInfo withIsNoEscape(bool NoEscape) const {
3460 ExtParameterInfo Copy = *this;
3461 if (NoEscape)
3462 Copy.Data |= IsNoEscape;
3463 else
3464 Copy.Data &= ~IsNoEscape;
3465 return Copy;
3466 }
3467
3468 unsigned char getOpaqueValue() const { return Data; }
3469 static ExtParameterInfo getFromOpaqueValue(unsigned char data) {
3470 ExtParameterInfo result;
3471 result.Data = data;
3472 return result;
3473 }
3474
3475 friend bool operator==(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3476 return lhs.Data == rhs.Data;
3477 }
3478
3479 friend bool operator!=(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3480 return lhs.Data != rhs.Data;
3481 }
3482 };
3483
3484 /// A class which abstracts out some details necessary for
3485 /// making a call.
3486 ///
3487 /// It is not actually used directly for storing this information in
3488 /// a FunctionType, although FunctionType does currently use the
3489 /// same bit-pattern.
3490 ///
3491 // If you add a field (say Foo), other than the obvious places (both,
3492 // constructors, compile failures), what you need to update is
3493 // * Operator==
3494 // * getFoo
3495 // * withFoo
3496 // * functionType. Add Foo, getFoo.
3497 // * ASTContext::getFooType
3498 // * ASTContext::mergeFunctionTypes
3499 // * FunctionNoProtoType::Profile
3500 // * FunctionProtoType::Profile
3501 // * TypePrinter::PrintFunctionProto
3502 // * AST read and write
3503 // * Codegen
3504 class ExtInfo {
3505 friend class FunctionType;
3506
3507 // Feel free to rearrange or add bits, but if you go over 12,
3508 // you'll need to adjust both the Bits field below and
3509 // Type::FunctionTypeBitfields.
3510
3511 // | CC |noreturn|produces|nocallersavedregs|regparm|nocfcheck|
3512 // |0 .. 4| 5 | 6 | 7 |8 .. 10| 11 |
3513 //
3514 // regparm is either 0 (no regparm attribute) or the regparm value+1.
3515 enum { CallConvMask = 0x1F };
3516 enum { NoReturnMask = 0x20 };
3517 enum { ProducesResultMask = 0x40 };
3518 enum { NoCallerSavedRegsMask = 0x80 };
3519 enum { NoCfCheckMask = 0x800 };
3520 enum {
3521 RegParmMask = ~(CallConvMask | NoReturnMask | ProducesResultMask |
3522 NoCallerSavedRegsMask | NoCfCheckMask),
3523 RegParmOffset = 8
3524 }; // Assumed to be the last field
3525 uint16_t Bits = CC_C;
3526
3527 ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {}
3528
3529 public:
3530 // Constructor with no defaults. Use this when you know that you
3531 // have all the elements (when reading an AST file for example).
3532 ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc,
3533 bool producesResult, bool noCallerSavedRegs, bool NoCfCheck) {
3534 assert((!hasRegParm || regParm < 7) && "Invalid regparm value")(((!hasRegParm || regParm < 7) && "Invalid regparm value"
) ? static_cast<void> (0) : __assert_fail ("(!hasRegParm || regParm < 7) && \"Invalid regparm value\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 3534, __PRETTY_FUNCTION__))
;
3535 Bits = ((unsigned)cc) | (noReturn ? NoReturnMask : 0) |
3536 (producesResult ? ProducesResultMask : 0) |
3537 (noCallerSavedRegs ? NoCallerSavedRegsMask : 0) |
3538 (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0) |
3539 (NoCfCheck ? NoCfCheckMask : 0);
3540 }
3541
3542 // Constructor with all defaults. Use when for example creating a
3543 // function known to use defaults.
3544 ExtInfo() = default;
3545
3546 // Constructor with just the calling convention, which is an important part
3547 // of the canonical type.
3548 ExtInfo(CallingConv CC) : Bits(CC) {}
3549
3550 bool getNoReturn() const { return Bits & NoReturnMask; }
3551 bool getProducesResult() const { return Bits & ProducesResultMask; }
3552 bool getNoCallerSavedRegs() const { return Bits & NoCallerSavedRegsMask; }
3553 bool getNoCfCheck() const { return Bits & NoCfCheckMask; }
3554 bool getHasRegParm() const { return (Bits >> RegParmOffset) != 0; }
3555
3556 unsigned getRegParm() const {
3557 unsigned RegParm = (Bits & RegParmMask) >> RegParmOffset;
3558 if (RegParm > 0)
3559 --RegParm;
3560 return RegParm;
3561 }
3562
3563 CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
3564
3565 bool operator==(ExtInfo Other) const {
3566 return Bits == Other.Bits;
3567 }
3568 bool operator!=(ExtInfo Other) const {
3569 return Bits != Other.Bits;
3570 }
3571
3572 // Note that we don't have setters. That is by design, use
3573 // the following with methods instead of mutating these objects.
3574
3575 ExtInfo withNoReturn(bool noReturn) const {
3576 if (noReturn)
3577 return ExtInfo(Bits | NoReturnMask);
3578 else
3579 return ExtInfo(Bits & ~NoReturnMask);
3580 }
3581
3582 ExtInfo withProducesResult(bool producesResult) const {
3583 if (producesResult)
3584 return ExtInfo(Bits | ProducesResultMask);
3585 else
3586 return ExtInfo(Bits & ~ProducesResultMask);
3587 }
3588
3589 ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const {
3590 if (noCallerSavedRegs)
3591 return ExtInfo(Bits | NoCallerSavedRegsMask);
3592 else
3593 return ExtInfo(Bits & ~NoCallerSavedRegsMask);
3594 }
3595
3596 ExtInfo withNoCfCheck(bool noCfCheck) const {
3597 if (noCfCheck)
3598 return ExtInfo(Bits | NoCfCheckMask);
3599 else
3600 return ExtInfo(Bits & ~NoCfCheckMask);
3601 }
3602
3603 ExtInfo withRegParm(unsigned RegParm) const {
3604 assert(RegParm < 7 && "Invalid regparm value")((RegParm < 7 && "Invalid regparm value") ? static_cast
<void> (0) : __assert_fail ("RegParm < 7 && \"Invalid regparm value\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 3604, __PRETTY_FUNCTION__))
;
3605 return ExtInfo((Bits & ~RegParmMask) |
3606 ((RegParm + 1) << RegParmOffset));
3607 }
3608
3609 ExtInfo withCallingConv(CallingConv cc) const {
3610 return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
3611 }
3612
3613 void Profile(llvm::FoldingSetNodeID &ID) const {
3614 ID.AddInteger(Bits);
3615 }
3616 };
3617
3618 /// A simple holder for a QualType representing a type in an
3619 /// exception specification. Unfortunately needed by FunctionProtoType
3620 /// because TrailingObjects cannot handle repeated types.
3621 struct ExceptionType { QualType Type; };
3622
3623 /// A simple holder for various uncommon bits which do not fit in
3624 /// FunctionTypeBitfields. Aligned to alignof(void *) to maintain the
3625 /// alignment of subsequent objects in TrailingObjects. You must update
3626 /// hasExtraBitfields in FunctionProtoType after adding extra data here.
3627 struct alignas(void *) FunctionTypeExtraBitfields {
3628 /// The number of types in the exception specification.
3629 /// A whole unsigned is not needed here and according to
3630 /// [implimits] 8 bits would be enough here.
3631 unsigned NumExceptionType;
3632 };
3633
3634protected:
3635 FunctionType(TypeClass tc, QualType res,
3636 QualType Canonical, bool Dependent,
3637 bool InstantiationDependent,
3638 bool VariablyModified, bool ContainsUnexpandedParameterPack,
3639 ExtInfo Info)
3640 : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
3641 ContainsUnexpandedParameterPack),
3642 ResultType(res) {
3643 FunctionTypeBits.ExtInfo = Info.Bits;
3644 }
3645
3646 Qualifiers getFastTypeQuals() const {
3647 return Qualifiers::fromFastMask(FunctionTypeBits.FastTypeQuals);
3648 }
3649
3650public:
3651 QualType getReturnType() const { return ResultType; }
3652
3653 bool getHasRegParm() const { return getExtInfo().getHasRegParm(); }
3654 unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
3655
3656 /// Determine whether this function type includes the GNU noreturn
3657 /// attribute. The C++11 [[noreturn]] attribute does not affect the function
3658 /// type.
3659 bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
3660
3661 CallingConv getCallConv() const { return getExtInfo().getCC(); }
3662 ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
3663
3664 static_assert((~Qualifiers::FastMask & Qualifiers::CVRMask) == 0,
3665 "Const, volatile and restrict are assumed to be a subset of "
3666 "the fast qualifiers.");
3667
3668 bool isConst() const { return getFastTypeQuals().hasConst(); }
3669 bool isVolatile() const { return getFastTypeQuals().hasVolatile(); }
3670 bool isRestrict() const { return getFastTypeQuals().hasRestrict(); }
3671
3672 /// Determine the type of an expression that calls a function of
3673 /// this type.
3674 QualType getCallResultType(const ASTContext &Context) const {
3675 return getReturnType().getNonLValueExprType(Context);
3676 }
3677
3678 static StringRef getNameForCallConv(CallingConv CC);
3679
3680 static bool classof(const Type *T) {
3681 return T->getTypeClass() == FunctionNoProto ||
3682 T->getTypeClass() == FunctionProto;
3683 }
3684};
3685
3686/// Represents a K&R-style 'int foo()' function, which has
3687/// no information available about its arguments.
3688class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
3689 friend class ASTContext; // ASTContext creates these.
3690
3691 FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info)
3692 : FunctionType(FunctionNoProto, Result, Canonical,
3693 /*Dependent=*/false, /*InstantiationDependent=*/false,
3694 Result->isVariablyModifiedType(),
3695 /*ContainsUnexpandedParameterPack=*/false, Info) {}
3696
3697public:
3698 // No additional state past what FunctionType provides.
3699
3700 bool isSugared() const { return false; }
3701 QualType desugar() const { return QualType(this, 0); }
3702
3703 void Profile(llvm::FoldingSetNodeID &ID) {
3704 Profile(ID, getReturnType(), getExtInfo());
3705 }
3706
3707 static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
3708 ExtInfo Info) {
3709 Info.Profile(ID);
3710 ID.AddPointer(ResultType.getAsOpaquePtr());
3711 }
3712
3713 static bool classof(const Type *T) {
3714 return T->getTypeClass() == FunctionNoProto;
3715 }
3716};
3717
3718/// Represents a prototype with parameter type info, e.g.
3719/// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no
3720/// parameters, not as having a single void parameter. Such a type can have
3721/// an exception specification, but this specification is not part of the
3722/// canonical type. FunctionProtoType has several trailing objects, some of
3723/// which optional. For more information about the trailing objects see
3724/// the first comment inside FunctionProtoType.
3725class FunctionProtoType final
3726 : public FunctionType,
3727 public llvm::FoldingSetNode,
3728 private llvm::TrailingObjects<
3729 FunctionProtoType, QualType, FunctionType::FunctionTypeExtraBitfields,
3730 FunctionType::ExceptionType, Expr *, FunctionDecl *,
3731 FunctionType::ExtParameterInfo, Qualifiers> {
3732 friend class ASTContext; // ASTContext creates these.
3733 friend TrailingObjects;
3734
3735 // FunctionProtoType is followed by several trailing objects, some of
3736 // which optional. They are in order:
3737 //
3738 // * An array of getNumParams() QualType holding the parameter types.
3739 // Always present. Note that for the vast majority of FunctionProtoType,
3740 // these will be the only trailing objects.
3741 //
3742 // * Optionally if some extra data is stored in FunctionTypeExtraBitfields
3743 // (see FunctionTypeExtraBitfields and FunctionTypeBitfields):
3744 // a single FunctionTypeExtraBitfields. Present if and only if
3745 // hasExtraBitfields() is true.
3746 //
3747 // * Optionally exactly one of:
3748 // * an array of getNumExceptions() ExceptionType,
3749 // * a single Expr *,
3750 // * a pair of FunctionDecl *,
3751 // * a single FunctionDecl *
3752 // used to store information about the various types of exception
3753 // specification. See getExceptionSpecSize for the details.
3754 //
3755 // * Optionally an array of getNumParams() ExtParameterInfo holding
3756 // an ExtParameterInfo for each of the parameters. Present if and
3757 // only if hasExtParameterInfos() is true.
3758 //
3759 // * Optionally a Qualifiers object to represent extra qualifiers that can't
3760 // be represented by FunctionTypeBitfields.FastTypeQuals. Present if and only
3761 // if hasExtQualifiers() is true.
3762 //
3763 // The optional FunctionTypeExtraBitfields has to be before the data
3764 // related to the exception specification since it contains the number
3765 // of exception types.
3766 //
3767 // We put the ExtParameterInfos last. If all were equal, it would make
3768 // more sense to put these before the exception specification, because
3769 // it's much easier to skip past them compared to the elaborate switch
3770 // required to skip the exception specification. However, all is not
3771 // equal; ExtParameterInfos are used to model very uncommon features,
3772 // and it's better not to burden the more common paths.
3773
3774public:
3775 /// Holds information about the various types of exception specification.
3776 /// ExceptionSpecInfo is not stored as such in FunctionProtoType but is
3777 /// used to group together the various bits of information about the
3778 /// exception specification.
3779 struct ExceptionSpecInfo {
3780 /// The kind of exception specification this is.
3781 ExceptionSpecificationType Type = EST_None;
3782
3783 /// Explicitly-specified list of exception types.
3784 ArrayRef<QualType> Exceptions;
3785
3786 /// Noexcept expression, if this is a computed noexcept specification.
3787 Expr *NoexceptExpr = nullptr;
3788
3789 /// The function whose exception specification this is, for
3790 /// EST_Unevaluated and EST_Uninstantiated.
3791 FunctionDecl *SourceDecl = nullptr;
3792
3793 /// The function template whose exception specification this is instantiated
3794 /// from, for EST_Uninstantiated.
3795 FunctionDecl *SourceTemplate = nullptr;
3796
3797 ExceptionSpecInfo() = default;
3798
3799 ExceptionSpecInfo(ExceptionSpecificationType EST) : Type(EST) {}
3800 };
3801
3802 /// Extra information about a function prototype. ExtProtoInfo is not
3803 /// stored as such in FunctionProtoType but is used to group together
3804 /// the various bits of extra information about a function prototype.
3805 struct ExtProtoInfo {
3806 FunctionType::ExtInfo ExtInfo;
3807 bool Variadic : 1;
3808 bool HasTrailingReturn : 1;
3809 Qualifiers TypeQuals;
3810 RefQualifierKind RefQualifier = RQ_None;
3811 ExceptionSpecInfo ExceptionSpec;
3812 const ExtParameterInfo *ExtParameterInfos = nullptr;
3813
3814 ExtProtoInfo() : Variadic(false), HasTrailingReturn(false) {}
3815
3816 ExtProtoInfo(CallingConv CC)
3817 : ExtInfo(CC), Variadic(false), HasTrailingReturn(false) {}
3818
3819 ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI) {
3820 ExtProtoInfo Result(*this);
3821 Result.ExceptionSpec = ESI;
3822 return Result;
3823 }
3824 };
3825
3826private:
3827 unsigned numTrailingObjects(OverloadToken<QualType>) const {
3828 return getNumParams();
3829 }
3830
3831 unsigned numTrailingObjects(OverloadToken<FunctionTypeExtraBitfields>) const {
3832 return hasExtraBitfields();
3833 }
3834
3835 unsigned numTrailingObjects(OverloadToken<ExceptionType>) const {
3836 return getExceptionSpecSize().NumExceptionType;
3837 }
3838
3839 unsigned numTrailingObjects(OverloadToken<Expr *>) const {
3840 return getExceptionSpecSize().NumExprPtr;
3841 }
3842
3843 unsigned numTrailingObjects(OverloadToken<FunctionDecl *>) const {
3844 return getExceptionSpecSize().NumFunctionDeclPtr;
3845 }
3846
3847 unsigned numTrailingObjects(OverloadToken<ExtParameterInfo>) const {
3848 return hasExtParameterInfos() ? getNumParams() : 0;
3849 }
3850
3851 /// Determine whether there are any argument types that
3852 /// contain an unexpanded parameter pack.
3853 static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray,
3854 unsigned numArgs) {
3855 for (unsigned Idx = 0; Idx < numArgs; ++Idx)
3856 if (ArgArray[Idx]->containsUnexpandedParameterPack())
3857 return true;
3858
3859 return false;
3860 }
3861
3862 FunctionProtoType(QualType result, ArrayRef<QualType> params,
3863 QualType canonical, const ExtProtoInfo &epi);
3864
3865 /// This struct is returned by getExceptionSpecSize and is used to
3866 /// translate an ExceptionSpecificationType to the number and kind
3867 /// of trailing objects related to the exception specification.
3868 struct ExceptionSpecSizeHolder {
3869 unsigned NumExceptionType;
3870 unsigned NumExprPtr;
3871 unsigned NumFunctionDeclPtr;
3872 };
3873
3874 /// Return the number and kind of trailing objects
3875 /// related to the exception specification.
3876 static ExceptionSpecSizeHolder
3877 getExceptionSpecSize(ExceptionSpecificationType EST, unsigned NumExceptions) {
3878 switch (EST) {
3879 case EST_None:
3880 case EST_DynamicNone:
3881 case EST_MSAny:
3882 case EST_BasicNoexcept:
3883 case EST_Unparsed:
3884 case EST_NoThrow:
3885 return {0, 0, 0};
3886
3887 case EST_Dynamic:
3888 return {NumExceptions, 0, 0};
3889
3890 case EST_DependentNoexcept:
3891 case EST_NoexceptFalse:
3892 case EST_NoexceptTrue:
3893 return {0, 1, 0};
3894
3895 case EST_Uninstantiated:
3896 return {0, 0, 2};
3897
3898 case EST_Unevaluated:
3899 return {0, 0, 1};
3900 }
3901 llvm_unreachable("bad exception specification kind")::llvm::llvm_unreachable_internal("bad exception specification kind"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 3901)
;
3902 }
3903
3904 /// Return the number and kind of trailing objects
3905 /// related to the exception specification.
3906 ExceptionSpecSizeHolder getExceptionSpecSize() const {
3907 return getExceptionSpecSize(getExceptionSpecType(), getNumExceptions());
3908 }
3909
3910 /// Whether the trailing FunctionTypeExtraBitfields is present.
3911 static bool hasExtraBitfields(ExceptionSpecificationType EST) {
3912 // If the exception spec type is EST_Dynamic then we have > 0 exception
3913 // types and the exact number is stored in FunctionTypeExtraBitfields.
3914 return EST == EST_Dynamic;
3915 }
3916
3917 /// Whether the trailing FunctionTypeExtraBitfields is present.
3918 bool hasExtraBitfields() const {
3919 return hasExtraBitfields(getExceptionSpecType());
3920 }
3921
3922 bool hasExtQualifiers() const {
3923 return FunctionTypeBits.HasExtQuals;
3924 }
3925
3926public:
3927 unsigned getNumParams() const { return FunctionTypeBits.NumParams; }
3928
3929 QualType getParamType(unsigned i) const {
3930 assert(i < getNumParams() && "invalid parameter index")((i < getNumParams() && "invalid parameter index")
? static_cast<void> (0) : __assert_fail ("i < getNumParams() && \"invalid parameter index\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 3930, __PRETTY_FUNCTION__))
;
3931 return param_type_begin()[i];
3932 }
3933
3934 ArrayRef<QualType> getParamTypes() const {
3935 return llvm::makeArrayRef(param_type_begin(), param_type_end());
3936 }
3937
3938 ExtProtoInfo getExtProtoInfo() const {
3939 ExtProtoInfo EPI;
3940 EPI.ExtInfo = getExtInfo();
3941 EPI.Variadic = isVariadic();
3942 EPI.HasTrailingReturn = hasTrailingReturn();
3943 EPI.ExceptionSpec.Type = getExceptionSpecType();
3944 EPI.TypeQuals = getMethodQuals();
3945 EPI.RefQualifier = getRefQualifier();
3946 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3947 EPI.ExceptionSpec.Exceptions = exceptions();
3948 } else if (isComputedNoexcept(EPI.ExceptionSpec.Type)) {
3949 EPI.ExceptionSpec.NoexceptExpr = getNoexceptExpr();
3950 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
3951 EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl();
3952 EPI.ExceptionSpec.SourceTemplate = getExceptionSpecTemplate();
3953 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
3954 EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl();
3955 }
3956 EPI.ExtParameterInfos = getExtParameterInfosOrNull();
3957 return EPI;
3958 }
3959
3960 /// Get the kind of exception specification on this function.
3961 ExceptionSpecificationType getExceptionSpecType() const {
3962 return static_cast<ExceptionSpecificationType>(
3963 FunctionTypeBits.ExceptionSpecType);
3964 }
3965
3966 /// Return whether this function has any kind of exception spec.
3967 bool hasExceptionSpec() const { return getExceptionSpecType() != EST_None; }
3968
3969 /// Return whether this function has a dynamic (throw) exception spec.
3970 bool hasDynamicExceptionSpec() const {
3971 return isDynamicExceptionSpec(getExceptionSpecType());
3972 }
3973
3974 /// Return whether this function has a noexcept exception spec.
3975 bool hasNoexceptExceptionSpec() const {
3976 return isNoexceptExceptionSpec(getExceptionSpecType());
3977 }
3978
3979 /// Return whether this function has a dependent exception spec.
3980 bool hasDependentExceptionSpec() const;
3981
3982 /// Return whether this function has an instantiation-dependent exception
3983 /// spec.
3984 bool hasInstantiationDependentExceptionSpec() const;
3985
3986 /// Return the number of types in the exception specification.
3987 unsigned getNumExceptions() const {
3988 return getExceptionSpecType() == EST_Dynamic
3989 ? getTrailingObjects<FunctionTypeExtraBitfields>()
3990 ->NumExceptionType
3991 : 0;
3992 }
3993
3994 /// Return the ith exception type, where 0 <= i < getNumExceptions().
3995 QualType getExceptionType(unsigned i) const {
3996 assert(i < getNumExceptions() && "Invalid exception number!")((i < getNumExceptions() && "Invalid exception number!"
) ? static_cast<void> (0) : __assert_fail ("i < getNumExceptions() && \"Invalid exception number!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 3996, __PRETTY_FUNCTION__))
;
3997 return exception_begin()[i];
3998 }
3999
4000 /// Return the expression inside noexcept(expression), or a null pointer
4001 /// if there is none (because the exception spec is not of this form).
4002 Expr *getNoexceptExpr() const {
4003 if (!isComputedNoexcept(getExceptionSpecType()))
4004 return nullptr;
4005 return *getTrailingObjects<Expr *>();
4006 }
4007
4008 /// If this function type has an exception specification which hasn't
4009 /// been determined yet (either because it has not been evaluated or because
4010 /// it has not been instantiated), this is the function whose exception
4011 /// specification is represented by this type.
4012 FunctionDecl *getExceptionSpecDecl() const {
4013 if (getExceptionSpecType() != EST_Uninstantiated &&
4014 getExceptionSpecType() != EST_Unevaluated)
4015 return nullptr;
4016 return getTrailingObjects<FunctionDecl *>()[0];
4017 }
4018
4019 /// If this function type has an uninstantiated exception
4020 /// specification, this is the function whose exception specification
4021 /// should be instantiated to find the exception specification for
4022 /// this type.
4023 FunctionDecl *getExceptionSpecTemplate() const {
4024 if (getExceptionSpecType() != EST_Uninstantiated)
4025 return nullptr;
4026 return getTrailingObjects<FunctionDecl *>()[1];
4027 }
4028
4029 /// Determine whether this function type has a non-throwing exception
4030 /// specification.
4031 CanThrowResult canThrow() const;
4032
4033 /// Determine whether this function type has a non-throwing exception
4034 /// specification. If this depends on template arguments, returns
4035 /// \c ResultIfDependent.
4036 bool isNothrow(bool ResultIfDependent = false) const {
4037 return ResultIfDependent ? canThrow() != CT_Can : canThrow() == CT_Cannot;
4038 }
4039
4040 /// Whether this function prototype is variadic.
4041 bool isVariadic() const { return FunctionTypeBits.Variadic; }
4042
4043 /// Determines whether this function prototype contains a
4044 /// parameter pack at the end.
4045 ///
4046 /// A function template whose last parameter is a parameter pack can be
4047 /// called with an arbitrary number of arguments, much like a variadic
4048 /// function.
4049 bool isTemplateVariadic() const;
4050
4051 /// Whether this function prototype has a trailing return type.
4052 bool hasTrailingReturn() const { return FunctionTypeBits.HasTrailingReturn; }
4053
4054 Qualifiers getMethodQuals() const {
4055 if (hasExtQualifiers())
4056 return *getTrailingObjects<Qualifiers>();
4057 else
4058 return getFastTypeQuals();
4059 }
4060
4061 /// Retrieve the ref-qualifier associated with this function type.
4062 RefQualifierKind getRefQualifier() const {
4063 return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier);
4064 }
4065
4066 using param_type_iterator = const QualType *;
4067 using param_type_range = llvm::iterator_range<param_type_iterator>;
4068
4069 param_type_range param_types() const {
4070 return param_type_range(param_type_begin(), param_type_end());
4071 }
4072
4073 param_type_iterator param_type_begin() const {
4074 return getTrailingObjects<QualType>();
4075 }
4076
4077 param_type_iterator param_type_end() const {
4078 return param_type_begin() + getNumParams();
4079 }
4080
4081 using exception_iterator = const QualType *;
4082
4083 ArrayRef<QualType> exceptions() const {
4084 return llvm::makeArrayRef(exception_begin(), exception_end());
4085 }
4086
4087 exception_iterator exception_begin() const {
4088 return reinterpret_cast<exception_iterator>(
4089 getTrailingObjects<ExceptionType>());
4090 }
4091
4092 exception_iterator exception_end() const {
4093 return exception_begin() + getNumExceptions();
4094 }
4095
4096 /// Is there any interesting extra information for any of the parameters
4097 /// of this function type?
4098 bool hasExtParameterInfos() const {
4099 return FunctionTypeBits.HasExtParameterInfos;
4100 }
4101
4102 ArrayRef<ExtParameterInfo> getExtParameterInfos() const {
4103 assert(hasExtParameterInfos())((hasExtParameterInfos()) ? static_cast<void> (0) : __assert_fail
("hasExtParameterInfos()", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 4103, __PRETTY_FUNCTION__))
;
4104 return ArrayRef<ExtParameterInfo>(getTrailingObjects<ExtParameterInfo>(),
4105 getNumParams());
4106 }
4107
4108 /// Return a pointer to the beginning of the array of extra parameter
4109 /// information, if present, or else null if none of the parameters
4110 /// carry it. This is equivalent to getExtProtoInfo().ExtParameterInfos.
4111 const ExtParameterInfo *getExtParameterInfosOrNull() const {
4112 if (!hasExtParameterInfos())
4113 return nullptr;
4114 return getTrailingObjects<ExtParameterInfo>();
4115 }
4116
4117 ExtParameterInfo getExtParameterInfo(unsigned I) const {
4118 assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range"
) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 4118, __PRETTY_FUNCTION__))
;
4119 if (hasExtParameterInfos())
4120 return getTrailingObjects<ExtParameterInfo>()[I];
4121 return ExtParameterInfo();
4122 }
4123
4124 ParameterABI getParameterABI(unsigned I) const {
4125 assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range"
) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 4125, __PRETTY_FUNCTION__))
;
4126 if (hasExtParameterInfos())
4127 return getTrailingObjects<ExtParameterInfo>()[I].getABI();
4128 return ParameterABI::Ordinary;
4129 }
4130
4131 bool isParamConsumed(unsigned I) const {
4132 assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range"
) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 4132, __PRETTY_FUNCTION__))
;
4133 if (hasExtParameterInfos())
4134 return getTrailingObjects<ExtParameterInfo>()[I].isConsumed();
4135 return false;
4136 }
4137
4138 bool isSugared() const { return false; }
4139 QualType desugar() const { return QualType(this, 0); }
4140
4141 void printExceptionSpecification(raw_ostream &OS,
4142 const PrintingPolicy &Policy) const;
4143
4144 static bool classof(const Type *T) {
4145 return T->getTypeClass() == FunctionProto;
4146 }
4147
4148 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx);
4149 static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
4150 param_type_iterator ArgTys, unsigned NumArgs,
4151 const ExtProtoInfo &EPI, const ASTContext &Context,
4152 bool Canonical);
4153};
4154
4155/// Represents the dependent type named by a dependently-scoped
4156/// typename using declaration, e.g.
4157/// using typename Base<T>::foo;
4158///
4159/// Template instantiation turns these into the underlying type.
4160class UnresolvedUsingType : public Type {
4161 friend class ASTContext; // ASTContext creates these.
4162
4163 UnresolvedUsingTypenameDecl *Decl;
4164
4165 UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D)
4166 : Type(UnresolvedUsing, QualType(), true, true, false,
4167 /*ContainsUnexpandedParameterPack=*/false),
4168 Decl(const_cast<UnresolvedUsingTypenameDecl*>(D)) {}
4169
4170public:
4171 UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
4172
4173 bool isSugared() const { return false; }
4174 QualType desugar() const { return QualType(this, 0); }
4175
4176 static bool classof(const Type *T) {
4177 return T->getTypeClass() == UnresolvedUsing;
4178 }
4179
4180 void Profile(llvm::FoldingSetNodeID &ID) {
4181 return Profile(ID, Decl);
4182 }
4183
4184 static void Profile(llvm::FoldingSetNodeID &ID,
4185 UnresolvedUsingTypenameDecl *D) {
4186 ID.AddPointer(D);
4187 }
4188};
4189
4190class TypedefType : public Type {
4191 TypedefNameDecl *Decl;
4192
4193protected:
4194 friend class ASTContext; // ASTContext creates these.
4195
4196 TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType can)
4197 : Type(tc, can, can->isDependentType(),
4198 can->isInstantiationDependentType(),
4199 can->isVariablyModifiedType(),
4200 /*ContainsUnexpandedParameterPack=*/false),
4201 Decl(const_cast<TypedefNameDecl*>(D)) {
4202 assert(!isa<TypedefType>(can) && "Invalid canonical type")((!isa<TypedefType>(can) && "Invalid canonical type"
) ? static_cast<void> (0) : __assert_fail ("!isa<TypedefType>(can) && \"Invalid canonical type\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 4202, __PRETTY_FUNCTION__))
;
4203 }
4204
4205public:
4206 TypedefNameDecl *getDecl() const { return Decl; }
4207
4208 bool isSugared() const { return true; }
4209 QualType desugar() const;
4210
4211 static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
4212};
4213
4214/// Sugar type that represents a type that was qualified by a qualifier written
4215/// as a macro invocation.
4216class MacroQualifiedType : public Type {
4217 friend class ASTContext; // ASTContext creates these.
4218
4219 QualType UnderlyingTy;
4220 const IdentifierInfo *MacroII;
4221
4222 MacroQualifiedType(QualType UnderlyingTy, QualType CanonTy,
4223 const IdentifierInfo *MacroII)
4224 : Type(MacroQualified, CanonTy, UnderlyingTy->isDependentType(),
4225 UnderlyingTy->isInstantiationDependentType(),
4226 UnderlyingTy->isVariablyModifiedType(),
4227 UnderlyingTy->containsUnexpandedParameterPack()),
4228 UnderlyingTy(UnderlyingTy), MacroII(MacroII) {
4229 assert(isa<AttributedType>(UnderlyingTy) &&((isa<AttributedType>(UnderlyingTy) && "Expected a macro qualified type to only wrap attributed types."
) ? static_cast<void> (0) : __assert_fail ("isa<AttributedType>(UnderlyingTy) && \"Expected a macro qualified type to only wrap attributed types.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 4230, __PRETTY_FUNCTION__))
4230 "Expected a macro qualified type to only wrap attributed types.")((isa<AttributedType>(UnderlyingTy) && "Expected a macro qualified type to only wrap attributed types."
) ? static_cast<void> (0) : __assert_fail ("isa<AttributedType>(UnderlyingTy) && \"Expected a macro qualified type to only wrap attributed types.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 4230, __PRETTY_FUNCTION__))
;
4231 }
4232
4233public:
4234 const IdentifierInfo *getMacroIdentifier() const { return MacroII; }
4235 QualType getUnderlyingType() const { return UnderlyingTy; }
4236
4237 /// Return this attributed type's modified type with no qualifiers attached to
4238 /// it.
4239 QualType getModifiedType() const;
4240
4241 bool isSugared() const { return true; }
4242 QualType desugar() const;
4243
4244 static bool classof(const Type *T) {
4245 return T->getTypeClass() == MacroQualified;
4246 }
4247};
4248
4249/// Represents a `typeof` (or __typeof__) expression (a GCC extension).
4250class TypeOfExprType : public Type {
4251 Expr *TOExpr;
4252
4253protected:
4254 friend class ASTContext; // ASTContext creates these.
4255
4256 TypeOfExprType(Expr *E, QualType can = QualType());
4257
4258public:
4259 Expr *getUnderlyingExpr() const { return TOExpr; }
4260
4261 /// Remove a single level of sugar.
4262 QualType desugar() const;
4263
4264 /// Returns whether this type directly provides sugar.
4265 bool isSugared() const;
4266
4267 static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
4268};
4269
4270/// Internal representation of canonical, dependent
4271/// `typeof(expr)` types.
4272///
4273/// This class is used internally by the ASTContext to manage
4274/// canonical, dependent types, only. Clients will only see instances
4275/// of this class via TypeOfExprType nodes.
4276class DependentTypeOfExprType
4277 : public TypeOfExprType, public llvm::FoldingSetNode {
4278 const ASTContext &Context;
4279
4280public:
4281 DependentTypeOfExprType(const ASTContext &Context, Expr *E)
4282 : TypeOfExprType(E), Context(Context) {}
4283
4284 void Profile(llvm::FoldingSetNodeID &ID) {
4285 Profile(ID, Context, getUnderlyingExpr());
4286 }
4287
4288 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4289 Expr *E);
4290};
4291
4292/// Represents `typeof(type)`, a GCC extension.
4293class TypeOfType : public Type {
4294 friend class ASTContext; // ASTContext creates these.
4295
4296 QualType TOType;
4297
4298 TypeOfType(QualType T, QualType can)
4299 : Type(TypeOf, can, T->isDependentType(),
4300 T->isInstantiationDependentType(),
4301 T->isVariablyModifiedType(),
4302 T->containsUnexpandedParameterPack()),
4303 TOType(T) {
4304 assert(!isa<TypedefType>(can) && "Invalid canonical type")((!isa<TypedefType>(can) && "Invalid canonical type"
) ? static_cast<void> (0) : __assert_fail ("!isa<TypedefType>(can) && \"Invalid canonical type\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 4304, __PRETTY_FUNCTION__))
;
4305 }
4306
4307public:
4308 QualType getUnderlyingType() const { return TOType; }
4309
4310 /// Remove a single level of sugar.
4311 QualType desugar() const { return getUnderlyingType(); }
4312
4313 /// Returns whether this type directly provides sugar.
4314 bool isSugared() const { return true; }
4315
4316 static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
4317};
4318
4319/// Represents the type `decltype(expr)` (C++11).
4320class DecltypeType : public Type {
4321 Expr *E;
4322 QualType UnderlyingType;
4323
4324protected:
4325 friend class ASTContext; // ASTContext creates these.
4326
4327 DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
4328
4329public:
4330 Expr *getUnderlyingExpr() const { return E; }
4331 QualType getUnderlyingType() const { return UnderlyingType; }
4332
4333 /// Remove a single level of sugar.
4334 QualType desugar() const;
4335
4336 /// Returns whether this type directly provides sugar.
4337 bool isSugared() const;
4338
4339 static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
4340};
4341
4342/// Internal representation of canonical, dependent
4343/// decltype(expr) types.
4344///
4345/// This class is used internally by the ASTContext to manage
4346/// canonical, dependent types, only. Clients will only see instances
4347/// of this class via DecltypeType nodes.
4348class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
4349 const ASTContext &Context;
4350
4351public:
4352 DependentDecltypeType(const ASTContext &Context, Expr *E);
4353
4354 void Profile(llvm::FoldingSetNodeID &ID) {
4355 Profile(ID, Context, getUnderlyingExpr());
4356 }
4357
4358 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4359 Expr *E);
4360};
4361
4362/// A unary type transform, which is a type constructed from another.
4363class UnaryTransformType : public Type {
4364public:
4365 enum UTTKind {
4366 EnumUnderlyingType
4367 };
4368
4369private:
4370 /// The untransformed type.
4371 QualType BaseType;
4372
4373 /// The transformed type if not dependent, otherwise the same as BaseType.
4374 QualType UnderlyingType;
4375
4376 UTTKind UKind;
4377
4378protected:
4379 friend class ASTContext;
4380
4381 UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind,
4382 QualType CanonicalTy);
4383
4384public:
4385 bool isSugared() const { return !isDependentType(); }
4386 QualType desugar() const { return UnderlyingType; }
4387
4388 QualType getUnderlyingType() const { return UnderlyingType; }
4389 QualType getBaseType() const { return BaseType; }
4390
4391 UTTKind getUTTKind() const { return UKind; }
4392
4393 static bool classof(const Type *T) {
4394 return T->getTypeClass() == UnaryTransform;
4395 }
4396};
4397
4398/// Internal representation of canonical, dependent
4399/// __underlying_type(type) types.
4400///
4401/// This class is used internally by the ASTContext to manage
4402/// canonical, dependent types, only. Clients will only see instances
4403/// of this class via UnaryTransformType nodes.
4404class DependentUnaryTransformType : public UnaryTransformType,
4405 public llvm::FoldingSetNode {
4406public:
4407 DependentUnaryTransformType(const ASTContext &C, QualType BaseType,
4408 UTTKind UKind);
4409
4410 void Profile(llvm::FoldingSetNodeID &ID) {
4411 Profile(ID, getBaseType(), getUTTKind());
4412 }
4413
4414 static void Profile(llvm::FoldingSetNodeID &ID, QualType BaseType,
4415 UTTKind UKind) {
4416 ID.AddPointer(BaseType.getAsOpaquePtr());
4417 ID.AddInteger((unsigned)UKind);
4418 }
4419};
4420
4421class TagType : public Type {
4422 friend class ASTReader;
4423
4424 /// Stores the TagDecl associated with this type. The decl may point to any
4425 /// TagDecl that declares the entity.
4426 TagDecl *decl;
4427
4428protected:
4429 TagType(TypeClass TC, const TagDecl *D, QualType can);
4430
4431public:
4432 TagDecl *getDecl() const;
4433
4434 /// Determines whether this type is in the process of being defined.
4435 bool isBeingDefined() const;
4436
4437 static bool classof(const Type *T) {
4438 return T->getTypeClass() == Enum || T->getTypeClass() == Record;
4439 }
4440};
4441
4442/// A helper class that allows the use of isa/cast/dyncast
4443/// to detect TagType objects of structs/unions/classes.
4444class RecordType : public TagType {
4445protected:
4446 friend class ASTContext; // ASTContext creates these.
4447
4448 explicit RecordType(const RecordDecl *D)
4449 : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4450 explicit RecordType(TypeClass TC, RecordDecl *D)
4451 : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4452
4453public:
4454 RecordDecl *getDecl() const {
4455 return reinterpret_cast<RecordDecl*>(TagType::getDecl());
4456 }
4457
4458 /// Recursively check all fields in the record for const-ness. If any field
4459 /// is declared const, return true. Otherwise, return false.
4460 bool hasConstFields() const;
4461
4462 bool isSugared() const { return false; }
4463 QualType desugar() const { return QualType(this, 0); }
4464
4465 static bool classof(const Type *T) { return T->getTypeClass() == Record; }
4466};
4467
4468/// A helper class that allows the use of isa/cast/dyncast
4469/// to detect TagType objects of enums.
4470class EnumType : public TagType {
4471 friend class ASTContext; // ASTContext creates these.
4472
4473 explicit EnumType(const EnumDecl *D)
4474 : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4475
4476public:
4477 EnumDecl *getDecl() const {
4478 return reinterpret_cast<EnumDecl*>(TagType::getDecl());
4479 }
4480
4481 bool isSugared() const { return false; }
4482 QualType desugar() const { return QualType(this, 0); }
4483
4484 static bool classof(const Type *T) { return T->getTypeClass() == Enum; }
4485};
4486
4487/// An attributed type is a type to which a type attribute has been applied.
4488///
4489/// The "modified type" is the fully-sugared type to which the attributed
4490/// type was applied; generally it is not canonically equivalent to the
4491/// attributed type. The "equivalent type" is the minimally-desugared type
4492/// which the type is canonically equivalent to.
4493///
4494/// For example, in the following attributed type:
4495/// int32_t __attribute__((vector_size(16)))
4496/// - the modified type is the TypedefType for int32_t
4497/// - the equivalent type is VectorType(16, int32_t)
4498/// - the canonical type is VectorType(16, int)
4499class AttributedType : public Type, public llvm::FoldingSetNode {
4500public:
4501 using Kind = attr::Kind;
4502
4503private:
4504 friend class ASTContext; // ASTContext creates these
4505
4506 QualType ModifiedType;
4507 QualType EquivalentType;
4508
4509 AttributedType(QualType canon, attr::Kind attrKind, QualType modified,
4510 QualType equivalent)
4511 : Type(Attributed, canon, equivalent->isDependentType(),
4512 equivalent->isInstantiationDependentType(),
4513 equivalent->isVariablyModifiedType(),
4514 equivalent->containsUnexpandedParameterPack()),
4515 ModifiedType(modified), EquivalentType(equivalent) {
4516 AttributedTypeBits.AttrKind = attrKind;
4517 }
4518
4519public:
4520 Kind getAttrKind() const {
4521 return static_cast<Kind>(AttributedTypeBits.AttrKind);
4522 }
4523
4524 QualType getModifiedType() const { return ModifiedType; }
4525 QualType getEquivalentType() const { return EquivalentType; }
4526
4527 bool isSugared() const { return true; }
4528 QualType desugar() const { return getEquivalentType(); }
4529
4530 /// Does this attribute behave like a type qualifier?
4531 ///
4532 /// A type qualifier adjusts a type to provide specialized rules for
4533 /// a specific object, like the standard const and volatile qualifiers.
4534 /// This includes attributes controlling things like nullability,
4535 /// address spaces, and ARC ownership. The value of the object is still
4536 /// largely described by the modified type.
4537 ///
4538 /// In contrast, many type attributes "rewrite" their modified type to
4539 /// produce a fundamentally different type, not necessarily related in any
4540 /// formalizable way to the original type. For example, calling convention
4541 /// and vector attributes are not simple type qualifiers.
4542 ///
4543 /// Type qualifiers are often, but not always, reflected in the canonical
4544 /// type.
4545 bool isQualifier() const;
4546
4547 bool isMSTypeSpec() const;
4548
4549 bool isCallingConv() const;
4550
4551 llvm::Optional<NullabilityKind> getImmediateNullability() const;
4552
4553 /// Retrieve the attribute kind corresponding to the given
4554 /// nullability kind.
4555 static Kind getNullabilityAttrKind(NullabilityKind kind) {
4556 switch (kind) {
4557 case NullabilityKind::NonNull:
4558 return attr::TypeNonNull;
4559
4560 case NullabilityKind::Nullable:
4561 return attr::TypeNullable;
4562
4563 case NullabilityKind::Unspecified:
4564 return attr::TypeNullUnspecified;
4565 }
4566 llvm_unreachable("Unknown nullability kind.")::llvm::llvm_unreachable_internal("Unknown nullability kind."
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 4566)
;
4567 }
4568
4569 /// Strip off the top-level nullability annotation on the given
4570 /// type, if it's there.
4571 ///
4572 /// \param T The type to strip. If the type is exactly an
4573 /// AttributedType specifying nullability (without looking through
4574 /// type sugar), the nullability is returned and this type changed
4575 /// to the underlying modified type.
4576 ///
4577 /// \returns the top-level nullability, if present.
4578 static Optional<NullabilityKind> stripOuterNullability(QualType &T);
4579
4580 void Profile(llvm::FoldingSetNodeID &ID) {
4581 Profile(ID, getAttrKind(), ModifiedType, EquivalentType);
4582 }
4583
4584 static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind,
4585 QualType modified, QualType equivalent) {
4586 ID.AddInteger(attrKind);
4587 ID.AddPointer(modified.getAsOpaquePtr());
4588 ID.AddPointer(equivalent.getAsOpaquePtr());
4589 }
4590
4591 static bool classof(const Type *T) {
4592 return T->getTypeClass() == Attributed;
4593 }
4594};
4595
4596class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4597 friend class ASTContext; // ASTContext creates these
4598
4599 // Helper data collector for canonical types.
4600 struct CanonicalTTPTInfo {
4601 unsigned Depth : 15;
4602 unsigned ParameterPack : 1;
4603 unsigned Index : 16;
4604 };
4605
4606 union {
4607 // Info for the canonical type.
4608 CanonicalTTPTInfo CanTTPTInfo;
4609
4610 // Info for the non-canonical type.
4611 TemplateTypeParmDecl *TTPDecl;
4612 };
4613
4614 /// Build a non-canonical type.
4615 TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon)
4616 : Type(TemplateTypeParm, Canon, /*Dependent=*/true,
4617 /*InstantiationDependent=*/true,
4618 /*VariablyModified=*/false,
4619 Canon->containsUnexpandedParameterPack()),
4620 TTPDecl(TTPDecl) {}
4621
4622 /// Build the canonical type.
4623 TemplateTypeParmType(unsigned D, unsigned I, bool PP)
4624 : Type(TemplateTypeParm, QualType(this, 0),
4625 /*Dependent=*/true,
4626 /*InstantiationDependent=*/true,
4627 /*VariablyModified=*/false, PP) {
4628 CanTTPTInfo.Depth = D;
4629 CanTTPTInfo.Index = I;
4630 CanTTPTInfo.ParameterPack = PP;
4631 }
4632
4633 const CanonicalTTPTInfo& getCanTTPTInfo() const {
4634 QualType Can = getCanonicalTypeInternal();
4635 return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo;
4636 }
4637
4638public:
4639 unsigned getDepth() const { return getCanTTPTInfo().Depth; }
4640 unsigned getIndex() const { return getCanTTPTInfo().Index; }
4641 bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; }
4642
4643 TemplateTypeParmDecl *getDecl() const {
4644 return isCanonicalUnqualified() ? nullptr : TTPDecl;
4645 }
4646
4647 IdentifierInfo *getIdentifier() const;
4648
4649 bool isSugared() const { return false; }
4650 QualType desugar() const { return QualType(this, 0); }
4651
4652 void Profile(llvm::FoldingSetNodeID &ID) {
4653 Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl());
4654 }
4655
4656 static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
4657 unsigned Index, bool ParameterPack,
4658 TemplateTypeParmDecl *TTPDecl) {
4659 ID.AddInteger(Depth);
4660 ID.AddInteger(Index);
4661 ID.AddBoolean(ParameterPack);
4662 ID.AddPointer(TTPDecl);
4663 }
4664
4665 static bool classof(const Type *T) {
4666 return T->getTypeClass() == TemplateTypeParm;
4667 }
4668};
4669
4670/// Represents the result of substituting a type for a template
4671/// type parameter.
4672///
4673/// Within an instantiated template, all template type parameters have
4674/// been replaced with these. They are used solely to record that a
4675/// type was originally written as a template type parameter;
4676/// therefore they are never canonical.
4677class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4678 friend class ASTContext;
4679
4680 // The original type parameter.
4681 const TemplateTypeParmType *Replaced;
4682
4683 SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon)
4684 : Type(SubstTemplateTypeParm, Canon, Canon->isDependentType(),
4685 Canon->isInstantiationDependentType(),
4686 Canon->isVariablyModifiedType(),
4687 Canon->containsUnexpandedParameterPack()),
4688 Replaced(Param) {}
4689
4690public:
4691 /// Gets the template parameter that was substituted for.
4692 const TemplateTypeParmType *getReplacedParameter() const {
4693 return Replaced;
4694 }
4695
4696 /// Gets the type that was substituted for the template
4697 /// parameter.
4698 QualType getReplacementType() const {
4699 return getCanonicalTypeInternal();
4700 }
4701
4702 bool isSugared() const { return true; }
4703 QualType desugar() const { return getReplacementType(); }
4704
4705 void Profile(llvm::FoldingSetNodeID &ID) {
4706 Profile(ID, getReplacedParameter(), getReplacementType());
4707 }
4708
4709 static void Profile(llvm::FoldingSetNodeID &ID,
4710 const TemplateTypeParmType *Replaced,
4711 QualType Replacement) {
4712 ID.AddPointer(Replaced);
4713 ID.AddPointer(Replacement.getAsOpaquePtr());
4714 }
4715
4716 static bool classof(const Type *T) {
4717 return T->getTypeClass() == SubstTemplateTypeParm;
4718 }
4719};
4720
4721/// Represents the result of substituting a set of types for a template
4722/// type parameter pack.
4723///
4724/// When a pack expansion in the source code contains multiple parameter packs
4725/// and those parameter packs correspond to different levels of template
4726/// parameter lists, this type node is used to represent a template type
4727/// parameter pack from an outer level, which has already had its argument pack
4728/// substituted but that still lives within a pack expansion that itself
4729/// could not be instantiated. When actually performing a substitution into
4730/// that pack expansion (e.g., when all template parameters have corresponding
4731/// arguments), this type will be replaced with the \c SubstTemplateTypeParmType
4732/// at the current pack substitution index.
4733class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode {
4734 friend class ASTContext;
4735
4736 /// The original type parameter.
4737 const TemplateTypeParmType *Replaced;
4738
4739 /// A pointer to the set of template arguments that this
4740 /// parameter pack is instantiated with.
4741 const TemplateArgument *Arguments;
4742
4743 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
4744 QualType Canon,
4745 const TemplateArgument &ArgPack);
4746
4747public:
4748 IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); }
4749
4750 /// Gets the template parameter that was substituted for.
4751 const TemplateTypeParmType *getReplacedParameter() const {
4752 return Replaced;
4753 }
4754
4755 unsigned getNumArgs() const {
4756 return SubstTemplateTypeParmPackTypeBits.NumArgs;
4757 }
4758
4759 bool isSugared() const { return false; }
4760 QualType desugar() const { return QualType(this, 0); }
4761
4762 TemplateArgument getArgumentPack() const;
4763
4764 void Profile(llvm::FoldingSetNodeID &ID);
4765 static void Profile(llvm::FoldingSetNodeID &ID,
4766 const TemplateTypeParmType *Replaced,
4767 const TemplateArgument &ArgPack);
4768
4769 static bool classof(const Type *T) {
4770 return T->getTypeClass() == SubstTemplateTypeParmPack;
4771 }
4772};
4773
4774/// Common base class for placeholders for types that get replaced by
4775/// placeholder type deduction: C++11 auto, C++14 decltype(auto), C++17 deduced
4776/// class template types, and (eventually) constrained type names from the C++
4777/// Concepts TS.
4778///
4779/// These types are usually a placeholder for a deduced type. However, before
4780/// the initializer is attached, or (usually) if the initializer is
4781/// type-dependent, there is no deduced type and the type is canonical. In
4782/// the latter case, it is also a dependent type.
4783class DeducedType : public Type {
4784protected:
4785 DeducedType(TypeClass TC, QualType DeducedAsType, bool IsDependent,
4786 bool IsInstantiationDependent, bool ContainsParameterPack)
4787 : Type(TC,
4788 // FIXME: Retain the sugared deduced type?
4789 DeducedAsType.isNull() ? QualType(this, 0)
4790 : DeducedAsType.getCanonicalType(),
4791 IsDependent, IsInstantiationDependent,
4792 /*VariablyModified=*/false, ContainsParameterPack) {
4793 if (!DeducedAsType.isNull()) {
4794 if (DeducedAsType->isDependentType())
4795 setDependent();
4796 if (DeducedAsType->isInstantiationDependentType())
4797 setInstantiationDependent();
4798 if (DeducedAsType->containsUnexpandedParameterPack())
4799 setContainsUnexpandedParameterPack();
4800 }
4801 }
4802
4803public:
4804 bool isSugared() const { return !isCanonicalUnqualified(); }
4805 QualType desugar() const { return getCanonicalTypeInternal(); }
4806
4807 /// Get the type deduced for this placeholder type, or null if it's
4808 /// either not been deduced or was deduced to a dependent type.
4809 QualType getDeducedType() const {
4810 return !isCanonicalUnqualified() ? getCanonicalTypeInternal() : QualType();
4811 }
4812 bool isDeduced() const {
4813 return !isCanonicalUnqualified() || isDependentType();
4814 }
4815
4816 static bool classof(const Type *T) {
4817 return T->getTypeClass() == Auto ||
4818 T->getTypeClass() == DeducedTemplateSpecialization;
4819 }
4820};
4821
4822/// Represents a C++11 auto or C++14 decltype(auto) type.
4823class AutoType : public DeducedType, public llvm::FoldingSetNode {
4824 friend class ASTContext; // ASTContext creates these
4825
4826 AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword,
4827 bool IsDeducedAsDependent, bool IsDeducedAsPack)
4828 : DeducedType(Auto, DeducedAsType, IsDeducedAsDependent,
4829 IsDeducedAsDependent, IsDeducedAsPack) {
4830 AutoTypeBits.Keyword = (unsigned)Keyword;
4831 }
4832
4833public:
4834 bool isDecltypeAuto() const {
4835 return getKeyword() == AutoTypeKeyword::DecltypeAuto;
4836 }
4837
4838 AutoTypeKeyword getKeyword() const {
4839 return (AutoTypeKeyword)AutoTypeBits.Keyword;
4840 }
4841
4842 void Profile(llvm::FoldingSetNodeID &ID) {
4843 Profile(ID, getDeducedType(), getKeyword(), isDependentType(),
4844 containsUnexpandedParameterPack());
4845 }
4846
4847 static void Profile(llvm::FoldingSetNodeID &ID, QualType Deduced,
4848 AutoTypeKeyword Keyword, bool IsDependent, bool IsPack) {
4849 ID.AddPointer(Deduced.getAsOpaquePtr());
4850 ID.AddInteger((unsigned)Keyword);
4851 ID.AddBoolean(IsDependent);
4852 ID.AddBoolean(IsPack);
4853 }
4854
4855 static bool classof(const Type *T) {
4856 return T->getTypeClass() == Auto;
4857 }
4858};
4859
4860/// Represents a C++17 deduced template specialization type.
4861class DeducedTemplateSpecializationType : public DeducedType,
4862 public llvm::FoldingSetNode {
4863 friend class ASTContext; // ASTContext creates these
4864
4865 /// The name of the template whose arguments will be deduced.
4866 TemplateName Template;
4867
4868 DeducedTemplateSpecializationType(TemplateName Template,
4869 QualType DeducedAsType,
4870 bool IsDeducedAsDependent)
4871 : DeducedType(DeducedTemplateSpecialization, DeducedAsType,
4872 IsDeducedAsDependent || Template.isDependent(),
4873 IsDeducedAsDependent || Template.isInstantiationDependent(),
4874 Template.containsUnexpandedParameterPack()),
4875 Template(Template) {}
4876
4877public:
4878 /// Retrieve the name of the template that we are deducing.
4879 TemplateName getTemplateName() const { return Template;}
4880
4881 void Profile(llvm::FoldingSetNodeID &ID) {
4882 Profile(ID, getTemplateName(), getDeducedType(), isDependentType());
4883 }
4884
4885 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName Template,
4886 QualType Deduced, bool IsDependent) {
4887 Template.Profile(ID);
4888 ID.AddPointer(Deduced.getAsOpaquePtr());
4889 ID.AddBoolean(IsDependent);
4890 }
4891
4892 static bool classof(const Type *T) {
4893 return T->getTypeClass() == DeducedTemplateSpecialization;
4894 }
4895};
4896
4897/// Represents a type template specialization; the template
4898/// must be a class template, a type alias template, or a template
4899/// template parameter. A template which cannot be resolved to one of
4900/// these, e.g. because it is written with a dependent scope
4901/// specifier, is instead represented as a
4902/// @c DependentTemplateSpecializationType.
4903///
4904/// A non-dependent template specialization type is always "sugar",
4905/// typically for a \c RecordType. For example, a class template
4906/// specialization type of \c vector<int> will refer to a tag type for
4907/// the instantiation \c std::vector<int, std::allocator<int>>
4908///
4909/// Template specializations are dependent if either the template or
4910/// any of the template arguments are dependent, in which case the
4911/// type may also be canonical.
4912///
4913/// Instances of this type are allocated with a trailing array of
4914/// TemplateArguments, followed by a QualType representing the
4915/// non-canonical aliased type when the template is a type alias
4916/// template.
4917class alignas(8) TemplateSpecializationType
4918 : public Type,
4919 public llvm::FoldingSetNode {
4920 friend class ASTContext; // ASTContext creates these
4921
4922 /// The name of the template being specialized. This is
4923 /// either a TemplateName::Template (in which case it is a
4924 /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a
4925 /// TypeAliasTemplateDecl*), a
4926 /// TemplateName::SubstTemplateTemplateParmPack, or a
4927 /// TemplateName::SubstTemplateTemplateParm (in which case the
4928 /// replacement must, recursively, be one of these).
4929 TemplateName Template;
4930
4931 TemplateSpecializationType(TemplateName T,
4932 ArrayRef<TemplateArgument> Args,
4933 QualType Canon,
4934 QualType Aliased);
4935
4936public:
4937 /// Determine whether any of the given template arguments are dependent.
4938 static bool anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
4939 bool &InstantiationDependent);
4940
4941 static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &,
4942 bool &InstantiationDependent);
4943
4944 /// True if this template specialization type matches a current
4945 /// instantiation in the context in which it is found.
4946 bool isCurrentInstantiation() const {
4947 return isa<InjectedClassNameType>(getCanonicalTypeInternal());
4948 }
4949
4950 /// Determine if this template specialization type is for a type alias
4951 /// template that has been substituted.
4952 ///
4953 /// Nearly every template specialization type whose template is an alias
4954 /// template will be substituted. However, this is not the case when
4955 /// the specialization contains a pack expansion but the template alias
4956 /// does not have a corresponding parameter pack, e.g.,
4957 ///
4958 /// \code
4959 /// template<typename T, typename U, typename V> struct S;
4960 /// template<typename T, typename U> using A = S<T, int, U>;
4961 /// template<typename... Ts> struct X {
4962 /// typedef A<Ts...> type; // not a type alias
4963 /// };
4964 /// \endcode
4965 bool isTypeAlias() const { return TemplateSpecializationTypeBits.TypeAlias; }
4966
4967 /// Get the aliased type, if this is a specialization of a type alias
4968 /// template.
4969 QualType getAliasedType() const {
4970 assert(isTypeAlias() && "not a type alias template specialization")((isTypeAlias() && "not a type alias template specialization"
) ? static_cast<void> (0) : __assert_fail ("isTypeAlias() && \"not a type alias template specialization\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 4970, __PRETTY_FUNCTION__))
;
4971 return *reinterpret_cast<const QualType*>(end());
4972 }
4973
4974 using iterator = const TemplateArgument *;
4975
4976 iterator begin() const { return getArgs(); }
4977 iterator end() const; // defined inline in TemplateBase.h
4978
4979 /// Retrieve the name of the template that we are specializing.
4980 TemplateName getTemplateName() const { return Template; }
4981
4982 /// Retrieve the template arguments.
4983 const TemplateArgument *getArgs() const {
4984 return reinterpret_cast<const TemplateArgument *>(this + 1);
4985 }
4986
4987 /// Retrieve the number of template arguments.
4988 unsigned getNumArgs() const {
4989 return TemplateSpecializationTypeBits.NumArgs;
4990 }
4991
4992 /// Retrieve a specific template argument as a type.
4993 /// \pre \c isArgType(Arg)
4994 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
4995
4996 ArrayRef<TemplateArgument> template_arguments() const {
4997 return {getArgs(), getNumArgs()};
4998 }
4999
5000 bool isSugared() const {
5001 return !isDependentType() || isCurrentInstantiation() || isTypeAlias();
5002 }
5003
5004 QualType desugar() const {
5005 return isTypeAlias() ? getAliasedType() : getCanonicalTypeInternal();
5006 }
5007
5008 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
5009 Profile(ID, Template, template_arguments(), Ctx);
5010 if (isTypeAlias())
5011 getAliasedType().Profile(ID);
5012 }
5013
5014 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
5015 ArrayRef<TemplateArgument> Args,
5016 const ASTContext &Context);
5017
5018 static bool classof(const Type *T) {
5019 return T->getTypeClass() == TemplateSpecialization;
5020 }
5021};
5022
5023/// Print a template argument list, including the '<' and '>'
5024/// enclosing the template arguments.
5025void printTemplateArgumentList(raw_ostream &OS,
5026 ArrayRef<TemplateArgument> Args,
5027 const PrintingPolicy &Policy);
5028
5029void printTemplateArgumentList(raw_ostream &OS,
5030 ArrayRef<TemplateArgumentLoc> Args,
5031 const PrintingPolicy &Policy);
5032
5033void printTemplateArgumentList(raw_ostream &OS,
5034 const TemplateArgumentListInfo &Args,
5035 const PrintingPolicy &Policy);
5036
5037/// The injected class name of a C++ class template or class
5038/// template partial specialization. Used to record that a type was
5039/// spelled with a bare identifier rather than as a template-id; the
5040/// equivalent for non-templated classes is just RecordType.
5041///
5042/// Injected class name types are always dependent. Template
5043/// instantiation turns these into RecordTypes.
5044///
5045/// Injected class name types are always canonical. This works
5046/// because it is impossible to compare an injected class name type
5047/// with the corresponding non-injected template type, for the same
5048/// reason that it is impossible to directly compare template
5049/// parameters from different dependent contexts: injected class name
5050/// types can only occur within the scope of a particular templated
5051/// declaration, and within that scope every template specialization
5052/// will canonicalize to the injected class name (when appropriate
5053/// according to the rules of the language).
5054class InjectedClassNameType : public Type {
5055 friend class ASTContext; // ASTContext creates these.
5056 friend class ASTNodeImporter;
5057 friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not
5058 // currently suitable for AST reading, too much
5059 // interdependencies.
5060
5061 CXXRecordDecl *Decl;
5062
5063 /// The template specialization which this type represents.
5064 /// For example, in
5065 /// template <class T> class A { ... };
5066 /// this is A<T>, whereas in
5067 /// template <class X, class Y> class A<B<X,Y> > { ... };
5068 /// this is A<B<X,Y> >.
5069 ///
5070 /// It is always unqualified, always a template specialization type,
5071 /// and always dependent.
5072 QualType InjectedType;
5073
5074 InjectedClassNameType(CXXRecordDecl *D, QualType TST)
5075 : Type(InjectedClassName, QualType(), /*Dependent=*/true,
5076 /*InstantiationDependent=*/true,
5077 /*VariablyModified=*/false,
5078 /*ContainsUnexpandedParameterPack=*/false),
5079 Decl(D), InjectedType(TST) {
5080 assert(isa<TemplateSpecializationType>(TST))((isa<TemplateSpecializationType>(TST)) ? static_cast<
void> (0) : __assert_fail ("isa<TemplateSpecializationType>(TST)"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 5080, __PRETTY_FUNCTION__))
;
5081 assert(!TST.hasQualifiers())((!TST.hasQualifiers()) ? static_cast<void> (0) : __assert_fail
("!TST.hasQualifiers()", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 5081, __PRETTY_FUNCTION__))
;
5082 assert(TST->isDependentType())((TST->isDependentType()) ? static_cast<void> (0) : __assert_fail
("TST->isDependentType()", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 5082, __PRETTY_FUNCTION__))
;
5083 }
5084
5085public:
5086 QualType getInjectedSpecializationType() const { return InjectedType; }
5087
5088 const TemplateSpecializationType *getInjectedTST() const {
5089 return cast<TemplateSpecializationType>(InjectedType.getTypePtr());
5090 }
5091
5092 TemplateName getTemplateName() const {
5093 return getInjectedTST()->getTemplateName();
5094 }
5095
5096 CXXRecordDecl *getDecl() const;
5097
5098 bool isSugared() const { return false; }
5099 QualType desugar() const { return QualType(this, 0); }
5100
5101 static bool classof(const Type *T) {
5102 return T->getTypeClass() == InjectedClassName;
5103 }
5104};
5105
5106/// The kind of a tag type.
5107enum TagTypeKind {
5108 /// The "struct" keyword.
5109 TTK_Struct,
5110
5111 /// The "__interface" keyword.
5112 TTK_Interface,
5113
5114 /// The "union" keyword.
5115 TTK_Union,
5116
5117 /// The "class" keyword.
5118 TTK_Class,
5119
5120 /// The "enum" keyword.
5121 TTK_Enum
5122};
5123
5124/// The elaboration keyword that precedes a qualified type name or
5125/// introduces an elaborated-type-specifier.
5126enum ElaboratedTypeKeyword {
5127 /// The "struct" keyword introduces the elaborated-type-specifier.
5128 ETK_Struct,
5129
5130 /// The "__interface" keyword introduces the elaborated-type-specifier.
5131 ETK_Interface,
5132
5133 /// The "union" keyword introduces the elaborated-type-specifier.
5134 ETK_Union,
5135
5136 /// The "class" keyword introduces the elaborated-type-specifier.
5137 ETK_Class,
5138
5139 /// The "enum" keyword introduces the elaborated-type-specifier.
5140 ETK_Enum,
5141
5142 /// The "typename" keyword precedes the qualified type name, e.g.,
5143 /// \c typename T::type.
5144 ETK_Typename,
5145
5146 /// No keyword precedes the qualified type name.
5147 ETK_None
5148};
5149
5150/// A helper class for Type nodes having an ElaboratedTypeKeyword.
5151/// The keyword in stored in the free bits of the base class.
5152/// Also provides a few static helpers for converting and printing
5153/// elaborated type keyword and tag type kind enumerations.
5154class TypeWithKeyword : public Type {
5155protected:
5156 TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc,
5157 QualType Canonical, bool Dependent,
5158 bool InstantiationDependent, bool VariablyModified,
5159 bool ContainsUnexpandedParameterPack)
5160 : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
5161 ContainsUnexpandedParameterPack) {
5162 TypeWithKeywordBits.Keyword = Keyword;
5163 }
5164
5165public:
5166 ElaboratedTypeKeyword getKeyword() const {
5167 return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword);
5168 }
5169
5170 /// Converts a type specifier (DeclSpec::TST) into an elaborated type keyword.
5171 static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec);
5172
5173 /// Converts a type specifier (DeclSpec::TST) into a tag type kind.
5174 /// It is an error to provide a type specifier which *isn't* a tag kind here.
5175 static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec);
5176
5177 /// Converts a TagTypeKind into an elaborated type keyword.
5178 static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag);
5179
5180 /// Converts an elaborated type keyword into a TagTypeKind.
5181 /// It is an error to provide an elaborated type keyword
5182 /// which *isn't* a tag kind here.
5183 static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword);
5184
5185 static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword);
5186
5187 static StringRef getKeywordName(ElaboratedTypeKeyword Keyword);
5188
5189 static StringRef getTagTypeKindName(TagTypeKind Kind) {
5190 return getKeywordName(getKeywordForTagTypeKind(Kind));
5191 }
5192
5193 class CannotCastToThisType {};
5194 static CannotCastToThisType classof(const Type *);
5195};
5196
5197/// Represents a type that was referred to using an elaborated type
5198/// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type,
5199/// or both.
5200///
5201/// This type is used to keep track of a type name as written in the
5202/// source code, including tag keywords and any nested-name-specifiers.
5203/// The type itself is always "sugar", used to express what was written
5204/// in the source code but containing no additional semantic information.
5205class ElaboratedType final
5206 : public TypeWithKeyword,
5207 public llvm::FoldingSetNode,
5208 private llvm::TrailingObjects<ElaboratedType, TagDecl *> {
5209 friend class ASTContext; // ASTContext creates these
5210 friend TrailingObjects;
5211
5212 /// The nested name specifier containing the qualifier.
5213 NestedNameSpecifier *NNS;
5214
5215 /// The type that this qualified name refers to.
5216 QualType NamedType;
5217
5218 /// The (re)declaration of this tag type owned by this occurrence is stored
5219 /// as a trailing object if there is one. Use getOwnedTagDecl to obtain
5220 /// it, or obtain a null pointer if there is none.
5221
5222 ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
5223 QualType NamedType, QualType CanonType, TagDecl *OwnedTagDecl)
5224 : TypeWithKeyword(Keyword, Elaborated, CanonType,
5225 NamedType->isDependentType(),
5226 NamedType->isInstantiationDependentType(),
5227 NamedType->isVariablyModifiedType(),
5228 NamedType->containsUnexpandedParameterPack()),
5229 NNS(NNS), NamedType(NamedType) {
5230 ElaboratedTypeBits.HasOwnedTagDecl = false;
5231 if (OwnedTagDecl) {
5232 ElaboratedTypeBits.HasOwnedTagDecl = true;
5233 *getTrailingObjects<TagDecl *>() = OwnedTagDecl;
5234 }
5235 assert(!(Keyword == ETK_None && NNS == nullptr) &&((!(Keyword == ETK_None && NNS == nullptr) &&
"ElaboratedType cannot have elaborated type keyword " "and name qualifier both null."
) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 5237, __PRETTY_FUNCTION__))
5236 "ElaboratedType cannot have elaborated type keyword "((!(Keyword == ETK_None && NNS == nullptr) &&
"ElaboratedType cannot have elaborated type keyword " "and name qualifier both null."
) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 5237, __PRETTY_FUNCTION__))
5237 "and name qualifier both null.")((!(Keyword == ETK_None && NNS == nullptr) &&
"ElaboratedType cannot have elaborated type keyword " "and name qualifier both null."
) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 5237, __PRETTY_FUNCTION__))
;
5238 }
5239
5240public:
5241 /// Retrieve the qualification on this type.
5242 NestedNameSpecifier *getQualifier() const { return NNS; }
5243
5244 /// Retrieve the type named by the qualified-id.
5245 QualType getNamedType() const { return NamedType; }
5246
5247 /// Remove a single level of sugar.
5248 QualType desugar() const { return getNamedType(); }
5249
5250 /// Returns whether this type directly provides sugar.
5251 bool isSugared() const { return true; }
5252
5253 /// Return the (re)declaration of this type owned by this occurrence of this
5254 /// type, or nullptr if there is none.
5255 TagDecl *getOwnedTagDecl() const {
5256 return ElaboratedTypeBits.HasOwnedTagDecl ? *getTrailingObjects<TagDecl *>()
5257 : nullptr;
5258 }
5259
5260 void Profile(llvm::FoldingSetNodeID &ID) {
5261 Profile(ID, getKeyword(), NNS, NamedType, getOwnedTagDecl());
5262 }
5263
5264 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
5265 NestedNameSpecifier *NNS, QualType NamedType,
5266 TagDecl *OwnedTagDecl) {
5267 ID.AddInteger(Keyword);
5268 ID.AddPointer(NNS);
5269 NamedType.Profile(ID);
5270 ID.AddPointer(OwnedTagDecl);
5271 }
5272
5273 static bool classof(const Type *T) { return T->getTypeClass() == Elaborated; }
5274};
5275
5276/// Represents a qualified type name for which the type name is
5277/// dependent.
5278///
5279/// DependentNameType represents a class of dependent types that involve a
5280/// possibly dependent nested-name-specifier (e.g., "T::") followed by a
5281/// name of a type. The DependentNameType may start with a "typename" (for a
5282/// typename-specifier), "class", "struct", "union", or "enum" (for a
5283/// dependent elaborated-type-specifier), or nothing (in contexts where we
5284/// know that we must be referring to a type, e.g., in a base class specifier).
5285/// Typically the nested-name-specifier is dependent, but in MSVC compatibility
5286/// mode, this type is used with non-dependent names to delay name lookup until
5287/// instantiation.
5288class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode {
5289 friend class ASTContext; // ASTContext creates these
5290
5291 /// The nested name specifier containing the qualifier.
5292 NestedNameSpecifier *NNS;
5293
5294 /// The type that this typename specifier refers to.
5295 const IdentifierInfo *Name;
5296
5297 DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
5298 const IdentifierInfo *Name, QualType CanonType)
5299 : TypeWithKeyword(Keyword, DependentName, CanonType, /*Dependent=*/true,
5300 /*InstantiationDependent=*/true,
5301 /*VariablyModified=*/false,
5302 NNS->containsUnexpandedParameterPack()),
5303 NNS(NNS), Name(Name) {}
5304
5305public:
5306 /// Retrieve the qualification on this type.
5307 NestedNameSpecifier *getQualifier() const { return NNS; }
5308
5309 /// Retrieve the type named by the typename specifier as an identifier.
5310 ///
5311 /// This routine will return a non-NULL identifier pointer when the
5312 /// form of the original typename was terminated by an identifier,
5313 /// e.g., "typename T::type".
5314 const IdentifierInfo *getIdentifier() const {
5315 return Name;
5316 }
5317
5318 bool isSugared() const { return false; }
5319 QualType desugar() const { return QualType(this, 0); }
5320
5321 void Profile(llvm::FoldingSetNodeID &ID) {
5322 Profile(ID, getKeyword(), NNS, Name);
5323 }
5324
5325 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
5326 NestedNameSpecifier *NNS, const IdentifierInfo *Name) {
5327 ID.AddInteger(Keyword);
5328 ID.AddPointer(NNS);
5329 ID.AddPointer(Name);
5330 }
5331
5332 static bool classof(const Type *T) {
5333 return T->getTypeClass() == DependentName;
5334 }
5335};
5336
5337/// Represents a template specialization type whose template cannot be
5338/// resolved, e.g.
5339/// A<T>::template B<T>
5340class alignas(8) DependentTemplateSpecializationType
5341 : public TypeWithKeyword,
5342 public llvm::FoldingSetNode {
5343 friend class ASTContext; // ASTContext creates these
5344
5345 /// The nested name specifier containing the qualifier.
5346 NestedNameSpecifier *NNS;
5347
5348 /// The identifier of the template.
5349 const IdentifierInfo *Name;
5350
5351 DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
5352 NestedNameSpecifier *NNS,
5353 const IdentifierInfo *Name,
5354 ArrayRef<TemplateArgument> Args,
5355 QualType Canon);
5356
5357 const TemplateArgument *getArgBuffer() const {
5358 return reinterpret_cast<const TemplateArgument*>(this+1);
5359 }
5360
5361 TemplateArgument *getArgBuffer() {
5362 return reinterpret_cast<TemplateArgument*>(this+1);
5363 }
5364
5365public:
5366 NestedNameSpecifier *getQualifier() const { return NNS; }
5367 const IdentifierInfo *getIdentifier() const { return Name; }
5368
5369 /// Retrieve the template arguments.
5370 const TemplateArgument *getArgs() const {
5371 return getArgBuffer();
5372 }
5373
5374 /// Retrieve the number of template arguments.
5375 unsigned getNumArgs() const {
5376 return DependentTemplateSpecializationTypeBits.NumArgs;
5377 }
5378
5379 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
5380
5381 ArrayRef<TemplateArgument> template_arguments() const {
5382 return {getArgs(), getNumArgs()};
5383 }
5384
5385 using iterator = const TemplateArgument *;
5386
5387 iterator begin() const { return getArgs(); }
5388 iterator end() const; // inline in TemplateBase.h
5389
5390 bool isSugared() const { return false; }
5391 QualType desugar() const { return QualType(this, 0); }
5392
5393 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
5394 Profile(ID, Context, getKeyword(), NNS, Name, {getArgs(), getNumArgs()});
5395 }
5396
5397 static void Profile(llvm::FoldingSetNodeID &ID,
5398 const ASTContext &Context,
5399 ElaboratedTypeKeyword Keyword,
5400 NestedNameSpecifier *Qualifier,
5401 const IdentifierInfo *Name,
5402 ArrayRef<TemplateArgument> Args);
5403
5404 static bool classof(const Type *T) {
5405 return T->getTypeClass() == DependentTemplateSpecialization;
5406 }
5407};
5408
5409/// Represents a pack expansion of types.
5410///
5411/// Pack expansions are part of C++11 variadic templates. A pack
5412/// expansion contains a pattern, which itself contains one or more
5413/// "unexpanded" parameter packs. When instantiated, a pack expansion
5414/// produces a series of types, each instantiated from the pattern of
5415/// the expansion, where the Ith instantiation of the pattern uses the
5416/// Ith arguments bound to each of the unexpanded parameter packs. The
5417/// pack expansion is considered to "expand" these unexpanded
5418/// parameter packs.
5419///
5420/// \code
5421/// template<typename ...Types> struct tuple;
5422///
5423/// template<typename ...Types>
5424/// struct tuple_of_references {
5425/// typedef tuple<Types&...> type;
5426/// };
5427/// \endcode
5428///
5429/// Here, the pack expansion \c Types&... is represented via a
5430/// PackExpansionType whose pattern is Types&.
5431class PackExpansionType : public Type, public llvm::FoldingSetNode {
5432 friend class ASTContext; // ASTContext creates these
5433
5434 /// The pattern of the pack expansion.
5435 QualType Pattern;
5436
5437 PackExpansionType(QualType Pattern, QualType Canon,
5438 Optional<unsigned> NumExpansions)
5439 : Type(PackExpansion, Canon, /*Dependent=*/Pattern->isDependentType(),
5440 /*InstantiationDependent=*/true,
5441 /*VariablyModified=*/Pattern->isVariablyModifiedType(),
5442 /*ContainsUnexpandedParameterPack=*/false),
5443 Pattern(Pattern) {
5444 PackExpansionTypeBits.NumExpansions =
5445 NumExpansions ? *NumExpansions + 1 : 0;
5446 }
5447
5448public:
5449 /// Retrieve the pattern of this pack expansion, which is the
5450 /// type that will be repeatedly instantiated when instantiating the
5451 /// pack expansion itself.
5452 QualType getPattern() const { return Pattern; }
5453
5454 /// Retrieve the number of expansions that this pack expansion will
5455 /// generate, if known.
5456 Optional<unsigned> getNumExpansions() const {
5457 if (PackExpansionTypeBits.NumExpansions)
5458 return PackExpansionTypeBits.NumExpansions - 1;
5459 return None;
5460 }
5461
5462 bool isSugared() const { return !Pattern->isDependentType(); }
5463 QualType desugar() const { return isSugared() ? Pattern : QualType(this, 0); }
5464
5465 void Profile(llvm::FoldingSetNodeID &ID) {
5466 Profile(ID, getPattern(), getNumExpansions());
5467 }
5468
5469 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern,
5470 Optional<unsigned> NumExpansions) {
5471 ID.AddPointer(Pattern.getAsOpaquePtr());
5472 ID.AddBoolean(NumExpansions.hasValue());
5473 if (NumExpansions)
5474 ID.AddInteger(*NumExpansions);
5475 }
5476
5477 static bool classof(const Type *T) {
5478 return T->getTypeClass() == PackExpansion;
5479 }
5480};
5481
5482/// This class wraps the list of protocol qualifiers. For types that can
5483/// take ObjC protocol qualifers, they can subclass this class.
5484template <class T>
5485class ObjCProtocolQualifiers {
5486protected:
5487 ObjCProtocolQualifiers() = default;
5488
5489 ObjCProtocolDecl * const *getProtocolStorage() const {
5490 return const_cast<ObjCProtocolQualifiers*>(this)->getProtocolStorage();
5491 }
5492
5493 ObjCProtocolDecl **getProtocolStorage() {
5494 return static_cast<T*>(this)->getProtocolStorageImpl();
5495 }
5496
5497 void setNumProtocols(unsigned N) {
5498 static_cast<T*>(this)->setNumProtocolsImpl(N);
5499 }
5500
5501 void initialize(ArrayRef<ObjCProtocolDecl *> protocols) {
5502 setNumProtocols(protocols.size());
5503 assert(getNumProtocols() == protocols.size() &&((getNumProtocols() == protocols.size() && "bitfield overflow in protocol count"
) ? static_cast<void> (0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 5504, __PRETTY_FUNCTION__))
5504 "bitfield overflow in protocol count")((getNumProtocols() == protocols.size() && "bitfield overflow in protocol count"
) ? static_cast<void> (0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 5504, __PRETTY_FUNCTION__))
;
5505 if (!protocols.empty())
5506 memcpy(getProtocolStorage(), protocols.data(),
5507 protocols.size() * sizeof(ObjCProtocolDecl*));
5508 }
5509
5510public:
5511 using qual_iterator = ObjCProtocolDecl * const *;
5512 using qual_range = llvm::iterator_range<qual_iterator>;
5513
5514 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
5515 qual_iterator qual_begin() const { return getProtocolStorage(); }
5516 qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); }
5517
5518 bool qual_empty() const { return getNumProtocols() == 0; }
5519
5520 /// Return the number of qualifying protocols in this type, or 0 if
5521 /// there are none.
5522 unsigned getNumProtocols() const {
5523 return static_cast<const T*>(this)->getNumProtocolsImpl();
5524 }
5525
5526 /// Fetch a protocol by index.
5527 ObjCProtocolDecl *getProtocol(unsigned I) const {
5528 assert(I < getNumProtocols() && "Out-of-range protocol access")((I < getNumProtocols() && "Out-of-range protocol access"
) ? static_cast<void> (0) : __assert_fail ("I < getNumProtocols() && \"Out-of-range protocol access\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 5528, __PRETTY_FUNCTION__))
;
5529 return qual_begin()[I];
5530 }
5531
5532 /// Retrieve all of the protocol qualifiers.
5533 ArrayRef<ObjCProtocolDecl *> getProtocols() const {
5534 return ArrayRef<ObjCProtocolDecl *>(qual_begin(), getNumProtocols());
5535 }
5536};
5537
5538/// Represents a type parameter type in Objective C. It can take
5539/// a list of protocols.
5540class ObjCTypeParamType : public Type,
5541 public ObjCProtocolQualifiers<ObjCTypeParamType>,
5542 public llvm::FoldingSetNode {
5543 friend class ASTContext;
5544 friend class ObjCProtocolQualifiers<ObjCTypeParamType>;
5545
5546 /// The number of protocols stored on this type.
5547 unsigned NumProtocols : 6;
5548
5549 ObjCTypeParamDecl *OTPDecl;
5550
5551 /// The protocols are stored after the ObjCTypeParamType node. In the
5552 /// canonical type, the list of protocols are sorted alphabetically
5553 /// and uniqued.
5554 ObjCProtocolDecl **getProtocolStorageImpl();
5555
5556 /// Return the number of qualifying protocols in this interface type,
5557 /// or 0 if there are none.
5558 unsigned getNumProtocolsImpl() const {
5559 return NumProtocols;
5560 }
5561
5562 void setNumProtocolsImpl(unsigned N) {
5563 NumProtocols = N;
5564 }
5565
5566 ObjCTypeParamType(const ObjCTypeParamDecl *D,
5567 QualType can,
5568 ArrayRef<ObjCProtocolDecl *> protocols);
5569
5570public:
5571 bool isSugared() const { return true; }
5572 QualType desugar() const;
5573
5574 static bool classof(const Type *T) {
5575 return T->getTypeClass() == ObjCTypeParam;
5576 }
5577
5578 void Profile(llvm::FoldingSetNodeID &ID);
5579 static void Profile(llvm::FoldingSetNodeID &ID,
5580 const ObjCTypeParamDecl *OTPDecl,
5581 ArrayRef<ObjCProtocolDecl *> protocols);
5582
5583 ObjCTypeParamDecl *getDecl() const { return OTPDecl; }
5584};
5585
5586/// Represents a class type in Objective C.
5587///
5588/// Every Objective C type is a combination of a base type, a set of
5589/// type arguments (optional, for parameterized classes) and a list of
5590/// protocols.
5591///
5592/// Given the following declarations:
5593/// \code
5594/// \@class C<T>;
5595/// \@protocol P;
5596/// \endcode
5597///
5598/// 'C' is an ObjCInterfaceType C. It is sugar for an ObjCObjectType
5599/// with base C and no protocols.
5600///
5601/// 'C<P>' is an unspecialized ObjCObjectType with base C and protocol list [P].
5602/// 'C<C*>' is a specialized ObjCObjectType with type arguments 'C*' and no
5603/// protocol list.
5604/// 'C<C*><P>' is a specialized ObjCObjectType with base C, type arguments 'C*',
5605/// and protocol list [P].
5606///
5607/// 'id' is a TypedefType which is sugar for an ObjCObjectPointerType whose
5608/// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType
5609/// and no protocols.
5610///
5611/// 'id<P>' is an ObjCObjectPointerType whose pointee is an ObjCObjectType
5612/// with base BuiltinType::ObjCIdType and protocol list [P]. Eventually
5613/// this should get its own sugar class to better represent the source.
5614class ObjCObjectType : public Type,
5615 public ObjCProtocolQualifiers<ObjCObjectType> {
5616 friend class ObjCProtocolQualifiers<ObjCObjectType>;
5617
5618 // ObjCObjectType.NumTypeArgs - the number of type arguments stored
5619 // after the ObjCObjectPointerType node.
5620 // ObjCObjectType.NumProtocols - the number of protocols stored
5621 // after the type arguments of ObjCObjectPointerType node.
5622 //
5623 // These protocols are those written directly on the type. If
5624 // protocol qualifiers ever become additive, the iterators will need
5625 // to get kindof complicated.
5626 //
5627 // In the canonical object type, these are sorted alphabetically
5628 // and uniqued.
5629
5630 /// Either a BuiltinType or an InterfaceType or sugar for either.
5631 QualType BaseType;
5632
5633 /// Cached superclass type.
5634 mutable llvm::PointerIntPair<const ObjCObjectType *, 1, bool>
5635 CachedSuperClassType;
5636
5637 QualType *getTypeArgStorage();
5638 const QualType *getTypeArgStorage() const {
5639 return const_cast<ObjCObjectType *>(this)->getTypeArgStorage();
5640 }
5641
5642 ObjCProtocolDecl **getProtocolStorageImpl();
5643 /// Return the number of qualifying protocols in this interface type,
5644 /// or 0 if there are none.
5645 unsigned getNumProtocolsImpl() const {
5646 return ObjCObjectTypeBits.NumProtocols;
5647 }
5648 void setNumProtocolsImpl(unsigned N) {
5649 ObjCObjectTypeBits.NumProtocols = N;
5650 }
5651
5652protected:
5653 enum Nonce_ObjCInterface { Nonce_ObjCInterface };
5654
5655 ObjCObjectType(QualType Canonical, QualType Base,
5656 ArrayRef<QualType> typeArgs,
5657 ArrayRef<ObjCProtocolDecl *> protocols,
5658 bool isKindOf);
5659
5660 ObjCObjectType(enum Nonce_ObjCInterface)
5661 : Type(ObjCInterface, QualType(), false, false, false, false),
5662 BaseType(QualType(this_(), 0)) {
5663 ObjCObjectTypeBits.NumProtocols = 0;
5664 ObjCObjectTypeBits.NumTypeArgs = 0;
5665 ObjCObjectTypeBits.IsKindOf = 0;
5666 }
5667
5668 void computeSuperClassTypeSlow() const;
5669
5670public:
5671 /// Gets the base type of this object type. This is always (possibly
5672 /// sugar for) one of:
5673 /// - the 'id' builtin type (as opposed to the 'id' type visible to the
5674 /// user, which is a typedef for an ObjCObjectPointerType)
5675 /// - the 'Class' builtin type (same caveat)
5676 /// - an ObjCObjectType (currently always an ObjCInterfaceType)
5677 QualType getBaseType() const { return BaseType; }
5678
5679 bool isObjCId() const {
5680 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId);
5681 }
5682
5683 bool isObjCClass() const {
5684 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass);
5685 }
5686
5687 bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); }
5688 bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); }
5689 bool isObjCUnqualifiedIdOrClass() const {
5690 if (!qual_empty()) return false;
5691 if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>())
5692 return T->getKind() == BuiltinType::ObjCId ||
5693 T->getKind() == BuiltinType::ObjCClass;
5694 return false;
5695 }
5696 bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); }
5697 bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); }
5698
5699 /// Gets the interface declaration for this object type, if the base type
5700 /// really is an interface.
5701 ObjCInterfaceDecl *getInterface() const;
5702
5703 /// Determine whether this object type is "specialized", meaning
5704 /// that it has type arguments.
5705 bool isSpecialized() const;
5706
5707 /// Determine whether this object type was written with type arguments.
5708 bool isSpecializedAsWritten() const {
5709 return ObjCObjectTypeBits.NumTypeArgs > 0;
5710 }
5711
5712 /// Determine whether this object type is "unspecialized", meaning
5713 /// that it has no type arguments.
5714 bool isUnspecialized() const { return !isSpecialized(); }
5715
5716 /// Determine whether this object type is "unspecialized" as
5717 /// written, meaning that it has no type arguments.
5718 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
5719
5720 /// Retrieve the type arguments of this object type (semantically).
5721 ArrayRef<QualType> getTypeArgs() const;
5722
5723 /// Retrieve the type arguments of this object type as they were
5724 /// written.
5725 ArrayRef<QualType> getTypeArgsAsWritten() const {
5726 return llvm::makeArrayRef(getTypeArgStorage(),
5727 ObjCObjectTypeBits.NumTypeArgs);
5728 }
5729
5730 /// Whether this is a "__kindof" type as written.
5731 bool isKindOfTypeAsWritten() const { return ObjCObjectTypeBits.IsKindOf; }
5732
5733 /// Whether this ia a "__kindof" type (semantically).
5734 bool isKindOfType() const;
5735
5736 /// Retrieve the type of the superclass of this object type.
5737 ///
5738 /// This operation substitutes any type arguments into the
5739 /// superclass of the current class type, potentially producing a
5740 /// specialization of the superclass type. Produces a null type if
5741 /// there is no superclass.
5742 QualType getSuperClassType() const {
5743 if (!CachedSuperClassType.getInt())
5744 computeSuperClassTypeSlow();
5745
5746 assert(CachedSuperClassType.getInt() && "Superclass not set?")((CachedSuperClassType.getInt() && "Superclass not set?"
) ? static_cast<void> (0) : __assert_fail ("CachedSuperClassType.getInt() && \"Superclass not set?\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 5746, __PRETTY_FUNCTION__))
;
5747 return QualType(CachedSuperClassType.getPointer(), 0);
5748 }
5749
5750 /// Strip off the Objective-C "kindof" type and (with it) any
5751 /// protocol qualifiers.
5752 QualType stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const;
5753
5754 bool isSugared() const { return false; }
5755 QualType desugar() const { return QualType(this, 0); }
5756
5757 static bool classof(const Type *T) {
5758 return T->getTypeClass() == ObjCObject ||
5759 T->getTypeClass() == ObjCInterface;
5760 }
5761};
5762
5763/// A class providing a concrete implementation
5764/// of ObjCObjectType, so as to not increase the footprint of
5765/// ObjCInterfaceType. Code outside of ASTContext and the core type
5766/// system should not reference this type.
5767class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode {
5768 friend class ASTContext;
5769
5770 // If anyone adds fields here, ObjCObjectType::getProtocolStorage()
5771 // will need to be modified.
5772
5773 ObjCObjectTypeImpl(QualType Canonical, QualType Base,
5774 ArrayRef<QualType> typeArgs,
5775 ArrayRef<ObjCProtocolDecl *> protocols,
5776 bool isKindOf)
5777 : ObjCObjectType(Canonical, Base, typeArgs, protocols, isKindOf) {}
5778
5779public:
5780 void Profile(llvm::FoldingSetNodeID &ID);
5781 static void Profile(llvm::FoldingSetNodeID &ID,
5782 QualType Base,
5783 ArrayRef<QualType> typeArgs,
5784 ArrayRef<ObjCProtocolDecl *> protocols,
5785 bool isKindOf);
5786};
5787
5788inline QualType *ObjCObjectType::getTypeArgStorage() {
5789 return reinterpret_cast<QualType *>(static_cast<ObjCObjectTypeImpl*>(this)+1);
5790}
5791
5792inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorageImpl() {
5793 return reinterpret_cast<ObjCProtocolDecl**>(
5794 getTypeArgStorage() + ObjCObjectTypeBits.NumTypeArgs);
5795}
5796
5797inline ObjCProtocolDecl **ObjCTypeParamType::getProtocolStorageImpl() {
5798 return reinterpret_cast<ObjCProtocolDecl**>(
5799 static_cast<ObjCTypeParamType*>(this)+1);
5800}
5801
5802/// Interfaces are the core concept in Objective-C for object oriented design.
5803/// They basically correspond to C++ classes. There are two kinds of interface
5804/// types: normal interfaces like `NSString`, and qualified interfaces, which
5805/// are qualified with a protocol list like `NSString<NSCopyable, NSAmazing>`.
5806///
5807/// ObjCInterfaceType guarantees the following properties when considered
5808/// as a subtype of its superclass, ObjCObjectType:
5809/// - There are no protocol qualifiers. To reinforce this, code which
5810/// tries to invoke the protocol methods via an ObjCInterfaceType will
5811/// fail to compile.
5812/// - It is its own base type. That is, if T is an ObjCInterfaceType*,
5813/// T->getBaseType() == QualType(T, 0).
5814class ObjCInterfaceType : public ObjCObjectType {
5815 friend class ASTContext; // ASTContext creates these.
5816 friend class ASTReader;
5817 friend class ObjCInterfaceDecl;
5818
5819 mutable ObjCInterfaceDecl *Decl;
5820
5821 ObjCInterfaceType(const ObjCInterfaceDecl *D)
5822 : ObjCObjectType(Nonce_ObjCInterface),
5823 Decl(const_cast<ObjCInterfaceDecl*>(D)) {}
5824
5825public:
5826 /// Get the declaration of this interface.
5827 ObjCInterfaceDecl *getDecl() const { return Decl; }
5828
5829 bool isSugared() const { return false; }
5830 QualType desugar() const { return QualType(this, 0); }
5831
5832 static bool classof(const Type *T) {
5833 return T->getTypeClass() == ObjCInterface;
5834 }
5835
5836 // Nonsense to "hide" certain members of ObjCObjectType within this
5837 // class. People asking for protocols on an ObjCInterfaceType are
5838 // not going to get what they want: ObjCInterfaceTypes are
5839 // guaranteed to have no protocols.
5840 enum {
5841 qual_iterator,
5842 qual_begin,
5843 qual_end,
5844 getNumProtocols,
5845 getProtocol
5846 };
5847};
5848
5849inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const {
5850 QualType baseType = getBaseType();
5851 while (const auto *ObjT = baseType->getAs<ObjCObjectType>()) {
5852 if (const auto *T = dyn_cast<ObjCInterfaceType>(ObjT))
5853 return T->getDecl();
5854
5855 baseType = ObjT->getBaseType();
5856 }
5857
5858 return nullptr;
5859}
5860
5861/// Represents a pointer to an Objective C object.
5862///
5863/// These are constructed from pointer declarators when the pointee type is
5864/// an ObjCObjectType (or sugar for one). In addition, the 'id' and 'Class'
5865/// types are typedefs for these, and the protocol-qualified types 'id<P>'
5866/// and 'Class<P>' are translated into these.
5867///
5868/// Pointers to pointers to Objective C objects are still PointerTypes;
5869/// only the first level of pointer gets it own type implementation.
5870class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
5871 friend class ASTContext; // ASTContext creates these.
5872
5873 QualType PointeeType;
5874
5875 ObjCObjectPointerType(QualType Canonical, QualType Pointee)
5876 : Type(ObjCObjectPointer, Canonical,
5877 Pointee->isDependentType(),
5878 Pointee->isInstantiationDependentType(),
5879 Pointee->isVariablyModifiedType(),
5880 Pointee->containsUnexpandedParameterPack()),
5881 PointeeType(Pointee) {}
5882
5883public:
5884 /// Gets the type pointed to by this ObjC pointer.
5885 /// The result will always be an ObjCObjectType or sugar thereof.
5886 QualType getPointeeType() const { return PointeeType; }
5887
5888 /// Gets the type pointed to by this ObjC pointer. Always returns non-null.
5889 ///
5890 /// This method is equivalent to getPointeeType() except that
5891 /// it discards any typedefs (or other sugar) between this
5892 /// type and the "outermost" object type. So for:
5893 /// \code
5894 /// \@class A; \@protocol P; \@protocol Q;
5895 /// typedef A<P> AP;
5896 /// typedef A A1;
5897 /// typedef A1<P> A1P;
5898 /// typedef A1P<Q> A1PQ;
5899 /// \endcode
5900 /// For 'A*', getObjectType() will return 'A'.
5901 /// For 'A<P>*', getObjectType() will return 'A<P>'.
5902 /// For 'AP*', getObjectType() will return 'A<P>'.
5903 /// For 'A1*', getObjectType() will return 'A'.
5904 /// For 'A1<P>*', getObjectType() will return 'A1<P>'.
5905 /// For 'A1P*', getObjectType() will return 'A1<P>'.
5906 /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because
5907 /// adding protocols to a protocol-qualified base discards the
5908 /// old qualifiers (for now). But if it didn't, getObjectType()
5909 /// would return 'A1P<Q>' (and we'd have to make iterating over
5910 /// qualifiers more complicated).
5911 const ObjCObjectType *getObjectType() const {
5912 return PointeeType->castAs<ObjCObjectType>();
5913 }
5914
5915 /// If this pointer points to an Objective C
5916 /// \@interface type, gets the type for that interface. Any protocol
5917 /// qualifiers on the interface are ignored.
5918 ///
5919 /// \return null if the base type for this pointer is 'id' or 'Class'
5920 const ObjCInterfaceType *getInterfaceType() const;
5921
5922 /// If this pointer points to an Objective \@interface
5923 /// type, gets the declaration for that interface.
5924 ///
5925 /// \return null if the base type for this pointer is 'id' or 'Class'
5926 ObjCInterfaceDecl *getInterfaceDecl() const {
5927 return getObjectType()->getInterface();
5928 }
5929
5930 /// True if this is equivalent to the 'id' type, i.e. if
5931 /// its object type is the primitive 'id' type with no protocols.
5932 bool isObjCIdType() const {
5933 return getObjectType()->isObjCUnqualifiedId();
5934 }
5935
5936 /// True if this is equivalent to the 'Class' type,
5937 /// i.e. if its object tive is the primitive 'Class' type with no protocols.
5938 bool isObjCClassType() const {
5939 return getObjectType()->isObjCUnqualifiedClass();
5940 }
5941
5942 /// True if this is equivalent to the 'id' or 'Class' type,
5943 bool isObjCIdOrClassType() const {
5944 return getObjectType()->isObjCUnqualifiedIdOrClass();
5945 }
5946
5947 /// True if this is equivalent to 'id<P>' for some non-empty set of
5948 /// protocols.
5949 bool isObjCQualifiedIdType() const {
5950 return getObjectType()->isObjCQualifiedId();
5951 }
5952
5953 /// True if this is equivalent to 'Class<P>' for some non-empty set of
5954 /// protocols.
5955 bool isObjCQualifiedClassType() const {
5956 return getObjectType()->isObjCQualifiedClass();
5957 }
5958
5959 /// Whether this is a "__kindof" type.
5960 bool isKindOfType() const { return getObjectType()->isKindOfType(); }
5961
5962 /// Whether this type is specialized, meaning that it has type arguments.
5963 bool isSpecialized() const { return getObjectType()->isSpecialized(); }
5964
5965 /// Whether this type is specialized, meaning that it has type arguments.
5966 bool isSpecializedAsWritten() const {
5967 return getObjectType()->isSpecializedAsWritten();
5968 }
5969
5970 /// Whether this type is unspecialized, meaning that is has no type arguments.
5971 bool isUnspecialized() const { return getObjectType()->isUnspecialized(); }
5972
5973 /// Determine whether this object type is "unspecialized" as
5974 /// written, meaning that it has no type arguments.
5975 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
5976
5977 /// Retrieve the type arguments for this type.
5978 ArrayRef<QualType> getTypeArgs() const {
5979 return getObjectType()->getTypeArgs();
5980 }
5981
5982 /// Retrieve the type arguments for this type.
5983 ArrayRef<QualType> getTypeArgsAsWritten() const {
5984 return getObjectType()->getTypeArgsAsWritten();
5985 }
5986
5987 /// An iterator over the qualifiers on the object type. Provided
5988 /// for convenience. This will always iterate over the full set of
5989 /// protocols on a type, not just those provided directly.
5990 using qual_iterator = ObjCObjectType::qual_iterator;
5991 using qual_range = llvm::iterator_range<qual_iterator>;
5992
5993 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
5994
5995 qual_iterator qual_begin() const {
5996 return getObjectType()->qual_begin();
5997 }
5998
5999 qual_iterator qual_end() const {
6000 return getObjectType()->qual_end();
6001 }
6002
6003 bool qual_empty() const { return getObjectType()->qual_empty(); }
6004
6005 /// Return the number of qualifying protocols on the object type.
6006 unsigned getNumProtocols() const {
6007 return getObjectType()->getNumProtocols();
6008 }
6009
6010 /// Retrieve a qualifying protocol by index on the object type.
6011 ObjCProtocolDecl *getProtocol(unsigned I) const {
6012 return getObjectType()->getProtocol(I);
6013 }
6014
6015 bool isSugared() const { return false; }
6016 QualType desugar() const { return QualType(this, 0); }
6017
6018 /// Retrieve the type of the superclass of this object pointer type.
6019 ///
6020 /// This operation substitutes any type arguments into the
6021 /// superclass of the current class type, potentially producing a
6022 /// pointer to a specialization of the superclass type. Produces a
6023 /// null type if there is no superclass.
6024 QualType getSuperClassType() const;
6025
6026 /// Strip off the Objective-C "kindof" type and (with it) any
6027 /// protocol qualifiers.
6028 const ObjCObjectPointerType *stripObjCKindOfTypeAndQuals(
6029 const ASTContext &ctx) const;
6030
6031 void Profile(llvm::FoldingSetNodeID &ID) {
6032 Profile(ID, getPointeeType());
6033 }
6034
6035 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
6036 ID.AddPointer(T.getAsOpaquePtr());
6037 }
6038
6039 static bool classof(const Type *T) {
6040 return T->getTypeClass() == ObjCObjectPointer;
6041 }
6042};
6043
6044class AtomicType : public Type, public llvm::FoldingSetNode {
6045 friend class ASTContext; // ASTContext creates these.
6046
6047 QualType ValueType;
6048
6049 AtomicType(QualType ValTy, QualType Canonical)
6050 : Type(Atomic, Canonical, ValTy->isDependentType(),
6051 ValTy->isInstantiationDependentType(),
6052 ValTy->isVariablyModifiedType(),
6053 ValTy->containsUnexpandedParameterPack()),
6054 ValueType(ValTy) {}
6055
6056public:
6057 /// Gets the type contained by this atomic type, i.e.
6058 /// the type returned by performing an atomic load of this atomic type.
6059 QualType getValueType() const { return ValueType; }
6060
6061 bool isSugared() const { return false; }
6062 QualType desugar() const { return QualType(this, 0); }
6063
6064 void Profile(llvm::FoldingSetNodeID &ID) {
6065 Profile(ID, getValueType());
6066 }
6067
6068 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
6069 ID.AddPointer(T.getAsOpaquePtr());
6070 }
6071
6072 static bool classof(const Type *T) {
6073 return T->getTypeClass() == Atomic;
6074 }
6075};
6076
6077/// PipeType - OpenCL20.
6078class PipeType : public Type, public llvm::FoldingSetNode {
6079 friend class ASTContext; // ASTContext creates these.
6080
6081 QualType ElementType;
6082 bool isRead;
6083
6084 PipeType(QualType elemType, QualType CanonicalPtr, bool isRead)
6085 : Type(Pipe, CanonicalPtr, elemType->isDependentType(),
6086 elemType->isInstantiationDependentType(),
6087 elemType->isVariablyModifiedType(),
6088 elemType->containsUnexpandedParameterPack()),
6089 ElementType(elemType), isRead(isRead) {}
6090
6091public:
6092 QualType getElementType() const { return ElementType; }
6093
6094 bool isSugared() const { return false; }
6095
6096 QualType desugar() const { return QualType(this, 0); }
6097
6098 void Profile(llvm::FoldingSetNodeID &ID) {
6099 Profile(ID, getElementType(), isReadOnly());
6100 }
6101
6102 static void Profile(llvm::FoldingSetNodeID &ID, QualType T, bool isRead) {
6103 ID.AddPointer(T.getAsOpaquePtr());
6104 ID.AddBoolean(isRead);
6105 }
6106
6107 static bool classof(const Type *T) {
6108 return T->getTypeClass() == Pipe;
6109 }
6110
6111 bool isReadOnly() const { return isRead; }
6112};
6113
6114/// A qualifier set is used to build a set of qualifiers.
6115class QualifierCollector : public Qualifiers {
6116public:
6117 QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {}
6118
6119 /// Collect any qualifiers on the given type and return an
6120 /// unqualified type. The qualifiers are assumed to be consistent
6121 /// with those already in the type.
6122 const Type *strip(QualType type) {
6123 addFastQualifiers(type.getLocalFastQualifiers());
6124 if (!type.hasLocalNonFastQualifiers())
6125 return type.getTypePtrUnsafe();
6126
6127 const ExtQuals *extQuals = type.getExtQualsUnsafe();
6128 addConsistentQualifiers(extQuals->getQualifiers());
6129 return extQuals->getBaseType();
6130 }
6131
6132 /// Apply the collected qualifiers to the given type.
6133 QualType apply(const ASTContext &Context, QualType QT) const;
6134
6135 /// Apply the collected qualifiers to the given type.
6136 QualType apply(const ASTContext &Context, const Type* T) const;
6137};
6138
6139// Inline function definitions.
6140
6141inline SplitQualType SplitQualType::getSingleStepDesugaredType() const {
6142 SplitQualType desugar =
6143 Ty->getLocallyUnqualifiedSingleStepDesugaredType().split();
6144 desugar.Quals.addConsistentQualifiers(Quals);
6145 return desugar;
6146}
6147
6148inline const Type *QualType::getTypePtr() const {
6149 return getCommonPtr()->BaseType;
6150}
6151
6152inline const Type *QualType::getTypePtrOrNull() const {
6153 return (isNull() ? nullptr : getCommonPtr()->BaseType);
6154}
6155
6156inline SplitQualType QualType::split() const {
6157 if (!hasLocalNonFastQualifiers())
6158 return SplitQualType(getTypePtrUnsafe(),
6159 Qualifiers::fromFastMask(getLocalFastQualifiers()));
6160
6161 const ExtQuals *eq = getExtQualsUnsafe();
6162 Qualifiers qs = eq->getQualifiers();
6163 qs.addFastQualifiers(getLocalFastQualifiers());
6164 return SplitQualType(eq->getBaseType(), qs);
6165}
6166
6167inline Qualifiers QualType::getLocalQualifiers() const {
6168 Qualifiers Quals;
6169 if (hasLocalNonFastQualifiers())
6170 Quals = getExtQualsUnsafe()->getQualifiers();
6171 Quals.addFastQualifiers(getLocalFastQualifiers());
6172 return Quals;
6173}
6174
6175inline Qualifiers QualType::getQualifiers() const {
6176 Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers();
6177 quals.addFastQualifiers(getLocalFastQualifiers());
6178 return quals;
6179}
6180
6181inline unsigned QualType::getCVRQualifiers() const {
6182 unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers();
6183 cvr |= getLocalCVRQualifiers();
6184 return cvr;
6185}
6186
6187inline QualType QualType::getCanonicalType() const {
6188 QualType canon = getCommonPtr()->CanonicalType;
6189 return canon.withFastQualifiers(getLocalFastQualifiers());
6190}
6191
6192inline bool QualType::isCanonical() const {
6193 return getTypePtr()->isCanonicalUnqualified();
6194}
6195
6196inline bool QualType::isCanonicalAsParam() const {
6197 if (!isCanonical()) return false;
6198 if (hasLocalQualifiers()) return false;
6199
6200 const Type *T = getTypePtr();
6201 if (T->isVariablyModifiedType() && T->hasSizedVLAType())
6202 return false;
6203
6204 return !isa<FunctionType>(T) && !isa<ArrayType>(T);
6205}
6206
6207inline bool QualType::isConstQualified() const {
6208 return isLocalConstQualified() ||
6209 getCommonPtr()->CanonicalType.isLocalConstQualified();
6210}
6211
6212inline bool QualType::isRestrictQualified() const {
6213 return isLocalRestrictQualified() ||
6214 getCommonPtr()->CanonicalType.isLocalRestrictQualified();
6215}
6216
6217
6218inline bool QualType::isVolatileQualified() const {
6219 return isLocalVolatileQualified() ||
6220 getCommonPtr()->CanonicalType.isLocalVolatileQualified();
6221}
6222
6223inline bool QualType::hasQualifiers() const {
6224 return hasLocalQualifiers() ||
6225 getCommonPtr()->CanonicalType.hasLocalQualifiers();
6226}
6227
6228inline QualType QualType::getUnqualifiedType() const {
6229 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
6230 return QualType(getTypePtr(), 0);
6231
6232 return QualType(getSplitUnqualifiedTypeImpl(*this).Ty, 0);
6233}
6234
6235inline SplitQualType QualType::getSplitUnqualifiedType() const {
6236 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
6237 return split();
6238
6239 return getSplitUnqualifiedTypeImpl(*this);
6240}
6241
6242inline void QualType::removeLocalConst() {
6243 removeLocalFastQualifiers(Qualifiers::Const);
6244}
6245
6246inline void QualType::removeLocalRestrict() {
6247 removeLocalFastQualifiers(Qualifiers::Restrict);
6248}
6249
6250inline void QualType::removeLocalVolatile() {
6251 removeLocalFastQualifiers(Qualifiers::Volatile);
6252}
6253
6254inline void QualType::removeLocalCVRQualifiers(unsigned Mask) {
6255 assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits")((!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(Mask & ~Qualifiers::CVRMask) && \"mask has non-CVR bits\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 6255, __PRETTY_FUNCTION__))
;
6256 static_assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask,
6257 "Fast bits differ from CVR bits!");
6258
6259 // Fast path: we don't need to touch the slow qualifiers.
6260 removeLocalFastQualifiers(Mask);
6261}
6262
6263/// Return the address space of this type.
6264inline LangAS QualType::getAddressSpace() const {
6265 return getQualifiers().getAddressSpace();
6266}
6267
6268/// Return the gc attribute of this type.
6269inline Qualifiers::GC QualType::getObjCGCAttr() const {
6270 return getQualifiers().getObjCGCAttr();
6271}
6272
6273inline bool QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion() const {
6274 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6275 return hasNonTrivialToPrimitiveDefaultInitializeCUnion(RD);
6276 return false;
6277}
6278
6279inline bool QualType::hasNonTrivialToPrimitiveDestructCUnion() const {
6280 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6281 return hasNonTrivialToPrimitiveDestructCUnion(RD);
6282 return false;
6283}
6284
6285inline bool QualType::hasNonTrivialToPrimitiveCopyCUnion() const {
6286 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6287 return hasNonTrivialToPrimitiveCopyCUnion(RD);
6288 return false;
6289}
6290
6291inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) {
6292 if (const auto *PT = t.getAs<PointerType>()) {
6293 if (const auto *FT = PT->getPointeeType()->getAs<FunctionType>())
6294 return FT->getExtInfo();
6295 } else if (const auto *FT = t.getAs<FunctionType>())
6296 return FT->getExtInfo();
6297
6298 return FunctionType::ExtInfo();
6299}
6300
6301inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) {
6302 return getFunctionExtInfo(*t);
6303}
6304
6305/// Determine whether this type is more
6306/// qualified than the Other type. For example, "const volatile int"
6307/// is more qualified than "const int", "volatile int", and
6308/// "int". However, it is not more qualified than "const volatile
6309/// int".
6310inline bool QualType::isMoreQualifiedThan(QualType other) const {
6311 Qualifiers MyQuals = getQualifiers();
6312 Qualifiers OtherQuals = other.getQualifiers();
6313 return (MyQuals != OtherQuals && MyQuals.compatiblyIncludes(OtherQuals));
6314}
6315
6316/// Determine whether this type is at last
6317/// as qualified as the Other type. For example, "const volatile
6318/// int" is at least as qualified as "const int", "volatile int",
6319/// "int", and "const volatile int".
6320inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const {
6321 Qualifiers OtherQuals = other.getQualifiers();
6322
6323 // Ignore __unaligned qualifier if this type is a void.
6324 if (getUnqualifiedType()->isVoidType())
6325 OtherQuals.removeUnaligned();
6326
6327 return getQualifiers().compatiblyIncludes(OtherQuals);
6328}
6329
6330/// If Type is a reference type (e.g., const
6331/// int&), returns the type that the reference refers to ("const
6332/// int"). Otherwise, returns the type itself. This routine is used
6333/// throughout Sema to implement C++ 5p6:
6334///
6335/// If an expression initially has the type "reference to T" (8.3.2,
6336/// 8.5.3), the type is adjusted to "T" prior to any further
6337/// analysis, the expression designates the object or function
6338/// denoted by the reference, and the expression is an lvalue.
6339inline QualType QualType::getNonReferenceType() const {
6340 if (const auto *RefType = (*this)->getAs<ReferenceType>())
6341 return RefType->getPointeeType();
6342 else
6343 return *this;
6344}
6345
6346inline bool QualType::isCForbiddenLValueType() const {
6347 return ((getTypePtr()->isVoidType() && !hasQualifiers()) ||
6348 getTypePtr()->isFunctionType());
6349}
6350
6351/// Tests whether the type is categorized as a fundamental type.
6352///
6353/// \returns True for types specified in C++0x [basic.fundamental].
6354inline bool Type::isFundamentalType() const {
6355 return isVoidType() ||
6356 isNullPtrType() ||
6357 // FIXME: It's really annoying that we don't have an
6358 // 'isArithmeticType()' which agrees with the standard definition.
6359 (isArithmeticType() && !isEnumeralType());
6360}
6361
6362/// Tests whether the type is categorized as a compound type.
6363///
6364/// \returns True for types specified in C++0x [basic.compound].
6365inline bool Type::isCompoundType() const {
6366 // C++0x [basic.compound]p1:
6367 // Compound types can be constructed in the following ways:
6368 // -- arrays of objects of a given type [...];
6369 return isArrayType() ||
6370 // -- functions, which have parameters of given types [...];
6371 isFunctionType() ||
6372 // -- pointers to void or objects or functions [...];
6373 isPointerType() ||
6374 // -- references to objects or functions of a given type. [...]
6375 isReferenceType() ||
6376 // -- classes containing a sequence of objects of various types, [...];
6377 isRecordType() ||
6378 // -- unions, which are classes capable of containing objects of different
6379 // types at different times;
6380 isUnionType() ||
6381 // -- enumerations, which comprise a set of named constant values. [...];
6382 isEnumeralType() ||
6383 // -- pointers to non-static class members, [...].
6384 isMemberPointerType();
6385}
6386
6387inline bool Type::isFunctionType() const {
6388 return isa<FunctionType>(CanonicalType);
6389}
6390
6391inline bool Type::isPointerType() const {
6392 return isa<PointerType>(CanonicalType);
6393}
6394
6395inline bool Type::isAnyPointerType() const {
6396 return isPointerType() || isObjCObjectPointerType();
6397}
6398
6399inline bool Type::isBlockPointerType() const {
6400 return isa<BlockPointerType>(CanonicalType);
6401}
6402
6403inline bool Type::isReferenceType() const {
6404 return isa<ReferenceType>(CanonicalType);
6405}
6406
6407inline bool Type::isLValueReferenceType() const {
6408 return isa<LValueReferenceType>(CanonicalType);
6409}
6410
6411inline bool Type::isRValueReferenceType() const {
6412 return isa<RValueReferenceType>(CanonicalType);
6413}
6414
6415inline bool Type::isFunctionPointerType() const {
6416 if (const auto *T = getAs<PointerType>())
6417 return T->getPointeeType()->isFunctionType();
6418 else
6419 return false;
6420}
6421
6422inline bool Type::isFunctionReferenceType() const {
6423 if (const auto *T = getAs<ReferenceType>())
6424 return T->getPointeeType()->isFunctionType();
6425 else
6426 return false;
6427}
6428
6429inline bool Type::isMemberPointerType() const {
6430 return isa<MemberPointerType>(CanonicalType);
6431}
6432
6433inline bool Type::isMemberFunctionPointerType() const {
6434 if (const auto *T = getAs<MemberPointerType>())
6435 return T->isMemberFunctionPointer();
6436 else
6437 return false;
6438}
6439
6440inline bool Type::isMemberDataPointerType() const {
6441 if (const auto *T = getAs<MemberPointerType>())
6442 return T->isMemberDataPointer();
6443 else
6444 return false;
6445}
6446
6447inline bool Type::isArrayType() const {
6448 return isa<ArrayType>(CanonicalType);
6449}
6450
6451inline bool Type::isConstantArrayType() const {
6452 return isa<ConstantArrayType>(CanonicalType);
6453}
6454
6455inline bool Type::isIncompleteArrayType() const {
6456 return isa<IncompleteArrayType>(CanonicalType);
6457}
6458
6459inline bool Type::isVariableArrayType() const {
6460 return isa<VariableArrayType>(CanonicalType);
6461}
6462
6463inline bool Type::isDependentSizedArrayType() const {
6464 return isa<DependentSizedArrayType>(CanonicalType);
6465}
6466
6467inline bool Type::isBuiltinType() const {
6468 return isa<BuiltinType>(CanonicalType);
6469}
6470
6471inline bool Type::isRecordType() const {
6472 return isa<RecordType>(CanonicalType);
6473}
6474
6475inline bool Type::isEnumeralType() const {
6476 return isa<EnumType>(CanonicalType);
6477}
6478
6479inline bool Type::isAnyComplexType() const {
6480 return isa<ComplexType>(CanonicalType);
6481}
6482
6483inline bool Type::isVectorType() const {
6484 return isa<VectorType>(CanonicalType);
6485}
6486
6487inline bool Type::isExtVectorType() const {
6488 return isa<ExtVectorType>(CanonicalType);
6489}
6490
6491inline bool Type::isDependentAddressSpaceType() const {
6492 return isa<DependentAddressSpaceType>(CanonicalType);
6493}
6494
6495inline bool Type::isObjCObjectPointerType() const {
6496 return isa<ObjCObjectPointerType>(CanonicalType);
6497}
6498
6499inline bool Type::isObjCObjectType() const {
6500 return isa<ObjCObjectType>(CanonicalType);
6501}
6502
6503inline bool Type::isObjCObjectOrInterfaceType() const {
6504 return isa<ObjCInterfaceType>(CanonicalType) ||
6505 isa<ObjCObjectType>(CanonicalType);
6506}
6507
6508inline bool Type::isAtomicType() const {
6509 return isa<AtomicType>(CanonicalType);
6510}
6511
6512inline bool Type::isObjCQualifiedIdType() const {
6513 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6514 return OPT->isObjCQualifiedIdType();
6515 return false;
6516}
6517
6518inline bool Type::isObjCQualifiedClassType() const {
6519 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6520 return OPT->isObjCQualifiedClassType();
6521 return false;
6522}
6523
6524inline bool Type::isObjCIdType() const {
6525 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6526 return OPT->isObjCIdType();
6527 return false;
6528}
6529
6530inline bool Type::isObjCClassType() const {
6531 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6532 return OPT->isObjCClassType();
6533 return false;
6534}
6535
6536inline bool Type::isObjCSelType() const {
6537 if (const auto *OPT = getAs<PointerType>())
6538 return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel);
6539 return false;
6540}
6541
6542inline bool Type::isObjCBuiltinType() const {
6543 return isObjCIdType() || isObjCClassType() || isObjCSelType();
6544}
6545
6546inline bool Type::isDecltypeType() const {
6547 return isa<DecltypeType>(this);
6548}
6549
6550#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6551 inline bool Type::is##Id##Type() const { \
6552 return isSpecificBuiltinType(BuiltinType::Id); \
6553 }
6554#include "clang/Basic/OpenCLImageTypes.def"
6555
6556inline bool Type::isSamplerT() const {
6557 return isSpecificBuiltinType(BuiltinType::OCLSampler);
6558}
6559
6560inline bool Type::isEventT() const {
6561 return isSpecificBuiltinType(BuiltinType::OCLEvent);
6562}
6563
6564inline bool Type::isClkEventT() const {
6565 return isSpecificBuiltinType(BuiltinType::OCLClkEvent);
6566}
6567
6568inline bool Type::isQueueT() const {
6569 return isSpecificBuiltinType(BuiltinType::OCLQueue);
6570}
6571
6572inline bool Type::isReserveIDT() const {
6573 return isSpecificBuiltinType(BuiltinType::OCLReserveID);
6574}
6575
6576inline bool Type::isImageType() const {
6577#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) is##Id##Type() ||
6578 return
6579#include "clang/Basic/OpenCLImageTypes.def"
6580 false; // end boolean or operation
6581}
6582
6583inline bool Type::isPipeType() const {
6584 return isa<PipeType>(CanonicalType);
6585}
6586
6587#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6588 inline bool Type::is##Id##Type() const { \
6589 return isSpecificBuiltinType(BuiltinType::Id); \
6590 }
6591#include "clang/Basic/OpenCLExtensionTypes.def"
6592
6593inline bool Type::isOCLIntelSubgroupAVCType() const {
6594#define INTEL_SUBGROUP_AVC_TYPE(ExtType, Id) \
6595 isOCLIntelSubgroupAVC##Id##Type() ||
6596 return
6597#include "clang/Basic/OpenCLExtensionTypes.def"
6598 false; // end of boolean or operation
6599}
6600
6601inline bool Type::isOCLExtOpaqueType() const {
6602#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) is##Id##Type() ||
6603 return
6604#include "clang/Basic/OpenCLExtensionTypes.def"
6605 false; // end of boolean or operation
6606}
6607
6608inline bool Type::isOpenCLSpecificType() const {
6609 return isSamplerT() || isEventT() || isImageType() || isClkEventT() ||
6610 isQueueT() || isReserveIDT() || isPipeType() || isOCLExtOpaqueType();
6611}
6612
6613inline bool Type::isTemplateTypeParmType() const {
6614 return isa<TemplateTypeParmType>(CanonicalType);
6615}
6616
6617inline bool Type::isSpecificBuiltinType(unsigned K) const {
6618 if (const BuiltinType *BT = getAs<BuiltinType>())
6619 if (BT->getKind() == (BuiltinType::Kind) K)
6620 return true;
6621 return false;
6622}
6623
6624inline bool Type::isPlaceholderType() const {
6625 if (const auto *BT = dyn_cast<BuiltinType>(this))
6626 return BT->isPlaceholderType();
6627 return false;
6628}
6629
6630inline const BuiltinType *Type::getAsPlaceholderType() const {
6631 if (const auto *BT = dyn_cast<BuiltinType>(this))
6632 if (BT->isPlaceholderType())
6633 return BT;
6634 return nullptr;
6635}
6636
6637inline bool Type::isSpecificPlaceholderType(unsigned K) const {
6638 assert(BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K))((BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K)) ?
static_cast<void> (0) : __assert_fail ("BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K)"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 6638, __PRETTY_FUNCTION__))
;
6639 if (const auto *BT = dyn_cast<BuiltinType>(this))
6640 return (BT->getKind() == (BuiltinType::Kind) K);
6641 return false;
6642}
6643
6644inline bool Type::isNonOverloadPlaceholderType() const {
6645 if (const auto *BT = dyn_cast<BuiltinType>(this))
6646 return BT->isNonOverloadPlaceholderType();
6647 return false;
6648}
6649
6650inline bool Type::isVoidType() const {
6651 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6652 return BT->getKind() == BuiltinType::Void;
6653 return false;
6654}
6655
6656inline bool Type::isHalfType() const {
6657 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6658 return BT->getKind() == BuiltinType::Half;
6659 // FIXME: Should we allow complex __fp16? Probably not.
6660 return false;
6661}
6662
6663inline bool Type::isFloat16Type() const {
6664 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6665 return BT->getKind() == BuiltinType::Float16;
6666 return false;
6667}
6668
6669inline bool Type::isFloat128Type() const {
6670 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6671 return BT->getKind() == BuiltinType::Float128;
6672 return false;
6673}
6674
6675inline bool Type::isNullPtrType() const {
6676 if (const auto *BT = getAs<BuiltinType>())
6677 return BT->getKind() == BuiltinType::NullPtr;
6678 return false;
6679}
6680
6681bool IsEnumDeclComplete(EnumDecl *);
6682bool IsEnumDeclScoped(EnumDecl *);
6683
6684inline bool Type::isIntegerType() const {
6685 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6686 return BT->getKind() >= BuiltinType::Bool &&
6687 BT->getKind() <= BuiltinType::Int128;
6688 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
6689 // Incomplete enum types are not treated as integer types.
6690 // FIXME: In C++, enum types are never integer types.
6691 return IsEnumDeclComplete(ET->getDecl()) &&
6692 !IsEnumDeclScoped(ET->getDecl());
6693 }
6694 return false;
6695}
6696
6697inline bool Type::isFixedPointType() const {
6698 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6699 return BT->getKind() >= BuiltinType::ShortAccum &&
6700 BT->getKind() <= BuiltinType::SatULongFract;
6701 }
6702 return false;
6703}
6704
6705inline bool Type::isFixedPointOrIntegerType() const {
6706 return isFixedPointType() || isIntegerType();
6707}
6708
6709inline bool Type::isSaturatedFixedPointType() const {
6710 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6711 return BT->getKind() >= BuiltinType::SatShortAccum &&
6712 BT->getKind() <= BuiltinType::SatULongFract;
6713 }
6714 return false;
6715}
6716
6717inline bool Type::isUnsaturatedFixedPointType() const {
6718 return isFixedPointType() && !isSaturatedFixedPointType();
6719}
6720
6721inline bool Type::isSignedFixedPointType() const {
6722 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6723 return ((BT->getKind() >= BuiltinType::ShortAccum &&
6724 BT->getKind() <= BuiltinType::LongAccum) ||
6725 (BT->getKind() >= BuiltinType::ShortFract &&
6726 BT->getKind() <= BuiltinType::LongFract) ||
6727 (BT->getKind() >= BuiltinType::SatShortAccum &&
6728 BT->getKind() <= BuiltinType::SatLongAccum) ||
6729 (BT->getKind() >= BuiltinType::SatShortFract &&
6730 BT->getKind() <= BuiltinType::SatLongFract));
6731 }
6732 return false;
6733}
6734
6735inline bool Type::isUnsignedFixedPointType() const {
6736 return isFixedPointType() && !isSignedFixedPointType();
6737}
6738
6739inline bool Type::isScalarType() const {
6740 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6741 return BT->getKind() > BuiltinType::Void &&
6742 BT->getKind() <= BuiltinType::NullPtr;
6743 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
6744 // Enums are scalar types, but only if they are defined. Incomplete enums
6745 // are not treated as scalar types.
6746 return IsEnumDeclComplete(ET->getDecl());
6747 return isa<PointerType>(CanonicalType) ||
6748 isa<BlockPointerType>(CanonicalType) ||
6749 isa<MemberPointerType>(CanonicalType) ||
6750 isa<ComplexType>(CanonicalType) ||
6751 isa<ObjCObjectPointerType>(CanonicalType);
6752}
6753
6754inline bool Type::isIntegralOrEnumerationType() const {
6755 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6756 return BT->getKind() >= BuiltinType::Bool &&
6757 BT->getKind() <= BuiltinType::Int128;
6758
6759 // Check for a complete enum type; incomplete enum types are not properly an
6760 // enumeration type in the sense required here.
6761 if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
6762 return IsEnumDeclComplete(ET->getDecl());
6763
6764 return false;
6765}
6766
6767inline bool Type::isBooleanType() const {
6768 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6769 return BT->getKind() == BuiltinType::Bool;
6770 return false;
6771}
6772
6773inline bool Type::isUndeducedType() const {
6774 auto *DT = getContainedDeducedType();
6775 return DT && !DT->isDeduced();
6776}
6777
6778/// Determines whether this is a type for which one can define
6779/// an overloaded operator.
6780inline bool Type::isOverloadableType() const {
6781 return isDependentType() || isRecordType() || isEnumeralType();
6782}
6783
6784/// Determines whether this type can decay to a pointer type.
6785inline bool Type::canDecayToPointerType() const {
6786 return isFunctionType() || isArrayType();
6787}
6788
6789inline bool Type::hasPointerRepresentation() const {
6790 return (isPointerType() || isReferenceType() || isBlockPointerType() ||
6791 isObjCObjectPointerType() || isNullPtrType());
6792}
6793
6794inline bool Type::hasObjCPointerRepresentation() const {
6795 return isObjCObjectPointerType();
6796}
6797
6798inline const Type *Type::getBaseElementTypeUnsafe() const {
6799 const Type *type = this;
6800 while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe())
6801 type = arrayType->getElementType().getTypePtr();
6802 return type;
6803}
6804
6805inline const Type *Type::getPointeeOrArrayElementType() const {
6806 const Type *type = this;
6807 if (type->isAnyPointerType())
6808 return type->getPointeeType().getTypePtr();
6809 else if (type->isArrayType())
6810 return type->getBaseElementTypeUnsafe();
6811 return type;
6812}
6813
6814/// Insertion operator for diagnostics. This allows sending Qualifiers into a
6815/// diagnostic with <<.
6816inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
6817 Qualifiers Q) {
6818 DB.AddTaggedVal(Q.getAsOpaqueValue(),
6819 DiagnosticsEngine::ArgumentKind::ak_qual);
6820 return DB;
6821}
6822
6823/// Insertion operator for partial diagnostics. This allows sending Qualifiers
6824/// into a diagnostic with <<.
6825inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
6826 Qualifiers Q) {
6827 PD.AddTaggedVal(Q.getAsOpaqueValue(),
6828 DiagnosticsEngine::ArgumentKind::ak_qual);
6829 return PD;
6830}
6831
6832/// Insertion operator for diagnostics. This allows sending QualType's into a
6833/// diagnostic with <<.
6834inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
6835 QualType T) {
6836 DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
6837 DiagnosticsEngine::ak_qualtype);
6838 return DB;
6839}
6840
6841/// Insertion operator for partial diagnostics. This allows sending QualType's
6842/// into a diagnostic with <<.
6843inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
6844 QualType T) {
6845 PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
6846 DiagnosticsEngine::ak_qualtype);
6847 return PD;
6848}
6849
6850// Helper class template that is used by Type::getAs to ensure that one does
6851// not try to look through a qualified type to get to an array type.
6852template <typename T>
6853using TypeIsArrayType =
6854 std::integral_constant<bool, std::is_same<T, ArrayType>::value ||
6855 std::is_base_of<ArrayType, T>::value>;
6856
6857// Member-template getAs<specific type>'.
6858template <typename T> const T *Type::getAs() const {
6859 static_assert(!TypeIsArrayType<T>::value,
6860 "ArrayType cannot be used with getAs!");
6861
6862 // If this is directly a T type, return it.
6863 if (const auto *Ty = dyn_cast<T>(this))
6864 return Ty;
6865
6866 // If the canonical form of this type isn't the right kind, reject it.
6867 if (!isa<T>(CanonicalType))
6868 return nullptr;
6869
6870 // If this is a typedef for the type, strip the typedef off without
6871 // losing all typedef information.
6872 return cast<T>(getUnqualifiedDesugaredType());
6873}
6874
6875template <typename T> const T *Type::getAsAdjusted() const {
6876 static_assert(!TypeIsArrayType<T>::value, "ArrayType cannot be used with getAsAdjusted!");
6877
6878 // If this is directly a T type, return it.
6879 if (const auto *Ty = dyn_cast<T>(this))
6880 return Ty;
6881
6882 // If the canonical form of this type isn't the right kind, reject it.
6883 if (!isa<T>(CanonicalType))
6884 return nullptr;
6885
6886 // Strip off type adjustments that do not modify the underlying nature of the
6887 // type.
6888 const Type *Ty = this;
6889 while (Ty) {
6890 if (const auto *A = dyn_cast<AttributedType>(Ty))
6891 Ty = A->getModifiedType().getTypePtr();
6892 else if (const auto *E = dyn_cast<ElaboratedType>(Ty))
6893 Ty = E->desugar().getTypePtr();
6894 else if (const auto *P = dyn_cast<ParenType>(Ty))
6895 Ty = P->desugar().getTypePtr();
6896 else if (const auto *A = dyn_cast<AdjustedType>(Ty))
6897 Ty = A->desugar().getTypePtr();
6898 else if (const auto *M = dyn_cast<MacroQualifiedType>(Ty))
6899 Ty = M->desugar().getTypePtr();
6900 else
6901 break;
6902 }
6903
6904 // Just because the canonical type is correct does not mean we can use cast<>,
6905 // since we may not have stripped off all the sugar down to the base type.
6906 return dyn_cast<T>(Ty);
6907}
6908
6909inline const ArrayType *Type::getAsArrayTypeUnsafe() const {
6910 // If this is directly an array type, return it.
6911 if (const auto *arr = dyn_cast<ArrayType>(this))
6912 return arr;
6913
6914 // If the canonical form of this type isn't the right kind, reject it.
6915 if (!isa<ArrayType>(CanonicalType))
6916 return nullptr;
6917
6918 // If this is a typedef for the type, strip the typedef off without
6919 // losing all typedef information.
6920 return cast<ArrayType>(getUnqualifiedDesugaredType());
6921}
6922
6923template <typename T> const T *Type::castAs() const {
6924 static_assert(!TypeIsArrayType<T>::value,
6925 "ArrayType cannot be used with castAs!");
6926
6927 if (const auto *ty = dyn_cast<T>(this)) return ty;
6928 assert(isa<T>(CanonicalType))((isa<T>(CanonicalType)) ? static_cast<void> (0) :
__assert_fail ("isa<T>(CanonicalType)", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 6928, __PRETTY_FUNCTION__))
;
6929 return cast<T>(getUnqualifiedDesugaredType());
6930}
6931
6932inline const ArrayType *Type::castAsArrayTypeUnsafe() const {
6933 assert(isa<ArrayType>(CanonicalType))((isa<ArrayType>(CanonicalType)) ? static_cast<void>
(0) : __assert_fail ("isa<ArrayType>(CanonicalType)", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 6933, __PRETTY_FUNCTION__))
;
6934 if (const auto *arr = dyn_cast<ArrayType>(this)) return arr;
6935 return cast<ArrayType>(getUnqualifiedDesugaredType());
6936}
6937
6938DecayedType::DecayedType(QualType OriginalType, QualType DecayedPtr,
6939 QualType CanonicalPtr)
6940 : AdjustedType(Decayed, OriginalType, DecayedPtr, CanonicalPtr) {
6941#ifndef NDEBUG
6942 QualType Adjusted = getAdjustedType();
6943 (void)AttributedType::stripOuterNullability(Adjusted);
6944 assert(isa<PointerType>(Adjusted))((isa<PointerType>(Adjusted)) ? static_cast<void>
(0) : __assert_fail ("isa<PointerType>(Adjusted)", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h"
, 6944, __PRETTY_FUNCTION__))
;
6945#endif
6946}
6947
6948QualType DecayedType::getPointeeType() const {
6949 QualType Decayed = getDecayedType();
6950 (void)AttributedType::stripOuterNullability(Decayed);
6951 return cast<PointerType>(Decayed)->getPointeeType();
6952}
6953
6954// Get the decimal string representation of a fixed point type, represented
6955// as a scaled integer.
6956// TODO: At some point, we should change the arguments to instead just accept an
6957// APFixedPoint instead of APSInt and scale.
6958void FixedPointValueToString(SmallVectorImpl<char> &Str, llvm::APSInt Val,
6959 unsigned Scale);
6960
6961} // namespace clang
6962
6963#endif // LLVM_CLANG_AST_TYPE_H

/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/ADT/PointerUnion.h

1//===- llvm/ADT/PointerUnion.h - Discriminated Union of 2 Ptrs --*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the PointerUnion class, which is a discriminated union of
10// pointer types.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_ADT_POINTERUNION_H
15#define LLVM_ADT_POINTERUNION_H
16
17#include "llvm/ADT/DenseMapInfo.h"
18#include "llvm/ADT/PointerIntPair.h"
19#include "llvm/Support/PointerLikeTypeTraits.h"
20#include <cassert>
21#include <cstddef>
22#include <cstdint>
23
24namespace llvm {
25
26template <typename T> struct PointerUnionTypeSelectorReturn {
27 using Return = T;
28};
29
30/// Get a type based on whether two types are the same or not.
31///
32/// For:
33///
34/// \code
35/// using Ret = typename PointerUnionTypeSelector<T1, T2, EQ, NE>::Return;
36/// \endcode
37///
38/// Ret will be EQ type if T1 is same as T2 or NE type otherwise.
39template <typename T1, typename T2, typename RET_EQ, typename RET_NE>
40struct PointerUnionTypeSelector {
41 using Return = typename PointerUnionTypeSelectorReturn<RET_NE>::Return;
42};
43
44template <typename T, typename RET_EQ, typename RET_NE>
45struct PointerUnionTypeSelector<T, T, RET_EQ, RET_NE> {
46 using Return = typename PointerUnionTypeSelectorReturn<RET_EQ>::Return;
47};
48
49template <typename T1, typename T2, typename RET_EQ, typename RET_NE>
50struct PointerUnionTypeSelectorReturn<
51 PointerUnionTypeSelector<T1, T2, RET_EQ, RET_NE>> {
52 using Return =
53 typename PointerUnionTypeSelector<T1, T2, RET_EQ, RET_NE>::Return;
54};
55
56namespace pointer_union_detail {
57 /// Determine the number of bits required to store integers with values < n.
58 /// This is ceil(log2(n)).
59 constexpr int bitsRequired(unsigned n) {
60 return n > 1 ? 1 + bitsRequired((n + 1) / 2) : 0;
61 }
62
63 template <typename... Ts> constexpr int lowBitsAvailable() {
64 return std::min<int>({PointerLikeTypeTraits<Ts>::NumLowBitsAvailable...});
65 }
66
67 /// Find the index of a type in a list of types. TypeIndex<T, Us...>::Index
68 /// is the index of T in Us, or sizeof...(Us) if T does not appear in the
69 /// list.
70 template <typename T, typename ...Us> struct TypeIndex;
71 template <typename T, typename ...Us> struct TypeIndex<T, T, Us...> {
72 static constexpr int Index = 0;
73 };
74 template <typename T, typename U, typename... Us>
75 struct TypeIndex<T, U, Us...> {
76 static constexpr int Index = 1 + TypeIndex<T, Us...>::Index;
77 };
78 template <typename T> struct TypeIndex<T> {
79 static constexpr int Index = 0;
80 };
81
82 /// Find the first type in a list of types.
83 template <typename T, typename...> struct GetFirstType {
84 using type = T;
85 };
86
87 /// Provide PointerLikeTypeTraits for void* that is used by PointerUnion
88 /// for the template arguments.
89 template <typename ...PTs> class PointerUnionUIntTraits {
90 public:
91 static inline void *getAsVoidPointer(void *P) { return P; }
92 static inline void *getFromVoidPointer(void *P) { return P; }
93 static constexpr int NumLowBitsAvailable = lowBitsAvailable<PTs...>();
94 };
95
96 /// Implement assigment in terms of construction.
97 template <typename Derived, typename T> struct AssignableFrom {
98 Derived &operator=(T t) {
99 return static_cast<Derived &>(*this) = Derived(t);
100 }
101 };
102
103 template <typename Derived, typename ValTy, int I, typename ...Types>
104 class PointerUnionMembers;
105
106 template <typename Derived, typename ValTy, int I>
107 class PointerUnionMembers<Derived, ValTy, I> {
108 protected:
109 ValTy Val;
110 PointerUnionMembers() = default;
111 PointerUnionMembers(ValTy Val) : Val(Val) {}
112
113 friend struct PointerLikeTypeTraits<Derived>;
114 };
115
116 template <typename Derived, typename ValTy, int I, typename Type,
117 typename ...Types>
118 class PointerUnionMembers<Derived, ValTy, I, Type, Types...>
119 : public PointerUnionMembers<Derived, ValTy, I + 1, Types...> {
120 using Base = PointerUnionMembers<Derived, ValTy, I + 1, Types...>;
121 public:
122 using Base::Base;
123 PointerUnionMembers() = default;
124 PointerUnionMembers(Type V)
125 : Base(ValTy(const_cast<void *>(
126 PointerLikeTypeTraits<Type>::getAsVoidPointer(V)),
127 I)) {}
128
129 using Base::operator=;
130 Derived &operator=(Type V) {
131 this->Val = ValTy(
132 const_cast<void *>(PointerLikeTypeTraits<Type>::getAsVoidPointer(V)),
133 I);
134 return static_cast<Derived &>(*this);
135 };
136 };
137}
138
139/// A discriminated union of two or more pointer types, with the discriminator
140/// in the low bit of the pointer.
141///
142/// This implementation is extremely efficient in space due to leveraging the
143/// low bits of the pointer, while exposing a natural and type-safe API.
144///
145/// Common use patterns would be something like this:
146/// PointerUnion<int*, float*> P;
147/// P = (int*)0;
148/// printf("%d %d", P.is<int*>(), P.is<float*>()); // prints "1 0"
149/// X = P.get<int*>(); // ok.
150/// Y = P.get<float*>(); // runtime assertion failure.
151/// Z = P.get<double*>(); // compile time failure.
152/// P = (float*)0;
153/// Y = P.get<float*>(); // ok.
154/// X = P.get<int*>(); // runtime assertion failure.
155template <typename... PTs>
156class PointerUnion
157 : public pointer_union_detail::PointerUnionMembers<
158 PointerUnion<PTs...>,
159 PointerIntPair<
160 void *, pointer_union_detail::bitsRequired(sizeof...(PTs)), int,
161 pointer_union_detail::PointerUnionUIntTraits<PTs...>>,
162 0, PTs...> {
163 // The first type is special because we want to directly cast a pointer to a
164 // default-initialized union to a pointer to the first type. But we don't
165 // want PointerUnion to be a 'template <typename First, typename ...Rest>'
166 // because it's much more convenient to have a name for the whole pack. So
167 // split off the first type here.
168 using First = typename pointer_union_detail::GetFirstType<PTs...>::type;
169 using Base = typename PointerUnion::PointerUnionMembers;
170
171public:
172 PointerUnion() = default;
173
174 PointerUnion(std::nullptr_t) : PointerUnion() {}
175 using Base::Base;
176
177 /// Test if the pointer held in the union is null, regardless of
178 /// which type it is.
179 bool isNull() const { return !this->Val.getPointer(); }
10
Assuming the condition is false
11
Returning zero, which participates in a condition later
180
181 explicit operator bool() const { return !isNull(); }
182
183 /// Test if the Union currently holds the type matching T.
184 template <typename T> int is() const {
185 constexpr int Index = pointer_union_detail::TypeIndex<T, PTs...>::Index;
186 static_assert(Index < sizeof...(PTs),
187 "PointerUnion::is<T> given type not in the union");
188 return this->Val.getInt() == Index;
189 }
190
191 /// Returns the value of the specified pointer type.
192 ///
193 /// If the specified pointer type is incorrect, assert.
194 template <typename T> T get() const {
195 assert(is<T>() && "Invalid accessor called")((is<T>() && "Invalid accessor called") ? static_cast
<void> (0) : __assert_fail ("is<T>() && \"Invalid accessor called\""
, "/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/ADT/PointerUnion.h"
, 195, __PRETTY_FUNCTION__))
;
196 return PointerLikeTypeTraits<T>::getFromVoidPointer(this->Val.getPointer());
197 }
198
199 /// Returns the current pointer if it is of the specified pointer type,
200 /// otherwises returns null.
201 template <typename T> T dyn_cast() const {
202 if (is<T>())
203 return get<T>();
204 return T();
205 }
206
207 /// If the union is set to the first pointer type get an address pointing to
208 /// it.
209 First const *getAddrOfPtr1() const {
210 return const_cast<PointerUnion *>(this)->getAddrOfPtr1();
211 }
212
213 /// If the union is set to the first pointer type get an address pointing to
214 /// it.
215 First *getAddrOfPtr1() {
216 assert(is<First>() && "Val is not the first pointer")((is<First>() && "Val is not the first pointer"
) ? static_cast<void> (0) : __assert_fail ("is<First>() && \"Val is not the first pointer\""
, "/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/ADT/PointerUnion.h"
, 216, __PRETTY_FUNCTION__))
;
217 assert(((PointerLikeTypeTraits<First>::getAsVoidPointer(get<
First>()) == this->Val.getPointer() && "Can't get the address because PointerLikeTypeTraits changes the ptr"
) ? static_cast<void> (0) : __assert_fail ("PointerLikeTypeTraits<First>::getAsVoidPointer(get<First>()) == this->Val.getPointer() && \"Can't get the address because PointerLikeTypeTraits changes the ptr\""
, "/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/ADT/PointerUnion.h"
, 220, __PRETTY_FUNCTION__))
218 PointerLikeTypeTraits<First>::getAsVoidPointer(get<First>()) ==((PointerLikeTypeTraits<First>::getAsVoidPointer(get<
First>()) == this->Val.getPointer() && "Can't get the address because PointerLikeTypeTraits changes the ptr"
) ? static_cast<void> (0) : __assert_fail ("PointerLikeTypeTraits<First>::getAsVoidPointer(get<First>()) == this->Val.getPointer() && \"Can't get the address because PointerLikeTypeTraits changes the ptr\""
, "/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/ADT/PointerUnion.h"
, 220, __PRETTY_FUNCTION__))
219 this->Val.getPointer() &&((PointerLikeTypeTraits<First>::getAsVoidPointer(get<
First>()) == this->Val.getPointer() && "Can't get the address because PointerLikeTypeTraits changes the ptr"
) ? static_cast<void> (0) : __assert_fail ("PointerLikeTypeTraits<First>::getAsVoidPointer(get<First>()) == this->Val.getPointer() && \"Can't get the address because PointerLikeTypeTraits changes the ptr\""
, "/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/ADT/PointerUnion.h"
, 220, __PRETTY_FUNCTION__))
220 "Can't get the address because PointerLikeTypeTraits changes the ptr")((PointerLikeTypeTraits<First>::getAsVoidPointer(get<
First>()) == this->Val.getPointer() && "Can't get the address because PointerLikeTypeTraits changes the ptr"
) ? static_cast<void> (0) : __assert_fail ("PointerLikeTypeTraits<First>::getAsVoidPointer(get<First>()) == this->Val.getPointer() && \"Can't get the address because PointerLikeTypeTraits changes the ptr\""
, "/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/ADT/PointerUnion.h"
, 220, __PRETTY_FUNCTION__))
;
221 return const_cast<First *>(
222 reinterpret_cast<const First *>(this->Val.getAddrOfPointer()));
223 }
224
225 /// Assignment from nullptr which just clears the union.
226 const PointerUnion &operator=(std::nullptr_t) {
227 this->Val.initWithPointer(nullptr);
228 return *this;
229 }
230
231 /// Assignment from elements of the union.
232 using Base::operator=;
233
234 void *getOpaqueValue() const { return this->Val.getOpaqueValue(); }
235 static inline PointerUnion getFromOpaqueValue(void *VP) {
236 PointerUnion V;
237 V.Val = decltype(V.Val)::getFromOpaqueValue(VP);
238 return V;
239 }
240};
241
242template <typename ...PTs>
243bool operator==(PointerUnion<PTs...> lhs, PointerUnion<PTs...> rhs) {
244 return lhs.getOpaqueValue() == rhs.getOpaqueValue();
245}
246
247template <typename ...PTs>
248bool operator!=(PointerUnion<PTs...> lhs, PointerUnion<PTs...> rhs) {
249 return lhs.getOpaqueValue() != rhs.getOpaqueValue();
250}
251
252template <typename ...PTs>
253bool operator<(PointerUnion<PTs...> lhs, PointerUnion<PTs...> rhs) {
254 return lhs.getOpaqueValue() < rhs.getOpaqueValue();
255}
256
257// Teach SmallPtrSet that PointerUnion is "basically a pointer", that has
258// # low bits available = min(PT1bits,PT2bits)-1.
259template <typename ...PTs>
260struct PointerLikeTypeTraits<PointerUnion<PTs...>> {
261 static inline void *getAsVoidPointer(const PointerUnion<PTs...> &P) {
262 return P.getOpaqueValue();
263 }
264
265 static inline PointerUnion<PTs...> getFromVoidPointer(void *P) {
266 return PointerUnion<PTs...>::getFromOpaqueValue(P);
267 }
268
269 // The number of bits available are the min of the pointer types minus the
270 // bits needed for the discriminator.
271 static constexpr int NumLowBitsAvailable = PointerLikeTypeTraits<decltype(
272 PointerUnion<PTs...>::Val)>::NumLowBitsAvailable;
273};
274
275/// A pointer union of three pointer types. See documentation for PointerUnion
276/// for usage.
277template <typename PT1, typename PT2, typename PT3>
278using PointerUnion3 = PointerUnion<PT1, PT2, PT3>;
279
280/// A pointer union of four pointer types. See documentation for PointerUnion
281/// for usage.
282template <typename PT1, typename PT2, typename PT3, typename PT4>
283using PointerUnion4 = PointerUnion<PT1, PT2, PT3, PT4>;
284
285// Teach DenseMap how to use PointerUnions as keys.
286template <typename ...PTs> struct DenseMapInfo<PointerUnion<PTs...>> {
287 using Union = PointerUnion<PTs...>;
288 using FirstInfo =
289 DenseMapInfo<typename pointer_union_detail::GetFirstType<PTs...>::type>;
290
291 static inline Union getEmptyKey() { return Union(FirstInfo::getEmptyKey()); }
292
293 static inline Union getTombstoneKey() {
294 return Union(FirstInfo::getTombstoneKey());
295 }
296
297 static unsigned getHashValue(const Union &UnionVal) {
298 intptr_t key = (intptr_t)UnionVal.getOpaqueValue();
299 return DenseMapInfo<intptr_t>::getHashValue(key);
300 }
301
302 static bool isEqual(const Union &LHS, const Union &RHS) {
303 return LHS == RHS;
304 }
305};
306
307} // end namespace llvm
308
309#endif // LLVM_ADT_POINTERUNION_H