Bug Summary

File:clang/lib/Sema/SemaExpr.cpp
Warning:line 3782, column 13
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaExpr.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 -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include -I /build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/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-12/lib/clang/12.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-12~++20201124111112+7b5254223ac/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-11-24-172238-38865-1 -x c++ /build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp

/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp

1//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
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 semantic analysis for expressions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TreeTransform.h"
14#include "UsedDeclVisitor.h"
15#include "clang/AST/ASTConsumer.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/ASTLambda.h"
18#include "clang/AST/ASTMutationListener.h"
19#include "clang/AST/CXXInheritance.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/EvaluatedExprVisitor.h"
23#include "clang/AST/Expr.h"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/ExprObjC.h"
26#include "clang/AST/ExprOpenMP.h"
27#include "clang/AST/OperationKinds.h"
28#include "clang/AST/RecursiveASTVisitor.h"
29#include "clang/AST/TypeLoc.h"
30#include "clang/Basic/Builtins.h"
31#include "clang/Basic/PartialDiagnostic.h"
32#include "clang/Basic/SourceManager.h"
33#include "clang/Basic/TargetInfo.h"
34#include "clang/Lex/LiteralSupport.h"
35#include "clang/Lex/Preprocessor.h"
36#include "clang/Sema/AnalysisBasedWarnings.h"
37#include "clang/Sema/DeclSpec.h"
38#include "clang/Sema/DelayedDiagnostic.h"
39#include "clang/Sema/Designator.h"
40#include "clang/Sema/Initialization.h"
41#include "clang/Sema/Lookup.h"
42#include "clang/Sema/Overload.h"
43#include "clang/Sema/ParsedTemplate.h"
44#include "clang/Sema/Scope.h"
45#include "clang/Sema/ScopeInfo.h"
46#include "clang/Sema/SemaFixItUtils.h"
47#include "clang/Sema/SemaInternal.h"
48#include "clang/Sema/Template.h"
49#include "llvm/Support/ConvertUTF.h"
50#include "llvm/Support/SaveAndRestore.h"
51using namespace clang;
52using namespace sema;
53using llvm::RoundingMode;
54
55/// Determine whether the use of this declaration is valid, without
56/// emitting diagnostics.
57bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
58 // See if this is an auto-typed variable whose initializer we are parsing.
59 if (ParsingInitForAutoVars.count(D))
60 return false;
61
62 // See if this is a deleted function.
63 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
64 if (FD->isDeleted())
65 return false;
66
67 // If the function has a deduced return type, and we can't deduce it,
68 // then we can't use it either.
69 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
70 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
71 return false;
72
73 // See if this is an aligned allocation/deallocation function that is
74 // unavailable.
75 if (TreatUnavailableAsInvalid &&
76 isUnavailableAlignedAllocationFunction(*FD))
77 return false;
78 }
79
80 // See if this function is unavailable.
81 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
82 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
83 return false;
84
85 return true;
86}
87
88static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
89 // Warn if this is used but marked unused.
90 if (const auto *A = D->getAttr<UnusedAttr>()) {
91 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
92 // should diagnose them.
93 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
94 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
95 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
96 if (DC && !DC->hasAttr<UnusedAttr>())
97 S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
98 }
99 }
100}
101
102/// Emit a note explaining that this function is deleted.
103void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
104 assert(Decl && Decl->isDeleted())((Decl && Decl->isDeleted()) ? static_cast<void
> (0) : __assert_fail ("Decl && Decl->isDeleted()"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 104, __PRETTY_FUNCTION__))
;
105
106 if (Decl->isDefaulted()) {
107 // If the method was explicitly defaulted, point at that declaration.
108 if (!Decl->isImplicit())
109 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
110
111 // Try to diagnose why this special member function was implicitly
112 // deleted. This might fail, if that reason no longer applies.
113 DiagnoseDeletedDefaultedFunction(Decl);
114 return;
115 }
116
117 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
118 if (Ctor && Ctor->isInheritingConstructor())
119 return NoteDeletedInheritingConstructor(Ctor);
120
121 Diag(Decl->getLocation(), diag::note_availability_specified_here)
122 << Decl << 1;
123}
124
125/// Determine whether a FunctionDecl was ever declared with an
126/// explicit storage class.
127static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
128 for (auto I : D->redecls()) {
129 if (I->getStorageClass() != SC_None)
130 return true;
131 }
132 return false;
133}
134
135/// Check whether we're in an extern inline function and referring to a
136/// variable or function with internal linkage (C11 6.7.4p3).
137///
138/// This is only a warning because we used to silently accept this code, but
139/// in many cases it will not behave correctly. This is not enabled in C++ mode
140/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
141/// and so while there may still be user mistakes, most of the time we can't
142/// prove that there are errors.
143static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
144 const NamedDecl *D,
145 SourceLocation Loc) {
146 // This is disabled under C++; there are too many ways for this to fire in
147 // contexts where the warning is a false positive, or where it is technically
148 // correct but benign.
149 if (S.getLangOpts().CPlusPlus)
150 return;
151
152 // Check if this is an inlined function or method.
153 FunctionDecl *Current = S.getCurFunctionDecl();
154 if (!Current)
155 return;
156 if (!Current->isInlined())
157 return;
158 if (!Current->isExternallyVisible())
159 return;
160
161 // Check if the decl has internal linkage.
162 if (D->getFormalLinkage() != InternalLinkage)
163 return;
164
165 // Downgrade from ExtWarn to Extension if
166 // (1) the supposedly external inline function is in the main file,
167 // and probably won't be included anywhere else.
168 // (2) the thing we're referencing is a pure function.
169 // (3) the thing we're referencing is another inline function.
170 // This last can give us false negatives, but it's better than warning on
171 // wrappers for simple C library functions.
172 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
173 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
174 if (!DowngradeWarning && UsedFn)
175 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
176
177 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
178 : diag::ext_internal_in_extern_inline)
179 << /*IsVar=*/!UsedFn << D;
180
181 S.MaybeSuggestAddingStaticToDecl(Current);
182
183 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
184 << D;
185}
186
187void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
188 const FunctionDecl *First = Cur->getFirstDecl();
189
190 // Suggest "static" on the function, if possible.
191 if (!hasAnyExplicitStorageClass(First)) {
192 SourceLocation DeclBegin = First->getSourceRange().getBegin();
193 Diag(DeclBegin, diag::note_convert_inline_to_static)
194 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
195 }
196}
197
198/// Determine whether the use of this declaration is valid, and
199/// emit any corresponding diagnostics.
200///
201/// This routine diagnoses various problems with referencing
202/// declarations that can occur when using a declaration. For example,
203/// it might warn if a deprecated or unavailable declaration is being
204/// used, or produce an error (and return true) if a C++0x deleted
205/// function is being used.
206///
207/// \returns true if there was an error (this declaration cannot be
208/// referenced), false otherwise.
209///
210bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
211 const ObjCInterfaceDecl *UnknownObjCClass,
212 bool ObjCPropertyAccess,
213 bool AvoidPartialAvailabilityChecks,
214 ObjCInterfaceDecl *ClassReceiver) {
215 SourceLocation Loc = Locs.front();
216 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
217 // If there were any diagnostics suppressed by template argument deduction,
218 // emit them now.
219 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
220 if (Pos != SuppressedDiagnostics.end()) {
221 for (const PartialDiagnosticAt &Suppressed : Pos->second)
222 Diag(Suppressed.first, Suppressed.second);
223
224 // Clear out the list of suppressed diagnostics, so that we don't emit
225 // them again for this specialization. However, we don't obsolete this
226 // entry from the table, because we want to avoid ever emitting these
227 // diagnostics again.
228 Pos->second.clear();
229 }
230
231 // C++ [basic.start.main]p3:
232 // The function 'main' shall not be used within a program.
233 if (cast<FunctionDecl>(D)->isMain())
234 Diag(Loc, diag::ext_main_used);
235
236 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
237 }
238
239 // See if this is an auto-typed variable whose initializer we are parsing.
240 if (ParsingInitForAutoVars.count(D)) {
241 if (isa<BindingDecl>(D)) {
242 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
243 << D->getDeclName();
244 } else {
245 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
246 << D->getDeclName() << cast<VarDecl>(D)->getType();
247 }
248 return true;
249 }
250
251 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
252 // See if this is a deleted function.
253 if (FD->isDeleted()) {
254 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
255 if (Ctor && Ctor->isInheritingConstructor())
256 Diag(Loc, diag::err_deleted_inherited_ctor_use)
257 << Ctor->getParent()
258 << Ctor->getInheritedConstructor().getConstructor()->getParent();
259 else
260 Diag(Loc, diag::err_deleted_function_use);
261 NoteDeletedFunction(FD);
262 return true;
263 }
264
265 // [expr.prim.id]p4
266 // A program that refers explicitly or implicitly to a function with a
267 // trailing requires-clause whose constraint-expression is not satisfied,
268 // other than to declare it, is ill-formed. [...]
269 //
270 // See if this is a function with constraints that need to be satisfied.
271 // Check this before deducing the return type, as it might instantiate the
272 // definition.
273 if (FD->getTrailingRequiresClause()) {
274 ConstraintSatisfaction Satisfaction;
275 if (CheckFunctionConstraints(FD, Satisfaction, Loc))
276 // A diagnostic will have already been generated (non-constant
277 // constraint expression, for example)
278 return true;
279 if (!Satisfaction.IsSatisfied) {
280 Diag(Loc,
281 diag::err_reference_to_function_with_unsatisfied_constraints)
282 << D;
283 DiagnoseUnsatisfiedConstraint(Satisfaction);
284 return true;
285 }
286 }
287
288 // If the function has a deduced return type, and we can't deduce it,
289 // then we can't use it either.
290 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
291 DeduceReturnType(FD, Loc))
292 return true;
293
294 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
295 return true;
296
297 if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD))
298 return true;
299 }
300
301 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
302 // Lambdas are only default-constructible or assignable in C++2a onwards.
303 if (MD->getParent()->isLambda() &&
304 ((isa<CXXConstructorDecl>(MD) &&
305 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
306 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
307 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
308 << !isa<CXXConstructorDecl>(MD);
309 }
310 }
311
312 auto getReferencedObjCProp = [](const NamedDecl *D) ->
313 const ObjCPropertyDecl * {
314 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
315 return MD->findPropertyDecl();
316 return nullptr;
317 };
318 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
319 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
320 return true;
321 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
322 return true;
323 }
324
325 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
326 // Only the variables omp_in and omp_out are allowed in the combiner.
327 // Only the variables omp_priv and omp_orig are allowed in the
328 // initializer-clause.
329 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
330 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
331 isa<VarDecl>(D)) {
332 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
333 << getCurFunction()->HasOMPDeclareReductionCombiner;
334 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
335 return true;
336 }
337
338 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
339 // List-items in map clauses on this construct may only refer to the declared
340 // variable var and entities that could be referenced by a procedure defined
341 // at the same location
342 if (LangOpts.OpenMP && isa<VarDecl>(D) &&
343 !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
344 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
345 << getOpenMPDeclareMapperVarName();
346 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
347 return true;
348 }
349
350 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
351 AvoidPartialAvailabilityChecks, ClassReceiver);
352
353 DiagnoseUnusedOfDecl(*this, D, Loc);
354
355 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
356
357 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) {
358 if (const auto *VD = dyn_cast<ValueDecl>(D))
359 checkDeviceDecl(VD, Loc);
360
361 if (!Context.getTargetInfo().isTLSSupported())
362 if (const auto *VD = dyn_cast<VarDecl>(D))
363 if (VD->getTLSKind() != VarDecl::TLS_None)
364 targetDiag(*Locs.begin(), diag::err_thread_unsupported);
365 }
366
367 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
368 !isUnevaluatedContext()) {
369 // C++ [expr.prim.req.nested] p3
370 // A local parameter shall only appear as an unevaluated operand
371 // (Clause 8) within the constraint-expression.
372 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
373 << D;
374 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
375 return true;
376 }
377
378 return false;
379}
380
381/// DiagnoseSentinelCalls - This routine checks whether a call or
382/// message-send is to a declaration with the sentinel attribute, and
383/// if so, it checks that the requirements of the sentinel are
384/// satisfied.
385void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
386 ArrayRef<Expr *> Args) {
387 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
388 if (!attr)
389 return;
390
391 // The number of formal parameters of the declaration.
392 unsigned numFormalParams;
393
394 // The kind of declaration. This is also an index into a %select in
395 // the diagnostic.
396 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
397
398 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
399 numFormalParams = MD->param_size();
400 calleeType = CT_Method;
401 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
402 numFormalParams = FD->param_size();
403 calleeType = CT_Function;
404 } else if (isa<VarDecl>(D)) {
405 QualType type = cast<ValueDecl>(D)->getType();
406 const FunctionType *fn = nullptr;
407 if (const PointerType *ptr = type->getAs<PointerType>()) {
408 fn = ptr->getPointeeType()->getAs<FunctionType>();
409 if (!fn) return;
410 calleeType = CT_Function;
411 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
412 fn = ptr->getPointeeType()->castAs<FunctionType>();
413 calleeType = CT_Block;
414 } else {
415 return;
416 }
417
418 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
419 numFormalParams = proto->getNumParams();
420 } else {
421 numFormalParams = 0;
422 }
423 } else {
424 return;
425 }
426
427 // "nullPos" is the number of formal parameters at the end which
428 // effectively count as part of the variadic arguments. This is
429 // useful if you would prefer to not have *any* formal parameters,
430 // but the language forces you to have at least one.
431 unsigned nullPos = attr->getNullPos();
432 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel")(((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"
) ? static_cast<void> (0) : __assert_fail ("(nullPos == 0 || nullPos == 1) && \"invalid null position on sentinel\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 432, __PRETTY_FUNCTION__))
;
433 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
434
435 // The number of arguments which should follow the sentinel.
436 unsigned numArgsAfterSentinel = attr->getSentinel();
437
438 // If there aren't enough arguments for all the formal parameters,
439 // the sentinel, and the args after the sentinel, complain.
440 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
441 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
442 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
443 return;
444 }
445
446 // Otherwise, find the sentinel expression.
447 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
448 if (!sentinelExpr) return;
449 if (sentinelExpr->isValueDependent()) return;
450 if (Context.isSentinelNullExpr(sentinelExpr)) return;
451
452 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
453 // or 'NULL' if those are actually defined in the context. Only use
454 // 'nil' for ObjC methods, where it's much more likely that the
455 // variadic arguments form a list of object pointers.
456 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
457 std::string NullValue;
458 if (calleeType == CT_Method && PP.isMacroDefined("nil"))
459 NullValue = "nil";
460 else if (getLangOpts().CPlusPlus11)
461 NullValue = "nullptr";
462 else if (PP.isMacroDefined("NULL"))
463 NullValue = "NULL";
464 else
465 NullValue = "(void*) 0";
466
467 if (MissingNilLoc.isInvalid())
468 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
469 else
470 Diag(MissingNilLoc, diag::warn_missing_sentinel)
471 << int(calleeType)
472 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
473 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
474}
475
476SourceRange Sema::getExprRange(Expr *E) const {
477 return E ? E->getSourceRange() : SourceRange();
478}
479
480//===----------------------------------------------------------------------===//
481// Standard Promotions and Conversions
482//===----------------------------------------------------------------------===//
483
484/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
485ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
486 // Handle any placeholder expressions which made it here.
487 if (E->getType()->isPlaceholderType()) {
488 ExprResult result = CheckPlaceholderExpr(E);
489 if (result.isInvalid()) return ExprError();
490 E = result.get();
491 }
492
493 QualType Ty = E->getType();
494 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type")((!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"
) ? static_cast<void> (0) : __assert_fail ("!Ty.isNull() && \"DefaultFunctionArrayConversion - missing type\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 494, __PRETTY_FUNCTION__))
;
495
496 if (Ty->isFunctionType()) {
497 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
498 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
499 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
500 return ExprError();
501
502 E = ImpCastExprToType(E, Context.getPointerType(Ty),
503 CK_FunctionToPointerDecay).get();
504 } else if (Ty->isArrayType()) {
505 // In C90 mode, arrays only promote to pointers if the array expression is
506 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
507 // type 'array of type' is converted to an expression that has type 'pointer
508 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
509 // that has type 'array of type' ...". The relevant change is "an lvalue"
510 // (C90) to "an expression" (C99).
511 //
512 // C++ 4.2p1:
513 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
514 // T" can be converted to an rvalue of type "pointer to T".
515 //
516 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
517 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
518 CK_ArrayToPointerDecay).get();
519 }
520 return E;
521}
522
523static void CheckForNullPointerDereference(Sema &S, Expr *E) {
524 // Check to see if we are dereferencing a null pointer. If so,
525 // and if not volatile-qualified, this is undefined behavior that the
526 // optimizer will delete, so warn about it. People sometimes try to use this
527 // to get a deterministic trap and are surprised by clang's behavior. This
528 // only handles the pattern "*null", which is a very syntactic check.
529 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
530 if (UO && UO->getOpcode() == UO_Deref &&
531 UO->getSubExpr()->getType()->isPointerType()) {
532 const LangAS AS =
533 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
534 if ((!isTargetAddressSpace(AS) ||
535 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
536 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
537 S.Context, Expr::NPC_ValueDependentIsNotNull) &&
538 !UO->getType().isVolatileQualified()) {
539 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
540 S.PDiag(diag::warn_indirection_through_null)
541 << UO->getSubExpr()->getSourceRange());
542 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
543 S.PDiag(diag::note_indirection_through_null));
544 }
545 }
546}
547
548static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
549 SourceLocation AssignLoc,
550 const Expr* RHS) {
551 const ObjCIvarDecl *IV = OIRE->getDecl();
552 if (!IV)
553 return;
554
555 DeclarationName MemberName = IV->getDeclName();
556 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
557 if (!Member || !Member->isStr("isa"))
558 return;
559
560 const Expr *Base = OIRE->getBase();
561 QualType BaseType = Base->getType();
562 if (OIRE->isArrow())
563 BaseType = BaseType->getPointeeType();
564 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
565 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
566 ObjCInterfaceDecl *ClassDeclared = nullptr;
567 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
568 if (!ClassDeclared->getSuperClass()
569 && (*ClassDeclared->ivar_begin()) == IV) {
570 if (RHS) {
571 NamedDecl *ObjectSetClass =
572 S.LookupSingleName(S.TUScope,
573 &S.Context.Idents.get("object_setClass"),
574 SourceLocation(), S.LookupOrdinaryName);
575 if (ObjectSetClass) {
576 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
577 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
578 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
579 "object_setClass(")
580 << FixItHint::CreateReplacement(
581 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
582 << FixItHint::CreateInsertion(RHSLocEnd, ")");
583 }
584 else
585 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
586 } else {
587 NamedDecl *ObjectGetClass =
588 S.LookupSingleName(S.TUScope,
589 &S.Context.Idents.get("object_getClass"),
590 SourceLocation(), S.LookupOrdinaryName);
591 if (ObjectGetClass)
592 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
593 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
594 "object_getClass(")
595 << FixItHint::CreateReplacement(
596 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
597 else
598 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
599 }
600 S.Diag(IV->getLocation(), diag::note_ivar_decl);
601 }
602 }
603}
604
605ExprResult Sema::DefaultLvalueConversion(Expr *E) {
606 // Handle any placeholder expressions which made it here.
607 if (E->getType()->isPlaceholderType()) {
608 ExprResult result = CheckPlaceholderExpr(E);
609 if (result.isInvalid()) return ExprError();
610 E = result.get();
611 }
612
613 // C++ [conv.lval]p1:
614 // A glvalue of a non-function, non-array type T can be
615 // converted to a prvalue.
616 if (!E->isGLValue()) return E;
617
618 QualType T = E->getType();
619 assert(!T.isNull() && "r-value conversion on typeless expression?")((!T.isNull() && "r-value conversion on typeless expression?"
) ? static_cast<void> (0) : __assert_fail ("!T.isNull() && \"r-value conversion on typeless expression?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 619, __PRETTY_FUNCTION__))
;
620
621 // lvalue-to-rvalue conversion cannot be applied to function or array types.
622 if (T->isFunctionType() || T->isArrayType())
623 return E;
624
625 // We don't want to throw lvalue-to-rvalue casts on top of
626 // expressions of certain types in C++.
627 if (getLangOpts().CPlusPlus &&
628 (E->getType() == Context.OverloadTy ||
629 T->isDependentType() ||
630 T->isRecordType()))
631 return E;
632
633 // The C standard is actually really unclear on this point, and
634 // DR106 tells us what the result should be but not why. It's
635 // generally best to say that void types just doesn't undergo
636 // lvalue-to-rvalue at all. Note that expressions of unqualified
637 // 'void' type are never l-values, but qualified void can be.
638 if (T->isVoidType())
639 return E;
640
641 // OpenCL usually rejects direct accesses to values of 'half' type.
642 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
643 T->isHalfType()) {
644 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
645 << 0 << T;
646 return ExprError();
647 }
648
649 CheckForNullPointerDereference(*this, E);
650 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
651 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
652 &Context.Idents.get("object_getClass"),
653 SourceLocation(), LookupOrdinaryName);
654 if (ObjectGetClass)
655 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
656 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
657 << FixItHint::CreateReplacement(
658 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
659 else
660 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
661 }
662 else if (const ObjCIvarRefExpr *OIRE =
663 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
664 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
665
666 // C++ [conv.lval]p1:
667 // [...] If T is a non-class type, the type of the prvalue is the
668 // cv-unqualified version of T. Otherwise, the type of the
669 // rvalue is T.
670 //
671 // C99 6.3.2.1p2:
672 // If the lvalue has qualified type, the value has the unqualified
673 // version of the type of the lvalue; otherwise, the value has the
674 // type of the lvalue.
675 if (T.hasQualifiers())
676 T = T.getUnqualifiedType();
677
678 // Under the MS ABI, lock down the inheritance model now.
679 if (T->isMemberPointerType() &&
680 Context.getTargetInfo().getCXXABI().isMicrosoft())
681 (void)isCompleteType(E->getExprLoc(), T);
682
683 ExprResult Res = CheckLValueToRValueConversionOperand(E);
684 if (Res.isInvalid())
685 return Res;
686 E = Res.get();
687
688 // Loading a __weak object implicitly retains the value, so we need a cleanup to
689 // balance that.
690 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
691 Cleanup.setExprNeedsCleanups(true);
692
693 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
694 Cleanup.setExprNeedsCleanups(true);
695
696 // C++ [conv.lval]p3:
697 // If T is cv std::nullptr_t, the result is a null pointer constant.
698 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
699 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue,
700 CurFPFeatureOverrides());
701
702 // C11 6.3.2.1p2:
703 // ... if the lvalue has atomic type, the value has the non-atomic version
704 // of the type of the lvalue ...
705 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
706 T = Atomic->getValueType().getUnqualifiedType();
707 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
708 nullptr, VK_RValue, FPOptionsOverride());
709 }
710
711 return Res;
712}
713
714ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
715 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
716 if (Res.isInvalid())
717 return ExprError();
718 Res = DefaultLvalueConversion(Res.get());
719 if (Res.isInvalid())
720 return ExprError();
721 return Res;
722}
723
724/// CallExprUnaryConversions - a special case of an unary conversion
725/// performed on a function designator of a call expression.
726ExprResult Sema::CallExprUnaryConversions(Expr *E) {
727 QualType Ty = E->getType();
728 ExprResult Res = E;
729 // Only do implicit cast for a function type, but not for a pointer
730 // to function type.
731 if (Ty->isFunctionType()) {
732 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
733 CK_FunctionToPointerDecay);
734 if (Res.isInvalid())
735 return ExprError();
736 }
737 Res = DefaultLvalueConversion(Res.get());
738 if (Res.isInvalid())
739 return ExprError();
740 return Res.get();
741}
742
743/// UsualUnaryConversions - Performs various conversions that are common to most
744/// operators (C99 6.3). The conversions of array and function types are
745/// sometimes suppressed. For example, the array->pointer conversion doesn't
746/// apply if the array is an argument to the sizeof or address (&) operators.
747/// In these instances, this routine should *not* be called.
748ExprResult Sema::UsualUnaryConversions(Expr *E) {
749 // First, convert to an r-value.
750 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
751 if (Res.isInvalid())
752 return ExprError();
753 E = Res.get();
754
755 QualType Ty = E->getType();
756 assert(!Ty.isNull() && "UsualUnaryConversions - missing type")((!Ty.isNull() && "UsualUnaryConversions - missing type"
) ? static_cast<void> (0) : __assert_fail ("!Ty.isNull() && \"UsualUnaryConversions - missing type\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 756, __PRETTY_FUNCTION__))
;
757
758 // Half FP have to be promoted to float unless it is natively supported
759 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
760 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
761
762 // Try to perform integral promotions if the object has a theoretically
763 // promotable type.
764 if (Ty->isIntegralOrUnscopedEnumerationType()) {
765 // C99 6.3.1.1p2:
766 //
767 // The following may be used in an expression wherever an int or
768 // unsigned int may be used:
769 // - an object or expression with an integer type whose integer
770 // conversion rank is less than or equal to the rank of int
771 // and unsigned int.
772 // - A bit-field of type _Bool, int, signed int, or unsigned int.
773 //
774 // If an int can represent all values of the original type, the
775 // value is converted to an int; otherwise, it is converted to an
776 // unsigned int. These are called the integer promotions. All
777 // other types are unchanged by the integer promotions.
778
779 QualType PTy = Context.isPromotableBitField(E);
780 if (!PTy.isNull()) {
781 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
782 return E;
783 }
784 if (Ty->isPromotableIntegerType()) {
785 QualType PT = Context.getPromotedIntegerType(Ty);
786 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
787 return E;
788 }
789 }
790 return E;
791}
792
793/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
794/// do not have a prototype. Arguments that have type float or __fp16
795/// are promoted to double. All other argument types are converted by
796/// UsualUnaryConversions().
797ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
798 QualType Ty = E->getType();
799 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type")((!Ty.isNull() && "DefaultArgumentPromotion - missing type"
) ? static_cast<void> (0) : __assert_fail ("!Ty.isNull() && \"DefaultArgumentPromotion - missing type\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 799, __PRETTY_FUNCTION__))
;
800
801 ExprResult Res = UsualUnaryConversions(E);
802 if (Res.isInvalid())
803 return ExprError();
804 E = Res.get();
805
806 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
807 // promote to double.
808 // Note that default argument promotion applies only to float (and
809 // half/fp16); it does not apply to _Float16.
810 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
811 if (BTy && (BTy->getKind() == BuiltinType::Half ||
812 BTy->getKind() == BuiltinType::Float)) {
813 if (getLangOpts().OpenCL &&
814 !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
815 if (BTy->getKind() == BuiltinType::Half) {
816 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
817 }
818 } else {
819 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
820 }
821 }
822
823 // C++ performs lvalue-to-rvalue conversion as a default argument
824 // promotion, even on class types, but note:
825 // C++11 [conv.lval]p2:
826 // When an lvalue-to-rvalue conversion occurs in an unevaluated
827 // operand or a subexpression thereof the value contained in the
828 // referenced object is not accessed. Otherwise, if the glvalue
829 // has a class type, the conversion copy-initializes a temporary
830 // of type T from the glvalue and the result of the conversion
831 // is a prvalue for the temporary.
832 // FIXME: add some way to gate this entire thing for correctness in
833 // potentially potentially evaluated contexts.
834 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
835 ExprResult Temp = PerformCopyInitialization(
836 InitializedEntity::InitializeTemporary(E->getType()),
837 E->getExprLoc(), E);
838 if (Temp.isInvalid())
839 return ExprError();
840 E = Temp.get();
841 }
842
843 return E;
844}
845
846/// Determine the degree of POD-ness for an expression.
847/// Incomplete types are considered POD, since this check can be performed
848/// when we're in an unevaluated context.
849Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
850 if (Ty->isIncompleteType()) {
851 // C++11 [expr.call]p7:
852 // After these conversions, if the argument does not have arithmetic,
853 // enumeration, pointer, pointer to member, or class type, the program
854 // is ill-formed.
855 //
856 // Since we've already performed array-to-pointer and function-to-pointer
857 // decay, the only such type in C++ is cv void. This also handles
858 // initializer lists as variadic arguments.
859 if (Ty->isVoidType())
860 return VAK_Invalid;
861
862 if (Ty->isObjCObjectType())
863 return VAK_Invalid;
864 return VAK_Valid;
865 }
866
867 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
868 return VAK_Invalid;
869
870 if (Ty.isCXX98PODType(Context))
871 return VAK_Valid;
872
873 // C++11 [expr.call]p7:
874 // Passing a potentially-evaluated argument of class type (Clause 9)
875 // having a non-trivial copy constructor, a non-trivial move constructor,
876 // or a non-trivial destructor, with no corresponding parameter,
877 // is conditionally-supported with implementation-defined semantics.
878 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
879 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
880 if (!Record->hasNonTrivialCopyConstructor() &&
881 !Record->hasNonTrivialMoveConstructor() &&
882 !Record->hasNonTrivialDestructor())
883 return VAK_ValidInCXX11;
884
885 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
886 return VAK_Valid;
887
888 if (Ty->isObjCObjectType())
889 return VAK_Invalid;
890
891 if (getLangOpts().MSVCCompat)
892 return VAK_MSVCUndefined;
893
894 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
895 // permitted to reject them. We should consider doing so.
896 return VAK_Undefined;
897}
898
899void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
900 // Don't allow one to pass an Objective-C interface to a vararg.
901 const QualType &Ty = E->getType();
902 VarArgKind VAK = isValidVarArgType(Ty);
903
904 // Complain about passing non-POD types through varargs.
905 switch (VAK) {
906 case VAK_ValidInCXX11:
907 DiagRuntimeBehavior(
908 E->getBeginLoc(), nullptr,
909 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
910 LLVM_FALLTHROUGH[[gnu::fallthrough]];
911 case VAK_Valid:
912 if (Ty->isRecordType()) {
913 // This is unlikely to be what the user intended. If the class has a
914 // 'c_str' member function, the user probably meant to call that.
915 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
916 PDiag(diag::warn_pass_class_arg_to_vararg)
917 << Ty << CT << hasCStrMethod(E) << ".c_str()");
918 }
919 break;
920
921 case VAK_Undefined:
922 case VAK_MSVCUndefined:
923 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
924 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
925 << getLangOpts().CPlusPlus11 << Ty << CT);
926 break;
927
928 case VAK_Invalid:
929 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
930 Diag(E->getBeginLoc(),
931 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
932 << Ty << CT;
933 else if (Ty->isObjCObjectType())
934 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
935 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
936 << Ty << CT);
937 else
938 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
939 << isa<InitListExpr>(E) << Ty << CT;
940 break;
941 }
942}
943
944/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
945/// will create a trap if the resulting type is not a POD type.
946ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
947 FunctionDecl *FDecl) {
948 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
949 // Strip the unbridged-cast placeholder expression off, if applicable.
950 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
951 (CT == VariadicMethod ||
952 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
953 E = stripARCUnbridgedCast(E);
954
955 // Otherwise, do normal placeholder checking.
956 } else {
957 ExprResult ExprRes = CheckPlaceholderExpr(E);
958 if (ExprRes.isInvalid())
959 return ExprError();
960 E = ExprRes.get();
961 }
962 }
963
964 ExprResult ExprRes = DefaultArgumentPromotion(E);
965 if (ExprRes.isInvalid())
966 return ExprError();
967
968 // Copy blocks to the heap.
969 if (ExprRes.get()->getType()->isBlockPointerType())
970 maybeExtendBlockObject(ExprRes);
971
972 E = ExprRes.get();
973
974 // Diagnostics regarding non-POD argument types are
975 // emitted along with format string checking in Sema::CheckFunctionCall().
976 if (isValidVarArgType(E->getType()) == VAK_Undefined) {
977 // Turn this into a trap.
978 CXXScopeSpec SS;
979 SourceLocation TemplateKWLoc;
980 UnqualifiedId Name;
981 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
982 E->getBeginLoc());
983 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
984 /*HasTrailingLParen=*/true,
985 /*IsAddressOfOperand=*/false);
986 if (TrapFn.isInvalid())
987 return ExprError();
988
989 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
990 None, E->getEndLoc());
991 if (Call.isInvalid())
992 return ExprError();
993
994 ExprResult Comma =
995 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
996 if (Comma.isInvalid())
997 return ExprError();
998 return Comma.get();
999 }
1000
1001 if (!getLangOpts().CPlusPlus &&
1002 RequireCompleteType(E->getExprLoc(), E->getType(),
1003 diag::err_call_incomplete_argument))
1004 return ExprError();
1005
1006 return E;
1007}
1008
1009/// Converts an integer to complex float type. Helper function of
1010/// UsualArithmeticConversions()
1011///
1012/// \return false if the integer expression is an integer type and is
1013/// successfully converted to the complex type.
1014static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1015 ExprResult &ComplexExpr,
1016 QualType IntTy,
1017 QualType ComplexTy,
1018 bool SkipCast) {
1019 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1020 if (SkipCast) return false;
1021 if (IntTy->isIntegerType()) {
1022 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1023 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1024 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1025 CK_FloatingRealToComplex);
1026 } else {
1027 assert(IntTy->isComplexIntegerType())((IntTy->isComplexIntegerType()) ? static_cast<void>
(0) : __assert_fail ("IntTy->isComplexIntegerType()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 1027, __PRETTY_FUNCTION__))
;
1028 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1029 CK_IntegralComplexToFloatingComplex);
1030 }
1031 return false;
1032}
1033
1034/// Handle arithmetic conversion with complex types. Helper function of
1035/// UsualArithmeticConversions()
1036static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1037 ExprResult &RHS, QualType LHSType,
1038 QualType RHSType,
1039 bool IsCompAssign) {
1040 // if we have an integer operand, the result is the complex type.
1041 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1042 /*skipCast*/false))
1043 return LHSType;
1044 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1045 /*skipCast*/IsCompAssign))
1046 return RHSType;
1047
1048 // This handles complex/complex, complex/float, or float/complex.
1049 // When both operands are complex, the shorter operand is converted to the
1050 // type of the longer, and that is the type of the result. This corresponds
1051 // to what is done when combining two real floating-point operands.
1052 // The fun begins when size promotion occur across type domains.
1053 // From H&S 6.3.4: When one operand is complex and the other is a real
1054 // floating-point type, the less precise type is converted, within it's
1055 // real or complex domain, to the precision of the other type. For example,
1056 // when combining a "long double" with a "double _Complex", the
1057 // "double _Complex" is promoted to "long double _Complex".
1058
1059 // Compute the rank of the two types, regardless of whether they are complex.
1060 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1061
1062 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1063 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1064 QualType LHSElementType =
1065 LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1066 QualType RHSElementType =
1067 RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1068
1069 QualType ResultType = S.Context.getComplexType(LHSElementType);
1070 if (Order < 0) {
1071 // Promote the precision of the LHS if not an assignment.
1072 ResultType = S.Context.getComplexType(RHSElementType);
1073 if (!IsCompAssign) {
1074 if (LHSComplexType)
1075 LHS =
1076 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1077 else
1078 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1079 }
1080 } else if (Order > 0) {
1081 // Promote the precision of the RHS.
1082 if (RHSComplexType)
1083 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1084 else
1085 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1086 }
1087 return ResultType;
1088}
1089
1090/// Handle arithmetic conversion from integer to float. Helper function
1091/// of UsualArithmeticConversions()
1092static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1093 ExprResult &IntExpr,
1094 QualType FloatTy, QualType IntTy,
1095 bool ConvertFloat, bool ConvertInt) {
1096 if (IntTy->isIntegerType()) {
1097 if (ConvertInt)
1098 // Convert intExpr to the lhs floating point type.
1099 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1100 CK_IntegralToFloating);
1101 return FloatTy;
1102 }
1103
1104 // Convert both sides to the appropriate complex float.
1105 assert(IntTy->isComplexIntegerType())((IntTy->isComplexIntegerType()) ? static_cast<void>
(0) : __assert_fail ("IntTy->isComplexIntegerType()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 1105, __PRETTY_FUNCTION__))
;
1106 QualType result = S.Context.getComplexType(FloatTy);
1107
1108 // _Complex int -> _Complex float
1109 if (ConvertInt)
1110 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1111 CK_IntegralComplexToFloatingComplex);
1112
1113 // float -> _Complex float
1114 if (ConvertFloat)
1115 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1116 CK_FloatingRealToComplex);
1117
1118 return result;
1119}
1120
1121/// Handle arithmethic conversion with floating point types. Helper
1122/// function of UsualArithmeticConversions()
1123static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1124 ExprResult &RHS, QualType LHSType,
1125 QualType RHSType, bool IsCompAssign) {
1126 bool LHSFloat = LHSType->isRealFloatingType();
1127 bool RHSFloat = RHSType->isRealFloatingType();
1128
1129 // N1169 4.1.4: If one of the operands has a floating type and the other
1130 // operand has a fixed-point type, the fixed-point operand
1131 // is converted to the floating type [...]
1132 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1133 if (LHSFloat)
1134 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1135 else if (!IsCompAssign)
1136 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1137 return LHSFloat ? LHSType : RHSType;
1138 }
1139
1140 // If we have two real floating types, convert the smaller operand
1141 // to the bigger result.
1142 if (LHSFloat && RHSFloat) {
1143 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1144 if (order > 0) {
1145 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1146 return LHSType;
1147 }
1148
1149 assert(order < 0 && "illegal float comparison")((order < 0 && "illegal float comparison") ? static_cast
<void> (0) : __assert_fail ("order < 0 && \"illegal float comparison\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 1149, __PRETTY_FUNCTION__))
;
1150 if (!IsCompAssign)
1151 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1152 return RHSType;
1153 }
1154
1155 if (LHSFloat) {
1156 // Half FP has to be promoted to float unless it is natively supported
1157 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1158 LHSType = S.Context.FloatTy;
1159
1160 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1161 /*ConvertFloat=*/!IsCompAssign,
1162 /*ConvertInt=*/ true);
1163 }
1164 assert(RHSFloat)((RHSFloat) ? static_cast<void> (0) : __assert_fail ("RHSFloat"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 1164, __PRETTY_FUNCTION__))
;
1165 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1166 /*ConvertFloat=*/ true,
1167 /*ConvertInt=*/!IsCompAssign);
1168}
1169
1170/// Diagnose attempts to convert between __float128 and long double if
1171/// there is no support for such conversion. Helper function of
1172/// UsualArithmeticConversions().
1173static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1174 QualType RHSType) {
1175 /* No issue converting if at least one of the types is not a floating point
1176 type or the two types have the same rank.
1177 */
1178 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1179 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1180 return false;
1181
1182 assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&((LHSType->isFloatingType() && RHSType->isFloatingType
() && "The remaining types must be floating point types."
) ? static_cast<void> (0) : __assert_fail ("LHSType->isFloatingType() && RHSType->isFloatingType() && \"The remaining types must be floating point types.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 1183, __PRETTY_FUNCTION__))
1183 "The remaining types must be floating point types.")((LHSType->isFloatingType() && RHSType->isFloatingType
() && "The remaining types must be floating point types."
) ? static_cast<void> (0) : __assert_fail ("LHSType->isFloatingType() && RHSType->isFloatingType() && \"The remaining types must be floating point types.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 1183, __PRETTY_FUNCTION__))
;
1184
1185 auto *LHSComplex = LHSType->getAs<ComplexType>();
1186 auto *RHSComplex = RHSType->getAs<ComplexType>();
1187
1188 QualType LHSElemType = LHSComplex ?
1189 LHSComplex->getElementType() : LHSType;
1190 QualType RHSElemType = RHSComplex ?
1191 RHSComplex->getElementType() : RHSType;
1192
1193 // No issue if the two types have the same representation
1194 if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1195 &S.Context.getFloatTypeSemantics(RHSElemType))
1196 return false;
1197
1198 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1199 RHSElemType == S.Context.LongDoubleTy);
1200 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1201 RHSElemType == S.Context.Float128Ty);
1202
1203 // We've handled the situation where __float128 and long double have the same
1204 // representation. We allow all conversions for all possible long double types
1205 // except PPC's double double.
1206 return Float128AndLongDouble &&
1207 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1208 &llvm::APFloat::PPCDoubleDouble());
1209}
1210
1211typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1212
1213namespace {
1214/// These helper callbacks are placed in an anonymous namespace to
1215/// permit their use as function template parameters.
1216ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1217 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1218}
1219
1220ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1221 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1222 CK_IntegralComplexCast);
1223}
1224}
1225
1226/// Handle integer arithmetic conversions. Helper function of
1227/// UsualArithmeticConversions()
1228template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1229static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1230 ExprResult &RHS, QualType LHSType,
1231 QualType RHSType, bool IsCompAssign) {
1232 // The rules for this case are in C99 6.3.1.8
1233 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1234 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1235 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1236 if (LHSSigned == RHSSigned) {
1237 // Same signedness; use the higher-ranked type
1238 if (order >= 0) {
1239 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1240 return LHSType;
1241 } else if (!IsCompAssign)
1242 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1243 return RHSType;
1244 } else if (order != (LHSSigned ? 1 : -1)) {
1245 // The unsigned type has greater than or equal rank to the
1246 // signed type, so use the unsigned type
1247 if (RHSSigned) {
1248 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1249 return LHSType;
1250 } else if (!IsCompAssign)
1251 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1252 return RHSType;
1253 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1254 // The two types are different widths; if we are here, that
1255 // means the signed type is larger than the unsigned type, so
1256 // use the signed type.
1257 if (LHSSigned) {
1258 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1259 return LHSType;
1260 } else if (!IsCompAssign)
1261 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1262 return RHSType;
1263 } else {
1264 // The signed type is higher-ranked than the unsigned type,
1265 // but isn't actually any bigger (like unsigned int and long
1266 // on most 32-bit systems). Use the unsigned type corresponding
1267 // to the signed type.
1268 QualType result =
1269 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1270 RHS = (*doRHSCast)(S, RHS.get(), result);
1271 if (!IsCompAssign)
1272 LHS = (*doLHSCast)(S, LHS.get(), result);
1273 return result;
1274 }
1275}
1276
1277/// Handle conversions with GCC complex int extension. Helper function
1278/// of UsualArithmeticConversions()
1279static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1280 ExprResult &RHS, QualType LHSType,
1281 QualType RHSType,
1282 bool IsCompAssign) {
1283 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1284 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1285
1286 if (LHSComplexInt && RHSComplexInt) {
1287 QualType LHSEltType = LHSComplexInt->getElementType();
1288 QualType RHSEltType = RHSComplexInt->getElementType();
1289 QualType ScalarType =
1290 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1291 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1292
1293 return S.Context.getComplexType(ScalarType);
1294 }
1295
1296 if (LHSComplexInt) {
1297 QualType LHSEltType = LHSComplexInt->getElementType();
1298 QualType ScalarType =
1299 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1300 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1301 QualType ComplexType = S.Context.getComplexType(ScalarType);
1302 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1303 CK_IntegralRealToComplex);
1304
1305 return ComplexType;
1306 }
1307
1308 assert(RHSComplexInt)((RHSComplexInt) ? static_cast<void> (0) : __assert_fail
("RHSComplexInt", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 1308, __PRETTY_FUNCTION__))
;
1309
1310 QualType RHSEltType = RHSComplexInt->getElementType();
1311 QualType ScalarType =
1312 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1313 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1314 QualType ComplexType = S.Context.getComplexType(ScalarType);
1315
1316 if (!IsCompAssign)
1317 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1318 CK_IntegralRealToComplex);
1319 return ComplexType;
1320}
1321
1322/// Return the rank of a given fixed point or integer type. The value itself
1323/// doesn't matter, but the values must be increasing with proper increasing
1324/// rank as described in N1169 4.1.1.
1325static unsigned GetFixedPointRank(QualType Ty) {
1326 const auto *BTy = Ty->getAs<BuiltinType>();
1327 assert(BTy && "Expected a builtin type.")((BTy && "Expected a builtin type.") ? static_cast<
void> (0) : __assert_fail ("BTy && \"Expected a builtin type.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 1327, __PRETTY_FUNCTION__))
;
1328
1329 switch (BTy->getKind()) {
1330 case BuiltinType::ShortFract:
1331 case BuiltinType::UShortFract:
1332 case BuiltinType::SatShortFract:
1333 case BuiltinType::SatUShortFract:
1334 return 1;
1335 case BuiltinType::Fract:
1336 case BuiltinType::UFract:
1337 case BuiltinType::SatFract:
1338 case BuiltinType::SatUFract:
1339 return 2;
1340 case BuiltinType::LongFract:
1341 case BuiltinType::ULongFract:
1342 case BuiltinType::SatLongFract:
1343 case BuiltinType::SatULongFract:
1344 return 3;
1345 case BuiltinType::ShortAccum:
1346 case BuiltinType::UShortAccum:
1347 case BuiltinType::SatShortAccum:
1348 case BuiltinType::SatUShortAccum:
1349 return 4;
1350 case BuiltinType::Accum:
1351 case BuiltinType::UAccum:
1352 case BuiltinType::SatAccum:
1353 case BuiltinType::SatUAccum:
1354 return 5;
1355 case BuiltinType::LongAccum:
1356 case BuiltinType::ULongAccum:
1357 case BuiltinType::SatLongAccum:
1358 case BuiltinType::SatULongAccum:
1359 return 6;
1360 default:
1361 if (BTy->isInteger())
1362 return 0;
1363 llvm_unreachable("Unexpected fixed point or integer type")::llvm::llvm_unreachable_internal("Unexpected fixed point or integer type"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 1363)
;
1364 }
1365}
1366
1367/// handleFixedPointConversion - Fixed point operations between fixed
1368/// point types and integers or other fixed point types do not fall under
1369/// usual arithmetic conversion since these conversions could result in loss
1370/// of precsision (N1169 4.1.4). These operations should be calculated with
1371/// the full precision of their result type (N1169 4.1.6.2.1).
1372static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1373 QualType RHSTy) {
1374 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&(((LHSTy->isFixedPointType() || RHSTy->isFixedPointType
()) && "Expected at least one of the operands to be a fixed point type"
) ? static_cast<void> (0) : __assert_fail ("(LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && \"Expected at least one of the operands to be a fixed point type\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 1375, __PRETTY_FUNCTION__))
1375 "Expected at least one of the operands to be a fixed point type")(((LHSTy->isFixedPointType() || RHSTy->isFixedPointType
()) && "Expected at least one of the operands to be a fixed point type"
) ? static_cast<void> (0) : __assert_fail ("(LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && \"Expected at least one of the operands to be a fixed point type\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 1375, __PRETTY_FUNCTION__))
;
1376 assert((LHSTy->isFixedPointOrIntegerType() ||(((LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType
()) && "Special fixed point arithmetic operation conversions are only "
"applied to ints or other fixed point types") ? static_cast<
void> (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 1379, __PRETTY_FUNCTION__))
1377 RHSTy->isFixedPointOrIntegerType()) &&(((LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType
()) && "Special fixed point arithmetic operation conversions are only "
"applied to ints or other fixed point types") ? static_cast<
void> (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 1379, __PRETTY_FUNCTION__))
1378 "Special fixed point arithmetic operation conversions are only "(((LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType
()) && "Special fixed point arithmetic operation conversions are only "
"applied to ints or other fixed point types") ? static_cast<
void> (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 1379, __PRETTY_FUNCTION__))
1379 "applied to ints or other fixed point types")(((LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType
()) && "Special fixed point arithmetic operation conversions are only "
"applied to ints or other fixed point types") ? static_cast<
void> (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 1379, __PRETTY_FUNCTION__))
;
1380
1381 // If one operand has signed fixed-point type and the other operand has
1382 // unsigned fixed-point type, then the unsigned fixed-point operand is
1383 // converted to its corresponding signed fixed-point type and the resulting
1384 // type is the type of the converted operand.
1385 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1386 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1387 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1388 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1389
1390 // The result type is the type with the highest rank, whereby a fixed-point
1391 // conversion rank is always greater than an integer conversion rank; if the
1392 // type of either of the operands is a saturating fixedpoint type, the result
1393 // type shall be the saturating fixed-point type corresponding to the type
1394 // with the highest rank; the resulting value is converted (taking into
1395 // account rounding and overflow) to the precision of the resulting type.
1396 // Same ranks between signed and unsigned types are resolved earlier, so both
1397 // types are either signed or both unsigned at this point.
1398 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1399 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1400
1401 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1402
1403 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1404 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1405
1406 return ResultTy;
1407}
1408
1409/// Check that the usual arithmetic conversions can be performed on this pair of
1410/// expressions that might be of enumeration type.
1411static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1412 SourceLocation Loc,
1413 Sema::ArithConvKind ACK) {
1414 // C++2a [expr.arith.conv]p1:
1415 // If one operand is of enumeration type and the other operand is of a
1416 // different enumeration type or a floating-point type, this behavior is
1417 // deprecated ([depr.arith.conv.enum]).
1418 //
1419 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1420 // Eventually we will presumably reject these cases (in C++23 onwards?).
1421 QualType L = LHS->getType(), R = RHS->getType();
1422 bool LEnum = L->isUnscopedEnumerationType(),
1423 REnum = R->isUnscopedEnumerationType();
1424 bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1425 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1426 (REnum && L->isFloatingType())) {
1427 S.Diag(Loc, S.getLangOpts().CPlusPlus20
1428 ? diag::warn_arith_conv_enum_float_cxx20
1429 : diag::warn_arith_conv_enum_float)
1430 << LHS->getSourceRange() << RHS->getSourceRange()
1431 << (int)ACK << LEnum << L << R;
1432 } else if (!IsCompAssign && LEnum && REnum &&
1433 !S.Context.hasSameUnqualifiedType(L, R)) {
1434 unsigned DiagID;
1435 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1436 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1437 // If either enumeration type is unnamed, it's less likely that the
1438 // user cares about this, but this situation is still deprecated in
1439 // C++2a. Use a different warning group.
1440 DiagID = S.getLangOpts().CPlusPlus20
1441 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1442 : diag::warn_arith_conv_mixed_anon_enum_types;
1443 } else if (ACK == Sema::ACK_Conditional) {
1444 // Conditional expressions are separated out because they have
1445 // historically had a different warning flag.
1446 DiagID = S.getLangOpts().CPlusPlus20
1447 ? diag::warn_conditional_mixed_enum_types_cxx20
1448 : diag::warn_conditional_mixed_enum_types;
1449 } else if (ACK == Sema::ACK_Comparison) {
1450 // Comparison expressions are separated out because they have
1451 // historically had a different warning flag.
1452 DiagID = S.getLangOpts().CPlusPlus20
1453 ? diag::warn_comparison_mixed_enum_types_cxx20
1454 : diag::warn_comparison_mixed_enum_types;
1455 } else {
1456 DiagID = S.getLangOpts().CPlusPlus20
1457 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1458 : diag::warn_arith_conv_mixed_enum_types;
1459 }
1460 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1461 << (int)ACK << L << R;
1462 }
1463}
1464
1465/// UsualArithmeticConversions - Performs various conversions that are common to
1466/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1467/// routine returns the first non-arithmetic type found. The client is
1468/// responsible for emitting appropriate error diagnostics.
1469QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1470 SourceLocation Loc,
1471 ArithConvKind ACK) {
1472 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1473
1474 if (ACK != ACK_CompAssign) {
1475 LHS = UsualUnaryConversions(LHS.get());
1476 if (LHS.isInvalid())
1477 return QualType();
1478 }
1479
1480 RHS = UsualUnaryConversions(RHS.get());
1481 if (RHS.isInvalid())
1482 return QualType();
1483
1484 // For conversion purposes, we ignore any qualifiers.
1485 // For example, "const float" and "float" are equivalent.
1486 QualType LHSType =
1487 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1488 QualType RHSType =
1489 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1490
1491 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1492 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1493 LHSType = AtomicLHS->getValueType();
1494
1495 // If both types are identical, no conversion is needed.
1496 if (LHSType == RHSType)
1497 return LHSType;
1498
1499 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1500 // The caller can deal with this (e.g. pointer + int).
1501 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1502 return QualType();
1503
1504 // Apply unary and bitfield promotions to the LHS's type.
1505 QualType LHSUnpromotedType = LHSType;
1506 if (LHSType->isPromotableIntegerType())
1507 LHSType = Context.getPromotedIntegerType(LHSType);
1508 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1509 if (!LHSBitfieldPromoteTy.isNull())
1510 LHSType = LHSBitfieldPromoteTy;
1511 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1512 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1513
1514 // If both types are identical, no conversion is needed.
1515 if (LHSType == RHSType)
1516 return LHSType;
1517
1518 // ExtInt types aren't subject to conversions between them or normal integers,
1519 // so this fails.
1520 if(LHSType->isExtIntType() || RHSType->isExtIntType())
1521 return QualType();
1522
1523 // At this point, we have two different arithmetic types.
1524
1525 // Diagnose attempts to convert between __float128 and long double where
1526 // such conversions currently can't be handled.
1527 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1528 return QualType();
1529
1530 // Handle complex types first (C99 6.3.1.8p1).
1531 if (LHSType->isComplexType() || RHSType->isComplexType())
1532 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1533 ACK == ACK_CompAssign);
1534
1535 // Now handle "real" floating types (i.e. float, double, long double).
1536 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1537 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1538 ACK == ACK_CompAssign);
1539
1540 // Handle GCC complex int extension.
1541 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1542 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1543 ACK == ACK_CompAssign);
1544
1545 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1546 return handleFixedPointConversion(*this, LHSType, RHSType);
1547
1548 // Finally, we have two differing integer types.
1549 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1550 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1551}
1552
1553//===----------------------------------------------------------------------===//
1554// Semantic Analysis for various Expression Types
1555//===----------------------------------------------------------------------===//
1556
1557
1558ExprResult
1559Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1560 SourceLocation DefaultLoc,
1561 SourceLocation RParenLoc,
1562 Expr *ControllingExpr,
1563 ArrayRef<ParsedType> ArgTypes,
1564 ArrayRef<Expr *> ArgExprs) {
1565 unsigned NumAssocs = ArgTypes.size();
1566 assert(NumAssocs == ArgExprs.size())((NumAssocs == ArgExprs.size()) ? static_cast<void> (0)
: __assert_fail ("NumAssocs == ArgExprs.size()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 1566, __PRETTY_FUNCTION__))
;
1567
1568 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1569 for (unsigned i = 0; i < NumAssocs; ++i) {
1570 if (ArgTypes[i])
1571 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1572 else
1573 Types[i] = nullptr;
1574 }
1575
1576 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1577 ControllingExpr,
1578 llvm::makeArrayRef(Types, NumAssocs),
1579 ArgExprs);
1580 delete [] Types;
1581 return ER;
1582}
1583
1584ExprResult
1585Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1586 SourceLocation DefaultLoc,
1587 SourceLocation RParenLoc,
1588 Expr *ControllingExpr,
1589 ArrayRef<TypeSourceInfo *> Types,
1590 ArrayRef<Expr *> Exprs) {
1591 unsigned NumAssocs = Types.size();
1592 assert(NumAssocs == Exprs.size())((NumAssocs == Exprs.size()) ? static_cast<void> (0) : __assert_fail
("NumAssocs == Exprs.size()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 1592, __PRETTY_FUNCTION__))
;
1593
1594 // Decay and strip qualifiers for the controlling expression type, and handle
1595 // placeholder type replacement. See committee discussion from WG14 DR423.
1596 {
1597 EnterExpressionEvaluationContext Unevaluated(
1598 *this, Sema::ExpressionEvaluationContext::Unevaluated);
1599 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1600 if (R.isInvalid())
1601 return ExprError();
1602 ControllingExpr = R.get();
1603 }
1604
1605 // The controlling expression is an unevaluated operand, so side effects are
1606 // likely unintended.
1607 if (!inTemplateInstantiation() &&
1608 ControllingExpr->HasSideEffects(Context, false))
1609 Diag(ControllingExpr->getExprLoc(),
1610 diag::warn_side_effects_unevaluated_context);
1611
1612 bool TypeErrorFound = false,
1613 IsResultDependent = ControllingExpr->isTypeDependent(),
1614 ContainsUnexpandedParameterPack
1615 = ControllingExpr->containsUnexpandedParameterPack();
1616
1617 for (unsigned i = 0; i < NumAssocs; ++i) {
1618 if (Exprs[i]->containsUnexpandedParameterPack())
1619 ContainsUnexpandedParameterPack = true;
1620
1621 if (Types[i]) {
1622 if (Types[i]->getType()->containsUnexpandedParameterPack())
1623 ContainsUnexpandedParameterPack = true;
1624
1625 if (Types[i]->getType()->isDependentType()) {
1626 IsResultDependent = true;
1627 } else {
1628 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1629 // complete object type other than a variably modified type."
1630 unsigned D = 0;
1631 if (Types[i]->getType()->isIncompleteType())
1632 D = diag::err_assoc_type_incomplete;
1633 else if (!Types[i]->getType()->isObjectType())
1634 D = diag::err_assoc_type_nonobject;
1635 else if (Types[i]->getType()->isVariablyModifiedType())
1636 D = diag::err_assoc_type_variably_modified;
1637
1638 if (D != 0) {
1639 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1640 << Types[i]->getTypeLoc().getSourceRange()
1641 << Types[i]->getType();
1642 TypeErrorFound = true;
1643 }
1644
1645 // C11 6.5.1.1p2 "No two generic associations in the same generic
1646 // selection shall specify compatible types."
1647 for (unsigned j = i+1; j < NumAssocs; ++j)
1648 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1649 Context.typesAreCompatible(Types[i]->getType(),
1650 Types[j]->getType())) {
1651 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1652 diag::err_assoc_compatible_types)
1653 << Types[j]->getTypeLoc().getSourceRange()
1654 << Types[j]->getType()
1655 << Types[i]->getType();
1656 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1657 diag::note_compat_assoc)
1658 << Types[i]->getTypeLoc().getSourceRange()
1659 << Types[i]->getType();
1660 TypeErrorFound = true;
1661 }
1662 }
1663 }
1664 }
1665 if (TypeErrorFound)
1666 return ExprError();
1667
1668 // If we determined that the generic selection is result-dependent, don't
1669 // try to compute the result expression.
1670 if (IsResultDependent)
1671 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1672 Exprs, DefaultLoc, RParenLoc,
1673 ContainsUnexpandedParameterPack);
1674
1675 SmallVector<unsigned, 1> CompatIndices;
1676 unsigned DefaultIndex = -1U;
1677 for (unsigned i = 0; i < NumAssocs; ++i) {
1678 if (!Types[i])
1679 DefaultIndex = i;
1680 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1681 Types[i]->getType()))
1682 CompatIndices.push_back(i);
1683 }
1684
1685 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1686 // type compatible with at most one of the types named in its generic
1687 // association list."
1688 if (CompatIndices.size() > 1) {
1689 // We strip parens here because the controlling expression is typically
1690 // parenthesized in macro definitions.
1691 ControllingExpr = ControllingExpr->IgnoreParens();
1692 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1693 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1694 << (unsigned)CompatIndices.size();
1695 for (unsigned I : CompatIndices) {
1696 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1697 diag::note_compat_assoc)
1698 << Types[I]->getTypeLoc().getSourceRange()
1699 << Types[I]->getType();
1700 }
1701 return ExprError();
1702 }
1703
1704 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1705 // its controlling expression shall have type compatible with exactly one of
1706 // the types named in its generic association list."
1707 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1708 // We strip parens here because the controlling expression is typically
1709 // parenthesized in macro definitions.
1710 ControllingExpr = ControllingExpr->IgnoreParens();
1711 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1712 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1713 return ExprError();
1714 }
1715
1716 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1717 // type name that is compatible with the type of the controlling expression,
1718 // then the result expression of the generic selection is the expression
1719 // in that generic association. Otherwise, the result expression of the
1720 // generic selection is the expression in the default generic association."
1721 unsigned ResultIndex =
1722 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1723
1724 return GenericSelectionExpr::Create(
1725 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1726 ContainsUnexpandedParameterPack, ResultIndex);
1727}
1728
1729/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1730/// location of the token and the offset of the ud-suffix within it.
1731static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1732 unsigned Offset) {
1733 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1734 S.getLangOpts());
1735}
1736
1737/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1738/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1739static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1740 IdentifierInfo *UDSuffix,
1741 SourceLocation UDSuffixLoc,
1742 ArrayRef<Expr*> Args,
1743 SourceLocation LitEndLoc) {
1744 assert(Args.size() <= 2 && "too many arguments for literal operator")((Args.size() <= 2 && "too many arguments for literal operator"
) ? static_cast<void> (0) : __assert_fail ("Args.size() <= 2 && \"too many arguments for literal operator\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 1744, __PRETTY_FUNCTION__))
;
1745
1746 QualType ArgTy[2];
1747 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1748 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1749 if (ArgTy[ArgIdx]->isArrayType())
1750 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1751 }
1752
1753 DeclarationName OpName =
1754 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1755 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1756 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1757
1758 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1759 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1760 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1761 /*AllowStringTemplatePack*/ false,
1762 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1763 return ExprError();
1764
1765 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1766}
1767
1768/// ActOnStringLiteral - The specified tokens were lexed as pasted string
1769/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1770/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1771/// multiple tokens. However, the common case is that StringToks points to one
1772/// string.
1773///
1774ExprResult
1775Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1776 assert(!StringToks.empty() && "Must have at least one string!")((!StringToks.empty() && "Must have at least one string!"
) ? static_cast<void> (0) : __assert_fail ("!StringToks.empty() && \"Must have at least one string!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 1776, __PRETTY_FUNCTION__))
;
1777
1778 StringLiteralParser Literal(StringToks, PP);
1779 if (Literal.hadError)
1780 return ExprError();
1781
1782 SmallVector<SourceLocation, 4> StringTokLocs;
1783 for (const Token &Tok : StringToks)
1784 StringTokLocs.push_back(Tok.getLocation());
1785
1786 QualType CharTy = Context.CharTy;
1787 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1788 if (Literal.isWide()) {
1789 CharTy = Context.getWideCharType();
1790 Kind = StringLiteral::Wide;
1791 } else if (Literal.isUTF8()) {
1792 if (getLangOpts().Char8)
1793 CharTy = Context.Char8Ty;
1794 Kind = StringLiteral::UTF8;
1795 } else if (Literal.isUTF16()) {
1796 CharTy = Context.Char16Ty;
1797 Kind = StringLiteral::UTF16;
1798 } else if (Literal.isUTF32()) {
1799 CharTy = Context.Char32Ty;
1800 Kind = StringLiteral::UTF32;
1801 } else if (Literal.isPascal()) {
1802 CharTy = Context.UnsignedCharTy;
1803 }
1804
1805 // Warn on initializing an array of char from a u8 string literal; this
1806 // becomes ill-formed in C++2a.
1807 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
1808 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1809 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
1810
1811 // Create removals for all 'u8' prefixes in the string literal(s). This
1812 // ensures C++2a compatibility (but may change the program behavior when
1813 // built by non-Clang compilers for which the execution character set is
1814 // not always UTF-8).
1815 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
1816 SourceLocation RemovalDiagLoc;
1817 for (const Token &Tok : StringToks) {
1818 if (Tok.getKind() == tok::utf8_string_literal) {
1819 if (RemovalDiagLoc.isInvalid())
1820 RemovalDiagLoc = Tok.getLocation();
1821 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1822 Tok.getLocation(),
1823 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1824 getSourceManager(), getLangOpts())));
1825 }
1826 }
1827 Diag(RemovalDiagLoc, RemovalDiag);
1828 }
1829
1830 QualType StrTy =
1831 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1832
1833 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1834 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1835 Kind, Literal.Pascal, StrTy,
1836 &StringTokLocs[0],
1837 StringTokLocs.size());
1838 if (Literal.getUDSuffix().empty())
1839 return Lit;
1840
1841 // We're building a user-defined literal.
1842 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1843 SourceLocation UDSuffixLoc =
1844 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1845 Literal.getUDSuffixOffset());
1846
1847 // Make sure we're allowed user-defined literals here.
1848 if (!UDLScope)
1849 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1850
1851 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1852 // operator "" X (str, len)
1853 QualType SizeType = Context.getSizeType();
1854
1855 DeclarationName OpName =
1856 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1857 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1858 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1859
1860 QualType ArgTy[] = {
1861 Context.getArrayDecayedType(StrTy), SizeType
1862 };
1863
1864 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1865 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1866 /*AllowRaw*/ false, /*AllowTemplate*/ true,
1867 /*AllowStringTemplatePack*/ true,
1868 /*DiagnoseMissing*/ true, Lit)) {
1869
1870 case LOLR_Cooked: {
1871 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1872 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1873 StringTokLocs[0]);
1874 Expr *Args[] = { Lit, LenArg };
1875
1876 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1877 }
1878
1879 case LOLR_Template: {
1880 TemplateArgumentListInfo ExplicitArgs;
1881 TemplateArgument Arg(Lit);
1882 TemplateArgumentLocInfo ArgInfo(Lit);
1883 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1884 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1885 &ExplicitArgs);
1886 }
1887
1888 case LOLR_StringTemplatePack: {
1889 TemplateArgumentListInfo ExplicitArgs;
1890
1891 unsigned CharBits = Context.getIntWidth(CharTy);
1892 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1893 llvm::APSInt Value(CharBits, CharIsUnsigned);
1894
1895 TemplateArgument TypeArg(CharTy);
1896 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1897 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1898
1899 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1900 Value = Lit->getCodeUnit(I);
1901 TemplateArgument Arg(Context, Value, CharTy);
1902 TemplateArgumentLocInfo ArgInfo;
1903 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1904 }
1905 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1906 &ExplicitArgs);
1907 }
1908 case LOLR_Raw:
1909 case LOLR_ErrorNoDiagnostic:
1910 llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 1910)
;
1911 case LOLR_Error:
1912 return ExprError();
1913 }
1914 llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 1914)
;
1915}
1916
1917DeclRefExpr *
1918Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1919 SourceLocation Loc,
1920 const CXXScopeSpec *SS) {
1921 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1922 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1923}
1924
1925DeclRefExpr *
1926Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1927 const DeclarationNameInfo &NameInfo,
1928 const CXXScopeSpec *SS, NamedDecl *FoundD,
1929 SourceLocation TemplateKWLoc,
1930 const TemplateArgumentListInfo *TemplateArgs) {
1931 NestedNameSpecifierLoc NNS =
1932 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1933 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1934 TemplateArgs);
1935}
1936
1937NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
1938 // A declaration named in an unevaluated operand never constitutes an odr-use.
1939 if (isUnevaluatedContext())
1940 return NOUR_Unevaluated;
1941
1942 // C++2a [basic.def.odr]p4:
1943 // A variable x whose name appears as a potentially-evaluated expression e
1944 // is odr-used by e unless [...] x is a reference that is usable in
1945 // constant expressions.
1946 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1947 if (VD->getType()->isReferenceType() &&
1948 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
1949 VD->isUsableInConstantExpressions(Context))
1950 return NOUR_Constant;
1951 }
1952
1953 // All remaining non-variable cases constitute an odr-use. For variables, we
1954 // need to wait and see how the expression is used.
1955 return NOUR_None;
1956}
1957
1958/// BuildDeclRefExpr - Build an expression that references a
1959/// declaration that does not require a closure capture.
1960DeclRefExpr *
1961Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1962 const DeclarationNameInfo &NameInfo,
1963 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
1964 SourceLocation TemplateKWLoc,
1965 const TemplateArgumentListInfo *TemplateArgs) {
1966 bool RefersToCapturedVariable =
1967 isa<VarDecl>(D) &&
1968 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1969
1970 DeclRefExpr *E = DeclRefExpr::Create(
1971 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
1972 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
1973 MarkDeclRefReferenced(E);
1974
1975 // C++ [except.spec]p17:
1976 // An exception-specification is considered to be needed when:
1977 // - in an expression, the function is the unique lookup result or
1978 // the selected member of a set of overloaded functions.
1979 //
1980 // We delay doing this until after we've built the function reference and
1981 // marked it as used so that:
1982 // a) if the function is defaulted, we get errors from defining it before /
1983 // instead of errors from computing its exception specification, and
1984 // b) if the function is a defaulted comparison, we can use the body we
1985 // build when defining it as input to the exception specification
1986 // computation rather than computing a new body.
1987 if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
1988 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
1989 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
1990 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
1991 }
1992 }
1993
1994 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1995 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1996 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
1997 getCurFunction()->recordUseOfWeak(E);
1998
1999 FieldDecl *FD = dyn_cast<FieldDecl>(D);
2000 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
2001 FD = IFD->getAnonField();
2002 if (FD) {
2003 UnusedPrivateFields.remove(FD);
2004 // Just in case we're building an illegal pointer-to-member.
2005 if (FD->isBitField())
2006 E->setObjectKind(OK_BitField);
2007 }
2008
2009 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2010 // designates a bit-field.
2011 if (auto *BD = dyn_cast<BindingDecl>(D))
2012 if (auto *BE = BD->getBinding())
2013 E->setObjectKind(BE->getObjectKind());
2014
2015 return E;
2016}
2017
2018/// Decomposes the given name into a DeclarationNameInfo, its location, and
2019/// possibly a list of template arguments.
2020///
2021/// If this produces template arguments, it is permitted to call
2022/// DecomposeTemplateName.
2023///
2024/// This actually loses a lot of source location information for
2025/// non-standard name kinds; we should consider preserving that in
2026/// some way.
2027void
2028Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2029 TemplateArgumentListInfo &Buffer,
2030 DeclarationNameInfo &NameInfo,
2031 const TemplateArgumentListInfo *&TemplateArgs) {
2032 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2033 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2034 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2035
2036 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2037 Id.TemplateId->NumArgs);
2038 translateTemplateArguments(TemplateArgsPtr, Buffer);
2039
2040 TemplateName TName = Id.TemplateId->Template.get();
2041 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2042 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2043 TemplateArgs = &Buffer;
2044 } else {
2045 NameInfo = GetNameFromUnqualifiedId(Id);
2046 TemplateArgs = nullptr;
2047 }
2048}
2049
2050static void emitEmptyLookupTypoDiagnostic(
2051 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2052 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2053 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2054 DeclContext *Ctx =
2055 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2056 if (!TC) {
2057 // Emit a special diagnostic for failed member lookups.
2058 // FIXME: computing the declaration context might fail here (?)
2059 if (Ctx)
2060 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2061 << SS.getRange();
2062 else
2063 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2064 return;
2065 }
2066
2067 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2068 bool DroppedSpecifier =
2069 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2070 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2071 ? diag::note_implicit_param_decl
2072 : diag::note_previous_decl;
2073 if (!Ctx)
2074 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2075 SemaRef.PDiag(NoteID));
2076 else
2077 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2078 << Typo << Ctx << DroppedSpecifier
2079 << SS.getRange(),
2080 SemaRef.PDiag(NoteID));
2081}
2082
2083/// Diagnose an empty lookup.
2084///
2085/// \return false if new lookup candidates were found
2086bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2087 CorrectionCandidateCallback &CCC,
2088 TemplateArgumentListInfo *ExplicitTemplateArgs,
2089 ArrayRef<Expr *> Args, TypoExpr **Out) {
2090 DeclarationName Name = R.getLookupName();
2091
2092 unsigned diagnostic = diag::err_undeclared_var_use;
2093 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2094 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2095 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2096 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2097 diagnostic = diag::err_undeclared_use;
2098 diagnostic_suggest = diag::err_undeclared_use_suggest;
2099 }
2100
2101 // If the original lookup was an unqualified lookup, fake an
2102 // unqualified lookup. This is useful when (for example) the
2103 // original lookup would not have found something because it was a
2104 // dependent name.
2105 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2106 while (DC) {
2107 if (isa<CXXRecordDecl>(DC)) {
2108 LookupQualifiedName(R, DC);
2109
2110 if (!R.empty()) {
2111 // Don't give errors about ambiguities in this lookup.
2112 R.suppressDiagnostics();
2113
2114 // During a default argument instantiation the CurContext points
2115 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2116 // function parameter list, hence add an explicit check.
2117 bool isDefaultArgument =
2118 !CodeSynthesisContexts.empty() &&
2119 CodeSynthesisContexts.back().Kind ==
2120 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2121 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2122 bool isInstance = CurMethod &&
2123 CurMethod->isInstance() &&
2124 DC == CurMethod->getParent() && !isDefaultArgument;
2125
2126 // Give a code modification hint to insert 'this->'.
2127 // TODO: fixit for inserting 'Base<T>::' in the other cases.
2128 // Actually quite difficult!
2129 if (getLangOpts().MSVCCompat)
2130 diagnostic = diag::ext_found_via_dependent_bases_lookup;
2131 if (isInstance) {
2132 Diag(R.getNameLoc(), diagnostic) << Name
2133 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2134 CheckCXXThisCapture(R.getNameLoc());
2135 } else {
2136 Diag(R.getNameLoc(), diagnostic) << Name;
2137 }
2138
2139 // Do we really want to note all of these?
2140 for (NamedDecl *D : R)
2141 Diag(D->getLocation(), diag::note_dependent_var_use);
2142
2143 // Return true if we are inside a default argument instantiation
2144 // and the found name refers to an instance member function, otherwise
2145 // the function calling DiagnoseEmptyLookup will try to create an
2146 // implicit member call and this is wrong for default argument.
2147 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2148 Diag(R.getNameLoc(), diag::err_member_call_without_object);
2149 return true;
2150 }
2151
2152 // Tell the callee to try to recover.
2153 return false;
2154 }
2155
2156 R.clear();
2157 }
2158
2159 DC = DC->getLookupParent();
2160 }
2161
2162 // We didn't find anything, so try to correct for a typo.
2163 TypoCorrection Corrected;
2164 if (S && Out) {
2165 SourceLocation TypoLoc = R.getNameLoc();
2166 assert(!ExplicitTemplateArgs &&((!ExplicitTemplateArgs && "Diagnosing an empty lookup with explicit template args!"
) ? static_cast<void> (0) : __assert_fail ("!ExplicitTemplateArgs && \"Diagnosing an empty lookup with explicit template args!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 2167, __PRETTY_FUNCTION__))
2167 "Diagnosing an empty lookup with explicit template args!")((!ExplicitTemplateArgs && "Diagnosing an empty lookup with explicit template args!"
) ? static_cast<void> (0) : __assert_fail ("!ExplicitTemplateArgs && \"Diagnosing an empty lookup with explicit template args!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 2167, __PRETTY_FUNCTION__))
;
2168 *Out = CorrectTypoDelayed(
2169 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2170 [=](const TypoCorrection &TC) {
2171 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2172 diagnostic, diagnostic_suggest);
2173 },
2174 nullptr, CTK_ErrorRecovery);
2175 if (*Out)
2176 return true;
2177 } else if (S &&
2178 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2179 S, &SS, CCC, CTK_ErrorRecovery))) {
2180 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2181 bool DroppedSpecifier =
2182 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2183 R.setLookupName(Corrected.getCorrection());
2184
2185 bool AcceptableWithRecovery = false;
2186 bool AcceptableWithoutRecovery = false;
2187 NamedDecl *ND = Corrected.getFoundDecl();
2188 if (ND) {
2189 if (Corrected.isOverloaded()) {
2190 OverloadCandidateSet OCS(R.getNameLoc(),
2191 OverloadCandidateSet::CSK_Normal);
2192 OverloadCandidateSet::iterator Best;
2193 for (NamedDecl *CD : Corrected) {
2194 if (FunctionTemplateDecl *FTD =
2195 dyn_cast<FunctionTemplateDecl>(CD))
2196 AddTemplateOverloadCandidate(
2197 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2198 Args, OCS);
2199 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2200 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2201 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2202 Args, OCS);
2203 }
2204 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2205 case OR_Success:
2206 ND = Best->FoundDecl;
2207 Corrected.setCorrectionDecl(ND);
2208 break;
2209 default:
2210 // FIXME: Arbitrarily pick the first declaration for the note.
2211 Corrected.setCorrectionDecl(ND);
2212 break;
2213 }
2214 }
2215 R.addDecl(ND);
2216 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2217 CXXRecordDecl *Record = nullptr;
2218 if (Corrected.getCorrectionSpecifier()) {
2219 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2220 Record = Ty->getAsCXXRecordDecl();
2221 }
2222 if (!Record)
2223 Record = cast<CXXRecordDecl>(
2224 ND->getDeclContext()->getRedeclContext());
2225 R.setNamingClass(Record);
2226 }
2227
2228 auto *UnderlyingND = ND->getUnderlyingDecl();
2229 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2230 isa<FunctionTemplateDecl>(UnderlyingND);
2231 // FIXME: If we ended up with a typo for a type name or
2232 // Objective-C class name, we're in trouble because the parser
2233 // is in the wrong place to recover. Suggest the typo
2234 // correction, but don't make it a fix-it since we're not going
2235 // to recover well anyway.
2236 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2237 getAsTypeTemplateDecl(UnderlyingND) ||
2238 isa<ObjCInterfaceDecl>(UnderlyingND);
2239 } else {
2240 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2241 // because we aren't able to recover.
2242 AcceptableWithoutRecovery = true;
2243 }
2244
2245 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2246 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2247 ? diag::note_implicit_param_decl
2248 : diag::note_previous_decl;
2249 if (SS.isEmpty())
2250 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2251 PDiag(NoteID), AcceptableWithRecovery);
2252 else
2253 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2254 << Name << computeDeclContext(SS, false)
2255 << DroppedSpecifier << SS.getRange(),
2256 PDiag(NoteID), AcceptableWithRecovery);
2257
2258 // Tell the callee whether to try to recover.
2259 return !AcceptableWithRecovery;
2260 }
2261 }
2262 R.clear();
2263
2264 // Emit a special diagnostic for failed member lookups.
2265 // FIXME: computing the declaration context might fail here (?)
2266 if (!SS.isEmpty()) {
2267 Diag(R.getNameLoc(), diag::err_no_member)
2268 << Name << computeDeclContext(SS, false)
2269 << SS.getRange();
2270 return true;
2271 }
2272
2273 // Give up, we can't recover.
2274 Diag(R.getNameLoc(), diagnostic) << Name;
2275 return true;
2276}
2277
2278/// In Microsoft mode, if we are inside a template class whose parent class has
2279/// dependent base classes, and we can't resolve an unqualified identifier, then
2280/// assume the identifier is a member of a dependent base class. We can only
2281/// recover successfully in static methods, instance methods, and other contexts
2282/// where 'this' is available. This doesn't precisely match MSVC's
2283/// instantiation model, but it's close enough.
2284static Expr *
2285recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2286 DeclarationNameInfo &NameInfo,
2287 SourceLocation TemplateKWLoc,
2288 const TemplateArgumentListInfo *TemplateArgs) {
2289 // Only try to recover from lookup into dependent bases in static methods or
2290 // contexts where 'this' is available.
2291 QualType ThisType = S.getCurrentThisType();
2292 const CXXRecordDecl *RD = nullptr;
2293 if (!ThisType.isNull())
2294 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2295 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2296 RD = MD->getParent();
2297 if (!RD || !RD->hasAnyDependentBases())
2298 return nullptr;
2299
2300 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2301 // is available, suggest inserting 'this->' as a fixit.
2302 SourceLocation Loc = NameInfo.getLoc();
2303 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2304 DB << NameInfo.getName() << RD;
2305
2306 if (!ThisType.isNull()) {
2307 DB << FixItHint::CreateInsertion(Loc, "this->");
2308 return CXXDependentScopeMemberExpr::Create(
2309 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2310 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2311 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2312 }
2313
2314 // Synthesize a fake NNS that points to the derived class. This will
2315 // perform name lookup during template instantiation.
2316 CXXScopeSpec SS;
2317 auto *NNS =
2318 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2319 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2320 return DependentScopeDeclRefExpr::Create(
2321 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2322 TemplateArgs);
2323}
2324
2325ExprResult
2326Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2327 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2328 bool HasTrailingLParen, bool IsAddressOfOperand,
2329 CorrectionCandidateCallback *CCC,
2330 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2331 assert(!(IsAddressOfOperand && HasTrailingLParen) &&((!(IsAddressOfOperand && HasTrailingLParen) &&
"cannot be direct & operand and have a trailing lparen")
? static_cast<void> (0) : __assert_fail ("!(IsAddressOfOperand && HasTrailingLParen) && \"cannot be direct & operand and have a trailing lparen\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 2332, __PRETTY_FUNCTION__))
2332 "cannot be direct & operand and have a trailing lparen")((!(IsAddressOfOperand && HasTrailingLParen) &&
"cannot be direct & operand and have a trailing lparen")
? static_cast<void> (0) : __assert_fail ("!(IsAddressOfOperand && HasTrailingLParen) && \"cannot be direct & operand and have a trailing lparen\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 2332, __PRETTY_FUNCTION__))
;
2333 if (SS.isInvalid())
2334 return ExprError();
2335
2336 TemplateArgumentListInfo TemplateArgsBuffer;
2337
2338 // Decompose the UnqualifiedId into the following data.
2339 DeclarationNameInfo NameInfo;
2340 const TemplateArgumentListInfo *TemplateArgs;
2341 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2342
2343 DeclarationName Name = NameInfo.getName();
2344 IdentifierInfo *II = Name.getAsIdentifierInfo();
2345 SourceLocation NameLoc = NameInfo.getLoc();
2346
2347 if (II && II->isEditorPlaceholder()) {
2348 // FIXME: When typed placeholders are supported we can create a typed
2349 // placeholder expression node.
2350 return ExprError();
2351 }
2352
2353 // C++ [temp.dep.expr]p3:
2354 // An id-expression is type-dependent if it contains:
2355 // -- an identifier that was declared with a dependent type,
2356 // (note: handled after lookup)
2357 // -- a template-id that is dependent,
2358 // (note: handled in BuildTemplateIdExpr)
2359 // -- a conversion-function-id that specifies a dependent type,
2360 // -- a nested-name-specifier that contains a class-name that
2361 // names a dependent type.
2362 // Determine whether this is a member of an unknown specialization;
2363 // we need to handle these differently.
2364 bool DependentID = false;
2365 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2366 Name.getCXXNameType()->isDependentType()) {
2367 DependentID = true;
2368 } else if (SS.isSet()) {
2369 if (DeclContext *DC = computeDeclContext(SS, false)) {
2370 if (RequireCompleteDeclContext(SS, DC))
2371 return ExprError();
2372 } else {
2373 DependentID = true;
2374 }
2375 }
2376
2377 if (DependentID)
2378 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2379 IsAddressOfOperand, TemplateArgs);
2380
2381 // Perform the required lookup.
2382 LookupResult R(*this, NameInfo,
2383 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2384 ? LookupObjCImplicitSelfParam
2385 : LookupOrdinaryName);
2386 if (TemplateKWLoc.isValid() || TemplateArgs) {
2387 // Lookup the template name again to correctly establish the context in
2388 // which it was found. This is really unfortunate as we already did the
2389 // lookup to determine that it was a template name in the first place. If
2390 // this becomes a performance hit, we can work harder to preserve those
2391 // results until we get here but it's likely not worth it.
2392 bool MemberOfUnknownSpecialization;
2393 AssumedTemplateKind AssumedTemplate;
2394 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2395 MemberOfUnknownSpecialization, TemplateKWLoc,
2396 &AssumedTemplate))
2397 return ExprError();
2398
2399 if (MemberOfUnknownSpecialization ||
2400 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2401 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2402 IsAddressOfOperand, TemplateArgs);
2403 } else {
2404 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2405 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2406
2407 // If the result might be in a dependent base class, this is a dependent
2408 // id-expression.
2409 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2410 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2411 IsAddressOfOperand, TemplateArgs);
2412
2413 // If this reference is in an Objective-C method, then we need to do
2414 // some special Objective-C lookup, too.
2415 if (IvarLookupFollowUp) {
2416 ExprResult E(LookupInObjCMethod(R, S, II, true));
2417 if (E.isInvalid())
2418 return ExprError();
2419
2420 if (Expr *Ex = E.getAs<Expr>())
2421 return Ex;
2422 }
2423 }
2424
2425 if (R.isAmbiguous())
2426 return ExprError();
2427
2428 // This could be an implicitly declared function reference (legal in C90,
2429 // extension in C99, forbidden in C++).
2430 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2431 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2432 if (D) R.addDecl(D);
2433 }
2434
2435 // Determine whether this name might be a candidate for
2436 // argument-dependent lookup.
2437 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2438
2439 if (R.empty() && !ADL) {
2440 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2441 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2442 TemplateKWLoc, TemplateArgs))
2443 return E;
2444 }
2445
2446 // Don't diagnose an empty lookup for inline assembly.
2447 if (IsInlineAsmIdentifier)
2448 return ExprError();
2449
2450 // If this name wasn't predeclared and if this is not a function
2451 // call, diagnose the problem.
2452 TypoExpr *TE = nullptr;
2453 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2454 : nullptr);
2455 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2456 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&(((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
"Typo correction callback misconfigured") ? static_cast<void
> (0) : __assert_fail ("(!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && \"Typo correction callback misconfigured\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 2457, __PRETTY_FUNCTION__))
2457 "Typo correction callback misconfigured")(((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
"Typo correction callback misconfigured") ? static_cast<void
> (0) : __assert_fail ("(!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && \"Typo correction callback misconfigured\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 2457, __PRETTY_FUNCTION__))
;
2458 if (CCC) {
2459 // Make sure the callback knows what the typo being diagnosed is.
2460 CCC->setTypoName(II);
2461 if (SS.isValid())
2462 CCC->setTypoNNS(SS.getScopeRep());
2463 }
2464 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2465 // a template name, but we happen to have always already looked up the name
2466 // before we get here if it must be a template name.
2467 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2468 None, &TE)) {
2469 if (TE && KeywordReplacement) {
2470 auto &State = getTypoExprState(TE);
2471 auto BestTC = State.Consumer->getNextCorrection();
2472 if (BestTC.isKeyword()) {
2473 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2474 if (State.DiagHandler)
2475 State.DiagHandler(BestTC);
2476 KeywordReplacement->startToken();
2477 KeywordReplacement->setKind(II->getTokenID());
2478 KeywordReplacement->setIdentifierInfo(II);
2479 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2480 // Clean up the state associated with the TypoExpr, since it has
2481 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2482 clearDelayedTypo(TE);
2483 // Signal that a correction to a keyword was performed by returning a
2484 // valid-but-null ExprResult.
2485 return (Expr*)nullptr;
2486 }
2487 State.Consumer->resetCorrectionStream();
2488 }
2489 return TE ? TE : ExprError();
2490 }
2491
2492 assert(!R.empty() &&((!R.empty() && "DiagnoseEmptyLookup returned false but added no results"
) ? static_cast<void> (0) : __assert_fail ("!R.empty() && \"DiagnoseEmptyLookup returned false but added no results\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 2493, __PRETTY_FUNCTION__))
2493 "DiagnoseEmptyLookup returned false but added no results")((!R.empty() && "DiagnoseEmptyLookup returned false but added no results"
) ? static_cast<void> (0) : __assert_fail ("!R.empty() && \"DiagnoseEmptyLookup returned false but added no results\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 2493, __PRETTY_FUNCTION__))
;
2494
2495 // If we found an Objective-C instance variable, let
2496 // LookupInObjCMethod build the appropriate expression to
2497 // reference the ivar.
2498 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2499 R.clear();
2500 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2501 // In a hopelessly buggy code, Objective-C instance variable
2502 // lookup fails and no expression will be built to reference it.
2503 if (!E.isInvalid() && !E.get())
2504 return ExprError();
2505 return E;
2506 }
2507 }
2508
2509 // This is guaranteed from this point on.
2510 assert(!R.empty() || ADL)((!R.empty() || ADL) ? static_cast<void> (0) : __assert_fail
("!R.empty() || ADL", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 2510, __PRETTY_FUNCTION__))
;
2511
2512 // Check whether this might be a C++ implicit instance member access.
2513 // C++ [class.mfct.non-static]p3:
2514 // When an id-expression that is not part of a class member access
2515 // syntax and not used to form a pointer to member is used in the
2516 // body of a non-static member function of class X, if name lookup
2517 // resolves the name in the id-expression to a non-static non-type
2518 // member of some class C, the id-expression is transformed into a
2519 // class member access expression using (*this) as the
2520 // postfix-expression to the left of the . operator.
2521 //
2522 // But we don't actually need to do this for '&' operands if R
2523 // resolved to a function or overloaded function set, because the
2524 // expression is ill-formed if it actually works out to be a
2525 // non-static member function:
2526 //
2527 // C++ [expr.ref]p4:
2528 // Otherwise, if E1.E2 refers to a non-static member function. . .
2529 // [t]he expression can be used only as the left-hand operand of a
2530 // member function call.
2531 //
2532 // There are other safeguards against such uses, but it's important
2533 // to get this right here so that we don't end up making a
2534 // spuriously dependent expression if we're inside a dependent
2535 // instance method.
2536 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2537 bool MightBeImplicitMember;
2538 if (!IsAddressOfOperand)
2539 MightBeImplicitMember = true;
2540 else if (!SS.isEmpty())
2541 MightBeImplicitMember = false;
2542 else if (R.isOverloadedResult())
2543 MightBeImplicitMember = false;
2544 else if (R.isUnresolvableResult())
2545 MightBeImplicitMember = true;
2546 else
2547 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2548 isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2549 isa<MSPropertyDecl>(R.getFoundDecl());
2550
2551 if (MightBeImplicitMember)
2552 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2553 R, TemplateArgs, S);
2554 }
2555
2556 if (TemplateArgs || TemplateKWLoc.isValid()) {
2557
2558 // In C++1y, if this is a variable template id, then check it
2559 // in BuildTemplateIdExpr().
2560 // The single lookup result must be a variable template declaration.
2561 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2562 Id.TemplateId->Kind == TNK_Var_template) {
2563 assert(R.getAsSingle<VarTemplateDecl>() &&((R.getAsSingle<VarTemplateDecl>() && "There should only be one declaration found."
) ? static_cast<void> (0) : __assert_fail ("R.getAsSingle<VarTemplateDecl>() && \"There should only be one declaration found.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 2564, __PRETTY_FUNCTION__))
2564 "There should only be one declaration found.")((R.getAsSingle<VarTemplateDecl>() && "There should only be one declaration found."
) ? static_cast<void> (0) : __assert_fail ("R.getAsSingle<VarTemplateDecl>() && \"There should only be one declaration found.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 2564, __PRETTY_FUNCTION__))
;
2565 }
2566
2567 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2568 }
2569
2570 return BuildDeclarationNameExpr(SS, R, ADL);
2571}
2572
2573/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2574/// declaration name, generally during template instantiation.
2575/// There's a large number of things which don't need to be done along
2576/// this path.
2577ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2578 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2579 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2580 DeclContext *DC = computeDeclContext(SS, false);
2581 if (!DC)
2582 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2583 NameInfo, /*TemplateArgs=*/nullptr);
2584
2585 if (RequireCompleteDeclContext(SS, DC))
2586 return ExprError();
2587
2588 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2589 LookupQualifiedName(R, DC);
2590
2591 if (R.isAmbiguous())
2592 return ExprError();
2593
2594 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2595 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2596 NameInfo, /*TemplateArgs=*/nullptr);
2597
2598 if (R.empty()) {
2599 // Don't diagnose problems with invalid record decl, the secondary no_member
2600 // diagnostic during template instantiation is likely bogus, e.g. if a class
2601 // is invalid because it's derived from an invalid base class, then missing
2602 // members were likely supposed to be inherited.
2603 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2604 if (CD->isInvalidDecl())
2605 return ExprError();
2606 Diag(NameInfo.getLoc(), diag::err_no_member)
2607 << NameInfo.getName() << DC << SS.getRange();
2608 return ExprError();
2609 }
2610
2611 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2612 // Diagnose a missing typename if this resolved unambiguously to a type in
2613 // a dependent context. If we can recover with a type, downgrade this to
2614 // a warning in Microsoft compatibility mode.
2615 unsigned DiagID = diag::err_typename_missing;
2616 if (RecoveryTSI && getLangOpts().MSVCCompat)
2617 DiagID = diag::ext_typename_missing;
2618 SourceLocation Loc = SS.getBeginLoc();
2619 auto D = Diag(Loc, DiagID);
2620 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2621 << SourceRange(Loc, NameInfo.getEndLoc());
2622
2623 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2624 // context.
2625 if (!RecoveryTSI)
2626 return ExprError();
2627
2628 // Only issue the fixit if we're prepared to recover.
2629 D << FixItHint::CreateInsertion(Loc, "typename ");
2630
2631 // Recover by pretending this was an elaborated type.
2632 QualType Ty = Context.getTypeDeclType(TD);
2633 TypeLocBuilder TLB;
2634 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2635
2636 QualType ET = getElaboratedType(ETK_None, SS, Ty);
2637 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2638 QTL.setElaboratedKeywordLoc(SourceLocation());
2639 QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2640
2641 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2642
2643 return ExprEmpty();
2644 }
2645
2646 // Defend against this resolving to an implicit member access. We usually
2647 // won't get here if this might be a legitimate a class member (we end up in
2648 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2649 // a pointer-to-member or in an unevaluated context in C++11.
2650 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2651 return BuildPossibleImplicitMemberExpr(SS,
2652 /*TemplateKWLoc=*/SourceLocation(),
2653 R, /*TemplateArgs=*/nullptr, S);
2654
2655 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2656}
2657
2658/// The parser has read a name in, and Sema has detected that we're currently
2659/// inside an ObjC method. Perform some additional checks and determine if we
2660/// should form a reference to an ivar.
2661///
2662/// Ideally, most of this would be done by lookup, but there's
2663/// actually quite a lot of extra work involved.
2664DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2665 IdentifierInfo *II) {
2666 SourceLocation Loc = Lookup.getNameLoc();
2667 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2668
2669 // Check for error condition which is already reported.
2670 if (!CurMethod)
2671 return DeclResult(true);
2672
2673 // There are two cases to handle here. 1) scoped lookup could have failed,
2674 // in which case we should look for an ivar. 2) scoped lookup could have
2675 // found a decl, but that decl is outside the current instance method (i.e.
2676 // a global variable). In these two cases, we do a lookup for an ivar with
2677 // this name, if the lookup sucedes, we replace it our current decl.
2678
2679 // If we're in a class method, we don't normally want to look for
2680 // ivars. But if we don't find anything else, and there's an
2681 // ivar, that's an error.
2682 bool IsClassMethod = CurMethod->isClassMethod();
2683
2684 bool LookForIvars;
2685 if (Lookup.empty())
2686 LookForIvars = true;
2687 else if (IsClassMethod)
2688 LookForIvars = false;
2689 else
2690 LookForIvars = (Lookup.isSingleResult() &&
2691 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2692 ObjCInterfaceDecl *IFace = nullptr;
2693 if (LookForIvars) {
2694 IFace = CurMethod->getClassInterface();
2695 ObjCInterfaceDecl *ClassDeclared;
2696 ObjCIvarDecl *IV = nullptr;
2697 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2698 // Diagnose using an ivar in a class method.
2699 if (IsClassMethod) {
2700 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2701 return DeclResult(true);
2702 }
2703
2704 // Diagnose the use of an ivar outside of the declaring class.
2705 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2706 !declaresSameEntity(ClassDeclared, IFace) &&
2707 !getLangOpts().DebuggerSupport)
2708 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2709
2710 // Success.
2711 return IV;
2712 }
2713 } else if (CurMethod->isInstanceMethod()) {
2714 // We should warn if a local variable hides an ivar.
2715 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2716 ObjCInterfaceDecl *ClassDeclared;
2717 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2718 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2719 declaresSameEntity(IFace, ClassDeclared))
2720 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2721 }
2722 }
2723 } else if (Lookup.isSingleResult() &&
2724 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2725 // If accessing a stand-alone ivar in a class method, this is an error.
2726 if (const ObjCIvarDecl *IV =
2727 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2728 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2729 return DeclResult(true);
2730 }
2731 }
2732
2733 // Didn't encounter an error, didn't find an ivar.
2734 return DeclResult(false);
2735}
2736
2737ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2738 ObjCIvarDecl *IV) {
2739 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2740 assert(CurMethod && CurMethod->isInstanceMethod() &&((CurMethod && CurMethod->isInstanceMethod() &&
"should not reference ivar from this context") ? static_cast
<void> (0) : __assert_fail ("CurMethod && CurMethod->isInstanceMethod() && \"should not reference ivar from this context\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 2741, __PRETTY_FUNCTION__))
2741 "should not reference ivar from this context")((CurMethod && CurMethod->isInstanceMethod() &&
"should not reference ivar from this context") ? static_cast
<void> (0) : __assert_fail ("CurMethod && CurMethod->isInstanceMethod() && \"should not reference ivar from this context\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 2741, __PRETTY_FUNCTION__))
;
2742
2743 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2744 assert(IFace && "should not reference ivar from this context")((IFace && "should not reference ivar from this context"
) ? static_cast<void> (0) : __assert_fail ("IFace && \"should not reference ivar from this context\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 2744, __PRETTY_FUNCTION__))
;
2745
2746 // If we're referencing an invalid decl, just return this as a silent
2747 // error node. The error diagnostic was already emitted on the decl.
2748 if (IV->isInvalidDecl())
2749 return ExprError();
2750
2751 // Check if referencing a field with __attribute__((deprecated)).
2752 if (DiagnoseUseOfDecl(IV, Loc))
2753 return ExprError();
2754
2755 // FIXME: This should use a new expr for a direct reference, don't
2756 // turn this into Self->ivar, just return a BareIVarExpr or something.
2757 IdentifierInfo &II = Context.Idents.get("self");
2758 UnqualifiedId SelfName;
2759 SelfName.setIdentifier(&II, SourceLocation());
2760 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2761 CXXScopeSpec SelfScopeSpec;
2762 SourceLocation TemplateKWLoc;
2763 ExprResult SelfExpr =
2764 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2765 /*HasTrailingLParen=*/false,
2766 /*IsAddressOfOperand=*/false);
2767 if (SelfExpr.isInvalid())
2768 return ExprError();
2769
2770 SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2771 if (SelfExpr.isInvalid())
2772 return ExprError();
2773
2774 MarkAnyDeclReferenced(Loc, IV, true);
2775
2776 ObjCMethodFamily MF = CurMethod->getMethodFamily();
2777 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2778 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2779 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2780
2781 ObjCIvarRefExpr *Result = new (Context)
2782 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2783 IV->getLocation(), SelfExpr.get(), true, true);
2784
2785 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2786 if (!isUnevaluatedContext() &&
2787 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2788 getCurFunction()->recordUseOfWeak(Result);
2789 }
2790 if (getLangOpts().ObjCAutoRefCount)
2791 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2792 ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2793
2794 return Result;
2795}
2796
2797/// The parser has read a name in, and Sema has detected that we're currently
2798/// inside an ObjC method. Perform some additional checks and determine if we
2799/// should form a reference to an ivar. If so, build an expression referencing
2800/// that ivar.
2801ExprResult
2802Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2803 IdentifierInfo *II, bool AllowBuiltinCreation) {
2804 // FIXME: Integrate this lookup step into LookupParsedName.
2805 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2806 if (Ivar.isInvalid())
2807 return ExprError();
2808 if (Ivar.isUsable())
2809 return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2810 cast<ObjCIvarDecl>(Ivar.get()));
2811
2812 if (Lookup.empty() && II && AllowBuiltinCreation)
2813 LookupBuiltin(Lookup);
2814
2815 // Sentinel value saying that we didn't do anything special.
2816 return ExprResult(false);
2817}
2818
2819/// Cast a base object to a member's actual type.
2820///
2821/// Logically this happens in three phases:
2822///
2823/// * First we cast from the base type to the naming class.
2824/// The naming class is the class into which we were looking
2825/// when we found the member; it's the qualifier type if a
2826/// qualifier was provided, and otherwise it's the base type.
2827///
2828/// * Next we cast from the naming class to the declaring class.
2829/// If the member we found was brought into a class's scope by
2830/// a using declaration, this is that class; otherwise it's
2831/// the class declaring the member.
2832///
2833/// * Finally we cast from the declaring class to the "true"
2834/// declaring class of the member. This conversion does not
2835/// obey access control.
2836ExprResult
2837Sema::PerformObjectMemberConversion(Expr *From,
2838 NestedNameSpecifier *Qualifier,
2839 NamedDecl *FoundDecl,
2840 NamedDecl *Member) {
2841 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2842 if (!RD)
2843 return From;
2844
2845 QualType DestRecordType;
2846 QualType DestType;
2847 QualType FromRecordType;
2848 QualType FromType = From->getType();
2849 bool PointerConversions = false;
2850 if (isa<FieldDecl>(Member)) {
2851 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2852 auto FromPtrType = FromType->getAs<PointerType>();
2853 DestRecordType = Context.getAddrSpaceQualType(
2854 DestRecordType, FromPtrType
2855 ? FromType->getPointeeType().getAddressSpace()
2856 : FromType.getAddressSpace());
2857
2858 if (FromPtrType) {
2859 DestType = Context.getPointerType(DestRecordType);
2860 FromRecordType = FromPtrType->getPointeeType();
2861 PointerConversions = true;
2862 } else {
2863 DestType = DestRecordType;
2864 FromRecordType = FromType;
2865 }
2866 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2867 if (Method->isStatic())
2868 return From;
2869
2870 DestType = Method->getThisType();
2871 DestRecordType = DestType->getPointeeType();
2872
2873 if (FromType->getAs<PointerType>()) {
2874 FromRecordType = FromType->getPointeeType();
2875 PointerConversions = true;
2876 } else {
2877 FromRecordType = FromType;
2878 DestType = DestRecordType;
2879 }
2880
2881 LangAS FromAS = FromRecordType.getAddressSpace();
2882 LangAS DestAS = DestRecordType.getAddressSpace();
2883 if (FromAS != DestAS) {
2884 QualType FromRecordTypeWithoutAS =
2885 Context.removeAddrSpaceQualType(FromRecordType);
2886 QualType FromTypeWithDestAS =
2887 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
2888 if (PointerConversions)
2889 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
2890 From = ImpCastExprToType(From, FromTypeWithDestAS,
2891 CK_AddressSpaceConversion, From->getValueKind())
2892 .get();
2893 }
2894 } else {
2895 // No conversion necessary.
2896 return From;
2897 }
2898
2899 if (DestType->isDependentType() || FromType->isDependentType())
2900 return From;
2901
2902 // If the unqualified types are the same, no conversion is necessary.
2903 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2904 return From;
2905
2906 SourceRange FromRange = From->getSourceRange();
2907 SourceLocation FromLoc = FromRange.getBegin();
2908
2909 ExprValueKind VK = From->getValueKind();
2910
2911 // C++ [class.member.lookup]p8:
2912 // [...] Ambiguities can often be resolved by qualifying a name with its
2913 // class name.
2914 //
2915 // If the member was a qualified name and the qualified referred to a
2916 // specific base subobject type, we'll cast to that intermediate type
2917 // first and then to the object in which the member is declared. That allows
2918 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2919 //
2920 // class Base { public: int x; };
2921 // class Derived1 : public Base { };
2922 // class Derived2 : public Base { };
2923 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2924 //
2925 // void VeryDerived::f() {
2926 // x = 17; // error: ambiguous base subobjects
2927 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2928 // }
2929 if (Qualifier && Qualifier->getAsType()) {
2930 QualType QType = QualType(Qualifier->getAsType(), 0);
2931 assert(QType->isRecordType() && "lookup done with non-record type")((QType->isRecordType() && "lookup done with non-record type"
) ? static_cast<void> (0) : __assert_fail ("QType->isRecordType() && \"lookup done with non-record type\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 2931, __PRETTY_FUNCTION__))
;
2932
2933 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2934
2935 // In C++98, the qualifier type doesn't actually have to be a base
2936 // type of the object type, in which case we just ignore it.
2937 // Otherwise build the appropriate casts.
2938 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2939 CXXCastPath BasePath;
2940 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2941 FromLoc, FromRange, &BasePath))
2942 return ExprError();
2943
2944 if (PointerConversions)
2945 QType = Context.getPointerType(QType);
2946 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2947 VK, &BasePath).get();
2948
2949 FromType = QType;
2950 FromRecordType = QRecordType;
2951
2952 // If the qualifier type was the same as the destination type,
2953 // we're done.
2954 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2955 return From;
2956 }
2957 }
2958
2959 bool IgnoreAccess = false;
2960
2961 // If we actually found the member through a using declaration, cast
2962 // down to the using declaration's type.
2963 //
2964 // Pointer equality is fine here because only one declaration of a
2965 // class ever has member declarations.
2966 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2967 assert(isa<UsingShadowDecl>(FoundDecl))((isa<UsingShadowDecl>(FoundDecl)) ? static_cast<void
> (0) : __assert_fail ("isa<UsingShadowDecl>(FoundDecl)"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 2967, __PRETTY_FUNCTION__))
;
2968 QualType URecordType = Context.getTypeDeclType(
2969 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2970
2971 // We only need to do this if the naming-class to declaring-class
2972 // conversion is non-trivial.
2973 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2974 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType))((IsDerivedFrom(FromLoc, FromRecordType, URecordType)) ? static_cast
<void> (0) : __assert_fail ("IsDerivedFrom(FromLoc, FromRecordType, URecordType)"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 2974, __PRETTY_FUNCTION__))
;
2975 CXXCastPath BasePath;
2976 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2977 FromLoc, FromRange, &BasePath))
2978 return ExprError();
2979
2980 QualType UType = URecordType;
2981 if (PointerConversions)
2982 UType = Context.getPointerType(UType);
2983 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2984 VK, &BasePath).get();
2985 FromType = UType;
2986 FromRecordType = URecordType;
2987 }
2988
2989 // We don't do access control for the conversion from the
2990 // declaring class to the true declaring class.
2991 IgnoreAccess = true;
2992 }
2993
2994 CXXCastPath BasePath;
2995 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2996 FromLoc, FromRange, &BasePath,
2997 IgnoreAccess))
2998 return ExprError();
2999
3000 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3001 VK, &BasePath);
3002}
3003
3004bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3005 const LookupResult &R,
3006 bool HasTrailingLParen) {
3007 // Only when used directly as the postfix-expression of a call.
3008 if (!HasTrailingLParen)
3009 return false;
3010
3011 // Never if a scope specifier was provided.
3012 if (SS.isSet())
3013 return false;
3014
3015 // Only in C++ or ObjC++.
3016 if (!getLangOpts().CPlusPlus)
3017 return false;
3018
3019 // Turn off ADL when we find certain kinds of declarations during
3020 // normal lookup:
3021 for (NamedDecl *D : R) {
3022 // C++0x [basic.lookup.argdep]p3:
3023 // -- a declaration of a class member
3024 // Since using decls preserve this property, we check this on the
3025 // original decl.
3026 if (D->isCXXClassMember())
3027 return false;
3028
3029 // C++0x [basic.lookup.argdep]p3:
3030 // -- a block-scope function declaration that is not a
3031 // using-declaration
3032 // NOTE: we also trigger this for function templates (in fact, we
3033 // don't check the decl type at all, since all other decl types
3034 // turn off ADL anyway).
3035 if (isa<UsingShadowDecl>(D))
3036 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3037 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3038 return false;
3039
3040 // C++0x [basic.lookup.argdep]p3:
3041 // -- a declaration that is neither a function or a function
3042 // template
3043 // And also for builtin functions.
3044 if (isa<FunctionDecl>(D)) {
3045 FunctionDecl *FDecl = cast<FunctionDecl>(D);
3046
3047 // But also builtin functions.
3048 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3049 return false;
3050 } else if (!isa<FunctionTemplateDecl>(D))
3051 return false;
3052 }
3053
3054 return true;
3055}
3056
3057
3058/// Diagnoses obvious problems with the use of the given declaration
3059/// as an expression. This is only actually called for lookups that
3060/// were not overloaded, and it doesn't promise that the declaration
3061/// will in fact be used.
3062static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3063 if (D->isInvalidDecl())
3064 return true;
3065
3066 if (isa<TypedefNameDecl>(D)) {
3067 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3068 return true;
3069 }
3070
3071 if (isa<ObjCInterfaceDecl>(D)) {
3072 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3073 return true;
3074 }
3075
3076 if (isa<NamespaceDecl>(D)) {
3077 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3078 return true;
3079 }
3080
3081 return false;
3082}
3083
3084// Certain multiversion types should be treated as overloaded even when there is
3085// only one result.
3086static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3087 assert(R.isSingleResult() && "Expected only a single result")((R.isSingleResult() && "Expected only a single result"
) ? static_cast<void> (0) : __assert_fail ("R.isSingleResult() && \"Expected only a single result\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 3087, __PRETTY_FUNCTION__))
;
3088 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3089 return FD &&
3090 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3091}
3092
3093ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3094 LookupResult &R, bool NeedsADL,
3095 bool AcceptInvalidDecl) {
3096 // If this is a single, fully-resolved result and we don't need ADL,
3097 // just build an ordinary singleton decl ref.
3098 if (!NeedsADL && R.isSingleResult() &&
3099 !R.getAsSingle<FunctionTemplateDecl>() &&
3100 !ShouldLookupResultBeMultiVersionOverload(R))
3101 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3102 R.getRepresentativeDecl(), nullptr,
3103 AcceptInvalidDecl);
3104
3105 // We only need to check the declaration if there's exactly one
3106 // result, because in the overloaded case the results can only be
3107 // functions and function templates.
3108 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3109 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3110 return ExprError();
3111
3112 // Otherwise, just build an unresolved lookup expression. Suppress
3113 // any lookup-related diagnostics; we'll hash these out later, when
3114 // we've picked a target.
3115 R.suppressDiagnostics();
3116
3117 UnresolvedLookupExpr *ULE
3118 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3119 SS.getWithLocInContext(Context),
3120 R.getLookupNameInfo(),
3121 NeedsADL, R.isOverloadedResult(),
3122 R.begin(), R.end());
3123
3124 return ULE;
3125}
3126
3127static void
3128diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3129 ValueDecl *var, DeclContext *DC);
3130
3131/// Complete semantic analysis for a reference to the given declaration.
3132ExprResult Sema::BuildDeclarationNameExpr(
3133 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3134 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3135 bool AcceptInvalidDecl) {
3136 assert(D && "Cannot refer to a NULL declaration")((D && "Cannot refer to a NULL declaration") ? static_cast
<void> (0) : __assert_fail ("D && \"Cannot refer to a NULL declaration\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 3136, __PRETTY_FUNCTION__))
;
3137 assert(!isa<FunctionTemplateDecl>(D) &&((!isa<FunctionTemplateDecl>(D) && "Cannot refer unambiguously to a function template"
) ? static_cast<void> (0) : __assert_fail ("!isa<FunctionTemplateDecl>(D) && \"Cannot refer unambiguously to a function template\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 3138, __PRETTY_FUNCTION__))
3138 "Cannot refer unambiguously to a function template")((!isa<FunctionTemplateDecl>(D) && "Cannot refer unambiguously to a function template"
) ? static_cast<void> (0) : __assert_fail ("!isa<FunctionTemplateDecl>(D) && \"Cannot refer unambiguously to a function template\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 3138, __PRETTY_FUNCTION__))
;
3139
3140 SourceLocation Loc = NameInfo.getLoc();
3141 if (CheckDeclInExpr(*this, Loc, D))
3142 return ExprError();
3143
3144 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3145 // Specifically diagnose references to class templates that are missing
3146 // a template argument list.
3147 diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3148 return ExprError();
3149 }
3150
3151 // Make sure that we're referring to a value.
3152 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3153 if (!VD) {
3154 Diag(Loc, diag::err_ref_non_value)
3155 << D << SS.getRange();
3156 Diag(D->getLocation(), diag::note_declared_at);
3157 return ExprError();
3158 }
3159
3160 // Check whether this declaration can be used. Note that we suppress
3161 // this check when we're going to perform argument-dependent lookup
3162 // on this function name, because this might not be the function
3163 // that overload resolution actually selects.
3164 if (DiagnoseUseOfDecl(VD, Loc))
3165 return ExprError();
3166
3167 // Only create DeclRefExpr's for valid Decl's.
3168 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3169 return ExprError();
3170
3171 // Handle members of anonymous structs and unions. If we got here,
3172 // and the reference is to a class member indirect field, then this
3173 // must be the subject of a pointer-to-member expression.
3174 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3175 if (!indirectField->isCXXClassMember())
3176 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3177 indirectField);
3178
3179 {
3180 QualType type = VD->getType();
3181 if (type.isNull())
3182 return ExprError();
3183 ExprValueKind valueKind = VK_RValue;
3184
3185 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3186 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3187 // is expanded by some outer '...' in the context of the use.
3188 type = type.getNonPackExpansionType();
3189
3190 switch (D->getKind()) {
3191 // Ignore all the non-ValueDecl kinds.
3192#define ABSTRACT_DECL(kind)
3193#define VALUE(type, base)
3194#define DECL(type, base) \
3195 case Decl::type:
3196#include "clang/AST/DeclNodes.inc"
3197 llvm_unreachable("invalid value decl kind")::llvm::llvm_unreachable_internal("invalid value decl kind", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 3197)
;
3198
3199 // These shouldn't make it here.
3200 case Decl::ObjCAtDefsField:
3201 llvm_unreachable("forming non-member reference to ivar?")::llvm::llvm_unreachable_internal("forming non-member reference to ivar?"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 3201)
;
3202
3203 // Enum constants are always r-values and never references.
3204 // Unresolved using declarations are dependent.
3205 case Decl::EnumConstant:
3206 case Decl::UnresolvedUsingValue:
3207 case Decl::OMPDeclareReduction:
3208 case Decl::OMPDeclareMapper:
3209 valueKind = VK_RValue;
3210 break;
3211
3212 // Fields and indirect fields that got here must be for
3213 // pointer-to-member expressions; we just call them l-values for
3214 // internal consistency, because this subexpression doesn't really
3215 // exist in the high-level semantics.
3216 case Decl::Field:
3217 case Decl::IndirectField:
3218 case Decl::ObjCIvar:
3219 assert(getLangOpts().CPlusPlus &&((getLangOpts().CPlusPlus && "building reference to field in C?"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"building reference to field in C?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 3220, __PRETTY_FUNCTION__))
3220 "building reference to field in C?")((getLangOpts().CPlusPlus && "building reference to field in C?"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"building reference to field in C?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 3220, __PRETTY_FUNCTION__))
;
3221
3222 // These can't have reference type in well-formed programs, but
3223 // for internal consistency we do this anyway.
3224 type = type.getNonReferenceType();
3225 valueKind = VK_LValue;
3226 break;
3227
3228 // Non-type template parameters are either l-values or r-values
3229 // depending on the type.
3230 case Decl::NonTypeTemplateParm: {
3231 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3232 type = reftype->getPointeeType();
3233 valueKind = VK_LValue; // even if the parameter is an r-value reference
3234 break;
3235 }
3236
3237 // [expr.prim.id.unqual]p2:
3238 // If the entity is a template parameter object for a template
3239 // parameter of type T, the type of the expression is const T.
3240 // [...] The expression is an lvalue if the entity is a [...] template
3241 // parameter object.
3242 if (type->isRecordType()) {
3243 type = type.getUnqualifiedType().withConst();
3244 valueKind = VK_LValue;
3245 break;
3246 }
3247
3248 // For non-references, we need to strip qualifiers just in case
3249 // the template parameter was declared as 'const int' or whatever.
3250 valueKind = VK_RValue;
3251 type = type.getUnqualifiedType();
3252 break;
3253 }
3254
3255 case Decl::Var:
3256 case Decl::VarTemplateSpecialization:
3257 case Decl::VarTemplatePartialSpecialization:
3258 case Decl::Decomposition:
3259 case Decl::OMPCapturedExpr:
3260 // In C, "extern void blah;" is valid and is an r-value.
3261 if (!getLangOpts().CPlusPlus &&
3262 !type.hasQualifiers() &&
3263 type->isVoidType()) {
3264 valueKind = VK_RValue;
3265 break;
3266 }
3267 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3268
3269 case Decl::ImplicitParam:
3270 case Decl::ParmVar: {
3271 // These are always l-values.
3272 valueKind = VK_LValue;
3273 type = type.getNonReferenceType();
3274
3275 // FIXME: Does the addition of const really only apply in
3276 // potentially-evaluated contexts? Since the variable isn't actually
3277 // captured in an unevaluated context, it seems that the answer is no.
3278 if (!isUnevaluatedContext()) {
3279 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3280 if (!CapturedType.isNull())
3281 type = CapturedType;
3282 }
3283
3284 break;
3285 }
3286
3287 case Decl::Binding: {
3288 // These are always lvalues.
3289 valueKind = VK_LValue;
3290 type = type.getNonReferenceType();
3291 // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3292 // decides how that's supposed to work.
3293 auto *BD = cast<BindingDecl>(VD);
3294 if (BD->getDeclContext() != CurContext) {
3295 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3296 if (DD && DD->hasLocalStorage())
3297 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3298 }
3299 break;
3300 }
3301
3302 case Decl::Function: {
3303 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3304 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3305 type = Context.BuiltinFnTy;
3306 valueKind = VK_RValue;
3307 break;
3308 }
3309 }
3310
3311 const FunctionType *fty = type->castAs<FunctionType>();
3312
3313 // If we're referring to a function with an __unknown_anytype
3314 // result type, make the entire expression __unknown_anytype.
3315 if (fty->getReturnType() == Context.UnknownAnyTy) {
3316 type = Context.UnknownAnyTy;
3317 valueKind = VK_RValue;
3318 break;
3319 }
3320
3321 // Functions are l-values in C++.
3322 if (getLangOpts().CPlusPlus) {
3323 valueKind = VK_LValue;
3324 break;
3325 }
3326
3327 // C99 DR 316 says that, if a function type comes from a
3328 // function definition (without a prototype), that type is only
3329 // used for checking compatibility. Therefore, when referencing
3330 // the function, we pretend that we don't have the full function
3331 // type.
3332 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3333 isa<FunctionProtoType>(fty))
3334 type = Context.getFunctionNoProtoType(fty->getReturnType(),
3335 fty->getExtInfo());
3336
3337 // Functions are r-values in C.
3338 valueKind = VK_RValue;
3339 break;
3340 }
3341
3342 case Decl::CXXDeductionGuide:
3343 llvm_unreachable("building reference to deduction guide")::llvm::llvm_unreachable_internal("building reference to deduction guide"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 3343)
;
3344
3345 case Decl::MSProperty:
3346 case Decl::MSGuid:
3347 case Decl::TemplateParamObject:
3348 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3349 // capture in OpenMP, or duplicated between host and device?
3350 valueKind = VK_LValue;
3351 break;
3352
3353 case Decl::CXXMethod:
3354 // If we're referring to a method with an __unknown_anytype
3355 // result type, make the entire expression __unknown_anytype.
3356 // This should only be possible with a type written directly.
3357 if (const FunctionProtoType *proto
3358 = dyn_cast<FunctionProtoType>(VD->getType()))
3359 if (proto->getReturnType() == Context.UnknownAnyTy) {
3360 type = Context.UnknownAnyTy;
3361 valueKind = VK_RValue;
3362 break;
3363 }
3364
3365 // C++ methods are l-values if static, r-values if non-static.
3366 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3367 valueKind = VK_LValue;
3368 break;
3369 }
3370 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3371
3372 case Decl::CXXConversion:
3373 case Decl::CXXDestructor:
3374 case Decl::CXXConstructor:
3375 valueKind = VK_RValue;
3376 break;
3377 }
3378
3379 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3380 /*FIXME: TemplateKWLoc*/ SourceLocation(),
3381 TemplateArgs);
3382 }
3383}
3384
3385static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3386 SmallString<32> &Target) {
3387 Target.resize(CharByteWidth * (Source.size() + 1));
3388 char *ResultPtr = &Target[0];
3389 const llvm::UTF8 *ErrorPtr;
3390 bool success =
3391 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3392 (void)success;
3393 assert(success)((success) ? static_cast<void> (0) : __assert_fail ("success"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 3393, __PRETTY_FUNCTION__))
;
3394 Target.resize(ResultPtr - &Target[0]);
3395}
3396
3397ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3398 PredefinedExpr::IdentKind IK) {
3399 // Pick the current block, lambda, captured statement or function.
3400 Decl *currentDecl = nullptr;
3401 if (const BlockScopeInfo *BSI = getCurBlock())
3402 currentDecl = BSI->TheDecl;
3403 else if (const LambdaScopeInfo *LSI = getCurLambda())
3404 currentDecl = LSI->CallOperator;
3405 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3406 currentDecl = CSI->TheCapturedDecl;
3407 else
3408 currentDecl = getCurFunctionOrMethodDecl();
3409
3410 if (!currentDecl) {
3411 Diag(Loc, diag::ext_predef_outside_function);
3412 currentDecl = Context.getTranslationUnitDecl();
3413 }
3414
3415 QualType ResTy;
3416 StringLiteral *SL = nullptr;
3417 if (cast<DeclContext>(currentDecl)->isDependentContext())
3418 ResTy = Context.DependentTy;
3419 else {
3420 // Pre-defined identifiers are of type char[x], where x is the length of
3421 // the string.
3422 auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3423 unsigned Length = Str.length();
3424
3425 llvm::APInt LengthI(32, Length + 1);
3426 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3427 ResTy =
3428 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3429 SmallString<32> RawChars;
3430 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3431 Str, RawChars);
3432 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3433 ArrayType::Normal,
3434 /*IndexTypeQuals*/ 0);
3435 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3436 /*Pascal*/ false, ResTy, Loc);
3437 } else {
3438 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3439 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3440 ArrayType::Normal,
3441 /*IndexTypeQuals*/ 0);
3442 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3443 /*Pascal*/ false, ResTy, Loc);
3444 }
3445 }
3446
3447 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3448}
3449
3450ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3451 PredefinedExpr::IdentKind IK;
3452
3453 switch (Kind) {
3454 default: llvm_unreachable("Unknown simple primary expr!")::llvm::llvm_unreachable_internal("Unknown simple primary expr!"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 3454)
;
3455 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3456 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3457 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3458 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3459 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3460 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3461 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3462 }
3463
3464 return BuildPredefinedExpr(Loc, IK);
3465}
3466
3467ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3468 SmallString<16> CharBuffer;
3469 bool Invalid = false;
3470 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3471 if (Invalid)
3472 return ExprError();
3473
3474 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3475 PP, Tok.getKind());
3476 if (Literal.hadError())
3477 return ExprError();
3478
3479 QualType Ty;
3480 if (Literal.isWide())
3481 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3482 else if (Literal.isUTF8() && getLangOpts().Char8)
3483 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3484 else if (Literal.isUTF16())
3485 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3486 else if (Literal.isUTF32())
3487 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3488 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3489 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3490 else
3491 Ty = Context.CharTy; // 'x' -> char in C++
3492
3493 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3494 if (Literal.isWide())
3495 Kind = CharacterLiteral::Wide;
3496 else if (Literal.isUTF16())
3497 Kind = CharacterLiteral::UTF16;
3498 else if (Literal.isUTF32())
3499 Kind = CharacterLiteral::UTF32;
3500 else if (Literal.isUTF8())
3501 Kind = CharacterLiteral::UTF8;
3502
3503 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3504 Tok.getLocation());
3505
3506 if (Literal.getUDSuffix().empty())
3507 return Lit;
3508
3509 // We're building a user-defined literal.
3510 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3511 SourceLocation UDSuffixLoc =
3512 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3513
3514 // Make sure we're allowed user-defined literals here.
3515 if (!UDLScope)
3516 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3517
3518 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3519 // operator "" X (ch)
3520 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3521 Lit, Tok.getLocation());
3522}
3523
3524ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3525 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3526 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3527 Context.IntTy, Loc);
3528}
3529
3530static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3531 QualType Ty, SourceLocation Loc) {
3532 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3533
3534 using llvm::APFloat;
3535 APFloat Val(Format);
3536
3537 APFloat::opStatus result = Literal.GetFloatValue(Val);
3538
3539 // Overflow is always an error, but underflow is only an error if
3540 // we underflowed to zero (APFloat reports denormals as underflow).
3541 if ((result & APFloat::opOverflow) ||
3542 ((result & APFloat::opUnderflow) && Val.isZero())) {
3543 unsigned diagnostic;
3544 SmallString<20> buffer;
3545 if (result & APFloat::opOverflow) {
3546 diagnostic = diag::warn_float_overflow;
3547 APFloat::getLargest(Format).toString(buffer);
3548 } else {
3549 diagnostic = diag::warn_float_underflow;
3550 APFloat::getSmallest(Format).toString(buffer);
3551 }
3552
3553 S.Diag(Loc, diagnostic)
3554 << Ty
3555 << StringRef(buffer.data(), buffer.size());
3556 }
3557
3558 bool isExact = (result == APFloat::opOK);
3559 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3560}
3561
3562bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3563 assert(E && "Invalid expression")((E && "Invalid expression") ? static_cast<void>
(0) : __assert_fail ("E && \"Invalid expression\"", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 3563, __PRETTY_FUNCTION__))
;
3564
3565 if (E->isValueDependent())
3566 return false;
3567
3568 QualType QT = E->getType();
3569 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3570 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3571 return true;
3572 }
3573
3574 llvm::APSInt ValueAPS;
3575 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3576
3577 if (R.isInvalid())
3578 return true;
3579
3580 bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3581 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3582 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3583 << ValueAPS.toString(10) << ValueIsPositive;
3584 return true;
3585 }
3586
3587 return false;
3588}
3589
3590ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3591 // Fast path for a single digit (which is quite common). A single digit
3592 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3593 if (Tok.getLength() == 1) {
1
Assuming the condition is false
2
Taking false branch
3594 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3595 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3596 }
3597
3598 SmallString<128> SpellingBuffer;
3599 // NumericLiteralParser wants to overread by one character. Add padding to
3600 // the buffer in case the token is copied to the buffer. If getSpelling()
3601 // returns a StringRef to the memory buffer, it should have a null char at
3602 // the EOF, so it is also safe.
3603 SpellingBuffer.resize(Tok.getLength() + 1);
3604
3605 // Get the spelling of the token, which eliminates trigraphs, etc.
3606 bool Invalid = false;
3607 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3608 if (Invalid)
3
Assuming 'Invalid' is false
4
Taking false branch
3609 return ExprError();
3610
3611 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3612 PP.getSourceManager(), PP.getLangOpts(),
3613 PP.getTargetInfo(), PP.getDiagnostics());
3614 if (Literal.hadError)
5
Assuming field 'hadError' is false
6
Taking false branch
3615 return ExprError();
3616
3617 if (Literal.hasUDSuffix()) {
7
Assuming the condition is false
8
Taking false branch
3618 // We're building a user-defined literal.
3619 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3620 SourceLocation UDSuffixLoc =
3621 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3622
3623 // Make sure we're allowed user-defined literals here.
3624 if (!UDLScope)
3625 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3626
3627 QualType CookedTy;
3628 if (Literal.isFloatingLiteral()) {
3629 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3630 // long double, the literal is treated as a call of the form
3631 // operator "" X (f L)
3632 CookedTy = Context.LongDoubleTy;
3633 } else {
3634 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3635 // unsigned long long, the literal is treated as a call of the form
3636 // operator "" X (n ULL)
3637 CookedTy = Context.UnsignedLongLongTy;
3638 }
3639
3640 DeclarationName OpName =
3641 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3642 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3643 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3644
3645 SourceLocation TokLoc = Tok.getLocation();
3646
3647 // Perform literal operator lookup to determine if we're building a raw
3648 // literal or a cooked one.
3649 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3650 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3651 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3652 /*AllowStringTemplatePack*/ false,
3653 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3654 case LOLR_ErrorNoDiagnostic:
3655 // Lookup failure for imaginary constants isn't fatal, there's still the
3656 // GNU extension producing _Complex types.
3657 break;
3658 case LOLR_Error:
3659 return ExprError();
3660 case LOLR_Cooked: {
3661 Expr *Lit;
3662 if (Literal.isFloatingLiteral()) {
3663 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3664 } else {
3665 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3666 if (Literal.GetIntegerValue(ResultVal))
3667 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3668 << /* Unsigned */ 1;
3669 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3670 Tok.getLocation());
3671 }
3672 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3673 }
3674
3675 case LOLR_Raw: {
3676 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3677 // literal is treated as a call of the form
3678 // operator "" X ("n")
3679 unsigned Length = Literal.getUDSuffixOffset();
3680 QualType StrTy = Context.getConstantArrayType(
3681 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3682 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3683 Expr *Lit = StringLiteral::Create(
3684 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3685 /*Pascal*/false, StrTy, &TokLoc, 1);
3686 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3687 }
3688
3689 case LOLR_Template: {
3690 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3691 // template), L is treated as a call fo the form
3692 // operator "" X <'c1', 'c2', ... 'ck'>()
3693 // where n is the source character sequence c1 c2 ... ck.
3694 TemplateArgumentListInfo ExplicitArgs;
3695 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3696 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3697 llvm::APSInt Value(CharBits, CharIsUnsigned);
3698 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3699 Value = TokSpelling[I];
3700 TemplateArgument Arg(Context, Value, Context.CharTy);
3701 TemplateArgumentLocInfo ArgInfo;
3702 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3703 }
3704 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3705 &ExplicitArgs);
3706 }
3707 case LOLR_StringTemplatePack:
3708 llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 3708)
;
3709 }
3710 }
3711
3712 Expr *Res;
3713
3714 if (Literal.isFixedPointLiteral()) {
9
Calling 'NumericLiteralParser::isFixedPointLiteral'
12
Returning from 'NumericLiteralParser::isFixedPointLiteral'
13
Assuming the condition is false
14
Taking false branch
3715 QualType Ty;
3716
3717 if (Literal.isAccum) {
3718 if (Literal.isHalf) {
3719 Ty = Context.ShortAccumTy;
3720 } else if (Literal.isLong) {
3721 Ty = Context.LongAccumTy;
3722 } else {
3723 Ty = Context.AccumTy;
3724 }
3725 } else if (Literal.isFract) {
3726 if (Literal.isHalf) {
3727 Ty = Context.ShortFractTy;
3728 } else if (Literal.isLong) {
3729 Ty = Context.LongFractTy;
3730 } else {
3731 Ty = Context.FractTy;
3732 }
3733 }
3734
3735 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3736
3737 bool isSigned = !Literal.isUnsigned;
3738 unsigned scale = Context.getFixedPointScale(Ty);
3739 unsigned bit_width = Context.getTypeInfo(Ty).Width;
3740
3741 llvm::APInt Val(bit_width, 0, isSigned);
3742 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3743 bool ValIsZero = Val.isNullValue() && !Overflowed;
3744
3745 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3746 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3747 // Clause 6.4.4 - The value of a constant shall be in the range of
3748 // representable values for its type, with exception for constants of a
3749 // fract type with a value of exactly 1; such a constant shall denote
3750 // the maximal value for the type.
3751 --Val;
3752 else if (Val.ugt(MaxVal) || Overflowed)
3753 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3754
3755 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3756 Tok.getLocation(), scale);
3757 } else if (Literal.isFloatingLiteral()) {
15
Calling 'NumericLiteralParser::isFloatingLiteral'
17
Returning from 'NumericLiteralParser::isFloatingLiteral'
18
Taking true branch
3758 QualType Ty;
3759 if (Literal.isHalf){
19
Assuming field 'isHalf' is false
20
Taking false branch
3760 if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3761 Ty = Context.HalfTy;
3762 else {
3763 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3764 return ExprError();
3765 }
3766 } else if (Literal.isFloat)
21
Assuming field 'isFloat' is false
22
Taking false branch
3767 Ty = Context.FloatTy;
3768 else if (Literal.isLong)
23
Assuming field 'isLong' is false
24
Taking false branch
3769 Ty = Context.LongDoubleTy;
3770 else if (Literal.isFloat16)
25
Assuming field 'isFloat16' is true
26
Taking true branch
3771 Ty = Context.Float16Ty;
3772 else if (Literal.isFloat128)
3773 Ty = Context.Float128Ty;
3774 else
3775 Ty = Context.DoubleTy;
3776
3777 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3778
3779 if (Ty == Context.DoubleTy) {
27
Calling 'operator=='
33
Returning from 'operator=='
34
Taking true branch
3780 if (getLangOpts().SinglePrecisionConstants) {
35
Assuming field 'SinglePrecisionConstants' is not equal to 0
36
Taking true branch
3781 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
37
Assuming the object is not a 'BuiltinType'
38
'BTy' initialized to a null pointer value
3782 if (BTy->getKind() != BuiltinType::Float) {
39
Called C++ object pointer is null
3783 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3784 }
3785 } else if (getLangOpts().OpenCL &&
3786 !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3787 // Impose single-precision float type when cl_khr_fp64 is not enabled.
3788 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3789 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3790 }
3791 }
3792 } else if (!Literal.isIntegerLiteral()) {
3793 return ExprError();
3794 } else {
3795 QualType Ty;
3796
3797 // 'long long' is a C99 or C++11 feature.
3798 if (!getLangOpts().C99 && Literal.isLongLong) {
3799 if (getLangOpts().CPlusPlus)
3800 Diag(Tok.getLocation(),
3801 getLangOpts().CPlusPlus11 ?
3802 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3803 else
3804 Diag(Tok.getLocation(), diag::ext_c99_longlong);
3805 }
3806
3807 // Get the value in the widest-possible width.
3808 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3809 llvm::APInt ResultVal(MaxWidth, 0);
3810
3811 if (Literal.GetIntegerValue(ResultVal)) {
3812 // If this value didn't fit into uintmax_t, error and force to ull.
3813 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3814 << /* Unsigned */ 1;
3815 Ty = Context.UnsignedLongLongTy;
3816 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&((Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
"long long is not intmax_t?") ? static_cast<void> (0) :
__assert_fail ("Context.getTypeSize(Ty) == ResultVal.getBitWidth() && \"long long is not intmax_t?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 3817, __PRETTY_FUNCTION__))
3817 "long long is not intmax_t?")((Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
"long long is not intmax_t?") ? static_cast<void> (0) :
__assert_fail ("Context.getTypeSize(Ty) == ResultVal.getBitWidth() && \"long long is not intmax_t?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 3817, __PRETTY_FUNCTION__))
;
3818 } else {
3819 // If this value fits into a ULL, try to figure out what else it fits into
3820 // according to the rules of C99 6.4.4.1p5.
3821
3822 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3823 // be an unsigned int.
3824 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3825
3826 // Check from smallest to largest, picking the smallest type we can.
3827 unsigned Width = 0;
3828
3829 // Microsoft specific integer suffixes are explicitly sized.
3830 if (Literal.MicrosoftInteger) {
3831 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3832 Width = 8;
3833 Ty = Context.CharTy;
3834 } else {
3835 Width = Literal.MicrosoftInteger;
3836 Ty = Context.getIntTypeForBitwidth(Width,
3837 /*Signed=*/!Literal.isUnsigned);
3838 }
3839 }
3840
3841 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3842 // Are int/unsigned possibilities?
3843 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3844
3845 // Does it fit in a unsigned int?
3846 if (ResultVal.isIntN(IntSize)) {
3847 // Does it fit in a signed int?
3848 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3849 Ty = Context.IntTy;
3850 else if (AllowUnsigned)
3851 Ty = Context.UnsignedIntTy;
3852 Width = IntSize;
3853 }
3854 }
3855
3856 // Are long/unsigned long possibilities?
3857 if (Ty.isNull() && !Literal.isLongLong) {
3858 unsigned LongSize = Context.getTargetInfo().getLongWidth();
3859
3860 // Does it fit in a unsigned long?
3861 if (ResultVal.isIntN(LongSize)) {
3862 // Does it fit in a signed long?
3863 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3864 Ty = Context.LongTy;
3865 else if (AllowUnsigned)
3866 Ty = Context.UnsignedLongTy;
3867 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3868 // is compatible.
3869 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3870 const unsigned LongLongSize =
3871 Context.getTargetInfo().getLongLongWidth();
3872 Diag(Tok.getLocation(),
3873 getLangOpts().CPlusPlus
3874 ? Literal.isLong
3875 ? diag::warn_old_implicitly_unsigned_long_cxx
3876 : /*C++98 UB*/ diag::
3877 ext_old_implicitly_unsigned_long_cxx
3878 : diag::warn_old_implicitly_unsigned_long)
3879 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3880 : /*will be ill-formed*/ 1);
3881 Ty = Context.UnsignedLongTy;
3882 }
3883 Width = LongSize;
3884 }
3885 }
3886
3887 // Check long long if needed.
3888 if (Ty.isNull()) {
3889 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3890
3891 // Does it fit in a unsigned long long?
3892 if (ResultVal.isIntN(LongLongSize)) {
3893 // Does it fit in a signed long long?
3894 // To be compatible with MSVC, hex integer literals ending with the
3895 // LL or i64 suffix are always signed in Microsoft mode.
3896 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3897 (getLangOpts().MSVCCompat && Literal.isLongLong)))
3898 Ty = Context.LongLongTy;
3899 else if (AllowUnsigned)
3900 Ty = Context.UnsignedLongLongTy;
3901 Width = LongLongSize;
3902 }
3903 }
3904
3905 // If we still couldn't decide a type, we probably have something that
3906 // does not fit in a signed long long, but has no U suffix.
3907 if (Ty.isNull()) {
3908 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3909 Ty = Context.UnsignedLongLongTy;
3910 Width = Context.getTargetInfo().getLongLongWidth();
3911 }
3912
3913 if (ResultVal.getBitWidth() != Width)
3914 ResultVal = ResultVal.trunc(Width);
3915 }
3916 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3917 }
3918
3919 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3920 if (Literal.isImaginary) {
3921 Res = new (Context) ImaginaryLiteral(Res,
3922 Context.getComplexType(Res->getType()));
3923
3924 Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3925 }
3926 return Res;
3927}
3928
3929ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3930 assert(E && "ActOnParenExpr() missing expr")((E && "ActOnParenExpr() missing expr") ? static_cast
<void> (0) : __assert_fail ("E && \"ActOnParenExpr() missing expr\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 3930, __PRETTY_FUNCTION__))
;
3931 return new (Context) ParenExpr(L, R, E);
3932}
3933
3934static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3935 SourceLocation Loc,
3936 SourceRange ArgRange) {
3937 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3938 // scalar or vector data type argument..."
3939 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3940 // type (C99 6.2.5p18) or void.
3941 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3942 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3943 << T << ArgRange;
3944 return true;
3945 }
3946
3947 assert((T->isVoidType() || !T->isIncompleteType()) &&(((T->isVoidType() || !T->isIncompleteType()) &&
"Scalar types should always be complete") ? static_cast<void
> (0) : __assert_fail ("(T->isVoidType() || !T->isIncompleteType()) && \"Scalar types should always be complete\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 3948, __PRETTY_FUNCTION__))
3948 "Scalar types should always be complete")(((T->isVoidType() || !T->isIncompleteType()) &&
"Scalar types should always be complete") ? static_cast<void
> (0) : __assert_fail ("(T->isVoidType() || !T->isIncompleteType()) && \"Scalar types should always be complete\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 3948, __PRETTY_FUNCTION__))
;
3949 return false;
3950}
3951
3952static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3953 SourceLocation Loc,
3954 SourceRange ArgRange,
3955 UnaryExprOrTypeTrait TraitKind) {
3956 // Invalid types must be hard errors for SFINAE in C++.
3957 if (S.LangOpts.CPlusPlus)
3958 return true;
3959
3960 // C99 6.5.3.4p1:
3961 if (T->isFunctionType() &&
3962 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
3963 TraitKind == UETT_PreferredAlignOf)) {
3964 // sizeof(function)/alignof(function) is allowed as an extension.
3965 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3966 << getTraitSpelling(TraitKind) << ArgRange;
3967 return false;
3968 }
3969
3970 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3971 // this is an error (OpenCL v1.1 s6.3.k)
3972 if (T->isVoidType()) {
3973 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3974 : diag::ext_sizeof_alignof_void_type;
3975 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
3976 return false;
3977 }
3978
3979 return true;
3980}
3981
3982static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3983 SourceLocation Loc,
3984 SourceRange ArgRange,
3985 UnaryExprOrTypeTrait TraitKind) {
3986 // Reject sizeof(interface) and sizeof(interface<proto>) if the
3987 // runtime doesn't allow it.
3988 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3989 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3990 << T << (TraitKind == UETT_SizeOf)
3991 << ArgRange;
3992 return true;
3993 }
3994
3995 return false;
3996}
3997
3998/// Check whether E is a pointer from a decayed array type (the decayed
3999/// pointer type is equal to T) and emit a warning if it is.
4000static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4001 Expr *E) {
4002 // Don't warn if the operation changed the type.
4003 if (T != E->getType())
4004 return;
4005
4006 // Now look for array decays.
4007 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4008 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4009 return;
4010
4011 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4012 << ICE->getType()
4013 << ICE->getSubExpr()->getType();
4014}
4015
4016/// Check the constraints on expression operands to unary type expression
4017/// and type traits.
4018///
4019/// Completes any types necessary and validates the constraints on the operand
4020/// expression. The logic mostly mirrors the type-based overload, but may modify
4021/// the expression as it completes the type for that expression through template
4022/// instantiation, etc.
4023bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4024 UnaryExprOrTypeTrait ExprKind) {
4025 QualType ExprTy = E->getType();
4026 assert(!ExprTy->isReferenceType())((!ExprTy->isReferenceType()) ? static_cast<void> (0
) : __assert_fail ("!ExprTy->isReferenceType()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 4026, __PRETTY_FUNCTION__))
;
4027
4028 bool IsUnevaluatedOperand =
4029 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4030 ExprKind == UETT_PreferredAlignOf);
4031 if (IsUnevaluatedOperand) {
4032 ExprResult Result = CheckUnevaluatedOperand(E);
4033 if (Result.isInvalid())
4034 return true;
4035 E = Result.get();
4036 }
4037
4038 if (ExprKind == UETT_VecStep)
4039 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4040 E->getSourceRange());
4041
4042 // Explicitly list some types as extensions.
4043 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4044 E->getSourceRange(), ExprKind))
4045 return false;
4046
4047 // 'alignof' applied to an expression only requires the base element type of
4048 // the expression to be complete. 'sizeof' requires the expression's type to
4049 // be complete (and will attempt to complete it if it's an array of unknown
4050 // bound).
4051 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4052 if (RequireCompleteSizedType(
4053 E->getExprLoc(), Context.getBaseElementType(E->getType()),
4054 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4055 getTraitSpelling(ExprKind), E->getSourceRange()))
4056 return true;
4057 } else {
4058 if (RequireCompleteSizedExprType(
4059 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4060 getTraitSpelling(ExprKind), E->getSourceRange()))
4061 return true;
4062 }
4063
4064 // Completing the expression's type may have changed it.
4065 ExprTy = E->getType();
4066 assert(!ExprTy->isReferenceType())((!ExprTy->isReferenceType()) ? static_cast<void> (0
) : __assert_fail ("!ExprTy->isReferenceType()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 4066, __PRETTY_FUNCTION__))
;
4067
4068 if (ExprTy->isFunctionType()) {
4069 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4070 << getTraitSpelling(ExprKind) << E->getSourceRange();
4071 return true;
4072 }
4073
4074 // The operand for sizeof and alignof is in an unevaluated expression context,
4075 // so side effects could result in unintended consequences.
4076 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4077 E->HasSideEffects(Context, false))
4078 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4079
4080 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4081 E->getSourceRange(), ExprKind))
4082 return true;
4083
4084 if (ExprKind == UETT_SizeOf) {
4085 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4086 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4087 QualType OType = PVD->getOriginalType();
4088 QualType Type = PVD->getType();
4089 if (Type->isPointerType() && OType->isArrayType()) {
4090 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4091 << Type << OType;
4092 Diag(PVD->getLocation(), diag::note_declared_at);
4093 }
4094 }
4095 }
4096
4097 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4098 // decays into a pointer and returns an unintended result. This is most
4099 // likely a typo for "sizeof(array) op x".
4100 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4101 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4102 BO->getLHS());
4103 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4104 BO->getRHS());
4105 }
4106 }
4107
4108 return false;
4109}
4110
4111/// Check the constraints on operands to unary expression and type
4112/// traits.
4113///
4114/// This will complete any types necessary, and validate the various constraints
4115/// on those operands.
4116///
4117/// The UsualUnaryConversions() function is *not* called by this routine.
4118/// C99 6.3.2.1p[2-4] all state:
4119/// Except when it is the operand of the sizeof operator ...
4120///
4121/// C++ [expr.sizeof]p4
4122/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4123/// standard conversions are not applied to the operand of sizeof.
4124///
4125/// This policy is followed for all of the unary trait expressions.
4126bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4127 SourceLocation OpLoc,
4128 SourceRange ExprRange,
4129 UnaryExprOrTypeTrait ExprKind) {
4130 if (ExprType->isDependentType())
4131 return false;
4132
4133 // C++ [expr.sizeof]p2:
4134 // When applied to a reference or a reference type, the result
4135 // is the size of the referenced type.
4136 // C++11 [expr.alignof]p3:
4137 // When alignof is applied to a reference type, the result
4138 // shall be the alignment of the referenced type.
4139 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4140 ExprType = Ref->getPointeeType();
4141
4142 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4143 // When alignof or _Alignof is applied to an array type, the result
4144 // is the alignment of the element type.
4145 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4146 ExprKind == UETT_OpenMPRequiredSimdAlign)
4147 ExprType = Context.getBaseElementType(ExprType);
4148
4149 if (ExprKind == UETT_VecStep)
4150 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4151
4152 // Explicitly list some types as extensions.
4153 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4154 ExprKind))
4155 return false;
4156
4157 if (RequireCompleteSizedType(
4158 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4159 getTraitSpelling(ExprKind), ExprRange))
4160 return true;
4161
4162 if (ExprType->isFunctionType()) {
4163 Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4164 << getTraitSpelling(ExprKind) << ExprRange;
4165 return true;
4166 }
4167
4168 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4169 ExprKind))
4170 return true;
4171
4172 return false;
4173}
4174
4175static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4176 // Cannot know anything else if the expression is dependent.
4177 if (E->isTypeDependent())
4178 return false;
4179
4180 if (E->getObjectKind() == OK_BitField) {
4181 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4182 << 1 << E->getSourceRange();
4183 return true;
4184 }
4185
4186 ValueDecl *D = nullptr;
4187 Expr *Inner = E->IgnoreParens();
4188 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4189 D = DRE->getDecl();
4190 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4191 D = ME->getMemberDecl();
4192 }
4193
4194 // If it's a field, require the containing struct to have a
4195 // complete definition so that we can compute the layout.
4196 //
4197 // This can happen in C++11 onwards, either by naming the member
4198 // in a way that is not transformed into a member access expression
4199 // (in an unevaluated operand, for instance), or by naming the member
4200 // in a trailing-return-type.
4201 //
4202 // For the record, since __alignof__ on expressions is a GCC
4203 // extension, GCC seems to permit this but always gives the
4204 // nonsensical answer 0.
4205 //
4206 // We don't really need the layout here --- we could instead just
4207 // directly check for all the appropriate alignment-lowing
4208 // attributes --- but that would require duplicating a lot of
4209 // logic that just isn't worth duplicating for such a marginal
4210 // use-case.
4211 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4212 // Fast path this check, since we at least know the record has a
4213 // definition if we can find a member of it.
4214 if (!FD->getParent()->isCompleteDefinition()) {
4215 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4216 << E->getSourceRange();
4217 return true;
4218 }
4219
4220 // Otherwise, if it's a field, and the field doesn't have
4221 // reference type, then it must have a complete type (or be a
4222 // flexible array member, which we explicitly want to
4223 // white-list anyway), which makes the following checks trivial.
4224 if (!FD->getType()->isReferenceType())
4225 return false;
4226 }
4227
4228 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4229}
4230
4231bool Sema::CheckVecStepExpr(Expr *E) {
4232 E = E->IgnoreParens();
4233
4234 // Cannot know anything else if the expression is dependent.
4235 if (E->isTypeDependent())
4236 return false;
4237
4238 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4239}
4240
4241static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4242 CapturingScopeInfo *CSI) {
4243 assert(T->isVariablyModifiedType())((T->isVariablyModifiedType()) ? static_cast<void> (
0) : __assert_fail ("T->isVariablyModifiedType()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 4243, __PRETTY_FUNCTION__))
;
4244 assert(CSI != nullptr)((CSI != nullptr) ? static_cast<void> (0) : __assert_fail
("CSI != nullptr", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 4244, __PRETTY_FUNCTION__))
;
4245
4246 // We're going to walk down into the type and look for VLA expressions.
4247 do {
4248 const Type *Ty = T.getTypePtr();
4249 switch (Ty->getTypeClass()) {
4250#define TYPE(Class, Base)
4251#define ABSTRACT_TYPE(Class, Base)
4252#define NON_CANONICAL_TYPE(Class, Base)
4253#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4254#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4255#include "clang/AST/TypeNodes.inc"
4256 T = QualType();
4257 break;
4258 // These types are never variably-modified.
4259 case Type::Builtin:
4260 case Type::Complex:
4261 case Type::Vector:
4262 case Type::ExtVector:
4263 case Type::ConstantMatrix:
4264 case Type::Record:
4265 case Type::Enum:
4266 case Type::Elaborated:
4267 case Type::TemplateSpecialization:
4268 case Type::ObjCObject:
4269 case Type::ObjCInterface:
4270 case Type::ObjCObjectPointer:
4271 case Type::ObjCTypeParam:
4272 case Type::Pipe:
4273 case Type::ExtInt:
4274 llvm_unreachable("type class is never variably-modified!")::llvm::llvm_unreachable_internal("type class is never variably-modified!"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 4274)
;
4275 case Type::Adjusted:
4276 T = cast<AdjustedType>(Ty)->getOriginalType();
4277 break;
4278 case Type::Decayed:
4279 T = cast<DecayedType>(Ty)->getPointeeType();
4280 break;
4281 case Type::Pointer:
4282 T = cast<PointerType>(Ty)->getPointeeType();
4283 break;
4284 case Type::BlockPointer:
4285 T = cast<BlockPointerType>(Ty)->getPointeeType();
4286 break;
4287 case Type::LValueReference:
4288 case Type::RValueReference:
4289 T = cast<ReferenceType>(Ty)->getPointeeType();
4290 break;
4291 case Type::MemberPointer:
4292 T = cast<MemberPointerType>(Ty)->getPointeeType();
4293 break;
4294 case Type::ConstantArray:
4295 case Type::IncompleteArray:
4296 // Losing element qualification here is fine.
4297 T = cast<ArrayType>(Ty)->getElementType();
4298 break;
4299 case Type::VariableArray: {
4300 // Losing element qualification here is fine.
4301 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4302
4303 // Unknown size indication requires no size computation.
4304 // Otherwise, evaluate and record it.
4305 auto Size = VAT->getSizeExpr();
4306 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4307 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4308 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4309
4310 T = VAT->getElementType();
4311 break;
4312 }
4313 case Type::FunctionProto:
4314 case Type::FunctionNoProto:
4315 T = cast<FunctionType>(Ty)->getReturnType();
4316 break;
4317 case Type::Paren:
4318 case Type::TypeOf:
4319 case Type::UnaryTransform:
4320 case Type::Attributed:
4321 case Type::SubstTemplateTypeParm:
4322 case Type::MacroQualified:
4323 // Keep walking after single level desugaring.
4324 T = T.getSingleStepDesugaredType(Context);
4325 break;
4326 case Type::Typedef:
4327 T = cast<TypedefType>(Ty)->desugar();
4328 break;
4329 case Type::Decltype:
4330 T = cast<DecltypeType>(Ty)->desugar();
4331 break;
4332 case Type::Auto:
4333 case Type::DeducedTemplateSpecialization:
4334 T = cast<DeducedType>(Ty)->getDeducedType();
4335 break;
4336 case Type::TypeOfExpr:
4337 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4338 break;
4339 case Type::Atomic:
4340 T = cast<AtomicType>(Ty)->getValueType();
4341 break;
4342 }
4343 } while (!T.isNull() && T->isVariablyModifiedType());
4344}
4345
4346/// Build a sizeof or alignof expression given a type operand.
4347ExprResult
4348Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4349 SourceLocation OpLoc,
4350 UnaryExprOrTypeTrait ExprKind,
4351 SourceRange R) {
4352 if (!TInfo)
4353 return ExprError();
4354
4355 QualType T = TInfo->getType();
4356
4357 if (!T->isDependentType() &&
4358 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4359 return ExprError();
4360
4361 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4362 if (auto *TT = T->getAs<TypedefType>()) {
4363 for (auto I = FunctionScopes.rbegin(),
4364 E = std::prev(FunctionScopes.rend());
4365 I != E; ++I) {
4366 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4367 if (CSI == nullptr)
4368 break;
4369 DeclContext *DC = nullptr;
4370 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4371 DC = LSI->CallOperator;
4372 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4373 DC = CRSI->TheCapturedDecl;
4374 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4375 DC = BSI->TheDecl;
4376 if (DC) {
4377 if (DC->containsDecl(TT->getDecl()))
4378 break;
4379 captureVariablyModifiedType(Context, T, CSI);
4380 }
4381 }
4382 }
4383 }
4384
4385 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4386 return new (Context) UnaryExprOrTypeTraitExpr(
4387 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4388}
4389
4390/// Build a sizeof or alignof expression given an expression
4391/// operand.
4392ExprResult
4393Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4394 UnaryExprOrTypeTrait ExprKind) {
4395 ExprResult PE = CheckPlaceholderExpr(E);
4396 if (PE.isInvalid())
4397 return ExprError();
4398
4399 E = PE.get();
4400
4401 // Verify that the operand is valid.
4402 bool isInvalid = false;
4403 if (E->isTypeDependent()) {
4404 // Delay type-checking for type-dependent expressions.
4405 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4406 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4407 } else if (ExprKind == UETT_VecStep) {
4408 isInvalid = CheckVecStepExpr(E);
4409 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4410 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4411 isInvalid = true;
4412 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4413 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4414 isInvalid = true;
4415 } else {
4416 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4417 }
4418
4419 if (isInvalid)
4420 return ExprError();
4421
4422 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4423 PE = TransformToPotentiallyEvaluated(E);
4424 if (PE.isInvalid()) return ExprError();
4425 E = PE.get();
4426 }
4427
4428 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4429 return new (Context) UnaryExprOrTypeTraitExpr(
4430 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4431}
4432
4433/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4434/// expr and the same for @c alignof and @c __alignof
4435/// Note that the ArgRange is invalid if isType is false.
4436ExprResult
4437Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4438 UnaryExprOrTypeTrait ExprKind, bool IsType,
4439 void *TyOrEx, SourceRange ArgRange) {
4440 // If error parsing type, ignore.
4441 if (!TyOrEx) return ExprError();
4442
4443 if (IsType) {
4444 TypeSourceInfo *TInfo;
4445 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4446 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4447 }
4448
4449 Expr *ArgEx = (Expr *)TyOrEx;
4450 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4451 return Result;
4452}
4453
4454static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4455 bool IsReal) {
4456 if (V.get()->isTypeDependent())
4457 return S.Context.DependentTy;
4458
4459 // _Real and _Imag are only l-values for normal l-values.
4460 if (V.get()->getObjectKind() != OK_Ordinary) {
4461 V = S.DefaultLvalueConversion(V.get());
4462 if (V.isInvalid())
4463 return QualType();
4464 }
4465
4466 // These operators return the element type of a complex type.
4467 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4468 return CT->getElementType();
4469
4470 // Otherwise they pass through real integer and floating point types here.
4471 if (V.get()->getType()->isArithmeticType())
4472 return V.get()->getType();
4473
4474 // Test for placeholders.
4475 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4476 if (PR.isInvalid()) return QualType();
4477 if (PR.get() != V.get()) {
4478 V = PR;
4479 return CheckRealImagOperand(S, V, Loc, IsReal);
4480 }
4481
4482 // Reject anything else.
4483 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4484 << (IsReal ? "__real" : "__imag");
4485 return QualType();
4486}
4487
4488
4489
4490ExprResult
4491Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4492 tok::TokenKind Kind, Expr *Input) {
4493 UnaryOperatorKind Opc;
4494 switch (Kind) {
4495 default: llvm_unreachable("Unknown unary op!")::llvm::llvm_unreachable_internal("Unknown unary op!", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 4495)
;
4496 case tok::plusplus: Opc = UO_PostInc; break;
4497 case tok::minusminus: Opc = UO_PostDec; break;
4498 }
4499
4500 // Since this might is a postfix expression, get rid of ParenListExprs.
4501 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4502 if (Result.isInvalid()) return ExprError();
4503 Input = Result.get();
4504
4505 return BuildUnaryOp(S, OpLoc, Opc, Input);
4506}
4507
4508/// Diagnose if arithmetic on the given ObjC pointer is illegal.
4509///
4510/// \return true on error
4511static bool checkArithmeticOnObjCPointer(Sema &S,
4512 SourceLocation opLoc,
4513 Expr *op) {
4514 assert(op->getType()->isObjCObjectPointerType())((op->getType()->isObjCObjectPointerType()) ? static_cast
<void> (0) : __assert_fail ("op->getType()->isObjCObjectPointerType()"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 4514, __PRETTY_FUNCTION__))
;
4515 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4516 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4517 return false;
4518
4519 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4520 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4521 << op->getSourceRange();
4522 return true;
4523}
4524
4525static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4526 auto *BaseNoParens = Base->IgnoreParens();
4527 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4528 return MSProp->getPropertyDecl()->getType()->isArrayType();
4529 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4530}
4531
4532ExprResult
4533Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4534 Expr *idx, SourceLocation rbLoc) {
4535 if (base && !base->getType().isNull() &&
4536 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4537 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4538 SourceLocation(), /*Length*/ nullptr,
4539 /*Stride=*/nullptr, rbLoc);
4540
4541 // Since this might be a postfix expression, get rid of ParenListExprs.
4542 if (isa<ParenListExpr>(base)) {
4543 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4544 if (result.isInvalid()) return ExprError();
4545 base = result.get();
4546 }
4547
4548 // Check if base and idx form a MatrixSubscriptExpr.
4549 //
4550 // Helper to check for comma expressions, which are not allowed as indices for
4551 // matrix subscript expressions.
4552 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4553 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4554 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4555 << SourceRange(base->getBeginLoc(), rbLoc);
4556 return true;
4557 }
4558 return false;
4559 };
4560 // The matrix subscript operator ([][])is considered a single operator.
4561 // Separating the index expressions by parenthesis is not allowed.
4562 if (base->getType()->isSpecificPlaceholderType(
4563 BuiltinType::IncompleteMatrixIdx) &&
4564 !isa<MatrixSubscriptExpr>(base)) {
4565 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4566 << SourceRange(base->getBeginLoc(), rbLoc);
4567 return ExprError();
4568 }
4569 // If the base is a MatrixSubscriptExpr, try to create a new
4570 // MatrixSubscriptExpr.
4571 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4572 if (matSubscriptE) {
4573 if (CheckAndReportCommaError(idx))
4574 return ExprError();
4575
4576 assert(matSubscriptE->isIncomplete() &&((matSubscriptE->isIncomplete() && "base has to be an incomplete matrix subscript"
) ? static_cast<void> (0) : __assert_fail ("matSubscriptE->isIncomplete() && \"base has to be an incomplete matrix subscript\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 4577, __PRETTY_FUNCTION__))
4577 "base has to be an incomplete matrix subscript")((matSubscriptE->isIncomplete() && "base has to be an incomplete matrix subscript"
) ? static_cast<void> (0) : __assert_fail ("matSubscriptE->isIncomplete() && \"base has to be an incomplete matrix subscript\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 4577, __PRETTY_FUNCTION__))
;
4578 return CreateBuiltinMatrixSubscriptExpr(
4579 matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc);
4580 }
4581
4582 // Handle any non-overload placeholder types in the base and index
4583 // expressions. We can't handle overloads here because the other
4584 // operand might be an overloadable type, in which case the overload
4585 // resolution for the operator overload should get the first crack
4586 // at the overload.
4587 bool IsMSPropertySubscript = false;
4588 if (base->getType()->isNonOverloadPlaceholderType()) {
4589 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4590 if (!IsMSPropertySubscript) {
4591 ExprResult result = CheckPlaceholderExpr(base);
4592 if (result.isInvalid())
4593 return ExprError();
4594 base = result.get();
4595 }
4596 }
4597
4598 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4599 if (base->getType()->isMatrixType()) {
4600 if (CheckAndReportCommaError(idx))
4601 return ExprError();
4602
4603 return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc);
4604 }
4605
4606 // A comma-expression as the index is deprecated in C++2a onwards.
4607 if (getLangOpts().CPlusPlus20 &&
4608 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4609 (isa<CXXOperatorCallExpr>(idx) &&
4610 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4611 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4612 << SourceRange(base->getBeginLoc(), rbLoc);
4613 }
4614
4615 if (idx->getType()->isNonOverloadPlaceholderType()) {
4616 ExprResult result = CheckPlaceholderExpr(idx);
4617 if (result.isInvalid()) return ExprError();
4618 idx = result.get();
4619 }
4620
4621 // Build an unanalyzed expression if either operand is type-dependent.
4622 if (getLangOpts().CPlusPlus &&
4623 (base->isTypeDependent() || idx->isTypeDependent())) {
4624 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4625 VK_LValue, OK_Ordinary, rbLoc);
4626 }
4627
4628 // MSDN, property (C++)
4629 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4630 // This attribute can also be used in the declaration of an empty array in a
4631 // class or structure definition. For example:
4632 // __declspec(property(get=GetX, put=PutX)) int x[];
4633 // The above statement indicates that x[] can be used with one or more array
4634 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4635 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4636 if (IsMSPropertySubscript) {
4637 // Build MS property subscript expression if base is MS property reference
4638 // or MS property subscript.
4639 return new (Context) MSPropertySubscriptExpr(
4640 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4641 }
4642
4643 // Use C++ overloaded-operator rules if either operand has record
4644 // type. The spec says to do this if either type is *overloadable*,
4645 // but enum types can't declare subscript operators or conversion
4646 // operators, so there's nothing interesting for overload resolution
4647 // to do if there aren't any record types involved.
4648 //
4649 // ObjC pointers have their own subscripting logic that is not tied
4650 // to overload resolution and so should not take this path.
4651 if (getLangOpts().CPlusPlus &&
4652 (base->getType()->isRecordType() ||
4653 (!base->getType()->isObjCObjectPointerType() &&
4654 idx->getType()->isRecordType()))) {
4655 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4656 }
4657
4658 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4659
4660 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4661 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4662
4663 return Res;
4664}
4665
4666ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
4667 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
4668 InitializationKind Kind =
4669 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
4670 InitializationSequence InitSeq(*this, Entity, Kind, E);
4671 return InitSeq.Perform(*this, Entity, Kind, E);
4672}
4673
4674ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4675 Expr *ColumnIdx,
4676 SourceLocation RBLoc) {
4677 ExprResult BaseR = CheckPlaceholderExpr(Base);
4678 if (BaseR.isInvalid())
4679 return BaseR;
4680 Base = BaseR.get();
4681
4682 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4683 if (RowR.isInvalid())
4684 return RowR;
4685 RowIdx = RowR.get();
4686
4687 if (!ColumnIdx)
4688 return new (Context) MatrixSubscriptExpr(
4689 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4690
4691 // Build an unanalyzed expression if any of the operands is type-dependent.
4692 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
4693 ColumnIdx->isTypeDependent())
4694 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4695 Context.DependentTy, RBLoc);
4696
4697 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
4698 if (ColumnR.isInvalid())
4699 return ColumnR;
4700 ColumnIdx = ColumnR.get();
4701
4702 // Check that IndexExpr is an integer expression. If it is a constant
4703 // expression, check that it is less than Dim (= the number of elements in the
4704 // corresponding dimension).
4705 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
4706 bool IsColumnIdx) -> Expr * {
4707 if (!IndexExpr->getType()->isIntegerType() &&
4708 !IndexExpr->isTypeDependent()) {
4709 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
4710 << IsColumnIdx;
4711 return nullptr;
4712 }
4713
4714 if (Optional<llvm::APSInt> Idx =
4715 IndexExpr->getIntegerConstantExpr(Context)) {
4716 if ((*Idx < 0 || *Idx >= Dim)) {
4717 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
4718 << IsColumnIdx << Dim;
4719 return nullptr;
4720 }
4721 }
4722
4723 ExprResult ConvExpr =
4724 tryConvertExprToType(IndexExpr, Context.getSizeType());
4725 assert(!ConvExpr.isInvalid() &&((!ConvExpr.isInvalid() && "should be able to convert any integer type to size type"
) ? static_cast<void> (0) : __assert_fail ("!ConvExpr.isInvalid() && \"should be able to convert any integer type to size type\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 4726, __PRETTY_FUNCTION__))
4726 "should be able to convert any integer type to size type")((!ConvExpr.isInvalid() && "should be able to convert any integer type to size type"
) ? static_cast<void> (0) : __assert_fail ("!ConvExpr.isInvalid() && \"should be able to convert any integer type to size type\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 4726, __PRETTY_FUNCTION__))
;
4727 return ConvExpr.get();
4728 };
4729
4730 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
4731 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
4732 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
4733 if (!RowIdx || !ColumnIdx)
4734 return ExprError();
4735
4736 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4737 MTy->getElementType(), RBLoc);
4738}
4739
4740void Sema::CheckAddressOfNoDeref(const Expr *E) {
4741 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4742 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4743
4744 // For expressions like `&(*s).b`, the base is recorded and what should be
4745 // checked.
4746 const MemberExpr *Member = nullptr;
4747 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4748 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4749
4750 LastRecord.PossibleDerefs.erase(StrippedExpr);
4751}
4752
4753void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4754 if (isUnevaluatedContext())
4755 return;
4756
4757 QualType ResultTy = E->getType();
4758 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4759
4760 // Bail if the element is an array since it is not memory access.
4761 if (isa<ArrayType>(ResultTy))
4762 return;
4763
4764 if (ResultTy->hasAttr(attr::NoDeref)) {
4765 LastRecord.PossibleDerefs.insert(E);
4766 return;
4767 }
4768
4769 // Check if the base type is a pointer to a member access of a struct
4770 // marked with noderef.
4771 const Expr *Base = E->getBase();
4772 QualType BaseTy = Base->getType();
4773 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4774 // Not a pointer access
4775 return;
4776
4777 const MemberExpr *Member = nullptr;
4778 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4779 Member->isArrow())
4780 Base = Member->getBase();
4781
4782 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4783 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4784 LastRecord.PossibleDerefs.insert(E);
4785 }
4786}
4787
4788ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4789 Expr *LowerBound,
4790 SourceLocation ColonLocFirst,
4791 SourceLocation ColonLocSecond,
4792 Expr *Length, Expr *Stride,
4793 SourceLocation RBLoc) {
4794 if (Base->getType()->isPlaceholderType() &&
4795 !Base->getType()->isSpecificPlaceholderType(
4796 BuiltinType::OMPArraySection)) {
4797 ExprResult Result = CheckPlaceholderExpr(Base);
4798 if (Result.isInvalid())
4799 return ExprError();
4800 Base = Result.get();
4801 }
4802 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4803 ExprResult Result = CheckPlaceholderExpr(LowerBound);
4804 if (Result.isInvalid())
4805 return ExprError();
4806 Result = DefaultLvalueConversion(Result.get());
4807 if (Result.isInvalid())
4808 return ExprError();
4809 LowerBound = Result.get();
4810 }
4811 if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4812 ExprResult Result = CheckPlaceholderExpr(Length);
4813 if (Result.isInvalid())
4814 return ExprError();
4815 Result = DefaultLvalueConversion(Result.get());
4816 if (Result.isInvalid())
4817 return ExprError();
4818 Length = Result.get();
4819 }
4820 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
4821 ExprResult Result = CheckPlaceholderExpr(Stride);
4822 if (Result.isInvalid())
4823 return ExprError();
4824 Result = DefaultLvalueConversion(Result.get());
4825 if (Result.isInvalid())
4826 return ExprError();
4827 Stride = Result.get();
4828 }
4829
4830 // Build an unanalyzed expression if either operand is type-dependent.
4831 if (Base->isTypeDependent() ||
4832 (LowerBound &&
4833 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4834 (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
4835 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
4836 return new (Context) OMPArraySectionExpr(
4837 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
4838 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
4839 }
4840
4841 // Perform default conversions.
4842 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4843 QualType ResultTy;
4844 if (OriginalTy->isAnyPointerType()) {
4845 ResultTy = OriginalTy->getPointeeType();
4846 } else if (OriginalTy->isArrayType()) {
4847 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4848 } else {
4849 return ExprError(
4850 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4851 << Base->getSourceRange());
4852 }
4853 // C99 6.5.2.1p1
4854 if (LowerBound) {
4855 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4856 LowerBound);
4857 if (Res.isInvalid())
4858 return ExprError(Diag(LowerBound->getExprLoc(),
4859 diag::err_omp_typecheck_section_not_integer)
4860 << 0 << LowerBound->getSourceRange());
4861 LowerBound = Res.get();
4862
4863 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4864 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4865 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4866 << 0 << LowerBound->getSourceRange();
4867 }
4868 if (Length) {
4869 auto Res =
4870 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4871 if (Res.isInvalid())
4872 return ExprError(Diag(Length->getExprLoc(),
4873 diag::err_omp_typecheck_section_not_integer)
4874 << 1 << Length->getSourceRange());
4875 Length = Res.get();
4876
4877 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4878 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4879 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4880 << 1 << Length->getSourceRange();
4881 }
4882 if (Stride) {
4883 ExprResult Res =
4884 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
4885 if (Res.isInvalid())
4886 return ExprError(Diag(Stride->getExprLoc(),
4887 diag::err_omp_typecheck_section_not_integer)
4888 << 1 << Stride->getSourceRange());
4889 Stride = Res.get();
4890
4891 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4892 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4893 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
4894 << 1 << Stride->getSourceRange();
4895 }
4896
4897 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4898 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4899 // type. Note that functions are not objects, and that (in C99 parlance)
4900 // incomplete types are not object types.
4901 if (ResultTy->isFunctionType()) {
4902 Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4903 << ResultTy << Base->getSourceRange();
4904 return ExprError();
4905 }
4906
4907 if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4908 diag::err_omp_section_incomplete_type, Base))
4909 return ExprError();
4910
4911 if (LowerBound && !OriginalTy->isAnyPointerType()) {
4912 Expr::EvalResult Result;
4913 if (LowerBound->EvaluateAsInt(Result, Context)) {
4914 // OpenMP 5.0, [2.1.5 Array Sections]
4915 // The array section must be a subset of the original array.
4916 llvm::APSInt LowerBoundValue = Result.Val.getInt();
4917 if (LowerBoundValue.isNegative()) {
4918 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4919 << LowerBound->getSourceRange();
4920 return ExprError();
4921 }
4922 }
4923 }
4924
4925 if (Length) {
4926 Expr::EvalResult Result;
4927 if (Length->EvaluateAsInt(Result, Context)) {
4928 // OpenMP 5.0, [2.1.5 Array Sections]
4929 // The length must evaluate to non-negative integers.
4930 llvm::APSInt LengthValue = Result.Val.getInt();
4931 if (LengthValue.isNegative()) {
4932 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4933 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4934 << Length->getSourceRange();
4935 return ExprError();
4936 }
4937 }
4938 } else if (ColonLocFirst.isValid() &&
4939 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4940 !OriginalTy->isVariableArrayType()))) {
4941 // OpenMP 5.0, [2.1.5 Array Sections]
4942 // When the size of the array dimension is not known, the length must be
4943 // specified explicitly.
4944 Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
4945 << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4946 return ExprError();
4947 }
4948
4949 if (Stride) {
4950 Expr::EvalResult Result;
4951 if (Stride->EvaluateAsInt(Result, Context)) {
4952 // OpenMP 5.0, [2.1.5 Array Sections]
4953 // The stride must evaluate to a positive integer.
4954 llvm::APSInt StrideValue = Result.Val.getInt();
4955 if (!StrideValue.isStrictlyPositive()) {
4956 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
4957 << StrideValue.toString(/*Radix=*/10, /*Signed=*/true)
4958 << Stride->getSourceRange();
4959 return ExprError();
4960 }
4961 }
4962 }
4963
4964 if (!Base->getType()->isSpecificPlaceholderType(
4965 BuiltinType::OMPArraySection)) {
4966 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4967 if (Result.isInvalid())
4968 return ExprError();
4969 Base = Result.get();
4970 }
4971 return new (Context) OMPArraySectionExpr(
4972 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
4973 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
4974}
4975
4976ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
4977 SourceLocation RParenLoc,
4978 ArrayRef<Expr *> Dims,
4979 ArrayRef<SourceRange> Brackets) {
4980 if (Base->getType()->isPlaceholderType()) {
4981 ExprResult Result = CheckPlaceholderExpr(Base);
4982 if (Result.isInvalid())
4983 return ExprError();
4984 Result = DefaultLvalueConversion(Result.get());
4985 if (Result.isInvalid())
4986 return ExprError();
4987 Base = Result.get();
4988 }
4989 QualType BaseTy = Base->getType();
4990 // Delay analysis of the types/expressions if instantiation/specialization is
4991 // required.
4992 if (!BaseTy->isPointerType() && Base->isTypeDependent())
4993 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
4994 LParenLoc, RParenLoc, Dims, Brackets);
4995 if (!BaseTy->isPointerType() ||
4996 (!Base->isTypeDependent() &&
4997 BaseTy->getPointeeType()->isIncompleteType()))
4998 return ExprError(Diag(Base->getExprLoc(),
4999 diag::err_omp_non_pointer_type_array_shaping_base)
5000 << Base->getSourceRange());
5001
5002 SmallVector<Expr *, 4> NewDims;
5003 bool ErrorFound = false;
5004 for (Expr *Dim : Dims) {
5005 if (Dim->getType()->isPlaceholderType()) {
5006 ExprResult Result = CheckPlaceholderExpr(Dim);
5007 if (Result.isInvalid()) {
5008 ErrorFound = true;
5009 continue;
5010 }
5011 Result = DefaultLvalueConversion(Result.get());
5012 if (Result.isInvalid()) {
5013 ErrorFound = true;
5014 continue;
5015 }
5016 Dim = Result.get();
5017 }
5018 if (!Dim->isTypeDependent()) {
5019 ExprResult Result =
5020 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5021 if (Result.isInvalid()) {
5022 ErrorFound = true;
5023 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5024 << Dim->getSourceRange();
5025 continue;
5026 }
5027 Dim = Result.get();
5028 Expr::EvalResult EvResult;
5029 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5030 // OpenMP 5.0, [2.1.4 Array Shaping]
5031 // Each si is an integral type expression that must evaluate to a
5032 // positive integer.
5033 llvm::APSInt Value = EvResult.Val.getInt();
5034 if (!Value.isStrictlyPositive()) {
5035 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5036 << Value.toString(/*Radix=*/10, /*Signed=*/true)
5037 << Dim->getSourceRange();
5038 ErrorFound = true;
5039 continue;
5040 }
5041 }
5042 }
5043 NewDims.push_back(Dim);
5044 }
5045 if (ErrorFound)
5046 return ExprError();
5047 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5048 LParenLoc, RParenLoc, NewDims, Brackets);
5049}
5050
5051ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5052 SourceLocation LLoc, SourceLocation RLoc,
5053 ArrayRef<OMPIteratorData> Data) {
5054 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5055 bool IsCorrect = true;
5056 for (const OMPIteratorData &D : Data) {
5057 TypeSourceInfo *TInfo = nullptr;
5058 SourceLocation StartLoc;
5059 QualType DeclTy;
5060 if (!D.Type.getAsOpaquePtr()) {
5061 // OpenMP 5.0, 2.1.6 Iterators
5062 // In an iterator-specifier, if the iterator-type is not specified then
5063 // the type of that iterator is of int type.
5064 DeclTy = Context.IntTy;
5065 StartLoc = D.DeclIdentLoc;
5066 } else {
5067 DeclTy = GetTypeFromParser(D.Type, &TInfo);
5068 StartLoc = TInfo->getTypeLoc().getBeginLoc();
5069 }
5070
5071 bool IsDeclTyDependent = DeclTy->isDependentType() ||
5072 DeclTy->containsUnexpandedParameterPack() ||
5073 DeclTy->isInstantiationDependentType();
5074 if (!IsDeclTyDependent) {
5075 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5076 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5077 // The iterator-type must be an integral or pointer type.
5078 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5079 << DeclTy;
5080 IsCorrect = false;
5081 continue;
5082 }
5083 if (DeclTy.isConstant(Context)) {
5084 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5085 // The iterator-type must not be const qualified.
5086 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5087 << DeclTy;
5088 IsCorrect = false;
5089 continue;
5090 }
5091 }
5092
5093 // Iterator declaration.
5094 assert(D.DeclIdent && "Identifier expected.")((D.DeclIdent && "Identifier expected.") ? static_cast
<void> (0) : __assert_fail ("D.DeclIdent && \"Identifier expected.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 5094, __PRETTY_FUNCTION__))
;
5095 // Always try to create iterator declarator to avoid extra error messages
5096 // about unknown declarations use.
5097 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5098 D.DeclIdent, DeclTy, TInfo, SC_None);
5099 VD->setImplicit();
5100 if (S) {
5101 // Check for conflicting previous declaration.
5102 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5103 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5104 ForVisibleRedeclaration);
5105 Previous.suppressDiagnostics();
5106 LookupName(Previous, S);
5107
5108 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5109 /*AllowInlineNamespace=*/false);
5110 if (!Previous.empty()) {
5111 NamedDecl *Old = Previous.getRepresentativeDecl();
5112 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5113 Diag(Old->getLocation(), diag::note_previous_definition);
5114 } else {
5115 PushOnScopeChains(VD, S);
5116 }
5117 } else {
5118 CurContext->addDecl(VD);
5119 }
5120 Expr *Begin = D.Range.Begin;
5121 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5122 ExprResult BeginRes =
5123 PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5124 Begin = BeginRes.get();
5125 }
5126 Expr *End = D.Range.End;
5127 if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5128 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5129 End = EndRes.get();
5130 }
5131 Expr *Step = D.Range.Step;
5132 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5133 if (!Step->getType()->isIntegralType(Context)) {
5134 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5135 << Step << Step->getSourceRange();
5136 IsCorrect = false;
5137 continue;
5138 }
5139 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context);
5140 // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5141 // If the step expression of a range-specification equals zero, the
5142 // behavior is unspecified.
5143 if (Result && Result->isNullValue()) {
5144 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5145 << Step << Step->getSourceRange();
5146 IsCorrect = false;
5147 continue;
5148 }
5149 }
5150 if (!Begin || !End || !IsCorrect) {
5151 IsCorrect = false;
5152 continue;
5153 }
5154 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5155 IDElem.IteratorDecl = VD;
5156 IDElem.AssignmentLoc = D.AssignLoc;
5157 IDElem.Range.Begin = Begin;
5158 IDElem.Range.End = End;
5159 IDElem.Range.Step = Step;
5160 IDElem.ColonLoc = D.ColonLoc;
5161 IDElem.SecondColonLoc = D.SecColonLoc;
5162 }
5163 if (!IsCorrect) {
5164 // Invalidate all created iterator declarations if error is found.
5165 for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5166 if (Decl *ID = D.IteratorDecl)
5167 ID->setInvalidDecl();
5168 }
5169 return ExprError();
5170 }
5171 SmallVector<OMPIteratorHelperData, 4> Helpers;
5172 if (!CurContext->isDependentContext()) {
5173 // Build number of ityeration for each iteration range.
5174 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5175 // ((Begini-Stepi-1-Endi) / -Stepi);
5176 for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5177 // (Endi - Begini)
5178 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5179 D.Range.Begin);
5180 if(!Res.isUsable()) {
5181 IsCorrect = false;
5182 continue;
5183 }
5184 ExprResult St, St1;
5185 if (D.Range.Step) {
5186 St = D.Range.Step;
5187 // (Endi - Begini) + Stepi
5188 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5189 if (!Res.isUsable()) {
5190 IsCorrect = false;
5191 continue;
5192 }
5193 // (Endi - Begini) + Stepi - 1
5194 Res =
5195 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5196 ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5197 if (!Res.isUsable()) {
5198 IsCorrect = false;
5199 continue;
5200 }
5201 // ((Endi - Begini) + Stepi - 1) / Stepi
5202 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5203 if (!Res.isUsable()) {
5204 IsCorrect = false;
5205 continue;
5206 }
5207 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5208 // (Begini - Endi)
5209 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5210 D.Range.Begin, D.Range.End);
5211 if (!Res1.isUsable()) {
5212 IsCorrect = false;
5213 continue;
5214 }
5215 // (Begini - Endi) - Stepi
5216 Res1 =
5217 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5218 if (!Res1.isUsable()) {
5219 IsCorrect = false;
5220 continue;
5221 }
5222 // (Begini - Endi) - Stepi - 1
5223 Res1 =
5224 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5225 ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5226 if (!Res1.isUsable()) {
5227 IsCorrect = false;
5228 continue;
5229 }
5230 // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5231 Res1 =
5232 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5233 if (!Res1.isUsable()) {
5234 IsCorrect = false;
5235 continue;
5236 }
5237 // Stepi > 0.
5238 ExprResult CmpRes =
5239 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5240 ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5241 if (!CmpRes.isUsable()) {
5242 IsCorrect = false;
5243 continue;
5244 }
5245 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5246 Res.get(), Res1.get());
5247 if (!Res.isUsable()) {
5248 IsCorrect = false;
5249 continue;
5250 }
5251 }
5252 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5253 if (!Res.isUsable()) {
5254 IsCorrect = false;
5255 continue;
5256 }
5257
5258 // Build counter update.
5259 // Build counter.
5260 auto *CounterVD =
5261 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5262 D.IteratorDecl->getBeginLoc(), nullptr,
5263 Res.get()->getType(), nullptr, SC_None);
5264 CounterVD->setImplicit();
5265 ExprResult RefRes =
5266 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5267 D.IteratorDecl->getBeginLoc());
5268 // Build counter update.
5269 // I = Begini + counter * Stepi;
5270 ExprResult UpdateRes;
5271 if (D.Range.Step) {
5272 UpdateRes = CreateBuiltinBinOp(
5273 D.AssignmentLoc, BO_Mul,
5274 DefaultLvalueConversion(RefRes.get()).get(), St.get());
5275 } else {
5276 UpdateRes = DefaultLvalueConversion(RefRes.get());
5277 }
5278 if (!UpdateRes.isUsable()) {
5279 IsCorrect = false;
5280 continue;
5281 }
5282 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5283 UpdateRes.get());
5284 if (!UpdateRes.isUsable()) {
5285 IsCorrect = false;
5286 continue;
5287 }
5288 ExprResult VDRes =
5289 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5290 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5291 D.IteratorDecl->getBeginLoc());
5292 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5293 UpdateRes.get());
5294 if (!UpdateRes.isUsable()) {
5295 IsCorrect = false;
5296 continue;
5297 }
5298 UpdateRes =
5299 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5300 if (!UpdateRes.isUsable()) {
5301 IsCorrect = false;
5302 continue;
5303 }
5304 ExprResult CounterUpdateRes =
5305 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5306 if (!CounterUpdateRes.isUsable()) {
5307 IsCorrect = false;
5308 continue;
5309 }
5310 CounterUpdateRes =
5311 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5312 if (!CounterUpdateRes.isUsable()) {
5313 IsCorrect = false;
5314 continue;
5315 }
5316 OMPIteratorHelperData &HD = Helpers.emplace_back();
5317 HD.CounterVD = CounterVD;
5318 HD.Upper = Res.get();
5319 HD.Update = UpdateRes.get();
5320 HD.CounterUpdate = CounterUpdateRes.get();
5321 }
5322 } else {
5323 Helpers.assign(ID.size(), {});
5324 }
5325 if (!IsCorrect) {
5326 // Invalidate all created iterator declarations if error is found.
5327 for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5328 if (Decl *ID = D.IteratorDecl)
5329 ID->setInvalidDecl();
5330 }
5331 return ExprError();
5332 }
5333 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5334 LLoc, RLoc, ID, Helpers);
5335}
5336
5337ExprResult
5338Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5339 Expr *Idx, SourceLocation RLoc) {
5340 Expr *LHSExp = Base;
5341 Expr *RHSExp = Idx;
5342
5343 ExprValueKind VK = VK_LValue;
5344 ExprObjectKind OK = OK_Ordinary;
5345
5346 // Per C++ core issue 1213, the result is an xvalue if either operand is
5347 // a non-lvalue array, and an lvalue otherwise.
5348 if (getLangOpts().CPlusPlus11) {
5349 for (auto *Op : {LHSExp, RHSExp}) {
5350 Op = Op->IgnoreImplicit();
5351 if (Op->getType()->isArrayType() && !Op->isLValue())
5352 VK = VK_XValue;
5353 }
5354 }
5355
5356 // Perform default conversions.
5357 if (!LHSExp->getType()->getAs<VectorType>()) {
5358 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5359 if (Result.isInvalid())
5360 return ExprError();
5361 LHSExp = Result.get();
5362 }
5363 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5364 if (Result.isInvalid())
5365 return ExprError();
5366 RHSExp = Result.get();
5367
5368 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5369
5370 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5371 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5372 // in the subscript position. As a result, we need to derive the array base
5373 // and index from the expression types.
5374 Expr *BaseExpr, *IndexExpr;
5375 QualType ResultType;
5376 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5377 BaseExpr = LHSExp;
5378 IndexExpr = RHSExp;
5379 ResultType = Context.DependentTy;
5380 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5381 BaseExpr = LHSExp;
5382 IndexExpr = RHSExp;
5383 ResultType = PTy->getPointeeType();
5384 } else if (const ObjCObjectPointerType *PTy =
5385 LHSTy->getAs<ObjCObjectPointerType>()) {
5386 BaseExpr = LHSExp;
5387 IndexExpr = RHSExp;
5388
5389 // Use custom logic if this should be the pseudo-object subscript
5390 // expression.
5391 if (!LangOpts.isSubscriptPointerArithmetic())
5392 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5393 nullptr);
5394
5395 ResultType = PTy->getPointeeType();
5396 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5397 // Handle the uncommon case of "123[Ptr]".
5398 BaseExpr = RHSExp;
5399 IndexExpr = LHSExp;
5400 ResultType = PTy->getPointeeType();
5401 } else if (const ObjCObjectPointerType *PTy =
5402 RHSTy->getAs<ObjCObjectPointerType>()) {
5403 // Handle the uncommon case of "123[Ptr]".
5404 BaseExpr = RHSExp;
5405 IndexExpr = LHSExp;
5406 ResultType = PTy->getPointeeType();
5407 if (!LangOpts.isSubscriptPointerArithmetic()) {
5408 Diag(LLoc, diag::err_subscript_nonfragile_interface)
5409 << ResultType << BaseExpr->getSourceRange();
5410 return ExprError();
5411 }
5412 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5413 BaseExpr = LHSExp; // vectors: V[123]
5414 IndexExpr = RHSExp;
5415 // We apply C++ DR1213 to vector subscripting too.
5416 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
5417 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5418 if (Materialized.isInvalid())
5419 return ExprError();
5420 LHSExp = Materialized.get();
5421 }
5422 VK = LHSExp->getValueKind();
5423 if (VK != VK_RValue)
5424 OK = OK_VectorComponent;
5425
5426 ResultType = VTy->getElementType();
5427 QualType BaseType = BaseExpr->getType();
5428 Qualifiers BaseQuals = BaseType.getQualifiers();
5429 Qualifiers MemberQuals = ResultType.getQualifiers();
5430 Qualifiers Combined = BaseQuals + MemberQuals;
5431 if (Combined != MemberQuals)
5432 ResultType = Context.getQualifiedType(ResultType, Combined);
5433 } else if (LHSTy->isArrayType()) {
5434 // If we see an array that wasn't promoted by
5435 // DefaultFunctionArrayLvalueConversion, it must be an array that
5436 // wasn't promoted because of the C90 rule that doesn't
5437 // allow promoting non-lvalue arrays. Warn, then
5438 // force the promotion here.
5439 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5440 << LHSExp->getSourceRange();
5441 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5442 CK_ArrayToPointerDecay).get();
5443 LHSTy = LHSExp->getType();
5444
5445 BaseExpr = LHSExp;
5446 IndexExpr = RHSExp;
5447 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
5448 } else if (RHSTy->isArrayType()) {
5449 // Same as previous, except for 123[f().a] case
5450 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5451 << RHSExp->getSourceRange();
5452 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5453 CK_ArrayToPointerDecay).get();
5454 RHSTy = RHSExp->getType();
5455
5456 BaseExpr = RHSExp;
5457 IndexExpr = LHSExp;
5458 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
5459 } else {
5460 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5461 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5462 }
5463 // C99 6.5.2.1p1
5464 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5465 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5466 << IndexExpr->getSourceRange());
5467
5468 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5469 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5470 && !IndexExpr->isTypeDependent())
5471 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5472
5473 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5474 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5475 // type. Note that Functions are not objects, and that (in C99 parlance)
5476 // incomplete types are not object types.
5477 if (ResultType->isFunctionType()) {
5478 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5479 << ResultType << BaseExpr->getSourceRange();
5480 return ExprError();
5481 }
5482
5483 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5484 // GNU extension: subscripting on pointer to void
5485 Diag(LLoc, diag::ext_gnu_subscript_void_type)
5486 << BaseExpr->getSourceRange();
5487
5488 // C forbids expressions of unqualified void type from being l-values.
5489 // See IsCForbiddenLValueType.
5490 if (!ResultType.hasQualifiers()) VK = VK_RValue;
5491 } else if (!ResultType->isDependentType() &&
5492 RequireCompleteSizedType(
5493 LLoc, ResultType,
5494 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5495 return ExprError();
5496
5497 assert(VK == VK_RValue || LangOpts.CPlusPlus ||((VK == VK_RValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType
()) ? static_cast<void> (0) : __assert_fail ("VK == VK_RValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType()"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 5498, __PRETTY_FUNCTION__))
5498 !ResultType.isCForbiddenLValueType())((VK == VK_RValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType
()) ? static_cast<void> (0) : __assert_fail ("VK == VK_RValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType()"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 5498, __PRETTY_FUNCTION__))
;
5499
5500 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5501 FunctionScopes.size() > 1) {
5502 if (auto *TT =
5503 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5504 for (auto I = FunctionScopes.rbegin(),
5505 E = std::prev(FunctionScopes.rend());
5506 I != E; ++I) {
5507 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5508 if (CSI == nullptr)
5509 break;
5510 DeclContext *DC = nullptr;
5511 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5512 DC = LSI->CallOperator;
5513 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5514 DC = CRSI->TheCapturedDecl;
5515 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5516 DC = BSI->TheDecl;
5517 if (DC) {
5518 if (DC->containsDecl(TT->getDecl()))
5519 break;
5520 captureVariablyModifiedType(
5521 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5522 }
5523 }
5524 }
5525 }
5526
5527 return new (Context)
5528 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5529}
5530
5531bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5532 ParmVarDecl *Param) {
5533 if (Param->hasUnparsedDefaultArg()) {
5534 // If we've already cleared out the location for the default argument,
5535 // that means we're parsing it right now.
5536 if (!UnparsedDefaultArgLocs.count(Param)) {
5537 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5538 Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5539 Param->setInvalidDecl();
5540 return true;
5541 }
5542
5543 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5544 << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5545 Diag(UnparsedDefaultArgLocs[Param],
5546 diag::note_default_argument_declared_here);
5547 return true;
5548 }
5549
5550 if (Param->hasUninstantiatedDefaultArg() &&
5551 InstantiateDefaultArgument(CallLoc, FD, Param))
5552 return true;
5553
5554 assert(Param->hasInit() && "default argument but no initializer?")((Param->hasInit() && "default argument but no initializer?"
) ? static_cast<void> (0) : __assert_fail ("Param->hasInit() && \"default argument but no initializer?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 5554, __PRETTY_FUNCTION__))
;
5555
5556 // If the default expression creates temporaries, we need to
5557 // push them to the current stack of expression temporaries so they'll
5558 // be properly destroyed.
5559 // FIXME: We should really be rebuilding the default argument with new
5560 // bound temporaries; see the comment in PR5810.
5561 // We don't need to do that with block decls, though, because
5562 // blocks in default argument expression can never capture anything.
5563 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5564 // Set the "needs cleanups" bit regardless of whether there are
5565 // any explicit objects.
5566 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5567
5568 // Append all the objects to the cleanup list. Right now, this
5569 // should always be a no-op, because blocks in default argument
5570 // expressions should never be able to capture anything.
5571 assert(!Init->getNumObjects() &&((!Init->getNumObjects() && "default argument expression has capturing blocks?"
) ? static_cast<void> (0) : __assert_fail ("!Init->getNumObjects() && \"default argument expression has capturing blocks?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 5572, __PRETTY_FUNCTION__))
5572 "default argument expression has capturing blocks?")((!Init->getNumObjects() && "default argument expression has capturing blocks?"
) ? static_cast<void> (0) : __assert_fail ("!Init->getNumObjects() && \"default argument expression has capturing blocks?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 5572, __PRETTY_FUNCTION__))
;
5573 }
5574
5575 // We already type-checked the argument, so we know it works.
5576 // Just mark all of the declarations in this potentially-evaluated expression
5577 // as being "referenced".
5578 EnterExpressionEvaluationContext EvalContext(
5579 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5580 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5581 /*SkipLocalVariables=*/true);
5582 return false;
5583}
5584
5585ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5586 FunctionDecl *FD, ParmVarDecl *Param) {
5587 assert(Param->hasDefaultArg() && "can't build nonexistent default arg")((Param->hasDefaultArg() && "can't build nonexistent default arg"
) ? static_cast<void> (0) : __assert_fail ("Param->hasDefaultArg() && \"can't build nonexistent default arg\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 5587, __PRETTY_FUNCTION__))
;
5588 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5589 return ExprError();
5590 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5591}
5592
5593Sema::VariadicCallType
5594Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5595 Expr *Fn) {
5596 if (Proto && Proto->isVariadic()) {
5597 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
5598 return VariadicConstructor;
5599 else if (Fn && Fn->getType()->isBlockPointerType())
5600 return VariadicBlock;
5601 else if (FDecl) {
5602 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5603 if (Method->isInstance())
5604 return VariadicMethod;
5605 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5606 return VariadicMethod;
5607 return VariadicFunction;
5608 }
5609 return VariadicDoesNotApply;
5610}
5611
5612namespace {
5613class FunctionCallCCC final : public FunctionCallFilterCCC {
5614public:
5615 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5616 unsigned NumArgs, MemberExpr *ME)
5617 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5618 FunctionName(FuncName) {}
5619
5620 bool ValidateCandidate(const TypoCorrection &candidate) override {
5621 if (!candidate.getCorrectionSpecifier() ||
5622 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5623 return false;
5624 }
5625
5626 return FunctionCallFilterCCC::ValidateCandidate(candidate);
5627 }
5628
5629 std::unique_ptr<CorrectionCandidateCallback> clone() override {
5630 return std::make_unique<FunctionCallCCC>(*this);
5631 }
5632
5633private:
5634 const IdentifierInfo *const FunctionName;
5635};
5636}
5637
5638static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5639 FunctionDecl *FDecl,
5640 ArrayRef<Expr *> Args) {
5641 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5642 DeclarationName FuncName = FDecl->getDeclName();
5643 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5644
5645 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5646 if (TypoCorrection Corrected = S.CorrectTypo(
5647 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5648 S.getScopeForContext(S.CurContext), nullptr, CCC,
5649 Sema::CTK_ErrorRecovery)) {
5650 if (NamedDecl *ND = Corrected.getFoundDecl()) {
5651 if (Corrected.isOverloaded()) {
5652 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5653 OverloadCandidateSet::iterator Best;
5654 for (NamedDecl *CD : Corrected) {
5655 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5656 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5657 OCS);
5658 }
5659 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5660 case OR_Success:
5661 ND = Best->FoundDecl;
5662 Corrected.setCorrectionDecl(ND);
5663 break;
5664 default:
5665 break;
5666 }
5667 }
5668 ND = ND->getUnderlyingDecl();
5669 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5670 return Corrected;
5671 }
5672 }
5673 return TypoCorrection();
5674}
5675
5676/// ConvertArgumentsForCall - Converts the arguments specified in
5677/// Args/NumArgs to the parameter types of the function FDecl with
5678/// function prototype Proto. Call is the call expression itself, and
5679/// Fn is the function expression. For a C++ member function, this
5680/// routine does not attempt to convert the object argument. Returns
5681/// true if the call is ill-formed.
5682bool
5683Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5684 FunctionDecl *FDecl,
5685 const FunctionProtoType *Proto,
5686 ArrayRef<Expr *> Args,
5687 SourceLocation RParenLoc,
5688 bool IsExecConfig) {
5689 // Bail out early if calling a builtin with custom typechecking.
5690 if (FDecl)
5691 if (unsigned ID = FDecl->getBuiltinID())
5692 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5693 return false;
5694
5695 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5696 // assignment, to the types of the corresponding parameter, ...
5697 unsigned NumParams = Proto->getNumParams();
5698 bool Invalid = false;
5699 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5700 unsigned FnKind = Fn->getType()->isBlockPointerType()
5701 ? 1 /* block */
5702 : (IsExecConfig ? 3 /* kernel function (exec config) */
5703 : 0 /* function */);
5704
5705 // If too few arguments are available (and we don't have default
5706 // arguments for the remaining parameters), don't make the call.
5707 if (Args.size() < NumParams) {
5708 if (Args.size() < MinArgs) {
5709 TypoCorrection TC;
5710 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5711 unsigned diag_id =
5712 MinArgs == NumParams && !Proto->isVariadic()
5713 ? diag::err_typecheck_call_too_few_args_suggest
5714 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5715 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5716 << static_cast<unsigned>(Args.size())
5717 << TC.getCorrectionRange());
5718 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5719 Diag(RParenLoc,
5720 MinArgs == NumParams && !Proto->isVariadic()
5721 ? diag::err_typecheck_call_too_few_args_one
5722 : diag::err_typecheck_call_too_few_args_at_least_one)
5723 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5724 else
5725 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5726 ? diag::err_typecheck_call_too_few_args
5727 : diag::err_typecheck_call_too_few_args_at_least)
5728 << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5729 << Fn->getSourceRange();
5730
5731 // Emit the location of the prototype.
5732 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5733 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5734
5735 return true;
5736 }
5737 // We reserve space for the default arguments when we create
5738 // the call expression, before calling ConvertArgumentsForCall.
5739 assert((Call->getNumArgs() == NumParams) &&(((Call->getNumArgs() == NumParams) && "We should have reserved space for the default arguments before!"
) ? static_cast<void> (0) : __assert_fail ("(Call->getNumArgs() == NumParams) && \"We should have reserved space for the default arguments before!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 5740, __PRETTY_FUNCTION__))
5740 "We should have reserved space for the default arguments before!")(((Call->getNumArgs() == NumParams) && "We should have reserved space for the default arguments before!"
) ? static_cast<void> (0) : __assert_fail ("(Call->getNumArgs() == NumParams) && \"We should have reserved space for the default arguments before!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 5740, __PRETTY_FUNCTION__))
;
5741 }
5742
5743 // If too many are passed and not variadic, error on the extras and drop
5744 // them.
5745 if (Args.size() > NumParams) {
5746 if (!Proto->isVariadic()) {
5747 TypoCorrection TC;
5748 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5749 unsigned diag_id =
5750 MinArgs == NumParams && !Proto->isVariadic()
5751 ? diag::err_typecheck_call_too_many_args_suggest
5752 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5753 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5754 << static_cast<unsigned>(Args.size())
5755 << TC.getCorrectionRange());
5756 } else if (NumParams == 1 && FDecl &&
5757 FDecl->getParamDecl(0)->getDeclName())
5758 Diag(Args[NumParams]->getBeginLoc(),
5759 MinArgs == NumParams
5760 ? diag::err_typecheck_call_too_many_args_one
5761 : diag::err_typecheck_call_too_many_args_at_most_one)
5762 << FnKind << FDecl->getParamDecl(0)
5763 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5764 << SourceRange(Args[NumParams]->getBeginLoc(),
5765 Args.back()->getEndLoc());
5766 else
5767 Diag(Args[NumParams]->getBeginLoc(),
5768 MinArgs == NumParams
5769 ? diag::err_typecheck_call_too_many_args
5770 : diag::err_typecheck_call_too_many_args_at_most)
5771 << FnKind << NumParams << static_cast<unsigned>(Args.size())
5772 << Fn->getSourceRange()
5773 << SourceRange(Args[NumParams]->getBeginLoc(),
5774 Args.back()->getEndLoc());
5775
5776 // Emit the location of the prototype.
5777 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5778 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5779
5780 // This deletes the extra arguments.
5781 Call->shrinkNumArgs(NumParams);
5782 return true;
5783 }
5784 }
5785 SmallVector<Expr *, 8> AllArgs;
5786 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5787
5788 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5789 AllArgs, CallType);
5790 if (Invalid)
5791 return true;
5792 unsigned TotalNumArgs = AllArgs.size();
5793 for (unsigned i = 0; i < TotalNumArgs; ++i)
5794 Call->setArg(i, AllArgs[i]);
5795
5796 return false;
5797}
5798
5799bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5800 const FunctionProtoType *Proto,
5801 unsigned FirstParam, ArrayRef<Expr *> Args,
5802 SmallVectorImpl<Expr *> &AllArgs,
5803 VariadicCallType CallType, bool AllowExplicit,
5804 bool IsListInitialization) {
5805 unsigned NumParams = Proto->getNumParams();
5806 bool Invalid = false;
5807 size_t ArgIx = 0;
5808 // Continue to check argument types (even if we have too few/many args).
5809 for (unsigned i = FirstParam; i < NumParams; i++) {
5810 QualType ProtoArgType = Proto->getParamType(i);
5811
5812 Expr *Arg;
5813 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5814 if (ArgIx < Args.size()) {
5815 Arg = Args[ArgIx++];
5816
5817 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5818 diag::err_call_incomplete_argument, Arg))
5819 return true;
5820
5821 // Strip the unbridged-cast placeholder expression off, if applicable.
5822 bool CFAudited = false;
5823 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5824 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5825 (!Param || !Param->hasAttr<CFConsumedAttr>()))
5826 Arg = stripARCUnbridgedCast(Arg);
5827 else if (getLangOpts().ObjCAutoRefCount &&
5828 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5829 (!Param || !Param->hasAttr<CFConsumedAttr>()))
5830 CFAudited = true;
5831
5832 if (Proto->getExtParameterInfo(i).isNoEscape())
5833 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5834 BE->getBlockDecl()->setDoesNotEscape();
5835
5836 InitializedEntity Entity =
5837 Param ? InitializedEntity::InitializeParameter(Context, Param,
5838 ProtoArgType)
5839 : InitializedEntity::InitializeParameter(
5840 Context, ProtoArgType, Proto->isParamConsumed(i));
5841
5842 // Remember that parameter belongs to a CF audited API.
5843 if (CFAudited)
5844 Entity.setParameterCFAudited();
5845
5846 ExprResult ArgE = PerformCopyInitialization(
5847 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5848 if (ArgE.isInvalid())
5849 return true;
5850
5851 Arg = ArgE.getAs<Expr>();
5852 } else {
5853 assert(Param && "can't use default arguments without a known callee")((Param && "can't use default arguments without a known callee"
) ? static_cast<void> (0) : __assert_fail ("Param && \"can't use default arguments without a known callee\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 5853, __PRETTY_FUNCTION__))
;
5854
5855 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5856 if (ArgExpr.isInvalid())
5857 return true;
5858
5859 Arg = ArgExpr.getAs<Expr>();
5860 }
5861
5862 // Check for array bounds violations for each argument to the call. This
5863 // check only triggers warnings when the argument isn't a more complex Expr
5864 // with its own checking, such as a BinaryOperator.
5865 CheckArrayAccess(Arg);
5866
5867 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5868 CheckStaticArrayArgument(CallLoc, Param, Arg);
5869
5870 AllArgs.push_back(Arg);
5871 }
5872
5873 // If this is a variadic call, handle args passed through "...".
5874 if (CallType != VariadicDoesNotApply) {
5875 // Assume that extern "C" functions with variadic arguments that
5876 // return __unknown_anytype aren't *really* variadic.
5877 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5878 FDecl->isExternC()) {
5879 for (Expr *A : Args.slice(ArgIx)) {
5880 QualType paramType; // ignored
5881 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5882 Invalid |= arg.isInvalid();
5883 AllArgs.push_back(arg.get());
5884 }
5885
5886 // Otherwise do argument promotion, (C99 6.5.2.2p7).
5887 } else {
5888 for (Expr *A : Args.slice(ArgIx)) {
5889 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5890 Invalid |= Arg.isInvalid();
5891 AllArgs.push_back(Arg.get());
5892 }
5893 }
5894
5895 // Check for array bounds violations.
5896 for (Expr *A : Args.slice(ArgIx))
5897 CheckArrayAccess(A);
5898 }
5899 return Invalid;
5900}
5901
5902static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5903 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5904 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5905 TL = DTL.getOriginalLoc();
5906 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5907 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5908 << ATL.getLocalSourceRange();
5909}
5910
5911/// CheckStaticArrayArgument - If the given argument corresponds to a static
5912/// array parameter, check that it is non-null, and that if it is formed by
5913/// array-to-pointer decay, the underlying array is sufficiently large.
5914///
5915/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5916/// array type derivation, then for each call to the function, the value of the
5917/// corresponding actual argument shall provide access to the first element of
5918/// an array with at least as many elements as specified by the size expression.
5919void
5920Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5921 ParmVarDecl *Param,
5922 const Expr *ArgExpr) {
5923 // Static array parameters are not supported in C++.
5924 if (!Param || getLangOpts().CPlusPlus)
5925 return;
5926
5927 QualType OrigTy = Param->getOriginalType();
5928
5929 const ArrayType *AT = Context.getAsArrayType(OrigTy);
5930 if (!AT || AT->getSizeModifier() != ArrayType::Static)
5931 return;
5932
5933 if (ArgExpr->isNullPointerConstant(Context,
5934 Expr::NPC_NeverValueDependent)) {
5935 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5936 DiagnoseCalleeStaticArrayParam(*this, Param);
5937 return;
5938 }
5939
5940 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5941 if (!CAT)
5942 return;
5943
5944 const ConstantArrayType *ArgCAT =
5945 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
5946 if (!ArgCAT)
5947 return;
5948
5949 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
5950 ArgCAT->getElementType())) {
5951 if (ArgCAT->getSize().ult(CAT->getSize())) {
5952 Diag(CallLoc, diag::warn_static_array_too_small)
5953 << ArgExpr->getSourceRange()
5954 << (unsigned)ArgCAT->getSize().getZExtValue()
5955 << (unsigned)CAT->getSize().getZExtValue() << 0;
5956 DiagnoseCalleeStaticArrayParam(*this, Param);
5957 }
5958 return;
5959 }
5960
5961 Optional<CharUnits> ArgSize =
5962 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
5963 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
5964 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
5965 Diag(CallLoc, diag::warn_static_array_too_small)
5966 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
5967 << (unsigned)ParmSize->getQuantity() << 1;
5968 DiagnoseCalleeStaticArrayParam(*this, Param);
5969 }
5970}
5971
5972/// Given a function expression of unknown-any type, try to rebuild it
5973/// to have a function type.
5974static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5975
5976/// Is the given type a placeholder that we need to lower out
5977/// immediately during argument processing?
5978static bool isPlaceholderToRemoveAsArg(QualType type) {
5979 // Placeholders are never sugared.
5980 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5981 if (!placeholder) return false;
5982
5983 switch (placeholder->getKind()) {
5984 // Ignore all the non-placeholder types.
5985#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5986 case BuiltinType::Id:
5987#include "clang/Basic/OpenCLImageTypes.def"
5988#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
5989 case BuiltinType::Id:
5990#include "clang/Basic/OpenCLExtensionTypes.def"
5991 // In practice we'll never use this, since all SVE types are sugared
5992 // via TypedefTypes rather than exposed directly as BuiltinTypes.
5993#define SVE_TYPE(Name, Id, SingletonId) \
5994 case BuiltinType::Id:
5995#include "clang/Basic/AArch64SVEACLETypes.def"
5996#define PPC_MMA_VECTOR_TYPE(Name, Id, Size) \
5997 case BuiltinType::Id:
5998#include "clang/Basic/PPCTypes.def"
5999#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6000#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6001#include "clang/AST/BuiltinTypes.def"
6002 return false;
6003
6004 // We cannot lower out overload sets; they might validly be resolved
6005 // by the call machinery.
6006 case BuiltinType::Overload:
6007 return false;
6008
6009 // Unbridged casts in ARC can be handled in some call positions and
6010 // should be left in place.
6011 case BuiltinType::ARCUnbridgedCast:
6012 return false;
6013
6014 // Pseudo-objects should be converted as soon as possible.
6015 case BuiltinType::PseudoObject:
6016 return true;
6017
6018 // The debugger mode could theoretically but currently does not try
6019 // to resolve unknown-typed arguments based on known parameter types.
6020 case BuiltinType::UnknownAny:
6021 return true;
6022
6023 // These are always invalid as call arguments and should be reported.
6024 case BuiltinType::BoundMember:
6025 case BuiltinType::BuiltinFn:
6026 case BuiltinType::IncompleteMatrixIdx:
6027 case BuiltinType::OMPArraySection:
6028 case BuiltinType::OMPArrayShaping:
6029 case BuiltinType::OMPIterator:
6030 return true;
6031
6032 }
6033 llvm_unreachable("bad builtin type kind")::llvm::llvm_unreachable_internal("bad builtin type kind", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 6033)
;
6034}
6035
6036/// Check an argument list for placeholders that we won't try to
6037/// handle later.
6038static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6039 // Apply this processing to all the arguments at once instead of
6040 // dying at the first failure.
6041 bool hasInvalid = false;
6042 for (size_t i = 0, e = args.size(); i != e; i++) {
6043 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6044 ExprResult result = S.CheckPlaceholderExpr(args[i]);
6045 if (result.isInvalid()) hasInvalid = true;
6046 else args[i] = result.get();
6047 }
6048 }
6049 return hasInvalid;
6050}
6051
6052/// If a builtin function has a pointer argument with no explicit address
6053/// space, then it should be able to accept a pointer to any address
6054/// space as input. In order to do this, we need to replace the
6055/// standard builtin declaration with one that uses the same address space
6056/// as the call.
6057///
6058/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6059/// it does not contain any pointer arguments without
6060/// an address space qualifer. Otherwise the rewritten
6061/// FunctionDecl is returned.
6062/// TODO: Handle pointer return types.
6063static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6064 FunctionDecl *FDecl,
6065 MultiExprArg ArgExprs) {
6066
6067 QualType DeclType = FDecl->getType();
6068 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6069
6070 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6071 ArgExprs.size() < FT->getNumParams())
6072 return nullptr;
6073
6074 bool NeedsNewDecl = false;
6075 unsigned i = 0;
6076 SmallVector<QualType, 8> OverloadParams;
6077
6078 for (QualType ParamType : FT->param_types()) {
6079
6080 // Convert array arguments to pointer to simplify type lookup.
6081 ExprResult ArgRes =
6082 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6083 if (ArgRes.isInvalid())
6084 return nullptr;
6085 Expr *Arg = ArgRes.get();
6086 QualType ArgType = Arg->getType();
6087 if (!ParamType->isPointerType() ||
6088 ParamType.hasAddressSpace() ||
6089 !ArgType->isPointerType() ||
6090 !ArgType->getPointeeType().hasAddressSpace()) {
6091 OverloadParams.push_back(ParamType);
6092 continue;
6093 }
6094
6095 QualType PointeeType = ParamType->getPointeeType();
6096 if (PointeeType.hasAddressSpace())
6097 continue;
6098
6099 NeedsNewDecl = true;
6100 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6101
6102 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6103 OverloadParams.push_back(Context.getPointerType(PointeeType));
6104 }
6105
6106 if (!NeedsNewDecl)
6107 return nullptr;
6108
6109 FunctionProtoType::ExtProtoInfo EPI;
6110 EPI.Variadic = FT->isVariadic();
6111 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6112 OverloadParams, EPI);
6113 DeclContext *Parent = FDecl->getParent();
6114 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
6115 FDecl->getLocation(),
6116 FDecl->getLocation(),
6117 FDecl->getIdentifier(),
6118 OverloadTy,
6119 /*TInfo=*/nullptr,
6120 SC_Extern, false,
6121 /*hasPrototype=*/true);
6122 SmallVector<ParmVarDecl*, 16> Params;
6123 FT = cast<FunctionProtoType>(OverloadTy);
6124 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6125 QualType ParamType = FT->getParamType(i);
6126 ParmVarDecl *Parm =
6127 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6128 SourceLocation(), nullptr, ParamType,
6129 /*TInfo=*/nullptr, SC_None, nullptr);
6130 Parm->setScopeInfo(0, i);
6131 Params.push_back(Parm);
6132 }
6133 OverloadDecl->setParams(Params);
6134 Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6135 return OverloadDecl;
6136}
6137
6138static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6139 FunctionDecl *Callee,
6140 MultiExprArg ArgExprs) {
6141 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6142 // similar attributes) really don't like it when functions are called with an
6143 // invalid number of args.
6144 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6145 /*PartialOverloading=*/false) &&
6146 !Callee->isVariadic())
6147 return;
6148 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6149 return;
6150
6151 if (const EnableIfAttr *Attr =
6152 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6153 S.Diag(Fn->getBeginLoc(),
6154 isa<CXXMethodDecl>(Callee)
6155 ? diag::err_ovl_no_viable_member_function_in_call
6156 : diag::err_ovl_no_viable_function_in_call)
6157 << Callee << Callee->getSourceRange();
6158 S.Diag(Callee->getLocation(),
6159 diag::note_ovl_candidate_disabled_by_function_cond_attr)
6160 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6161 return;
6162 }
6163}
6164
6165static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6166 const UnresolvedMemberExpr *const UME, Sema &S) {
6167
6168 const auto GetFunctionLevelDCIfCXXClass =
6169 [](Sema &S) -> const CXXRecordDecl * {
6170 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6171 if (!DC || !DC->getParent())
6172 return nullptr;
6173
6174 // If the call to some member function was made from within a member
6175 // function body 'M' return return 'M's parent.
6176 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6177 return MD->getParent()->getCanonicalDecl();
6178 // else the call was made from within a default member initializer of a
6179 // class, so return the class.
6180 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6181 return RD->getCanonicalDecl();
6182 return nullptr;
6183 };
6184 // If our DeclContext is neither a member function nor a class (in the
6185 // case of a lambda in a default member initializer), we can't have an
6186 // enclosing 'this'.
6187
6188 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6189 if (!CurParentClass)
6190 return false;
6191
6192 // The naming class for implicit member functions call is the class in which
6193 // name lookup starts.
6194 const CXXRecordDecl *const NamingClass =
6195 UME->getNamingClass()->getCanonicalDecl();
6196 assert(NamingClass && "Must have naming class even for implicit access")((NamingClass && "Must have naming class even for implicit access"
) ? static_cast<void> (0) : __assert_fail ("NamingClass && \"Must have naming class even for implicit access\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 6196, __PRETTY_FUNCTION__))
;
6197
6198 // If the unresolved member functions were found in a 'naming class' that is
6199 // related (either the same or derived from) to the class that contains the
6200 // member function that itself contained the implicit member access.
6201
6202 return CurParentClass == NamingClass ||
6203 CurParentClass->isDerivedFrom(NamingClass);
6204}
6205
6206static void
6207tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6208 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6209
6210 if (!UME)
6211 return;
6212
6213 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6214 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6215 // already been captured, or if this is an implicit member function call (if
6216 // it isn't, an attempt to capture 'this' should already have been made).
6217 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6218 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6219 return;
6220
6221 // Check if the naming class in which the unresolved members were found is
6222 // related (same as or is a base of) to the enclosing class.
6223
6224 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6225 return;
6226
6227
6228 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6229 // If the enclosing function is not dependent, then this lambda is
6230 // capture ready, so if we can capture this, do so.
6231 if (!EnclosingFunctionCtx->isDependentContext()) {
6232 // If the current lambda and all enclosing lambdas can capture 'this' -
6233 // then go ahead and capture 'this' (since our unresolved overload set
6234 // contains at least one non-static member function).
6235 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6236 S.CheckCXXThisCapture(CallLoc);
6237 } else if (S.CurContext->isDependentContext()) {
6238 // ... since this is an implicit member reference, that might potentially
6239 // involve a 'this' capture, mark 'this' for potential capture in
6240 // enclosing lambdas.
6241 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6242 CurLSI->addPotentialThisCapture(CallLoc);
6243 }
6244}
6245
6246ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6247 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6248 Expr *ExecConfig) {
6249 ExprResult Call =
6250 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig);
6251 if (Call.isInvalid())
6252 return Call;
6253
6254 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6255 // language modes.
6256 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
6257 if (ULE->hasExplicitTemplateArgs() &&
6258 ULE->decls_begin() == ULE->decls_end()) {
6259 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6260 ? diag::warn_cxx17_compat_adl_only_template_id
6261 : diag::ext_adl_only_template_id)
6262 << ULE->getName();
6263 }
6264 }
6265
6266 if (LangOpts.OpenMP)
6267 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6268 ExecConfig);
6269
6270 return Call;
6271}
6272
6273/// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6274/// This provides the location of the left/right parens and a list of comma
6275/// locations.
6276ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6277 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6278 Expr *ExecConfig, bool IsExecConfig) {
6279 // Since this might be a postfix expression, get rid of ParenListExprs.
6280 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6281 if (Result.isInvalid()) return ExprError();
6282 Fn = Result.get();
6283
6284 if (checkArgsForPlaceholders(*this, ArgExprs))
6285 return ExprError();
6286
6287 if (getLangOpts().CPlusPlus) {
6288 // If this is a pseudo-destructor expression, build the call immediately.
6289 if (isa<CXXPseudoDestructorExpr>(Fn)) {
6290 if (!ArgExprs.empty()) {
6291 // Pseudo-destructor calls should not have any arguments.
6292 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6293 << FixItHint::CreateRemoval(
6294 SourceRange(ArgExprs.front()->getBeginLoc(),
6295 ArgExprs.back()->getEndLoc()));
6296 }
6297
6298 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6299 VK_RValue, RParenLoc, CurFPFeatureOverrides());
6300 }
6301 if (Fn->getType() == Context.PseudoObjectTy) {
6302 ExprResult result = CheckPlaceholderExpr(Fn);
6303 if (result.isInvalid()) return ExprError();
6304 Fn = result.get();
6305 }
6306
6307 // Determine whether this is a dependent call inside a C++ template,
6308 // in which case we won't do any semantic analysis now.
6309 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6310 if (ExecConfig) {
6311 return CUDAKernelCallExpr::Create(
6312 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
6313 Context.DependentTy, VK_RValue, RParenLoc, CurFPFeatureOverrides());
6314 } else {
6315
6316 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6317 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6318 Fn->getBeginLoc());
6319
6320 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6321 VK_RValue, RParenLoc, CurFPFeatureOverrides());
6322 }
6323 }
6324
6325 // Determine whether this is a call to an object (C++ [over.call.object]).
6326 if (Fn->getType()->isRecordType())
6327 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6328 RParenLoc);
6329
6330 if (Fn->getType() == Context.UnknownAnyTy) {
6331 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6332 if (result.isInvalid()) return ExprError();
6333 Fn = result.get();
6334 }
6335
6336 if (Fn->getType() == Context.BoundMemberTy) {
6337 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6338 RParenLoc);
6339 }
6340 }
6341
6342 // Check for overloaded calls. This can happen even in C due to extensions.
6343 if (Fn->getType() == Context.OverloadTy) {
6344 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6345
6346 // We aren't supposed to apply this logic if there's an '&' involved.
6347 if (!find.HasFormOfMemberPointer) {
6348 if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6349 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6350 VK_RValue, RParenLoc, CurFPFeatureOverrides());
6351 OverloadExpr *ovl = find.Expression;
6352 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6353 return BuildOverloadedCallExpr(
6354 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6355 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6356 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6357 RParenLoc);
6358 }
6359 }
6360
6361 // If we're directly calling a function, get the appropriate declaration.
6362 if (Fn->getType() == Context.UnknownAnyTy) {
6363 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6364 if (result.isInvalid()) return ExprError();
6365 Fn = result.get();
6366 }
6367
6368 Expr *NakedFn = Fn->IgnoreParens();
6369
6370 bool CallingNDeclIndirectly = false;
6371 NamedDecl *NDecl = nullptr;
6372 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6373 if (UnOp->getOpcode() == UO_AddrOf) {
6374 CallingNDeclIndirectly = true;
6375 NakedFn = UnOp->getSubExpr()->IgnoreParens();
6376 }
6377 }
6378
6379 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6380 NDecl = DRE->getDecl();
6381
6382 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6383 if (FDecl && FDecl->getBuiltinID()) {
6384 // Rewrite the function decl for this builtin by replacing parameters
6385 // with no explicit address space with the address space of the arguments
6386 // in ArgExprs.
6387 if ((FDecl =
6388 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6389 NDecl = FDecl;
6390 Fn = DeclRefExpr::Create(
6391 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6392 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6393 nullptr, DRE->isNonOdrUse());
6394 }
6395 }
6396 } else if (isa<MemberExpr>(NakedFn))
6397 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
6398
6399 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6400 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6401 FD, /*Complain=*/true, Fn->getBeginLoc()))
6402 return ExprError();
6403
6404 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
6405 return ExprError();
6406
6407 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6408 }
6409
6410 if (Context.isDependenceAllowed() &&
6411 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
6412 assert(!getLangOpts().CPlusPlus)((!getLangOpts().CPlusPlus) ? static_cast<void> (0) : __assert_fail
("!getLangOpts().CPlusPlus", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 6412, __PRETTY_FUNCTION__))
;
6413 assert((Fn->containsErrors() ||(((Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang
::Expr *E) { return E->containsErrors(); })) && "should only occur in error-recovery path."
) ? static_cast<void> (0) : __assert_fail ("(Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors(); })) && \"should only occur in error-recovery path.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 6416, __PRETTY_FUNCTION__))
6414 llvm::any_of(ArgExprs,(((Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang
::Expr *E) { return E->containsErrors(); })) && "should only occur in error-recovery path."
) ? static_cast<void> (0) : __assert_fail ("(Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors(); })) && \"should only occur in error-recovery path.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 6416, __PRETTY_FUNCTION__))
6415 [](clang::Expr *E) { return E->containsErrors(); })) &&(((Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang
::Expr *E) { return E->containsErrors(); })) && "should only occur in error-recovery path."
) ? static_cast<void> (0) : __assert_fail ("(Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors(); })) && \"should only occur in error-recovery path.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 6416, __PRETTY_FUNCTION__))
6416 "should only occur in error-recovery path.")(((Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang
::Expr *E) { return E->containsErrors(); })) && "should only occur in error-recovery path."
) ? static_cast<void> (0) : __assert_fail ("(Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors(); })) && \"should only occur in error-recovery path.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 6416, __PRETTY_FUNCTION__))
;
6417 QualType ReturnType =
6418 llvm::isa_and_nonnull<FunctionDecl>(NDecl)
6419 ? dyn_cast<FunctionDecl>(NDecl)->getCallResultType()
6420 : Context.DependentTy;
6421 return CallExpr::Create(Context, Fn, ArgExprs, ReturnType,
6422 Expr::getValueKindForType(ReturnType), RParenLoc,
6423 CurFPFeatureOverrides());
6424 }
6425 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6426 ExecConfig, IsExecConfig);
6427}
6428
6429/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
6430///
6431/// __builtin_astype( value, dst type )
6432///
6433ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6434 SourceLocation BuiltinLoc,
6435 SourceLocation RParenLoc) {
6436 ExprValueKind VK = VK_RValue;
6437 ExprObjectKind OK = OK_Ordinary;
6438 QualType DstTy = GetTypeFromParser(ParsedDestTy);
6439 QualType SrcTy = E->getType();
6440 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
6441 return ExprError(Diag(BuiltinLoc,
6442 diag::err_invalid_astype_of_different_size)
6443 << DstTy
6444 << SrcTy
6445 << E->getSourceRange());
6446 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6447}
6448
6449/// ActOnConvertVectorExpr - create a new convert-vector expression from the
6450/// provided arguments.
6451///
6452/// __builtin_convertvector( value, dst type )
6453///
6454ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6455 SourceLocation BuiltinLoc,
6456 SourceLocation RParenLoc) {
6457 TypeSourceInfo *TInfo;
6458 GetTypeFromParser(ParsedDestTy, &TInfo);
6459 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6460}
6461
6462/// BuildResolvedCallExpr - Build a call to a resolved expression,
6463/// i.e. an expression not of \p OverloadTy. The expression should
6464/// unary-convert to an expression of function-pointer or
6465/// block-pointer type.
6466///
6467/// \param NDecl the declaration being called, if available
6468ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
6469 SourceLocation LParenLoc,
6470 ArrayRef<Expr *> Args,
6471 SourceLocation RParenLoc, Expr *Config,
6472 bool IsExecConfig, ADLCallKind UsesADL) {
6473 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6474 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6475
6476 // Functions with 'interrupt' attribute cannot be called directly.
6477 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6478 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6479 return ExprError();
6480 }
6481
6482 // Interrupt handlers don't save off the VFP regs automatically on ARM,
6483 // so there's some risk when calling out to non-interrupt handler functions
6484 // that the callee might not preserve them. This is easy to diagnose here,
6485 // but can be very challenging to debug.
6486 if (auto *Caller = getCurFunctionDecl())
6487 if (Caller->hasAttr<ARMInterruptAttr>()) {
6488 bool VFP = Context.getTargetInfo().hasFeature("vfp");
6489 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
6490 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6491 }
6492
6493 // Promote the function operand.
6494 // We special-case function promotion here because we only allow promoting
6495 // builtin functions to function pointers in the callee of a call.
6496 ExprResult Result;
6497 QualType ResultTy;
6498 if (BuiltinID &&
6499 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6500 // Extract the return type from the (builtin) function pointer type.
6501 // FIXME Several builtins still have setType in
6502 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6503 // Builtins.def to ensure they are correct before removing setType calls.
6504 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6505 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6506 ResultTy = FDecl->getCallResultType();
6507 } else {
6508 Result = CallExprUnaryConversions(Fn);
6509 ResultTy = Context.BoolTy;
6510 }
6511 if (Result.isInvalid())
6512 return ExprError();
6513 Fn = Result.get();
6514
6515 // Check for a valid function type, but only if it is not a builtin which
6516 // requires custom type checking. These will be handled by
6517 // CheckBuiltinFunctionCall below just after creation of the call expression.
6518 const FunctionType *FuncT = nullptr;
6519 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6520 retry:
6521 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6522 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6523 // have type pointer to function".
6524 FuncT = PT->getPointeeType()->getAs<FunctionType>();
6525 if (!FuncT)
6526 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6527 << Fn->getType() << Fn->getSourceRange());
6528 } else if (const BlockPointerType *BPT =
6529 Fn->getType()->getAs<BlockPointerType>()) {
6530 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6531 } else {
6532 // Handle calls to expressions of unknown-any type.
6533 if (Fn->getType() == Context.UnknownAnyTy) {
6534 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6535 if (rewrite.isInvalid())
6536 return ExprError();
6537 Fn = rewrite.get();
6538 goto retry;
6539 }
6540
6541 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6542 << Fn->getType() << Fn->getSourceRange());
6543 }
6544 }
6545
6546 // Get the number of parameters in the function prototype, if any.
6547 // We will allocate space for max(Args.size(), NumParams) arguments
6548 // in the call expression.
6549 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6550 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6551
6552 CallExpr *TheCall;
6553 if (Config) {
6554 assert(UsesADL == ADLCallKind::NotADL &&((UsesADL == ADLCallKind::NotADL && "CUDAKernelCallExpr should not use ADL"
) ? static_cast<void> (0) : __assert_fail ("UsesADL == ADLCallKind::NotADL && \"CUDAKernelCallExpr should not use ADL\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 6555, __PRETTY_FUNCTION__))
6555 "CUDAKernelCallExpr should not use ADL")((UsesADL == ADLCallKind::NotADL && "CUDAKernelCallExpr should not use ADL"
) ? static_cast<void> (0) : __assert_fail ("UsesADL == ADLCallKind::NotADL && \"CUDAKernelCallExpr should not use ADL\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 6555, __PRETTY_FUNCTION__))
;
6556 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
6557 Args, ResultTy, VK_RValue, RParenLoc,
6558 CurFPFeatureOverrides(), NumParams);
6559 } else {
6560 TheCall =
6561 CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc,
6562 CurFPFeatureOverrides(), NumParams, UsesADL);
6563 }
6564
6565 if (!Context.isDependenceAllowed()) {
6566 // Forget about the nulled arguments since typo correction
6567 // do not handle them well.
6568 TheCall->shrinkNumArgs(Args.size());
6569 // C cannot always handle TypoExpr nodes in builtin calls and direct
6570 // function calls as their argument checking don't necessarily handle
6571 // dependent types properly, so make sure any TypoExprs have been
6572 // dealt with.
6573 ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
6574 if (!Result.isUsable()) return ExprError();
6575 CallExpr *TheOldCall = TheCall;
6576 TheCall = dyn_cast<CallExpr>(Result.get());
6577 bool CorrectedTypos = TheCall != TheOldCall;
6578 if (!TheCall) return Result;
6579 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6580
6581 // A new call expression node was created if some typos were corrected.
6582 // However it may not have been constructed with enough storage. In this
6583 // case, rebuild the node with enough storage. The waste of space is
6584 // immaterial since this only happens when some typos were corrected.
6585 if (CorrectedTypos && Args.size() < NumParams) {
6586 if (Config)
6587 TheCall = CUDAKernelCallExpr::Create(
6588 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
6589 RParenLoc, CurFPFeatureOverrides(), NumParams);
6590 else
6591 TheCall =
6592 CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc,
6593 CurFPFeatureOverrides(), NumParams, UsesADL);
6594 }
6595 // We can now handle the nulled arguments for the default arguments.
6596 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6597 }
6598
6599 // Bail out early if calling a builtin with custom type checking.
6600 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
6601 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6602
6603 if (getLangOpts().CUDA) {
6604 if (Config) {
6605 // CUDA: Kernel calls must be to global functions
6606 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6607 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6608 << FDecl << Fn->getSourceRange());
6609
6610 // CUDA: Kernel function must have 'void' return type
6611 if (!FuncT->getReturnType()->isVoidType() &&
6612 !FuncT->getReturnType()->getAs<AutoType>() &&
6613 !FuncT->getReturnType()->isInstantiationDependentType())
6614 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6615 << Fn->getType() << Fn->getSourceRange());
6616 } else {
6617 // CUDA: Calls to global functions must be configured
6618 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6619 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6620 << FDecl << Fn->getSourceRange());
6621 }
6622 }
6623
6624 // Check for a valid return type
6625 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6626 FDecl))
6627 return ExprError();
6628
6629 // We know the result type of the call, set it.
6630 TheCall->setType(FuncT->getCallResultType(Context));
6631 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
6632
6633 if (Proto) {
6634 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6635 IsExecConfig))
6636 return ExprError();
6637 } else {
6638 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!")((isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"
) ? static_cast<void> (0) : __assert_fail ("isa<FunctionNoProtoType>(FuncT) && \"Unknown FunctionType!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 6638, __PRETTY_FUNCTION__))
;
6639
6640 if (FDecl) {
6641 // Check if we have too few/too many template arguments, based
6642 // on our knowledge of the function definition.
6643 const FunctionDecl *Def = nullptr;
6644 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6645 Proto = Def->getType()->getAs<FunctionProtoType>();
6646 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6647 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6648 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6649 }
6650
6651 // If the function we're calling isn't a function prototype, but we have
6652 // a function prototype from a prior declaratiom, use that prototype.
6653 if (!FDecl->hasPrototype())
6654 Proto = FDecl->getType()->getAs<FunctionProtoType>();
6655 }
6656
6657 // Promote the arguments (C99 6.5.2.2p6).
6658 for (unsigned i = 0, e = Args.size(); i != e; i++) {
6659 Expr *Arg = Args[i];
6660
6661 if (Proto && i < Proto->getNumParams()) {
6662 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6663 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
6664 ExprResult ArgE =
6665 PerformCopyInitialization(Entity, SourceLocation(), Arg);
6666 if (ArgE.isInvalid())
6667 return true;
6668
6669 Arg = ArgE.getAs<Expr>();
6670
6671 } else {
6672 ExprResult ArgE = DefaultArgumentPromotion(Arg);
6673
6674 if (ArgE.isInvalid())
6675 return true;
6676
6677 Arg = ArgE.getAs<Expr>();
6678 }
6679
6680 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
6681 diag::err_call_incomplete_argument, Arg))
6682 return ExprError();
6683
6684 TheCall->setArg(i, Arg);
6685 }
6686 }
6687
6688 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6689 if (!Method->isStatic())
6690 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
6691 << Fn->getSourceRange());
6692
6693 // Check for sentinels
6694 if (NDecl)
6695 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
6696
6697 // Warn for unions passing across security boundary (CMSE).
6698 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
6699 for (unsigned i = 0, e = Args.size(); i != e; i++) {
6700 if (const auto *RT =
6701 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
6702 if (RT->getDecl()->isOrContainsUnion())
6703 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
6704 << 0 << i;
6705 }
6706 }
6707 }
6708
6709 // Do special checking on direct calls to functions.
6710 if (FDecl) {
6711 if (CheckFunctionCall(FDecl, TheCall, Proto))
6712 return ExprError();
6713
6714 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
6715
6716 if (BuiltinID)
6717 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6718 } else if (NDecl) {
6719 if (CheckPointerCall(NDecl, TheCall, Proto))
6720 return ExprError();
6721 } else {
6722 if (CheckOtherCall(TheCall, Proto))
6723 return ExprError();
6724 }
6725
6726 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
6727}
6728
6729ExprResult
6730Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
6731 SourceLocation RParenLoc, Expr *InitExpr) {
6732 assert(Ty && "ActOnCompoundLiteral(): missing type")((Ty && "ActOnCompoundLiteral(): missing type") ? static_cast
<void> (0) : __assert_fail ("Ty && \"ActOnCompoundLiteral(): missing type\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 6732, __PRETTY_FUNCTION__))
;
6733 assert(InitExpr && "ActOnCompoundLiteral(): missing expression")((InitExpr && "ActOnCompoundLiteral(): missing expression"
) ? static_cast<void> (0) : __assert_fail ("InitExpr && \"ActOnCompoundLiteral(): missing expression\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 6733, __PRETTY_FUNCTION__))
;
6734
6735 TypeSourceInfo *TInfo;
6736 QualType literalType = GetTypeFromParser(Ty, &TInfo);
6737 if (!TInfo)
6738 TInfo = Context.getTrivialTypeSourceInfo(literalType);
6739
6740 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6741}
6742
6743ExprResult
6744Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
6745 SourceLocation RParenLoc, Expr *LiteralExpr) {
6746 QualType literalType = TInfo->getType();
6747
6748 if (literalType->isArrayType()) {
6749 if (RequireCompleteSizedType(
6750 LParenLoc, Context.getBaseElementType(literalType),
6751 diag::err_array_incomplete_or_sizeless_type,
6752 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6753 return ExprError();
6754 if (literalType->isVariableArrayType())
6755 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
6756 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
6757 } else if (!literalType->isDependentType() &&
6758 RequireCompleteType(LParenLoc, literalType,
6759 diag::err_typecheck_decl_incomplete_type,
6760 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6761 return ExprError();
6762
6763 InitializedEntity Entity
6764 = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
6765 InitializationKind Kind
6766 = InitializationKind::CreateCStyleCast(LParenLoc,
6767 SourceRange(LParenLoc, RParenLoc),
6768 /*InitList=*/true);
6769 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
6770 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
6771 &literalType);
6772 if (Result.isInvalid())
6773 return ExprError();
6774 LiteralExpr = Result.get();
6775
6776 bool isFileScope = !CurContext->isFunctionOrMethod();
6777
6778 // In C, compound literals are l-values for some reason.
6779 // For GCC compatibility, in C++, file-scope array compound literals with
6780 // constant initializers are also l-values, and compound literals are
6781 // otherwise prvalues.
6782 //
6783 // (GCC also treats C++ list-initialized file-scope array prvalues with
6784 // constant initializers as l-values, but that's non-conforming, so we don't
6785 // follow it there.)
6786 //
6787 // FIXME: It would be better to handle the lvalue cases as materializing and
6788 // lifetime-extending a temporary object, but our materialized temporaries
6789 // representation only supports lifetime extension from a variable, not "out
6790 // of thin air".
6791 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
6792 // is bound to the result of applying array-to-pointer decay to the compound
6793 // literal.
6794 // FIXME: GCC supports compound literals of reference type, which should
6795 // obviously have a value kind derived from the kind of reference involved.
6796 ExprValueKind VK =
6797 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
6798 ? VK_RValue
6799 : VK_LValue;
6800
6801 if (isFileScope)
6802 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
6803 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
6804 Expr *Init = ILE->getInit(i);
6805 ILE->setInit(i, ConstantExpr::Create(Context, Init));
6806 }
6807
6808 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6809 VK, LiteralExpr, isFileScope);
6810 if (isFileScope) {
6811 if (!LiteralExpr->isTypeDependent() &&
6812 !LiteralExpr->isValueDependent() &&
6813 !literalType->isDependentType()) // C99 6.5.2.5p3
6814 if (CheckForConstantInitializer(LiteralExpr, literalType))
6815 return ExprError();
6816 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
6817 literalType.getAddressSpace() != LangAS::Default) {
6818 // Embedded-C extensions to C99 6.5.2.5:
6819 // "If the compound literal occurs inside the body of a function, the
6820 // type name shall not be qualified by an address-space qualifier."
6821 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
6822 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
6823 return ExprError();
6824 }
6825
6826 if (!isFileScope && !getLangOpts().CPlusPlus) {
6827 // Compound literals that have automatic storage duration are destroyed at
6828 // the end of the scope in C; in C++, they're just temporaries.
6829
6830 // Emit diagnostics if it is or contains a C union type that is non-trivial
6831 // to destruct.
6832 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
6833 checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
6834 NTCUC_CompoundLiteral, NTCUK_Destruct);
6835
6836 // Diagnose jumps that enter or exit the lifetime of the compound literal.
6837 if (literalType.isDestructedType()) {
6838 Cleanup.setExprNeedsCleanups(true);
6839 ExprCleanupObjects.push_back(E);
6840 getCurFunction()->setHasBranchProtectedScope();
6841 }
6842 }
6843
6844 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
6845 E->getType().hasNonTrivialToPrimitiveCopyCUnion())
6846 checkNonTrivialCUnionInInitializer(E->getInitializer(),
6847 E->getInitializer()->getExprLoc());
6848
6849 return MaybeBindToTemporary(E);
6850}
6851
6852ExprResult
6853Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6854 SourceLocation RBraceLoc) {
6855 // Only produce each kind of designated initialization diagnostic once.
6856 SourceLocation FirstDesignator;
6857 bool DiagnosedArrayDesignator = false;
6858 bool DiagnosedNestedDesignator = false;
6859 bool DiagnosedMixedDesignator = false;
6860
6861 // Check that any designated initializers are syntactically valid in the
6862 // current language mode.
6863 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6864 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
6865 if (FirstDesignator.isInvalid())
6866 FirstDesignator = DIE->getBeginLoc();
6867
6868 if (!getLangOpts().CPlusPlus)
6869 break;
6870
6871 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
6872 DiagnosedNestedDesignator = true;
6873 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
6874 << DIE->getDesignatorsSourceRange();
6875 }
6876
6877 for (auto &Desig : DIE->designators()) {
6878 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
6879 DiagnosedArrayDesignator = true;
6880 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
6881 << Desig.getSourceRange();
6882 }
6883 }
6884
6885 if (!DiagnosedMixedDesignator &&
6886 !isa<DesignatedInitExpr>(InitArgList[0])) {
6887 DiagnosedMixedDesignator = true;
6888 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6889 << DIE->getSourceRange();
6890 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
6891 << InitArgList[0]->getSourceRange();
6892 }
6893 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
6894 isa<DesignatedInitExpr>(InitArgList[0])) {
6895 DiagnosedMixedDesignator = true;
6896 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
6897 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6898 << DIE->getSourceRange();
6899 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
6900 << InitArgList[I]->getSourceRange();
6901 }
6902 }
6903
6904 if (FirstDesignator.isValid()) {
6905 // Only diagnose designated initiaization as a C++20 extension if we didn't
6906 // already diagnose use of (non-C++20) C99 designator syntax.
6907 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
6908 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
6909 Diag(FirstDesignator, getLangOpts().CPlusPlus20
6910 ? diag::warn_cxx17_compat_designated_init
6911 : diag::ext_cxx_designated_init);
6912 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
6913 Diag(FirstDesignator, diag::ext_designated_init);
6914 }
6915 }
6916
6917 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
6918}
6919
6920ExprResult
6921Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6922 SourceLocation RBraceLoc) {
6923 // Semantic analysis for initializers is done by ActOnDeclarator() and
6924 // CheckInitializer() - it requires knowledge of the object being initialized.
6925
6926 // Immediately handle non-overload placeholders. Overloads can be
6927 // resolved contextually, but everything else here can't.
6928 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6929 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
6930 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
6931
6932 // Ignore failures; dropping the entire initializer list because
6933 // of one failure would be terrible for indexing/etc.
6934 if (result.isInvalid()) continue;
6935
6936 InitArgList[I] = result.get();
6937 }
6938 }
6939
6940 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
6941 RBraceLoc);
6942 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
6943 return E;
6944}
6945
6946/// Do an explicit extend of the given block pointer if we're in ARC.
6947void Sema::maybeExtendBlockObject(ExprResult &E) {
6948 assert(E.get()->getType()->isBlockPointerType())((E.get()->getType()->isBlockPointerType()) ? static_cast
<void> (0) : __assert_fail ("E.get()->getType()->isBlockPointerType()"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 6948, __PRETTY_FUNCTION__))
;
6949 assert(E.get()->isRValue())((E.get()->isRValue()) ? static_cast<void> (0) : __assert_fail
("E.get()->isRValue()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 6949, __PRETTY_FUNCTION__))
;
6950
6951 // Only do this in an r-value context.
6952 if (!getLangOpts().ObjCAutoRefCount) return;
6953
6954 E = ImplicitCastExpr::Create(
6955 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
6956 /*base path*/ nullptr, VK_RValue, FPOptionsOverride());
6957 Cleanup.setExprNeedsCleanups(true);
6958}
6959
6960/// Prepare a conversion of the given expression to an ObjC object
6961/// pointer type.
6962CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
6963 QualType type = E.get()->getType();
6964 if (type->isObjCObjectPointerType()) {
6965 return CK_BitCast;
6966 } else if (type->isBlockPointerType()) {
6967 maybeExtendBlockObject(E);
6968 return CK_BlockPointerToObjCPointerCast;
6969 } else {
6970 assert(type->isPointerType())((type->isPointerType()) ? static_cast<void> (0) : __assert_fail
("type->isPointerType()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 6970, __PRETTY_FUNCTION__))
;
6971 return CK_CPointerToObjCPointerCast;
6972 }
6973}
6974
6975/// Prepares for a scalar cast, performing all the necessary stages
6976/// except the final cast and returning the kind required.
6977CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
6978 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
6979 // Also, callers should have filtered out the invalid cases with
6980 // pointers. Everything else should be possible.
6981
6982 QualType SrcTy = Src.get()->getType();
6983 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
6984 return CK_NoOp;
6985
6986 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
6987 case Type::STK_MemberPointer:
6988 llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C",
"/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 6988)
;
6989
6990 case Type::STK_CPointer:
6991 case Type::STK_BlockPointer:
6992 case Type::STK_ObjCObjectPointer:
6993 switch (DestTy->getScalarTypeKind()) {
6994 case Type::STK_CPointer: {
6995 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
6996 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
6997 if (SrcAS != DestAS)
6998 return CK_AddressSpaceConversion;
6999 if (Context.hasCvrSimilarType(SrcTy, DestTy))
7000 return CK_NoOp;
7001 return CK_BitCast;
7002 }
7003 case Type::STK_BlockPointer:
7004 return (SrcKind == Type::STK_BlockPointer
7005 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7006 case Type::STK_ObjCObjectPointer:
7007 if (SrcKind == Type::STK_ObjCObjectPointer)
7008 return CK_BitCast;
7009 if (SrcKind == Type::STK_CPointer)
7010 return CK_CPointerToObjCPointerCast;
7011 maybeExtendBlockObject(Src);
7012 return CK_BlockPointerToObjCPointerCast;
7013 case Type::STK_Bool:
7014 return CK_PointerToBoolean;
7015 case Type::STK_Integral:
7016 return CK_PointerToIntegral;
7017 case Type::STK_Floating:
7018 case Type::STK_FloatingComplex:
7019 case Type::STK_IntegralComplex:
7020 case Type::STK_MemberPointer:
7021 case Type::STK_FixedPoint:
7022 llvm_unreachable("illegal cast from pointer")::llvm::llvm_unreachable_internal("illegal cast from pointer"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 7022)
;
7023 }
7024 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 7024)
;
7025
7026 case Type::STK_FixedPoint:
7027 switch (DestTy->getScalarTypeKind()) {
7028 case Type::STK_FixedPoint:
7029 return CK_FixedPointCast;
7030 case Type::STK_Bool:
7031 return CK_FixedPointToBoolean;
7032 case Type::STK_Integral:
7033 return CK_FixedPointToIntegral;
7034 case Type::STK_Floating:
7035 return CK_FixedPointToFloating;
7036 case Type::STK_IntegralComplex:
7037 case Type::STK_FloatingComplex:
7038 Diag(Src.get()->getExprLoc(),
7039 diag::err_unimplemented_conversion_with_fixed_point_type)
7040 << DestTy;
7041 return CK_IntegralCast;
7042 case Type::STK_CPointer:
7043 case Type::STK_ObjCObjectPointer:
7044 case Type::STK_BlockPointer:
7045 case Type::STK_MemberPointer:
7046 llvm_unreachable("illegal cast to pointer type")::llvm::llvm_unreachable_internal("illegal cast to pointer type"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 7046)
;
7047 }
7048 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 7048)
;
7049
7050 case Type::STK_Bool: // casting from bool is like casting from an integer
7051 case Type::STK_Integral:
7052 switch (DestTy->getScalarTypeKind()) {
7053 case Type::STK_CPointer:
7054 case Type::STK_ObjCObjectPointer:
7055 case Type::STK_BlockPointer:
7056 if (Src.get()->isNullPointerConstant(Context,
7057 Expr::NPC_ValueDependentIsNull))
7058 return CK_NullToPointer;
7059 return CK_IntegralToPointer;
7060 case Type::STK_Bool:
7061 return CK_IntegralToBoolean;
7062 case Type::STK_Integral:
7063 return CK_IntegralCast;
7064 case Type::STK_Floating:
7065 return CK_IntegralToFloating;
7066 case Type::STK_IntegralComplex:
7067 Src = ImpCastExprToType(Src.get(),
7068 DestTy->castAs<ComplexType>()->getElementType(),
7069 CK_IntegralCast);
7070 return CK_IntegralRealToComplex;
7071 case Type::STK_FloatingComplex:
7072 Src = ImpCastExprToType(Src.get(),
7073 DestTy->castAs<ComplexType>()->getElementType(),
7074 CK_IntegralToFloating);
7075 return CK_FloatingRealToComplex;
7076 case Type::STK_MemberPointer:
7077 llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C",
"/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 7077)
;
7078 case Type::STK_FixedPoint:
7079 return CK_IntegralToFixedPoint;
7080 }
7081 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 7081)
;
7082
7083 case Type::STK_Floating:
7084 switch (DestTy->getScalarTypeKind()) {
7085 case Type::STK_Floating:
7086 return CK_FloatingCast;
7087 case Type::STK_Bool:
7088 return CK_FloatingToBoolean;
7089 case Type::STK_Integral:
7090 return CK_FloatingToIntegral;
7091 case Type::STK_FloatingComplex:
7092 Src = ImpCastExprToType(Src.get(),
7093 DestTy->castAs<ComplexType>()->getElementType(),
7094 CK_FloatingCast);
7095 return CK_FloatingRealToComplex;
7096 case Type::STK_IntegralComplex:
7097 Src = ImpCastExprToType(Src.get(),
7098 DestTy->castAs<ComplexType>()->getElementType(),
7099 CK_FloatingToIntegral);
7100 return CK_IntegralRealToComplex;
7101 case Type::STK_CPointer:
7102 case Type::STK_ObjCObjectPointer:
7103 case Type::STK_BlockPointer:
7104 llvm_unreachable("valid float->pointer cast?")::llvm::llvm_unreachable_internal("valid float->pointer cast?"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 7104)
;
7105 case Type::STK_MemberPointer:
7106 llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C",
"/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 7106)
;
7107 case Type::STK_FixedPoint:
7108 return CK_FloatingToFixedPoint;
7109 }
7110 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 7110)
;
7111
7112 case Type::STK_FloatingComplex:
7113 switch (DestTy->getScalarTypeKind()) {
7114 case Type::STK_FloatingComplex:
7115 return CK_FloatingComplexCast;
7116 case Type::STK_IntegralComplex:
7117 return CK_FloatingComplexToIntegralComplex;
7118 case Type::STK_Floating: {
7119 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7120 if (Context.hasSameType(ET, DestTy))
7121 return CK_FloatingComplexToReal;
7122 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7123 return CK_FloatingCast;
7124 }
7125 case Type::STK_Bool:
7126 return CK_FloatingComplexToBoolean;
7127 case Type::STK_Integral:
7128 Src = ImpCastExprToType(Src.get(),
7129 SrcTy->castAs<ComplexType>()->getElementType(),
7130 CK_FloatingComplexToReal);
7131 return CK_FloatingToIntegral;
7132 case Type::STK_CPointer:
7133 case Type::STK_ObjCObjectPointer:
7134 case Type::STK_BlockPointer:
7135 llvm_unreachable("valid complex float->pointer cast?")::llvm::llvm_unreachable_internal("valid complex float->pointer cast?"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 7135)
;
7136 case Type::STK_MemberPointer:
7137 llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C",
"/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 7137)
;
7138 case Type::STK_FixedPoint:
7139 Diag(Src.get()->getExprLoc(),
7140 diag::err_unimplemented_conversion_with_fixed_point_type)
7141 << SrcTy;
7142 return CK_IntegralCast;
7143 }
7144 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 7144)
;
7145
7146 case Type::STK_IntegralComplex:
7147 switch (DestTy->getScalarTypeKind()) {
7148 case Type::STK_FloatingComplex:
7149 return CK_IntegralComplexToFloatingComplex;
7150 case Type::STK_IntegralComplex:
7151 return CK_IntegralComplexCast;
7152 case Type::STK_Integral: {
7153 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7154 if (Context.hasSameType(ET, DestTy))
7155 return CK_IntegralComplexToReal;
7156 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7157 return CK_IntegralCast;
7158 }
7159 case Type::STK_Bool:
7160 return CK_IntegralComplexToBoolean;
7161 case Type::STK_Floating:
7162 Src = ImpCastExprToType(Src.get(),
7163 SrcTy->castAs<ComplexType>()->getElementType(),
7164 CK_IntegralComplexToReal);
7165 return CK_IntegralToFloating;
7166 case Type::STK_CPointer:
7167 case Type::STK_ObjCObjectPointer:
7168 case Type::STK_BlockPointer:
7169 llvm_unreachable("valid complex int->pointer cast?")::llvm::llvm_unreachable_internal("valid complex int->pointer cast?"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 7169)
;
7170 case Type::STK_MemberPointer:
7171 llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C",
"/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 7171)
;
7172 case Type::STK_FixedPoint:
7173 Diag(Src.get()->getExprLoc(),
7174 diag::err_unimplemented_conversion_with_fixed_point_type)
7175 << SrcTy;
7176 return CK_IntegralCast;
7177 }
7178 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 7178)
;
7179 }
7180
7181 llvm_unreachable("Unhandled scalar cast")::llvm::llvm_unreachable_internal("Unhandled scalar cast", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 7181)
;
7182}
7183
7184static bool breakDownVectorType(QualType type, uint64_t &len,
7185 QualType &eltType) {
7186 // Vectors are simple.
7187 if (const VectorType *vecType = type->getAs<VectorType>()) {
7188 len = vecType->getNumElements();
7189 eltType = vecType->getElementType();
7190 assert(eltType->isScalarType())((eltType->isScalarType()) ? static_cast<void> (0) :
__assert_fail ("eltType->isScalarType()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 7190, __PRETTY_FUNCTION__))
;
7191 return true;
7192 }
7193
7194 // We allow lax conversion to and from non-vector types, but only if
7195 // they're real types (i.e. non-complex, non-pointer scalar types).
7196 if (!type->isRealType()) return false;
7197
7198 len = 1;
7199 eltType = type;
7200 return true;
7201}
7202
7203/// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the
7204/// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST)
7205/// allowed?
7206///
7207/// This will also return false if the two given types do not make sense from
7208/// the perspective of SVE bitcasts.
7209bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
7210 assert(srcTy->isVectorType() || destTy->isVectorType())((srcTy->isVectorType() || destTy->isVectorType()) ? static_cast
<void> (0) : __assert_fail ("srcTy->isVectorType() || destTy->isVectorType()"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 7210, __PRETTY_FUNCTION__))
;
7211
7212 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7213 if (!FirstType->isSizelessBuiltinType())
7214 return false;
7215
7216 const auto *VecTy = SecondType->getAs<VectorType>();
7217 return VecTy &&
7218 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector;
7219 };
7220
7221 return ValidScalableConversion(srcTy, destTy) ||
7222 ValidScalableConversion(destTy, srcTy);
7223}
7224
7225/// Are the two types lax-compatible vector types? That is, given
7226/// that one of them is a vector, do they have equal storage sizes,
7227/// where the storage size is the number of elements times the element
7228/// size?
7229///
7230/// This will also return false if either of the types is neither a
7231/// vector nor a real type.
7232bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7233 assert(destTy->isVectorType() || srcTy->isVectorType())((destTy->isVectorType() || srcTy->isVectorType()) ? static_cast
<void> (0) : __assert_fail ("destTy->isVectorType() || srcTy->isVectorType()"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 7233, __PRETTY_FUNCTION__))
;
7234
7235 // Disallow lax conversions between scalars and ExtVectors (these
7236 // conversions are allowed for other vector types because common headers
7237 // depend on them). Most scalar OP ExtVector cases are handled by the
7238 // splat path anyway, which does what we want (convert, not bitcast).
7239 // What this rules out for ExtVectors is crazy things like char4*float.
7240 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7241 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7242
7243 uint64_t srcLen, destLen;
7244 QualType srcEltTy, destEltTy;
7245 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
7246 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
7247
7248 // ASTContext::getTypeSize will return the size rounded up to a
7249 // power of 2, so instead of using that, we need to use the raw
7250 // element size multiplied by the element count.
7251 uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
7252 uint64_t destEltSize = Context.getTypeSize(destEltTy);
7253
7254 return (srcLen * srcEltSize == destLen * destEltSize);
7255}
7256
7257/// Is this a legal conversion between two types, one of which is
7258/// known to be a vector type?
7259bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7260 assert(destTy->isVectorType() || srcTy->isVectorType())((destTy->isVectorType() || srcTy->isVectorType()) ? static_cast
<void> (0) : __assert_fail ("destTy->isVectorType() || srcTy->isVectorType()"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 7260, __PRETTY_FUNCTION__))
;
7261
7262 switch (Context.getLangOpts().getLaxVectorConversions()) {
7263 case LangOptions::LaxVectorConversionKind::None:
7264 return false;
7265
7266 case LangOptions::LaxVectorConversionKind::Integer:
7267 if (!srcTy->isIntegralOrEnumerationType()) {
7268 auto *Vec = srcTy->getAs<VectorType>();
7269 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7270 return false;
7271 }
7272 if (!destTy->isIntegralOrEnumerationType()) {
7273 auto *Vec = destTy->getAs<VectorType>();
7274 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7275 return false;
7276 }
7277 // OK, integer (vector) -> integer (vector) bitcast.
7278 break;
7279
7280 case LangOptions::LaxVectorConversionKind::All:
7281 break;
7282 }
7283
7284 return areLaxCompatibleVectorTypes(srcTy, destTy);
7285}
7286
7287bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7288 CastKind &Kind) {
7289 assert(VectorTy->isVectorType() && "Not a vector type!")((VectorTy->isVectorType() && "Not a vector type!"
) ? static_cast<void> (0) : __assert_fail ("VectorTy->isVectorType() && \"Not a vector type!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 7289, __PRETTY_FUNCTION__))
;
7290
7291 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7292 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7293 return Diag(R.getBegin(),
7294 Ty->isVectorType() ?
7295 diag::err_invalid_conversion_between_vectors :
7296 diag::err_invalid_conversion_between_vector_and_integer)
7297 << VectorTy << Ty << R;
7298 } else
7299 return Diag(R.getBegin(),
7300 diag::err_invalid_conversion_between_vector_and_scalar)
7301 << VectorTy << Ty << R;
7302
7303 Kind = CK_BitCast;
7304 return false;
7305}
7306
7307ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7308 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7309
7310 if (DestElemTy == SplattedExpr->getType())
7311 return SplattedExpr;
7312
7313 assert(DestElemTy->isFloatingType() ||((DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType
()) ? static_cast<void> (0) : __assert_fail ("DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 7314, __PRETTY_FUNCTION__))
7314 DestElemTy->isIntegralOrEnumerationType())((DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType
()) ? static_cast<void> (0) : __assert_fail ("DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 7314, __PRETTY_FUNCTION__))
;
7315
7316 CastKind CK;
7317 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7318 // OpenCL requires that we convert `true` boolean expressions to -1, but
7319 // only when splatting vectors.
7320 if (DestElemTy->isFloatingType()) {
7321 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7322 // in two steps: boolean to signed integral, then to floating.
7323 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7324 CK_BooleanToSignedIntegral);
7325 SplattedExpr = CastExprRes.get();
7326 CK = CK_IntegralToFloating;
7327 } else {
7328 CK = CK_BooleanToSignedIntegral;
7329 }
7330 } else {
7331 ExprResult CastExprRes = SplattedExpr;
7332 CK = PrepareScalarCast(CastExprRes, DestElemTy);
7333 if (CastExprRes.isInvalid())
7334 return ExprError();
7335 SplattedExpr = CastExprRes.get();
7336 }
7337 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7338}
7339
7340ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
7341 Expr *CastExpr, CastKind &Kind) {
7342 assert(DestTy->isExtVectorType() && "Not an extended vector type!")((DestTy->isExtVectorType() && "Not an extended vector type!"
) ? static_cast<void> (0) : __assert_fail ("DestTy->isExtVectorType() && \"Not an extended vector type!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 7342, __PRETTY_FUNCTION__))
;
7343
7344 QualType SrcTy = CastExpr->getType();
7345
7346 // If SrcTy is a VectorType, the total size must match to explicitly cast to
7347 // an ExtVectorType.
7348 // In OpenCL, casts between vectors of different types are not allowed.
7349 // (See OpenCL 6.2).
7350 if (SrcTy->isVectorType()) {
7351 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7352 (getLangOpts().OpenCL &&
7353 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7354 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7355 << DestTy << SrcTy << R;
7356 return ExprError();
7357 }
7358 Kind = CK_BitCast;
7359 return CastExpr;
7360 }
7361
7362 // All non-pointer scalars can be cast to ExtVector type. The appropriate
7363 // conversion will take place first from scalar to elt type, and then
7364 // splat from elt type to vector.
7365 if (SrcTy->isPointerType())
7366 return Diag(R.getBegin(),
7367 diag::err_invalid_conversion_between_vector_and_scalar)
7368 << DestTy << SrcTy << R;
7369
7370 Kind = CK_VectorSplat;
7371 return prepareVectorSplat(DestTy, CastExpr);
7372}
7373
7374ExprResult
7375Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7376 Declarator &D, ParsedType &Ty,
7377 SourceLocation RParenLoc, Expr *CastExpr) {
7378 assert(!D.isInvalidType() && (CastExpr != nullptr) &&((!D.isInvalidType() && (CastExpr != nullptr) &&
"ActOnCastExpr(): missing type or expr") ? static_cast<void
> (0) : __assert_fail ("!D.isInvalidType() && (CastExpr != nullptr) && \"ActOnCastExpr(): missing type or expr\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 7379, __PRETTY_FUNCTION__))
7379 "ActOnCastExpr(): missing type or expr")((!D.isInvalidType() && (CastExpr != nullptr) &&
"ActOnCastExpr(): missing type or expr") ? static_cast<void
> (0) : __assert_fail ("!D.isInvalidType() && (CastExpr != nullptr) && \"ActOnCastExpr(): missing type or expr\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 7379, __PRETTY_FUNCTION__))
;
7380
7381 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
7382 if (D.isInvalidType())
7383 return ExprError();
7384
7385 if (getLangOpts().CPlusPlus) {
7386 // Check that there are no default arguments (C++ only).
7387 CheckExtraCXXDefaultArguments(D);
7388 } else {
7389 // Make sure any TypoExprs have been dealt with.
7390 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
7391 if (!Res.isUsable())
7392 return ExprError();
7393 CastExpr = Res.get();
7394 }
7395
7396 checkUnusedDeclAttributes(D);
7397
7398 QualType castType = castTInfo->getType();
7399 Ty = CreateParsedType(castType, castTInfo);
7400
7401 bool isVectorLiteral = false;
7402
7403 // Check for an altivec or OpenCL literal,
7404 // i.e. all the elements are integer constants.
7405 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7406 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7407 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7408 && castType->isVectorType() && (PE || PLE)) {
7409 if (PLE && PLE->getNumExprs() == 0) {
7410 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7411 return ExprError();
7412 }
7413 if (PE || PLE->getNumExprs() == 1) {
7414 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7415 if (!E->isTypeDependent() && !E->getType()->isVectorType())
7416 isVectorLiteral = true;
7417 }
7418 else
7419 isVectorLiteral = true;
7420 }
7421
7422 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7423 // then handle it as such.
7424 if (isVectorLiteral)
7425 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7426
7427 // If the Expr being casted is a ParenListExpr, handle it specially.
7428 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7429 // sequence of BinOp comma operators.
7430 if (isa<ParenListExpr>(CastExpr)) {
7431 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
7432 if (Result.isInvalid()) return ExprError();
7433 CastExpr = Result.get();
7434 }
7435
7436 if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
7437 !getSourceManager().isInSystemMacro(LParenLoc))
7438 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7439
7440 CheckTollFreeBridgeCast(castType, CastExpr);
7441
7442 CheckObjCBridgeRelatedCast(castType, CastExpr);
7443
7444 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
7445
7446 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7447}
7448
7449ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
7450 SourceLocation RParenLoc, Expr *E,
7451 TypeSourceInfo *TInfo) {
7452 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&(((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
"Expected paren or paren list expression") ? static_cast<
void> (0) : __assert_fail ("(isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && \"Expected paren or paren list expression\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 7453, __PRETTY_FUNCTION__))
7453 "Expected paren or paren list expression")(((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
"Expected paren or paren list expression") ? static_cast<
void> (0) : __assert_fail ("(isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && \"Expected paren or paren list expression\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 7453, __PRETTY_FUNCTION__))
;
7454
7455 Expr **exprs;
7456 unsigned numExprs;
7457 Expr *subExpr;
7458 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7459 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7460 LiteralLParenLoc = PE->getLParenLoc();
7461 LiteralRParenLoc = PE->getRParenLoc();
7462 exprs = PE->getExprs();
7463 numExprs = PE->getNumExprs();
7464 } else { // isa<ParenExpr> by assertion at function entrance
7465 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7466 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7467 subExpr = cast<ParenExpr>(E)->getSubExpr();
7468 exprs = &subExpr;
7469 numExprs = 1;
7470 }
7471
7472 QualType Ty = TInfo->getType();
7473 assert(Ty->isVectorType() && "Expected vector type")((Ty->isVectorType() && "Expected vector type") ? static_cast
<void> (0) : __assert_fail ("Ty->isVectorType() && \"Expected vector type\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 7473, __PRETTY_FUNCTION__))
;
7474
7475 SmallVector<Expr *, 8> initExprs;
7476 const VectorType *VTy = Ty->castAs<VectorType>();
7477 unsigned numElems = VTy->getNumElements();
7478
7479 // '(...)' form of vector initialization in AltiVec: the number of
7480 // initializers must be one or must match the size of the vector.
7481 // If a single value is specified in the initializer then it will be
7482 // replicated to all the components of the vector
7483 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
7484 // The number of initializers must be one or must match the size of the
7485 // vector. If a single value is specified in the initializer then it will
7486 // be replicated to all the components of the vector
7487 if (numExprs == 1) {
7488 QualType ElemTy = VTy->getElementType();
7489 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7490 if (Literal.isInvalid())
7491 return ExprError();
7492 Literal = ImpCastExprToType(Literal.get(), ElemTy,
7493 PrepareScalarCast(Literal, ElemTy));
7494 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7495 }
7496 else if (numExprs < numElems) {
7497 Diag(E->getExprLoc(),
7498 diag::err_incorrect_number_of_vector_initializers);
7499 return ExprError();
7500 }
7501 else
7502 initExprs.append(exprs, exprs + numExprs);
7503 }
7504 else {
7505 // For OpenCL, when the number of initializers is a single value,
7506 // it will be replicated to all components of the vector.
7507 if (getLangOpts().OpenCL &&
7508 VTy->getVectorKind() == VectorType::GenericVector &&
7509 numExprs == 1) {
7510 QualType ElemTy = VTy->getElementType();
7511 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7512 if (Literal.isInvalid())
7513 return ExprError();
7514 Literal = ImpCastExprToType(Literal.get(), ElemTy,
7515 PrepareScalarCast(Literal, ElemTy));
7516 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7517 }
7518
7519 initExprs.append(exprs, exprs + numExprs);
7520 }
7521 // FIXME: This means that pretty-printing the final AST will produce curly
7522 // braces instead of the original commas.
7523 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
7524 initExprs, LiteralRParenLoc);
7525 initE->setType(Ty);
7526 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
7527}
7528
7529/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7530/// the ParenListExpr into a sequence of comma binary operators.
7531ExprResult
7532Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
7533 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
7534 if (!E)
7535 return OrigExpr;
7536
7537 ExprResult Result(E->getExpr(0));
7538
7539 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
7540 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
7541 E->getExpr(i));
7542
7543 if (Result.isInvalid()) return ExprError();
7544
7545 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
7546}
7547
7548ExprResult Sema::ActOnParenListExpr(SourceLocation L,
7549 SourceLocation R,
7550 MultiExprArg Val) {
7551 return ParenListExpr::Create(Context, L, Val, R);
7552}
7553
7554/// Emit a specialized diagnostic when one expression is a null pointer
7555/// constant and the other is not a pointer. Returns true if a diagnostic is
7556/// emitted.
7557bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
7558 SourceLocation QuestionLoc) {
7559 Expr *NullExpr = LHSExpr;
7560 Expr *NonPointerExpr = RHSExpr;
7561 Expr::NullPointerConstantKind NullKind =
7562 NullExpr->isNullPointerConstant(Context,
7563 Expr::NPC_ValueDependentIsNotNull);
7564
7565 if (NullKind == Expr::NPCK_NotNull) {
7566 NullExpr = RHSExpr;
7567 NonPointerExpr = LHSExpr;
7568 NullKind =
7569 NullExpr->isNullPointerConstant(Context,
7570 Expr::NPC_ValueDependentIsNotNull);
7571 }
7572
7573 if (NullKind == Expr::NPCK_NotNull)
7574 return false;
7575
7576 if (NullKind == Expr::NPCK_ZeroExpression)
7577 return false;
7578
7579 if (NullKind == Expr::NPCK_ZeroLiteral) {
7580 // In this case, check to make sure that we got here from a "NULL"
7581 // string in the source code.
7582 NullExpr = NullExpr->IgnoreParenImpCasts();
7583 SourceLocation loc = NullExpr->getExprLoc();
7584 if (!findMacroSpelling(loc, "NULL"))
7585 return false;
7586 }
7587
7588 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
7589 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
7590 << NonPointerExpr->getType() << DiagType
7591 << NonPointerExpr->getSourceRange();
7592 return true;
7593}
7594
7595/// Return false if the condition expression is valid, true otherwise.
7596static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
7597 QualType CondTy = Cond->getType();
7598
7599 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
7600 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
7601 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7602 << CondTy << Cond->getSourceRange();
7603 return true;
7604 }
7605
7606 // C99 6.5.15p2
7607 if (CondTy->isScalarType()) return false;
7608
7609 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
7610 << CondTy << Cond->getSourceRange();
7611 return true;
7612}
7613
7614/// Handle when one or both operands are void type.
7615static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
7616 ExprResult &RHS) {
7617 Expr *LHSExpr = LHS.get();
7618 Expr *RHSExpr = RHS.get();
7619
7620 if (!LHSExpr->getType()->isVoidType())
7621 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7622 << RHSExpr->getSourceRange();
7623 if (!RHSExpr->getType()->isVoidType())
7624 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7625 << LHSExpr->getSourceRange();
7626 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
7627 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
7628 return S.Context.VoidTy;
7629}
7630
7631/// Return false if the NullExpr can be promoted to PointerTy,
7632/// true otherwise.
7633static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
7634 QualType PointerTy) {
7635 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
7636 !NullExpr.get()->isNullPointerConstant(S.Context,
7637 Expr::NPC_ValueDependentIsNull))
7638 return true;
7639
7640 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
7641 return false;
7642}
7643
7644/// Checks compatibility between two pointers and return the resulting
7645/// type.
7646static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
7647 ExprResult &RHS,
7648 SourceLocation Loc) {
7649 QualType LHSTy = LHS.get()->getType();
7650 QualType RHSTy = RHS.get()->getType();
7651
7652 if (S.Context.hasSameType(LHSTy, RHSTy)) {
7653 // Two identical pointers types are always compatible.
7654 return LHSTy;
7655 }
7656
7657 QualType lhptee, rhptee;
7658
7659 // Get the pointee types.
7660 bool IsBlockPointer = false;
7661 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
7662 lhptee = LHSBTy->getPointeeType();
7663 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
7664 IsBlockPointer = true;
7665 } else {
7666 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7667 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7668 }
7669
7670 // C99 6.5.15p6: If both operands are pointers to compatible types or to
7671 // differently qualified versions of compatible types, the result type is
7672 // a pointer to an appropriately qualified version of the composite
7673 // type.
7674
7675 // Only CVR-qualifiers exist in the standard, and the differently-qualified
7676 // clause doesn't make sense for our extensions. E.g. address space 2 should
7677 // be incompatible with address space 3: they may live on different devices or
7678 // anything.
7679 Qualifiers lhQual = lhptee.getQualifiers();
7680 Qualifiers rhQual = rhptee.getQualifiers();
7681
7682 LangAS ResultAddrSpace = LangAS::Default;
7683 LangAS LAddrSpace = lhQual.getAddressSpace();
7684 LangAS RAddrSpace = rhQual.getAddressSpace();
7685
7686 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
7687 // spaces is disallowed.
7688 if (lhQual.isAddressSpaceSupersetOf(rhQual))
7689 ResultAddrSpace = LAddrSpace;
7690 else if (rhQual.isAddressSpaceSupersetOf(lhQual))
7691 ResultAddrSpace = RAddrSpace;
7692 else {
7693 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7694 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
7695 << RHS.get()->getSourceRange();
7696 return QualType();
7697 }
7698
7699 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
7700 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
7701 lhQual.removeCVRQualifiers();
7702 rhQual.removeCVRQualifiers();
7703
7704 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
7705 // (C99 6.7.3) for address spaces. We assume that the check should behave in
7706 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
7707 // qual types are compatible iff
7708 // * corresponded types are compatible
7709 // * CVR qualifiers are equal
7710 // * address spaces are equal
7711 // Thus for conditional operator we merge CVR and address space unqualified
7712 // pointees and if there is a composite type we return a pointer to it with
7713 // merged qualifiers.
7714 LHSCastKind =
7715 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7716 RHSCastKind =
7717 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7718 lhQual.removeAddressSpace();
7719 rhQual.removeAddressSpace();
7720
7721 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
7722 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
7723
7724 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
7725
7726 if (CompositeTy.isNull()) {
7727 // In this situation, we assume void* type. No especially good
7728 // reason, but this is what gcc does, and we do have to pick
7729 // to get a consistent AST.
7730 QualType incompatTy;
7731 incompatTy = S.Context.getPointerType(
7732 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
7733 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
7734 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
7735
7736 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
7737 // for casts between types with incompatible address space qualifiers.
7738 // For the following code the compiler produces casts between global and
7739 // local address spaces of the corresponded innermost pointees:
7740 // local int *global *a;
7741 // global int *global *b;
7742 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
7743 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
7744 << LHSTy << RHSTy << LHS.get()->getSourceRange()
7745 << RHS.get()->getSourceRange();
7746
7747 return incompatTy;
7748 }
7749
7750 // The pointer types are compatible.
7751 // In case of OpenCL ResultTy should have the address space qualifier
7752 // which is a superset of address spaces of both the 2nd and the 3rd
7753 // operands of the conditional operator.
7754 QualType ResultTy = [&, ResultAddrSpace]() {
7755 if (S.getLangOpts().OpenCL) {
7756 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
7757 CompositeQuals.setAddressSpace(ResultAddrSpace);
7758 return S.Context
7759 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
7760 .withCVRQualifiers(MergedCVRQual);
7761 }
7762 return CompositeTy.withCVRQualifiers(MergedCVRQual);
7763 }();
7764 if (IsBlockPointer)
7765 ResultTy = S.Context.getBlockPointerType(ResultTy);
7766 else
7767 ResultTy = S.Context.getPointerType(ResultTy);
7768
7769 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
7770 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
7771 return ResultTy;
7772}
7773
7774/// Return the resulting type when the operands are both block pointers.
7775static QualType checkConditionalBlockPointerCompatibility(Sema &S,
7776 ExprResult &LHS,
7777 ExprResult &RHS,
7778 SourceLocation Loc) {
7779 QualType LHSTy = LHS.get()->getType();
7780 QualType RHSTy = RHS.get()->getType();
7781
7782 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
7783 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
7784 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
7785 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7786 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7787 return destType;
7788 }
7789 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
7790 << LHSTy << RHSTy << LHS.get()->getSourceRange()
7791 << RHS.get()->getSourceRange();
7792 return QualType();
7793 }
7794
7795 // We have 2 block pointer types.
7796 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7797}
7798
7799/// Return the resulting type when the operands are both pointers.
7800static QualType
7801checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
7802 ExprResult &RHS,
7803 SourceLocation Loc) {
7804 // get the pointer types
7805 QualType LHSTy = LHS.get()->getType();
7806 QualType RHSTy = RHS.get()->getType();
7807
7808 // get the "pointed to" types
7809 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7810 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7811
7812 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
7813 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
7814 // Figure out necessary qualifiers (C99 6.5.15p6)
7815 QualType destPointee
7816 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7817 QualType destType = S.Context.getPointerType(destPointee);
7818 // Add qualifiers if necessary.
7819 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7820 // Promote to void*.
7821 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7822 return destType;
7823 }
7824 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
7825 QualType destPointee
7826 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7827 QualType destType = S.Context.getPointerType(destPointee);
7828 // Add qualifiers if necessary.
7829 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7830 // Promote to void*.
7831 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7832 return destType;
7833 }
7834
7835 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7836}
7837
7838/// Return false if the first expression is not an integer and the second
7839/// expression is not a pointer, true otherwise.
7840static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
7841 Expr* PointerExpr, SourceLocation Loc,
7842 bool IsIntFirstExpr) {
7843 if (!PointerExpr->getType()->isPointerType() ||
7844 !Int.get()->getType()->isIntegerType())
7845 return false;
7846
7847 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
7848 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
7849
7850 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
7851 << Expr1->getType() << Expr2->getType()
7852 << Expr1->getSourceRange() << Expr2->getSourceRange();
7853 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
7854 CK_IntegralToPointer);
7855 return true;
7856}
7857
7858/// Simple conversion between integer and floating point types.
7859///
7860/// Used when handling the OpenCL conditional operator where the
7861/// condition is a vector while the other operands are scalar.
7862///
7863/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
7864/// types are either integer or floating type. Between the two
7865/// operands, the type with the higher rank is defined as the "result
7866/// type". The other operand needs to be promoted to the same type. No
7867/// other type promotion is allowed. We cannot use
7868/// UsualArithmeticConversions() for this purpose, since it always
7869/// promotes promotable types.
7870static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
7871 ExprResult &RHS,
7872 SourceLocation QuestionLoc) {
7873 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
7874 if (LHS.isInvalid())
7875 return QualType();
7876 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
7877 if (RHS.isInvalid())
7878 return QualType();
7879
7880 // For conversion purposes, we ignore any qualifiers.
7881 // For example, "const float" and "float" are equivalent.
7882 QualType LHSType =
7883 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
7884 QualType RHSType =
7885 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
7886
7887 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
7888 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7889 << LHSType << LHS.get()->getSourceRange();
7890 return QualType();
7891 }
7892
7893 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
7894 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7895 << RHSType << RHS.get()->getSourceRange();
7896 return QualType();
7897 }
7898
7899 // If both types are identical, no conversion is needed.
7900 if (LHSType == RHSType)
7901 return LHSType;
7902
7903 // Now handle "real" floating types (i.e. float, double, long double).
7904 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
7905 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
7906 /*IsCompAssign = */ false);
7907
7908 // Finally, we have two differing integer types.
7909 return handleIntegerConversion<doIntegralCast, doIntegralCast>
7910 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
7911}
7912
7913/// Convert scalar operands to a vector that matches the
7914/// condition in length.
7915///
7916/// Used when handling the OpenCL conditional operator where the
7917/// condition is a vector while the other operands are scalar.
7918///
7919/// We first compute the "result type" for the scalar operands
7920/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
7921/// into a vector of that type where the length matches the condition
7922/// vector type. s6.11.6 requires that the element types of the result
7923/// and the condition must have the same number of bits.
7924static QualType
7925OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
7926 QualType CondTy, SourceLocation QuestionLoc) {
7927 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
7928 if (ResTy.isNull()) return QualType();
7929
7930 const VectorType *CV = CondTy->getAs<VectorType>();
7931 assert(CV)((CV) ? static_cast<void> (0) : __assert_fail ("CV", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 7931, __PRETTY_FUNCTION__))
;
7932
7933 // Determine the vector result type
7934 unsigned NumElements = CV->getNumElements();
7935 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
7936
7937 // Ensure that all types have the same number of bits
7938 if (S.Context.getTypeSize(CV->getElementType())
7939 != S.Context.getTypeSize(ResTy)) {
7940 // Since VectorTy is created internally, it does not pretty print
7941 // with an OpenCL name. Instead, we just print a description.
7942 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
7943 SmallString<64> Str;
7944 llvm::raw_svector_ostream OS(Str);
7945 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
7946 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7947 << CondTy << OS.str();
7948 return QualType();
7949 }
7950
7951 // Convert operands to the vector result type
7952 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
7953 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
7954
7955 return VectorTy;
7956}
7957
7958/// Return false if this is a valid OpenCL condition vector
7959static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
7960 SourceLocation QuestionLoc) {
7961 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
7962 // integral type.
7963 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
7964 assert(CondTy)((CondTy) ? static_cast<void> (0) : __assert_fail ("CondTy"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 7964, __PRETTY_FUNCTION__))
;
7965 QualType EleTy = CondTy->getElementType();
7966 if (EleTy->isIntegerType()) return false;
7967
7968 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7969 << Cond->getType() << Cond->getSourceRange();
7970 return true;
7971}
7972
7973/// Return false if the vector condition type and the vector
7974/// result type are compatible.
7975///
7976/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
7977/// number of elements, and their element types have the same number
7978/// of bits.
7979static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
7980 SourceLocation QuestionLoc) {
7981 const VectorType *CV = CondTy->getAs<VectorType>();
7982 const VectorType *RV = VecResTy->getAs<VectorType>();
7983 assert(CV && RV)((CV && RV) ? static_cast<void> (0) : __assert_fail
("CV && RV", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 7983, __PRETTY_FUNCTION__))
;
7984
7985 if (CV->getNumElements() != RV->getNumElements()) {
7986 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
7987 << CondTy << VecResTy;
7988 return true;
7989 }
7990
7991 QualType CVE = CV->getElementType();
7992 QualType RVE = RV->getElementType();
7993
7994 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
7995 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7996 << CondTy << VecResTy;
7997 return true;
7998 }
7999
8000 return false;
8001}
8002
8003/// Return the resulting type for the conditional operator in
8004/// OpenCL (aka "ternary selection operator", OpenCL v1.1
8005/// s6.3.i) when the condition is a vector type.
8006static QualType
8007OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8008 ExprResult &LHS, ExprResult &RHS,
8009 SourceLocation QuestionLoc) {
8010 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
8011 if (Cond.isInvalid())
8012 return QualType();
8013 QualType CondTy = Cond.get()->getType();
8014
8015 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8016 return QualType();
8017
8018 // If either operand is a vector then find the vector type of the
8019 // result as specified in OpenCL v1.1 s6.3.i.
8020 if (LHS.get()->getType()->isVectorType() ||
8021 RHS.get()->getType()->isVectorType()) {
8022 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8023 /*isCompAssign*/false,
8024 /*AllowBothBool*/true,
8025 /*AllowBoolConversions*/false);
8026 if (VecResTy.isNull()) return QualType();
8027 // The result type must match the condition type as specified in
8028 // OpenCL v1.1 s6.11.6.
8029 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8030 return QualType();
8031 return VecResTy;
8032 }
8033
8034 // Both operands are scalar.
8035 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8036}
8037
8038/// Return true if the Expr is block type
8039static bool checkBlockType(Sema &S, const Expr *E) {
8040 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8041 QualType Ty = CE->getCallee()->getType();
8042 if (Ty->isBlockPointerType()) {
8043 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8044 return true;
8045 }
8046 }
8047 return false;
8048}
8049
8050/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8051/// In that case, LHS = cond.
8052/// C99 6.5.15
8053QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8054 ExprResult &RHS, ExprValueKind &VK,
8055 ExprObjectKind &OK,
8056 SourceLocation QuestionLoc) {
8057
8058 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8059 if (!LHSResult.isUsable()) return QualType();
8060 LHS = LHSResult;
8061
8062 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8063 if (!RHSResult.isUsable()) return QualType();
8064 RHS = RHSResult;
8065
8066 // C++ is sufficiently different to merit its own checker.
8067 if (getLangOpts().CPlusPlus)
8068 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8069
8070 VK = VK_RValue;
8071 OK = OK_Ordinary;
8072
8073 if (Context.isDependenceAllowed() &&
8074 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8075 RHS.get()->isTypeDependent())) {
8076 assert(!getLangOpts().CPlusPlus)((!getLangOpts().CPlusPlus) ? static_cast<void> (0) : __assert_fail
("!getLangOpts().CPlusPlus", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 8076, __PRETTY_FUNCTION__))
;
8077 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||(((Cond.get()->containsErrors() || LHS.get()->containsErrors
() || RHS.get()->containsErrors()) && "should only occur in error-recovery path."
) ? static_cast<void> (0) : __assert_fail ("(Cond.get()->containsErrors() || LHS.get()->containsErrors() || RHS.get()->containsErrors()) && \"should only occur in error-recovery path.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 8079, __PRETTY_FUNCTION__))
8078 RHS.get()->containsErrors()) &&(((Cond.get()->containsErrors() || LHS.get()->containsErrors
() || RHS.get()->containsErrors()) && "should only occur in error-recovery path."
) ? static_cast<void> (0) : __assert_fail ("(Cond.get()->containsErrors() || LHS.get()->containsErrors() || RHS.get()->containsErrors()) && \"should only occur in error-recovery path.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 8079, __PRETTY_FUNCTION__))
8079 "should only occur in error-recovery path.")(((Cond.get()->containsErrors() || LHS.get()->containsErrors
() || RHS.get()->containsErrors()) && "should only occur in error-recovery path."
) ? static_cast<void> (0) : __assert_fail ("(Cond.get()->containsErrors() || LHS.get()->containsErrors() || RHS.get()->containsErrors()) && \"should only occur in error-recovery path.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 8079, __PRETTY_FUNCTION__))
;
8080 return Context.DependentTy;
8081 }
8082
8083 // The OpenCL operator with a vector condition is sufficiently
8084 // different to merit its own checker.
8085 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8086 Cond.get()->getType()->isExtVectorType())
8087 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8088
8089 // First, check the condition.
8090 Cond = UsualUnaryConversions(Cond.get());
8091 if (Cond.isInvalid())
8092 return QualType();
8093 if (checkCondition(*this, Cond.get(), QuestionLoc))
8094 return QualType();
8095
8096 // Now check the two expressions.
8097 if (LHS.get()->getType()->isVectorType() ||
8098 RHS.get()->getType()->isVectorType())
8099 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
8100 /*AllowBothBool*/true,
8101 /*AllowBoolConversions*/false);
8102
8103 QualType ResTy =
8104 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8105 if (LHS.isInvalid() || RHS.isInvalid())
8106 return QualType();
8107
8108 QualType LHSTy = LHS.get()->getType();
8109 QualType RHSTy = RHS.get()->getType();
8110
8111 // Diagnose attempts to convert between __float128 and long double where
8112 // such conversions currently can't be handled.
8113 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8114 Diag(QuestionLoc,
8115 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8116 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8117 return QualType();
8118 }
8119
8120 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8121 // selection operator (?:).
8122 if (getLangOpts().OpenCL &&
8123 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
8124 return QualType();
8125 }
8126
8127 // If both operands have arithmetic type, do the usual arithmetic conversions
8128 // to find a common type: C99 6.5.15p3,5.
8129 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8130 // Disallow invalid arithmetic conversions, such as those between ExtInts of
8131 // different sizes, or between ExtInts and other types.
8132 if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) {
8133 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8134 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8135 << RHS.get()->getSourceRange();
8136 return QualType();
8137 }
8138
8139 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8140 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8141
8142 return ResTy;
8143 }
8144
8145 // And if they're both bfloat (which isn't arithmetic), that's fine too.
8146 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
8147 return LHSTy;
8148 }
8149
8150 // If both operands are the same structure or union type, the result is that
8151 // type.
8152 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
8153 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8154 if (LHSRT->getDecl() == RHSRT->getDecl())
8155 // "If both the operands have structure or union type, the result has
8156 // that type." This implies that CV qualifiers are dropped.
8157 return LHSTy.getUnqualifiedType();
8158 // FIXME: Type of conditional expression must be complete in C mode.
8159 }
8160
8161 // C99 6.5.15p5: "If both operands have void type, the result has void type."
8162 // The following || allows only one side to be void (a GCC-ism).
8163 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8164 return checkConditionalVoidType(*this, LHS, RHS);
8165 }
8166
8167 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8168 // the type of the other operand."
8169 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8170 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8171
8172 // All objective-c pointer type analysis is done here.
8173 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
8174 QuestionLoc);
8175 if (LHS.isInvalid() || RHS.isInvalid())
8176 return QualType();
8177 if (!compositeType.isNull())
8178 return compositeType;
8179
8180
8181 // Handle block pointer types.
8182 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8183 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8184 QuestionLoc);
8185
8186 // Check constraints for C object pointers types (C99 6.5.15p3,6).
8187 if (LHSTy->isPointerType() && RHSTy->isPointerType())
8188 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8189 QuestionLoc);
8190
8191 // GCC compatibility: soften pointer/integer mismatch. Note that
8192 // null pointers have been filtered out by this point.
8193 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8194 /*IsIntFirstExpr=*/true))
8195 return RHSTy;
8196 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8197 /*IsIntFirstExpr=*/false))
8198 return LHSTy;
8199
8200 // Allow ?: operations in which both operands have the same
8201 // built-in sizeless type.
8202 if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy)
8203 return LHSTy;
8204
8205 // Emit a better diagnostic if one of the expressions is a null pointer
8206 // constant and the other is not a pointer type. In this case, the user most
8207 // likely forgot to take the address of the other expression.
8208 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8209 return QualType();
8210
8211 // Otherwise, the operands are not compatible.
8212 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8213 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8214 << RHS.get()->getSourceRange();
8215 return QualType();
8216}
8217
8218/// FindCompositeObjCPointerType - Helper method to find composite type of
8219/// two objective-c pointer types of the two input expressions.
8220QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8221 SourceLocation QuestionLoc) {
8222 QualType LHSTy = LHS.get()->getType();
8223 QualType RHSTy = RHS.get()->getType();
8224
8225 // Handle things like Class and struct objc_class*. Here we case the result
8226 // to the pseudo-builtin, because that will be implicitly cast back to the
8227 // redefinition type if an attempt is made to access its fields.
8228 if (LHSTy->isObjCClassType() &&
8229 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
8230 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8231 return LHSTy;
8232 }
8233 if (RHSTy->isObjCClassType() &&
8234 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
8235 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8236 return RHSTy;
8237 }
8238 // And the same for struct objc_object* / id
8239 if (LHSTy->isObjCIdType() &&
8240 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
8241 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8242 return LHSTy;
8243 }
8244 if (RHSTy->isObjCIdType() &&
8245 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
8246 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8247 return RHSTy;
8248 }
8249 // And the same for struct objc_selector* / SEL
8250 if (Context.isObjCSelType(LHSTy) &&
8251 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
8252 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
8253 return LHSTy;
8254 }
8255 if (Context.isObjCSelType(RHSTy) &&
8256 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
8257 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
8258 return RHSTy;
8259 }
8260 // Check constraints for Objective-C object pointers types.
8261 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
8262
8263 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
8264 // Two identical object pointer types are always compatible.
8265 return LHSTy;
8266 }
8267 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
8268 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
8269 QualType compositeType = LHSTy;
8270
8271 // If both operands are interfaces and either operand can be
8272 // assigned to the other, use that type as the composite
8273 // type. This allows
8274 // xxx ? (A*) a : (B*) b
8275 // where B is a subclass of A.
8276 //
8277 // Additionally, as for assignment, if either type is 'id'
8278 // allow silent coercion. Finally, if the types are
8279 // incompatible then make sure to use 'id' as the composite
8280 // type so the result is acceptable for sending messages to.
8281
8282 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
8283 // It could return the composite type.
8284 if (!(compositeType =
8285 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
8286 // Nothing more to do.
8287 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
8288 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
8289 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
8290 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
8291 } else if ((LHSOPT->isObjCQualifiedIdType() ||
8292 RHSOPT->isObjCQualifiedIdType()) &&
8293 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
8294 true)) {
8295 // Need to handle "id<xx>" explicitly.
8296 // GCC allows qualified id and any Objective-C type to devolve to
8297 // id. Currently localizing to here until clear this should be
8298 // part of ObjCQualifiedIdTypesAreCompatible.
8299 compositeType = Context.getObjCIdType();
8300 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
8301 compositeType = Context.getObjCIdType();
8302 } else {
8303 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
8304 << LHSTy << RHSTy
8305 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8306 QualType incompatTy = Context.getObjCIdType();
8307 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
8308 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
8309 return incompatTy;
8310 }
8311 // The object pointer types are compatible.
8312 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
8313 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
8314 return compositeType;
8315 }
8316 // Check Objective-C object pointer types and 'void *'
8317 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
8318 if (getLangOpts().ObjCAutoRefCount) {
8319 // ARC forbids the implicit conversion of object pointers to 'void *',
8320 // so these types are not compatible.
8321 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8322 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8323 LHS = RHS = true;
8324 return QualType();
8325 }
8326 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8327 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8328 QualType destPointee
8329 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8330 QualType destType = Context.getPointerType(destPointee);
8331 // Add qualifiers if necessary.
8332 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8333 // Promote to void*.
8334 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8335 return destType;
8336 }
8337 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
8338 if (getLangOpts().ObjCAutoRefCount) {
8339 // ARC forbids the implicit conversion of object pointers to 'void *',
8340 // so these types are not compatible.
8341 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8342 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8343 LHS = RHS = true;
8344 return QualType();
8345 }
8346 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8347 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8348 QualType destPointee
8349 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8350 QualType destType = Context.getPointerType(destPointee);
8351 // Add qualifiers if necessary.
8352 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8353 // Promote to void*.
8354 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8355 return destType;
8356 }
8357 return QualType();
8358}
8359
8360/// SuggestParentheses - Emit a note with a fixit hint that wraps
8361/// ParenRange in parentheses.
8362static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8363 const PartialDiagnostic &Note,
8364 SourceRange ParenRange) {
8365 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8366 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8367 EndLoc.isValid()) {
8368 Self.Diag(Loc, Note)
8369 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8370 << FixItHint::CreateInsertion(EndLoc, ")");
8371 } else {
8372 // We can't display the parentheses, so just show the bare note.
8373 Self.Diag(Loc, Note) << ParenRange;
8374 }
8375}
8376
8377static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8378 return BinaryOperator::isAdditiveOp(Opc) ||
8379 BinaryOperator::isMultiplicativeOp(Opc) ||
8380 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8381 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8382 // not any of the logical operators. Bitwise-xor is commonly used as a
8383 // logical-xor because there is no logical-xor operator. The logical
8384 // operators, including uses of xor, have a high false positive rate for
8385 // precedence warnings.
8386}
8387
8388/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8389/// expression, either using a built-in or overloaded operator,
8390/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8391/// expression.
8392static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
8393 Expr **RHSExprs) {
8394 // Don't strip parenthesis: we should not warn if E is in parenthesis.
8395 E = E->IgnoreImpCasts();
8396 E = E->IgnoreConversionOperatorSingleStep();
8397 E = E->IgnoreImpCasts();
8398 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8399 E = MTE->getSubExpr();
8400 E = E->IgnoreImpCasts();
8401 }
8402
8403 // Built-in binary operator.
8404 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
8405 if (IsArithmeticOp(OP->getOpcode())) {
8406 *Opcode = OP->getOpcode();
8407 *RHSExprs = OP->getRHS();
8408 return true;
8409 }
8410 }
8411
8412 // Overloaded operator.
8413 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8414 if (Call->getNumArgs() != 2)
8415 return false;
8416
8417 // Make sure this is really a binary operator that is safe to pass into
8418 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8419 OverloadedOperatorKind OO = Call->getOperator();
8420 if (OO < OO_Plus || OO > OO_Arrow ||
8421 OO == OO_PlusPlus || OO == OO_MinusMinus)
8422 return false;
8423
8424 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
8425 if (IsArithmeticOp(OpKind)) {
8426 *Opcode = OpKind;
8427 *RHSExprs = Call->getArg(1);
8428 return true;
8429 }
8430 }
8431
8432 return false;
8433}
8434
8435/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8436/// or is a logical expression such as (x==y) which has int type, but is
8437/// commonly interpreted as boolean.
8438static bool ExprLooksBoolean(Expr *E) {
8439 E = E->IgnoreParenImpCasts();
8440
8441 if (E->getType()->isBooleanType())
8442 return true;
8443 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
8444 return OP->isComparisonOp() || OP->isLogicalOp();
8445 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
8446 return OP->getOpcode() == UO_LNot;
8447 if (E->getType()->isPointerType())
8448 return true;
8449 // FIXME: What about overloaded operator calls returning "unspecified boolean
8450 // type"s (commonly pointer-to-members)?
8451
8452 return false;
8453}
8454
8455/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8456/// and binary operator are mixed in a way that suggests the programmer assumed
8457/// the conditional operator has higher precedence, for example:
8458/// "int x = a + someBinaryCondition ? 1 : 2".
8459static void DiagnoseConditionalPrecedence(Sema &Self,
8460 SourceLocation OpLoc,
8461 Expr *Condition,
8462 Expr *LHSExpr,
8463 Expr *RHSExpr) {
8464 BinaryOperatorKind CondOpcode;
8465 Expr *CondRHS;
8466
8467 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8468 return;
8469 if (!ExprLooksBoolean(CondRHS))
8470 return;
8471
8472 // The condition is an arithmetic binary expression, with a right-
8473 // hand side that looks boolean, so warn.
8474
8475 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8476 ? diag::warn_precedence_bitwise_conditional
8477 : diag::warn_precedence_conditional;
8478
8479 Self.Diag(OpLoc, DiagID)
8480 << Condition->getSourceRange()
8481 << BinaryOperator::getOpcodeStr(CondOpcode);
8482
8483 SuggestParentheses(
8484 Self, OpLoc,
8485 Self.PDiag(diag::note_precedence_silence)
8486 << BinaryOperator::getOpcodeStr(CondOpcode),
8487 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8488
8489 SuggestParentheses(Self, OpLoc,
8490 Self.PDiag(diag::note_precedence_conditional_first),
8491 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8492}
8493
8494/// Compute the nullability of a conditional expression.
8495static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
8496 QualType LHSTy, QualType RHSTy,
8497 ASTContext &Ctx) {
8498 if (!ResTy->isAnyPointerType())
8499 return ResTy;
8500
8501 auto GetNullability = [&Ctx](QualType Ty) {
8502 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
8503 if (Kind)
8504 return *Kind;
8505 return NullabilityKind::Unspecified;
8506 };
8507
8508 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8509 NullabilityKind MergedKind;
8510
8511 // Compute nullability of a binary conditional expression.
8512 if (IsBin) {
8513 if (LHSKind == NullabilityKind::NonNull)
8514 MergedKind = NullabilityKind::NonNull;
8515 else
8516 MergedKind = RHSKind;
8517 // Compute nullability of a normal conditional expression.
8518 } else {
8519 if (LHSKind == NullabilityKind::Nullable ||
8520 RHSKind == NullabilityKind::Nullable)
8521 MergedKind = NullabilityKind::Nullable;
8522 else if (LHSKind == NullabilityKind::NonNull)
8523 MergedKind = RHSKind;
8524 else if (RHSKind == NullabilityKind::NonNull)
8525 MergedKind = LHSKind;
8526 else
8527 MergedKind = NullabilityKind::Unspecified;
8528 }
8529
8530 // Return if ResTy already has the correct nullability.
8531 if (GetNullability(ResTy) == MergedKind)
8532 return ResTy;
8533
8534 // Strip all nullability from ResTy.
8535 while (ResTy->getNullability(Ctx))
8536 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8537
8538 // Create a new AttributedType with the new nullability kind.
8539 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
8540 return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
8541}
8542
8543/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
8544/// in the case of a the GNU conditional expr extension.
8545ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
8546 SourceLocation ColonLoc,
8547 Expr *CondExpr, Expr *LHSExpr,
8548 Expr *RHSExpr) {
8549 if (!Context.isDependenceAllowed()) {
8550 // C cannot handle TypoExpr nodes in the condition because it
8551 // doesn't handle dependent types properly, so make sure any TypoExprs have
8552 // been dealt with before checking the operands.
8553 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
8554 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
8555 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
8556
8557 if (!CondResult.isUsable())
8558 return ExprError();
8559
8560 if (LHSExpr) {
8561 if (!LHSResult.isUsable())
8562 return ExprError();
8563 }
8564
8565 if (!RHSResult.isUsable())
8566 return ExprError();
8567
8568 CondExpr = CondResult.get();
8569 LHSExpr = LHSResult.get();
8570 RHSExpr = RHSResult.get();
8571 }
8572
8573 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8574 // was the condition.
8575 OpaqueValueExpr *opaqueValue = nullptr;
8576 Expr *commonExpr = nullptr;
8577 if (!LHSExpr) {
8578 commonExpr = CondExpr;
8579 // Lower out placeholder types first. This is important so that we don't
8580 // try to capture a placeholder. This happens in few cases in C++; such
8581 // as Objective-C++'s dictionary subscripting syntax.
8582 if (commonExpr->hasPlaceholderType()) {
8583 ExprResult result = CheckPlaceholderExpr(commonExpr);
8584 if (!result.isUsable()) return ExprError();
8585 commonExpr = result.get();
8586 }
8587 // We usually want to apply unary conversions *before* saving, except
8588 // in the special case of a C++ l-value conditional.
8589 if (!(getLangOpts().CPlusPlus
8590 && !commonExpr->isTypeDependent()
8591 && commonExpr->getValueKind() == RHSExpr->getValueKind()
8592 && commonExpr->isGLValue()
8593 && commonExpr->isOrdinaryOrBitFieldObject()
8594 && RHSExpr->isOrdinaryOrBitFieldObject()
8595 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
8596 ExprResult commonRes = UsualUnaryConversions(commonExpr);
8597 if (commonRes.isInvalid())
8598 return ExprError();
8599 commonExpr = commonRes.get();
8600 }
8601
8602 // If the common expression is a class or array prvalue, materialize it
8603 // so that we can safely refer to it multiple times.
8604 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
8605 commonExpr->getType()->isArrayType())) {
8606 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
8607 if (MatExpr.isInvalid())
8608 return ExprError();
8609 commonExpr = MatExpr.get();
8610 }
8611
8612 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
8613 commonExpr->getType(),
8614 commonExpr->getValueKind(),
8615 commonExpr->getObjectKind(),
8616 commonExpr);
8617 LHSExpr = CondExpr = opaqueValue;
8618 }
8619
8620 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
8621 ExprValueKind VK = VK_RValue;
8622 ExprObjectKind OK = OK_Ordinary;
8623 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
8624 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
8625 VK, OK, QuestionLoc);
8626 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
8627 RHS.isInvalid())
8628 return ExprError();
8629
8630 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
8631 RHS.get());
8632
8633 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8634
8635 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8636 Context);
8637
8638 if (!commonExpr)
8639 return new (Context)
8640 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8641 RHS.get(), result, VK, OK);
8642
8643 return new (Context) BinaryConditionalOperator(
8644 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8645 ColonLoc, result, VK, OK);
8646}
8647
8648// Check if we have a conversion between incompatible cmse function pointer
8649// types, that is, a conversion between a function pointer with the
8650// cmse_nonsecure_call attribute and one without.
8651static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
8652 QualType ToType) {
8653 if (const auto *ToFn =
8654 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
8655 if (const auto *FromFn =
8656 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
8657 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
8658 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
8659
8660 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
8661 }
8662 }
8663 return false;
8664}
8665
8666// checkPointerTypesForAssignment - This is a very tricky routine (despite
8667// being closely modeled after the C99 spec:-). The odd characteristic of this
8668// routine is it effectively iqnores the qualifiers on the top level pointee.
8669// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
8670// FIXME: add a couple examples in this comment.
8671static Sema::AssignConvertType
8672checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
8673 assert(LHSType.isCanonical() && "LHS not canonicalized!")((LHSType.isCanonical() && "LHS not canonicalized!") ?
static_cast<void> (0) : __assert_fail ("LHSType.isCanonical() && \"LHS not canonicalized!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 8673, __PRETTY_FUNCTION__))
;
8674 assert(RHSType.isCanonical() && "RHS not canonicalized!")((RHSType.isCanonical() && "RHS not canonicalized!") ?
static_cast<void> (0) : __assert_fail ("RHSType.isCanonical() && \"RHS not canonicalized!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 8674, __PRETTY_FUNCTION__))
;
8675
8676 // get the "pointed to" type (ignoring qualifiers at the top level)
8677 const Type *lhptee, *rhptee;
8678 Qualifiers lhq, rhq;
8679 std::tie(lhptee, lhq) =
8680 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
8681 std::tie(rhptee, rhq) =
8682 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
8683
8684 Sema::AssignConvertType ConvTy = Sema::Compatible;
8685
8686 // C99 6.5.16.1p1: This following citation is common to constraints
8687 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
8688 // qualifiers of the type *pointed to* by the right;
8689
8690 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
8691 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
8692 lhq.compatiblyIncludesObjCLifetime(rhq)) {
8693 // Ignore lifetime for further calculation.
8694 lhq.removeObjCLifetime();
8695 rhq.removeObjCLifetime();
8696 }
8697
8698 if (!lhq.compatiblyIncludes(rhq)) {
8699 // Treat address-space mismatches as fatal.
8700 if (!lhq.isAddressSpaceSupersetOf(rhq))
8701 return Sema::IncompatiblePointerDiscardsQualifiers;
8702
8703 // It's okay to add or remove GC or lifetime qualifiers when converting to
8704 // and from void*.
8705 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
8706 .compatiblyIncludes(
8707 rhq.withoutObjCGCAttr().withoutObjCLifetime())
8708 && (lhptee->isVoidType() || rhptee->isVoidType()))
8709 ; // keep old
8710
8711 // Treat lifetime mismatches as fatal.
8712 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
8713 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
8714
8715 // For GCC/MS compatibility, other qualifier mismatches are treated
8716 // as still compatible in C.
8717 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8718 }
8719
8720 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
8721 // incomplete type and the other is a pointer to a qualified or unqualified
8722 // version of void...
8723 if (lhptee->isVoidType()) {
8724 if (rhptee->isIncompleteOrObjectType())
8725 return ConvTy;
8726
8727 // As an extension, we allow cast to/from void* to function pointer.
8728 assert(rhptee->isFunctionType())((rhptee->isFunctionType()) ? static_cast<void> (0) :
__assert_fail ("rhptee->isFunctionType()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 8728, __PRETTY_FUNCTION__))
;
8729 return Sema::FunctionVoidPointer;
8730 }
8731
8732 if (rhptee->isVoidType()) {
8733 if (lhptee->isIncompleteOrObjectType())
8734 return ConvTy;
8735
8736 // As an extension, we allow cast to/from void* to function pointer.
8737 assert(lhptee->isFunctionType())((lhptee->isFunctionType()) ? static_cast<void> (0) :
__assert_fail ("lhptee->isFunctionType()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 8737, __PRETTY_FUNCTION__))
;
8738 return Sema::FunctionVoidPointer;
8739 }
8740
8741 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
8742 // unqualified versions of compatible types, ...
8743 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
8744 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
8745 // Check if the pointee types are compatible ignoring the sign.
8746 // We explicitly check for char so that we catch "char" vs
8747 // "unsigned char" on systems where "char" is unsigned.
8748 if (lhptee->isCharType())
8749 ltrans = S.Context.UnsignedCharTy;
8750 else if (lhptee->hasSignedIntegerRepresentation())
8751 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
8752
8753 if (rhptee->isCharType())
8754 rtrans = S.Context.UnsignedCharTy;
8755 else if (rhptee->hasSignedIntegerRepresentation())
8756 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
8757
8758 if (ltrans == rtrans) {
8759 // Types are compatible ignoring the sign. Qualifier incompatibility
8760 // takes priority over sign incompatibility because the sign
8761 // warning can be disabled.
8762 if (ConvTy != Sema::Compatible)
8763 return ConvTy;
8764
8765 return Sema::IncompatiblePointerSign;
8766 }
8767
8768 // If we are a multi-level pointer, it's possible that our issue is simply
8769 // one of qualification - e.g. char ** -> const char ** is not allowed. If
8770 // the eventual target type is the same and the pointers have the same
8771 // level of indirection, this must be the issue.
8772 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
8773 do {
8774 std::tie(lhptee, lhq) =
8775 cast<PointerType>(lhptee)->getPointeeType().split().asPair();
8776 std::tie(rhptee, rhq) =
8777 cast<PointerType>(rhptee)->getPointeeType().split().asPair();
8778
8779 // Inconsistent address spaces at this point is invalid, even if the
8780 // address spaces would be compatible.
8781 // FIXME: This doesn't catch address space mismatches for pointers of
8782 // different nesting levels, like:
8783 // __local int *** a;
8784 // int ** b = a;
8785 // It's not clear how to actually determine when such pointers are
8786 // invalidly incompatible.
8787 if (lhq.getAddressSpace() != rhq.getAddressSpace())
8788 return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
8789
8790 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
8791
8792 if (lhptee == rhptee)
8793 return Sema::IncompatibleNestedPointerQualifiers;
8794 }
8795
8796 // General pointer incompatibility takes priority over qualifiers.
8797 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
8798 return Sema::IncompatibleFunctionPointer;
8799 return Sema::IncompatiblePointer;
8800 }
8801 if (!S.getLangOpts().CPlusPlus &&
8802 S.IsFunctionConversion(ltrans, rtrans, ltrans))
8803 return Sema::IncompatibleFunctionPointer;
8804 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
8805 return Sema::IncompatibleFunctionPointer;
8806 return ConvTy;
8807}
8808
8809/// checkBlockPointerTypesForAssignment - This routine determines whether two
8810/// block pointer types are compatible or whether a block and normal pointer
8811/// are compatible. It is more restrict than comparing two function pointer
8812// types.
8813static Sema::AssignConvertType
8814checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
8815 QualType RHSType) {
8816 assert(LHSType.isCanonical() && "LHS not canonicalized!")((LHSType.isCanonical() && "LHS not canonicalized!") ?
static_cast<void> (0) : __assert_fail ("LHSType.isCanonical() && \"LHS not canonicalized!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 8816, __PRETTY_FUNCTION__))
;
8817 assert(RHSType.isCanonical() && "RHS not canonicalized!")((RHSType.isCanonical() && "RHS not canonicalized!") ?
static_cast<void> (0) : __assert_fail ("RHSType.isCanonical() && \"RHS not canonicalized!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 8817, __PRETTY_FUNCTION__))
;
8818
8819 QualType lhptee, rhptee;
8820
8821 // get the "pointed to" type (ignoring qualifiers at the top level)
8822 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
8823 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
8824
8825 // In C++, the types have to match exactly.
8826 if (S.getLangOpts().CPlusPlus)
8827 return Sema::IncompatibleBlockPointer;
8828
8829 Sema::AssignConvertType ConvTy = Sema::Compatible;
8830
8831 // For blocks we enforce that qualifiers are identical.
8832 Qualifiers LQuals = lhptee.getLocalQualifiers();
8833 Qualifiers RQuals = rhptee.getLocalQualifiers();
8834 if (S.getLangOpts().OpenCL) {
8835 LQuals.removeAddressSpace();
8836 RQuals.removeAddressSpace();
8837 }
8838 if (LQuals != RQuals)
8839 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8840
8841 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
8842 // assignment.
8843 // The current behavior is similar to C++ lambdas. A block might be
8844 // assigned to a variable iff its return type and parameters are compatible
8845 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
8846 // an assignment. Presumably it should behave in way that a function pointer
8847 // assignment does in C, so for each parameter and return type:
8848 // * CVR and address space of LHS should be a superset of CVR and address
8849 // space of RHS.
8850 // * unqualified types should be compatible.
8851 if (S.getLangOpts().OpenCL) {
8852 if (!S.Context.typesAreBlockPointerCompatible(
8853 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
8854 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
8855 return Sema::IncompatibleBlockPointer;
8856 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
8857 return Sema::IncompatibleBlockPointer;
8858
8859 return ConvTy;
8860}
8861
8862/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
8863/// for assignment compatibility.
8864static Sema::AssignConvertType
8865checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
8866 QualType RHSType) {
8867 assert(LHSType.isCanonical() && "LHS was not canonicalized!")((LHSType.isCanonical() && "LHS was not canonicalized!"
) ? static_cast<void> (0) : __assert_fail ("LHSType.isCanonical() && \"LHS was not canonicalized!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 8867, __PRETTY_FUNCTION__))
;
8868 assert(RHSType.isCanonical() && "RHS was not canonicalized!")((RHSType.isCanonical() && "RHS was not canonicalized!"
) ? static_cast<void> (0) : __assert_fail ("RHSType.isCanonical() && \"RHS was not canonicalized!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 8868, __PRETTY_FUNCTION__))
;
8869
8870 if (LHSType->isObjCBuiltinType()) {
8871 // Class is not compatible with ObjC object pointers.
8872 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
8873 !RHSType->isObjCQualifiedClassType())
8874 return Sema::IncompatiblePointer;
8875 return Sema::Compatible;
8876 }
8877 if (RHSType->isObjCBuiltinType()) {
8878 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
8879 !LHSType->isObjCQualifiedClassType())
8880 return Sema::IncompatiblePointer;
8881 return Sema::Compatible;
8882 }
8883 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8884 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8885
8886 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
8887 // make an exception for id<P>
8888 !LHSType->isObjCQualifiedIdType())
8889 return Sema::CompatiblePointerDiscardsQualifiers;
8890
8891 if (S.Context.typesAreCompatible(LHSType, RHSType))
8892 return Sema::Compatible;
8893 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
8894 return Sema::IncompatibleObjCQualifiedId;
8895 return Sema::IncompatiblePointer;
8896}
8897
8898Sema::AssignConvertType
8899Sema::CheckAssignmentConstraints(SourceLocation Loc,
8900 QualType LHSType, QualType RHSType) {
8901 // Fake up an opaque expression. We don't actually care about what
8902 // cast operations are required, so if CheckAssignmentConstraints
8903 // adds casts to this they'll be wasted, but fortunately that doesn't
8904 // usually happen on valid code.
8905 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
8906 ExprResult RHSPtr = &RHSExpr;
8907 CastKind K;
8908
8909 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
8910}
8911
8912/// This helper function returns true if QT is a vector type that has element
8913/// type ElementType.
8914static bool isVector(QualType QT, QualType ElementType) {
8915 if (const VectorType *VT = QT->getAs<VectorType>())
8916 return VT->getElementType().getCanonicalType() == ElementType;
8917 return false;
8918}
8919
8920/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
8921/// has code to accommodate several GCC extensions when type checking
8922/// pointers. Here are some objectionable examples that GCC considers warnings:
8923///
8924/// int a, *pint;
8925/// short *pshort;
8926/// struct foo *pfoo;
8927///
8928/// pint = pshort; // warning: assignment from incompatible pointer type
8929/// a = pint; // warning: assignment makes integer from pointer without a cast
8930/// pint = a; // warning: assignment makes pointer from integer without a cast
8931/// pint = pfoo; // warning: assignment from incompatible pointer type
8932///
8933/// As a result, the code for dealing with pointers is more complex than the
8934/// C99 spec dictates.
8935///
8936/// Sets 'Kind' for any result kind except Incompatible.
8937Sema::AssignConvertType
8938Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
8939 CastKind &Kind, bool ConvertRHS) {
8940 QualType RHSType = RHS.get()->getType();
8941 QualType OrigLHSType = LHSType;
8942
8943 // Get canonical types. We're not formatting these types, just comparing
8944 // them.
8945 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
8946 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
8947
8948 // Common case: no conversion required.
8949 if (LHSType == RHSType) {
8950 Kind = CK_NoOp;
8951 return Compatible;
8952 }
8953
8954 // If we have an atomic type, try a non-atomic assignment, then just add an
8955 // atomic qualification step.
8956 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
8957 Sema::AssignConvertType result =
8958 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
8959 if (result != Compatible)
8960 return result;
8961 if (Kind != CK_NoOp && ConvertRHS)
8962 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
8963 Kind = CK_NonAtomicToAtomic;
8964 return Compatible;
8965 }
8966
8967 // If the left-hand side is a reference type, then we are in a
8968 // (rare!) case where we've allowed the use of references in C,
8969 // e.g., as a parameter type in a built-in function. In this case,
8970 // just make sure that the type referenced is compatible with the
8971 // right-hand side type. The caller is responsible for adjusting
8972 // LHSType so that the resulting expression does not have reference
8973 // type.
8974 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
8975 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
8976 Kind = CK_LValueBitCast;
8977 return Compatible;
8978 }
8979 return Incompatible;
8980 }
8981
8982 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
8983 // to the same ExtVector type.
8984 if (LHSType->isExtVectorType()) {
8985 if (RHSType->isExtVectorType())
8986 return Incompatible;
8987 if (RHSType->isArithmeticType()) {
8988 // CK_VectorSplat does T -> vector T, so first cast to the element type.
8989 if (ConvertRHS)
8990 RHS = prepareVectorSplat(LHSType, RHS.get());
8991 Kind = CK_VectorSplat;
8992 return Compatible;
8993 }
8994 }
8995
8996 // Conversions to or from vector type.
8997 if (LHSType->isVectorType() || RHSType->isVectorType()) {
8998 if (LHSType->isVectorType() && RHSType->isVectorType()) {
8999 // Allow assignments of an AltiVec vector type to an equivalent GCC
9000 // vector type and vice versa
9001 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9002 Kind = CK_BitCast;
9003 return Compatible;
9004 }
9005
9006 // If we are allowing lax vector conversions, and LHS and RHS are both
9007 // vectors, the total size only needs to be the same. This is a bitcast;
9008 // no bits are changed but the result type is different.
9009 if (isLaxVectorConversion(RHSType, LHSType)) {
9010 Kind = CK_BitCast;
9011 return IncompatibleVectors;
9012 }
9013 }
9014
9015 // When the RHS comes from another lax conversion (e.g. binops between
9016 // scalars and vectors) the result is canonicalized as a vector. When the
9017 // LHS is also a vector, the lax is allowed by the condition above. Handle
9018 // the case where LHS is a scalar.
9019 if (LHSType->isScalarType()) {
9020 const VectorType *VecType = RHSType->getAs<VectorType>();
9021 if (VecType && VecType->getNumElements() == 1 &&
9022 isLaxVectorConversion(RHSType, LHSType)) {
9023 ExprResult *VecExpr = &RHS;
9024 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9025 Kind = CK_BitCast;
9026 return Compatible;
9027 }
9028 }
9029
9030 // Allow assignments between fixed-length and sizeless SVE vectors.
9031 if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) ||
9032 (LHSType->isVectorType() && RHSType->isSizelessBuiltinType()))
9033 if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
9034 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
9035 Kind = CK_BitCast;
9036 return Compatible;
9037 }
9038
9039 return Incompatible;
9040 }
9041
9042 // Diagnose attempts to convert between __float128 and long double where
9043 // such conversions currently can't be handled.
9044 if (unsupportedTypeConversion(*this, LHSType, RHSType))
9045 return Incompatible;
9046
9047 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9048 // discards the imaginary part.
9049 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9050 !LHSType->getAs<ComplexType>())
9051 return Incompatible;
9052
9053 // Arithmetic conversions.
9054 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9055 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9056 if (ConvertRHS)
9057 Kind = PrepareScalarCast(RHS, LHSType);
9058 return Compatible;
9059 }
9060
9061 // Conversions to normal pointers.
9062 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9063 // U* -> T*
9064 if (isa<PointerType>(RHSType)) {
9065 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9066 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9067 if (AddrSpaceL != AddrSpaceR)
9068 Kind = CK_AddressSpaceConversion;
9069 else if (Context.hasCvrSimilarType(RHSType, LHSType))
9070 Kind = CK_NoOp;
9071 else
9072 Kind = CK_BitCast;
9073 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
9074 }
9075
9076 // int -> T*
9077 if (RHSType->isIntegerType()) {
9078 Kind = CK_IntegralToPointer; // FIXME: null?
9079 return IntToPointer;
9080 }
9081
9082 // C pointers are not compatible with ObjC object pointers,
9083 // with two exceptions:
9084 if (isa<ObjCObjectPointerType>(RHSType)) {
9085 // - conversions to void*
9086 if (LHSPointer->getPointeeType()->isVoidType()) {
9087 Kind = CK_BitCast;
9088 return Compatible;
9089 }
9090
9091 // - conversions from 'Class' to the redefinition type
9092 if (RHSType->isObjCClassType() &&
9093 Context.hasSameType(LHSType,
9094 Context.getObjCClassRedefinitionType())) {
9095 Kind = CK_BitCast;
9096 return Compatible;
9097 }
9098
9099 Kind = CK_BitCast;
9100 return IncompatiblePointer;
9101 }
9102
9103 // U^ -> void*
9104 if (RHSType->getAs<BlockPointerType>()) {
9105 if (LHSPointer->getPointeeType()->isVoidType()) {
9106 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9107 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9108 ->getPointeeType()
9109 .getAddressSpace();
9110 Kind =
9111 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9112 return Compatible;
9113 }
9114 }
9115
9116 return Incompatible;
9117 }
9118
9119 // Conversions to block pointers.
9120 if (isa<BlockPointerType>(LHSType)) {
9121 // U^ -> T^
9122 if (RHSType->isBlockPointerType()) {
9123 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9124 ->getPointeeType()
9125 .getAddressSpace();
9126 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9127 ->getPointeeType()
9128 .getAddressSpace();
9129 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9130 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9131 }
9132
9133 // int or null -> T^
9134 if (RHSType->isIntegerType()) {
9135 Kind = CK_IntegralToPointer; // FIXME: null
9136 return IntToBlockPointer;
9137 }
9138
9139 // id -> T^
9140 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9141 Kind = CK_AnyPointerToBlockPointerCast;
9142 return Compatible;
9143 }
9144
9145 // void* -> T^
9146 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9147 if (RHSPT->getPointeeType()->isVoidType()) {
9148 Kind = CK_AnyPointerToBlockPointerCast;
9149 return Compatible;
9150 }
9151
9152 return Incompatible;
9153 }
9154
9155 // Conversions to Objective-C pointers.
9156 if (isa<ObjCObjectPointerType>(LHSType)) {
9157 // A* -> B*
9158 if (RHSType->isObjCObjectPointerType()) {
9159 Kind = CK_BitCast;
9160 Sema::AssignConvertType result =
9161 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9162 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9163 result == Compatible &&
9164 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9165 result = IncompatibleObjCWeakRef;
9166 return result;
9167 }
9168
9169 // int or null -> A*
9170 if (RHSType->isIntegerType()) {
9171 Kind = CK_IntegralToPointer; // FIXME: null
9172 return IntToPointer;
9173 }
9174
9175 // In general, C pointers are not compatible with ObjC object pointers,
9176 // with two exceptions:
9177 if (isa<PointerType>(RHSType)) {
9178 Kind = CK_CPointerToObjCPointerCast;
9179
9180 // - conversions from 'void*'
9181 if (RHSType->isVoidPointerType()) {
9182 return Compatible;
9183 }
9184
9185 // - conversions to 'Class' from its redefinition type
9186 if (LHSType->isObjCClassType() &&
9187 Context.hasSameType(RHSType,
9188 Context.getObjCClassRedefinitionType())) {
9189 return Compatible;
9190 }
9191
9192 return IncompatiblePointer;
9193 }
9194
9195 // Only under strict condition T^ is compatible with an Objective-C pointer.
9196 if (RHSType->isBlockPointerType() &&
9197 LHSType->isBlockCompatibleObjCPointerType(Context)) {
9198 if (ConvertRHS)
9199 maybeExtendBlockObject(RHS);
9200 Kind = CK_BlockPointerToObjCPointerCast;
9201 return Compatible;
9202 }
9203
9204 return Incompatible;
9205 }
9206
9207 // Conversions from pointers that are not covered by the above.
9208 if (isa<PointerType>(RHSType)) {
9209 // T* -> _Bool
9210 if (LHSType == Context.BoolTy) {
9211 Kind = CK_PointerToBoolean;
9212 return Compatible;
9213 }
9214
9215 // T* -> int
9216 if (LHSType->isIntegerType()) {
9217 Kind = CK_PointerToIntegral;
9218 return PointerToInt;
9219 }
9220
9221 return Incompatible;
9222 }
9223
9224 // Conversions from Objective-C pointers that are not covered by the above.
9225 if (isa<ObjCObjectPointerType>(RHSType)) {
9226 // T* -> _Bool
9227 if (LHSType == Context.BoolTy) {
9228 Kind = CK_PointerToBoolean;
9229 return Compatible;
9230 }
9231
9232 // T* -> int
9233 if (LHSType->isIntegerType()) {
9234 Kind = CK_PointerToIntegral;
9235 return PointerToInt;
9236 }
9237
9238 return Incompatible;
9239 }
9240
9241 // struct A -> struct B
9242 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9243 if (Context.typesAreCompatible(LHSType, RHSType)) {
9244 Kind = CK_NoOp;
9245 return Compatible;
9246 }
9247 }
9248
9249 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9250 Kind = CK_IntToOCLSampler;
9251 return Compatible;
9252 }
9253
9254 return Incompatible;
9255}
9256
9257/// Constructs a transparent union from an expression that is
9258/// used to initialize the transparent union.
9259static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9260 ExprResult &EResult, QualType UnionType,
9261 FieldDecl *Field) {
9262 // Build an initializer list that designates the appropriate member
9263 // of the transparent union.
9264 Expr *E = EResult.get();
9265 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9266 E, SourceLocation());
9267 Initializer->setType(UnionType);
9268 Initializer->setInitializedFieldInUnion(Field);
9269
9270 // Build a compound literal constructing a value of the transparent
9271 // union type from this initializer list.
9272 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9273 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9274 VK_RValue, Initializer, false);
9275}
9276
9277Sema::AssignConvertType
9278Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
9279 ExprResult &RHS) {
9280 QualType RHSType = RHS.get()->getType();
9281
9282 // If the ArgType is a Union type, we want to handle a potential
9283 // transparent_union GCC extension.
9284 const RecordType *UT = ArgType->getAsUnionType();
9285 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9286 return Incompatible;
9287
9288 // The field to initialize within the transparent union.
9289 RecordDecl *UD = UT->getDecl();
9290 FieldDecl *InitField = nullptr;
9291 // It's compatible if the expression matches any of the fields.
9292 for (auto *it : UD->fields()) {
9293 if (it->getType()->isPointerType()) {
9294 // If the transparent union contains a pointer type, we allow:
9295 // 1) void pointer
9296 // 2) null pointer constant
9297 if (RHSType->isPointerType())
9298 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9299 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9300 InitField = it;
9301 break;
9302 }
9303
9304 if (RHS.get()->isNullPointerConstant(Context,
9305 Expr::NPC_ValueDependentIsNull)) {
9306 RHS = ImpCastExprToType(RHS.get(), it->getType(),
9307 CK_NullToPointer);
9308 InitField = it;
9309 break;
9310 }
9311 }
9312
9313 CastKind Kind;
9314 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9315 == Compatible) {
9316 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9317 InitField = it;
9318 break;
9319 }
9320 }
9321
9322 if (!InitField)
9323 return Incompatible;
9324
9325 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9326 return Compatible;
9327}
9328
9329Sema::AssignConvertType
9330Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
9331 bool Diagnose,
9332 bool DiagnoseCFAudited,
9333 bool ConvertRHS) {
9334 // We need to be able to tell the caller whether we diagnosed a problem, if
9335 // they ask us to issue diagnostics.
9336 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed")(((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"
) ? static_cast<void> (0) : __assert_fail ("(ConvertRHS || !Diagnose) && \"can't indicate whether we diagnosed\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 9336, __PRETTY_FUNCTION__))
;
9337
9338 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9339 // we can't avoid *all* modifications at the moment, so we need some somewhere
9340 // to put the updated value.
9341 ExprResult LocalRHS = CallerRHS;
9342 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9343
9344 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9345 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9346 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9347 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9348 Diag(RHS.get()->getExprLoc(),
9349 diag::warn_noderef_to_dereferenceable_pointer)
9350 << RHS.get()->getSourceRange();
9351 }
9352 }
9353 }
9354
9355 if (getLangOpts().CPlusPlus) {
9356 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9357 // C++ 5.17p3: If the left operand is not of class type, the
9358 // expression is implicitly converted (C++ 4) to the
9359 // cv-unqualified type of the left operand.
9360 QualType RHSType = RHS.get()->getType();
9361 if (Diagnose) {
9362 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9363 AA_Assigning);
9364 } else {
9365 ImplicitConversionSequence ICS =
9366 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9367 /*SuppressUserConversions=*/false,
9368 AllowedExplicit::None,
9369 /*InOverloadResolution=*/false,
9370 /*CStyle=*/false,
9371 /*AllowObjCWritebackConversion=*/false);
9372 if (ICS.isFailure())
9373 return Incompatible;
9374 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9375 ICS, AA_Assigning);
9376 }
9377 if (RHS.isInvalid())
9378 return Incompatible;
9379 Sema::AssignConvertType result = Compatible;
9380 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9381 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9382 result = IncompatibleObjCWeakRef;
9383 return result;
9384 }
9385
9386 // FIXME: Currently, we fall through and treat C++ classes like C
9387 // structures.
9388 // FIXME: We also fall through for atomics; not sure what should
9389 // happen there, though.
9390 } else if (RHS.get()->getType() == Context.OverloadTy) {
9391 // As a set of extensions to C, we support overloading on functions. These
9392 // functions need to be resolved here.
9393 DeclAccessPair DAP;
9394 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9395 RHS.get(), LHSType, /*Complain=*/false, DAP))
9396 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9397 else
9398 return Incompatible;
9399 }
9400
9401 // C99 6.5.16.1p1: the left operand is a pointer and the right is
9402 // a null pointer constant.
9403 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
9404 LHSType->isBlockPointerType()) &&
9405 RHS.get()->isNullPointerConstant(Context,
9406 Expr::NPC_ValueDependentIsNull)) {
9407 if (Diagnose || ConvertRHS) {
9408 CastKind Kind;
9409 CXXCastPath Path;
9410 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9411 /*IgnoreBaseAccess=*/false, Diagnose);
9412 if (ConvertRHS)
9413 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
9414 }
9415 return Compatible;
9416 }
9417
9418 // OpenCL queue_t type assignment.
9419 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9420 Context, Expr::NPC_ValueDependentIsNull)) {
9421 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9422 return Compatible;
9423 }
9424
9425 // This check seems unnatural, however it is necessary to ensure the proper
9426 // conversion of functions/arrays. If the conversion were done for all
9427 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9428 // expressions that suppress this implicit conversion (&, sizeof).
9429 //
9430 // Suppress this for references: C++ 8.5.3p5.
9431 if (!LHSType->isReferenceType()) {
9432 // FIXME: We potentially allocate here even if ConvertRHS is false.
9433 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
9434 if (RHS.isInvalid())
9435 return Incompatible;
9436 }
9437 CastKind Kind;
9438 Sema::AssignConvertType result =
9439 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9440
9441 // C99 6.5.16.1p2: The value of the right operand is converted to the
9442 // type of the assignment expression.
9443 // CheckAssignmentConstraints allows the left-hand side to be a reference,
9444 // so that we can use references in built-in functions even in C.
9445 // The getNonReferenceType() call makes sure that the resulting expression
9446 // does not have reference type.
9447 if (result != Incompatible && RHS.get()->getType() != LHSType) {
9448 QualType Ty = LHSType.getNonLValueExprType(Context);
9449 Expr *E = RHS.get();
9450
9451 // Check for various Objective-C errors. If we are not reporting
9452 // diagnostics and just checking for errors, e.g., during overload
9453 // resolution, return Incompatible to indicate the failure.
9454 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9455 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
9456 Diagnose, DiagnoseCFAudited) != ACR_okay) {
9457 if (!Diagnose)
9458 return Incompatible;
9459 }
9460 if (getLangOpts().ObjC &&
9461 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9462 E->getType(), E, Diagnose) ||
9463 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9464 if (!Diagnose)
9465 return Incompatible;
9466 // Replace the expression with a corrected version and continue so we
9467 // can find further errors.
9468 RHS = E;
9469 return Compatible;
9470 }
9471
9472 if (ConvertRHS)
9473 RHS = ImpCastExprToType(E, Ty, Kind);
9474 }
9475
9476 return result;
9477}
9478
9479namespace {
9480/// The original operand to an operator, prior to the application of the usual
9481/// arithmetic conversions and converting the arguments of a builtin operator
9482/// candidate.
9483struct OriginalOperand {
9484 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9485 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9486 Op = MTE->getSubExpr();
9487 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9488 Op = BTE->getSubExpr();
9489 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9490 Orig = ICE->getSubExprAsWritten();
9491 Conversion = ICE->getConversionFunction();
9492 }
9493 }
9494
9495 QualType getType() const { return Orig->getType(); }
9496
9497 Expr *Orig;
9498 NamedDecl *Conversion;
9499};
9500}
9501
9502QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9503 ExprResult &RHS) {
9504 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9505
9506 Diag(Loc, diag::err_typecheck_invalid_operands)
9507 << OrigLHS.getType() << OrigRHS.getType()
9508 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9509
9510 // If a user-defined conversion was applied to either of the operands prior
9511 // to applying the built-in operator rules, tell the user about it.
9512 if (OrigLHS.Conversion) {
9513 Diag(OrigLHS.Conversion->getLocation(),
9514 diag::note_typecheck_invalid_operands_converted)
9515 << 0 << LHS.get()->getType();
9516 }
9517 if (OrigRHS.Conversion) {
9518 Diag(OrigRHS.Conversion->getLocation(),
9519 diag::note_typecheck_invalid_operands_converted)
9520 << 1 << RHS.get()->getType();
9521 }
9522
9523 return QualType();
9524}
9525
9526// Diagnose cases where a scalar was implicitly converted to a vector and
9527// diagnose the underlying types. Otherwise, diagnose the error
9528// as invalid vector logical operands for non-C++ cases.
9529QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9530 ExprResult &RHS) {
9531 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9532 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9533
9534 bool LHSNatVec = LHSType->isVectorType();
9535 bool RHSNatVec = RHSType->isVectorType();
9536
9537 if (!(LHSNatVec && RHSNatVec)) {
9538 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
9539 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
9540 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9541 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
9542 << Vector->getSourceRange();
9543 return QualType();
9544 }
9545
9546 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9547 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
9548 << RHS.get()->getSourceRange();
9549
9550 return QualType();
9551}
9552
9553/// Try to convert a value of non-vector type to a vector type by converting
9554/// the type to the element type of the vector and then performing a splat.
9555/// If the language is OpenCL, we only use conversions that promote scalar
9556/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
9557/// for float->int.
9558///
9559/// OpenCL V2.0 6.2.6.p2:
9560/// An error shall occur if any scalar operand type has greater rank
9561/// than the type of the vector element.
9562///
9563/// \param scalar - if non-null, actually perform the conversions
9564/// \return true if the operation fails (but without diagnosing the failure)
9565static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
9566 QualType scalarTy,
9567 QualType vectorEltTy,
9568 QualType vectorTy,
9569 unsigned &DiagID) {
9570 // The conversion to apply to the scalar before splatting it,
9571 // if necessary.
9572 CastKind scalarCast = CK_NoOp;
9573
9574 if (vectorEltTy->isIntegralType(S.Context)) {
9575 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
9576 (scalarTy->isIntegerType() &&
9577 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
9578 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9579 return true;
9580 }
9581 if (!scalarTy->isIntegralType(S.Context))
9582 return true;
9583 scalarCast = CK_IntegralCast;
9584 } else if (vectorEltTy->isRealFloatingType()) {
9585 if (scalarTy->isRealFloatingType()) {
9586 if (S.getLangOpts().OpenCL &&
9587 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
9588 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9589 return true;
9590 }
9591 scalarCast = CK_FloatingCast;
9592 }
9593 else if (scalarTy->isIntegralType(S.Context))
9594 scalarCast = CK_IntegralToFloating;
9595 else
9596 return true;
9597 } else {
9598 return true;
9599 }
9600
9601 // Adjust scalar if desired.
9602 if (scalar) {
9603 if (scalarCast != CK_NoOp)
9604 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
9605 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
9606 }
9607 return false;
9608}
9609
9610/// Convert vector E to a vector with the same number of elements but different
9611/// element type.
9612static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
9613 const auto *VecTy = E->getType()->getAs<VectorType>();
9614 assert(VecTy && "Expression E must be a vector")((VecTy && "Expression E must be a vector") ? static_cast
<void> (0) : __assert_fail ("VecTy && \"Expression E must be a vector\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 9614, __PRETTY_FUNCTION__))
;
9615 QualType NewVecTy = S.Context.getVectorType(ElementType,
9616 VecTy->getNumElements(),
9617 VecTy->getVectorKind());
9618
9619 // Look through the implicit cast. Return the subexpression if its type is
9620 // NewVecTy.
9621 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9622 if (ICE->getSubExpr()->getType() == NewVecTy)
9623 return ICE->getSubExpr();
9624
9625 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
9626 return S.ImpCastExprToType(E, NewVecTy, Cast);
9627}
9628
9629/// Test if a (constant) integer Int can be casted to another integer type
9630/// IntTy without losing precision.
9631static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
9632 QualType OtherIntTy) {
9633 QualType IntTy = Int->get()->getType().getUnqualifiedType();
9634
9635 // Reject cases where the value of the Int is unknown as that would
9636 // possibly cause truncation, but accept cases where the scalar can be
9637 // demoted without loss of precision.
9638 Expr::EvalResult EVResult;
9639 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9640 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
9641 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
9642 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
9643
9644 if (CstInt) {
9645 // If the scalar is constant and is of a higher order and has more active
9646 // bits that the vector element type, reject it.
9647 llvm::APSInt Result = EVResult.Val.getInt();
9648 unsigned NumBits = IntSigned
9649 ? (Result.isNegative() ? Result.getMinSignedBits()
9650 : Result.getActiveBits())
9651 : Result.getActiveBits();
9652 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
9653 return true;
9654
9655 // If the signedness of the scalar type and the vector element type
9656 // differs and the number of bits is greater than that of the vector
9657 // element reject it.
9658 return (IntSigned != OtherIntSigned &&
9659 NumBits > S.Context.getIntWidth(OtherIntTy));
9660 }
9661
9662 // Reject cases where the value of the scalar is not constant and it's
9663 // order is greater than that of the vector element type.
9664 return (Order < 0);
9665}
9666
9667/// Test if a (constant) integer Int can be casted to floating point type
9668/// FloatTy without losing precision.
9669static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
9670 QualType FloatTy) {
9671 QualType IntTy = Int->get()->getType().getUnqualifiedType();
9672
9673 // Determine if the integer constant can be expressed as a floating point
9674 // number of the appropriate type.
9675 Expr::EvalResult EVResult;
9676 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9677
9678 uint64_t Bits = 0;
9679 if (CstInt) {
9680 // Reject constants that would be truncated if they were converted to
9681 // the floating point type. Test by simple to/from conversion.
9682 // FIXME: Ideally the conversion to an APFloat and from an APFloat
9683 // could be avoided if there was a convertFromAPInt method
9684 // which could signal back if implicit truncation occurred.
9685 llvm::APSInt Result = EVResult.Val.getInt();
9686 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
9687 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
9688 llvm::APFloat::rmTowardZero);
9689 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
9690 !IntTy->hasSignedIntegerRepresentation());
9691 bool Ignored = false;
9692 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
9693 &Ignored);
9694 if (Result != ConvertBack)
9695 return true;
9696 } else {
9697 // Reject types that cannot be fully encoded into the mantissa of
9698 // the float.
9699 Bits = S.Context.getTypeSize(IntTy);
9700 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
9701 S.Context.getFloatTypeSemantics(FloatTy));
9702 if (Bits > FloatPrec)
9703 return true;
9704 }
9705
9706 return false;
9707}
9708
9709/// Attempt to convert and splat Scalar into a vector whose types matches
9710/// Vector following GCC conversion rules. The rule is that implicit
9711/// conversion can occur when Scalar can be casted to match Vector's element
9712/// type without causing truncation of Scalar.
9713static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
9714 ExprResult *Vector) {
9715 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
9716 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
9717 const VectorType *VT = VectorTy->getAs<VectorType>();
9718
9719 assert(!isa<ExtVectorType>(VT) &&((!isa<ExtVectorType>(VT) && "ExtVectorTypes should not be handled here!"
) ? static_cast<void> (0) : __assert_fail ("!isa<ExtVectorType>(VT) && \"ExtVectorTypes should not be handled here!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 9720, __PRETTY_FUNCTION__))
9720 "ExtVectorTypes should not be handled here!")((!isa<ExtVectorType>(VT) && "ExtVectorTypes should not be handled here!"
) ? static_cast<void> (0) : __assert_fail ("!isa<ExtVectorType>(VT) && \"ExtVectorTypes should not be handled here!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 9720, __PRETTY_FUNCTION__))
;
9721
9722 QualType VectorEltTy = VT->getElementType();
9723
9724 // Reject cases where the vector element type or the scalar element type are
9725 // not integral or floating point types.
9726 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
9727 return true;
9728
9729 // The conversion to apply to the scalar before splatting it,
9730 // if necessary.
9731 CastKind ScalarCast = CK_NoOp;
9732
9733 // Accept cases where the vector elements are integers and the scalar is
9734 // an integer.
9735 // FIXME: Notionally if the scalar was a floating point value with a precise
9736 // integral representation, we could cast it to an appropriate integer
9737 // type and then perform the rest of the checks here. GCC will perform
9738 // this conversion in some cases as determined by the input language.
9739 // We should accept it on a language independent basis.
9740 if (VectorEltTy->isIntegralType(S.Context) &&
9741 ScalarTy->isIntegralType(S.Context) &&
9742 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
9743
9744 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
9745 return true;
9746
9747 ScalarCast = CK_IntegralCast;
9748 } else if (VectorEltTy->isIntegralType(S.Context) &&
9749 ScalarTy->isRealFloatingType()) {
9750 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
9751 ScalarCast = CK_FloatingToIntegral;
9752 else
9753 return true;
9754 } else if (VectorEltTy->isRealFloatingType()) {
9755 if (ScalarTy->isRealFloatingType()) {
9756
9757 // Reject cases where the scalar type is not a constant and has a higher
9758 // Order than the vector element type.
9759 llvm::APFloat Result(0.0);
9760
9761 // Determine whether this is a constant scalar. In the event that the
9762 // value is dependent (and thus cannot be evaluated by the constant
9763 // evaluator), skip the evaluation. This will then diagnose once the
9764 // expression is instantiated.
9765 bool CstScalar = Scalar->get()->isValueDependent() ||
9766 Scalar->get()->EvaluateAsFloat(Result, S.Context);
9767 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
9768 if (!CstScalar && Order < 0)
9769 return true;
9770
9771 // If the scalar cannot be safely casted to the vector element type,
9772 // reject it.
9773 if (CstScalar) {
9774 bool Truncated = false;
9775 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
9776 llvm::APFloat::rmNearestTiesToEven, &Truncated);
9777 if (Truncated)
9778 return true;
9779 }
9780
9781 ScalarCast = CK_FloatingCast;
9782 } else if (ScalarTy->isIntegralType(S.Context)) {
9783 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
9784 return true;
9785
9786 ScalarCast = CK_IntegralToFloating;
9787 } else
9788 return true;
9789 } else if (ScalarTy->isEnumeralType())
9790 return true;
9791
9792 // Adjust scalar if desired.
9793 if (Scalar) {
9794 if (ScalarCast != CK_NoOp)
9795 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
9796 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
9797 }
9798 return false;
9799}
9800
9801QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9802 SourceLocation Loc, bool IsCompAssign,
9803 bool AllowBothBool,
9804 bool AllowBoolConversions) {
9805 if (!IsCompAssign) {
9806 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
9807 if (LHS.isInvalid())
9808 return QualType();
9809 }
9810 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
9811 if (RHS.isInvalid())
9812 return QualType();
9813
9814 // For conversion purposes, we ignore any qualifiers.
9815 // For example, "const float" and "float" are equivalent.
9816 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
9817 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
9818
9819 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
9820 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
9821 assert(LHSVecType || RHSVecType)((LHSVecType || RHSVecType) ? static_cast<void> (0) : __assert_fail
("LHSVecType || RHSVecType", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 9821, __PRETTY_FUNCTION__))
;
9822
9823 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) ||
9824 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type()))
9825 return InvalidOperands(Loc, LHS, RHS);
9826
9827 // AltiVec-style "vector bool op vector bool" combinations are allowed
9828 // for some operators but not others.
9829 if (!AllowBothBool &&
9830 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9831 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9832 return InvalidOperands(Loc, LHS, RHS);
9833
9834 // If the vector types are identical, return.
9835 if (Context.hasSameType(LHSType, RHSType))
9836 return LHSType;
9837
9838 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
9839 if (LHSVecType && RHSVecType &&
9840 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9841 if (isa<ExtVectorType>(LHSVecType)) {
9842 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9843 return LHSType;
9844 }
9845
9846 if (!IsCompAssign)
9847 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9848 return RHSType;
9849 }
9850
9851 // AllowBoolConversions says that bool and non-bool AltiVec vectors
9852 // can be mixed, with the result being the non-bool type. The non-bool
9853 // operand must have integer element type.
9854 if (AllowBoolConversions && LHSVecType && RHSVecType &&
9855 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
9856 (Context.getTypeSize(LHSVecType->getElementType()) ==
9857 Context.getTypeSize(RHSVecType->getElementType()))) {
9858 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9859 LHSVecType->getElementType()->isIntegerType() &&
9860 RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
9861 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9862 return LHSType;
9863 }
9864 if (!IsCompAssign &&
9865 LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9866 RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9867 RHSVecType->getElementType()->isIntegerType()) {
9868 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9869 return RHSType;
9870 }
9871 }
9872
9873 // Expressions containing fixed-length and sizeless SVE vectors are invalid
9874 // since the ambiguity can affect the ABI.
9875 auto IsSveConversion = [](QualType FirstType, QualType SecondType) {
9876 const VectorType *VecType = SecondType->getAs<VectorType>();
9877 return FirstType->isSizelessBuiltinType() && VecType &&
9878 (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector ||
9879 VecType->getVectorKind() ==
9880 VectorType::SveFixedLengthPredicateVector);
9881 };
9882
9883 if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) {
9884 Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType;
9885 return QualType();
9886 }
9887
9888 // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid
9889 // since the ambiguity can affect the ABI.
9890 auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) {
9891 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
9892 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
9893
9894 if (FirstVecType && SecondVecType)
9895 return FirstVecType->getVectorKind() == VectorType::GenericVector &&
9896 (SecondVecType->getVectorKind() ==
9897 VectorType::SveFixedLengthDataVector ||
9898 SecondVecType->getVectorKind() ==
9899 VectorType::SveFixedLengthPredicateVector);
9900
9901 return FirstType->isSizelessBuiltinType() && SecondVecType &&
9902 SecondVecType->getVectorKind() == VectorType::GenericVector;
9903 };
9904
9905 if (IsSveGnuConversion(LHSType, RHSType) ||
9906 IsSveGnuConversion(RHSType, LHSType)) {
9907 Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType;
9908 return QualType();
9909 }
9910
9911 // If there's a vector type and a scalar, try to convert the scalar to
9912 // the vector element type and splat.
9913 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
9914 if (!RHSVecType) {
9915 if (isa<ExtVectorType>(LHSVecType)) {
9916 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
9917 LHSVecType->getElementType(), LHSType,
9918 DiagID))
9919 return LHSType;
9920 } else {
9921 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
9922 return LHSType;
9923 }
9924 }
9925 if (!LHSVecType) {
9926 if (isa<ExtVectorType>(RHSVecType)) {
9927 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
9928 LHSType, RHSVecType->getElementType(),
9929 RHSType, DiagID))
9930 return RHSType;
9931 } else {
9932 if (LHS.get()->getValueKind() == VK_LValue ||
9933 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
9934 return RHSType;
9935 }
9936 }
9937
9938 // FIXME: The code below also handles conversion between vectors and
9939 // non-scalars, we should break this down into fine grained specific checks
9940 // and emit proper diagnostics.
9941 QualType VecType = LHSVecType ? LHSType : RHSType;
9942 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
9943 QualType OtherType = LHSVecType ? RHSType : LHSType;
9944 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
9945 if (isLaxVectorConversion(OtherType, VecType)) {
9946 // If we're allowing lax vector conversions, only the total (data) size
9947 // needs to be the same. For non compound assignment, if one of the types is
9948 // scalar, the result is always the vector type.
9949 if (!IsCompAssign) {
9950 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
9951 return VecType;
9952 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
9953 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
9954 // type. Note that this is already done by non-compound assignments in
9955 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
9956 // <1 x T> -> T. The result is also a vector type.
9957 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
9958 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
9959 ExprResult *RHSExpr = &RHS;
9960 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
9961 return VecType;
9962 }
9963 }
9964
9965 // Okay, the expression is invalid.
9966
9967 // If there's a non-vector, non-real operand, diagnose that.
9968 if ((!RHSVecType && !RHSType->isRealType()) ||
9969 (!LHSVecType && !LHSType->isRealType())) {
9970 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
9971 << LHSType << RHSType
9972 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9973 return QualType();
9974 }
9975
9976 // OpenCL V1.1 6.2.6.p1:
9977 // If the operands are of more than one vector type, then an error shall
9978 // occur. Implicit conversions between vector types are not permitted, per
9979 // section 6.2.1.
9980 if (getLangOpts().OpenCL &&
9981 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
9982 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
9983 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
9984 << RHSType;
9985 return QualType();
9986 }
9987
9988
9989 // If there is a vector type that is not a ExtVector and a scalar, we reach
9990 // this point if scalar could not be converted to the vector's element type
9991 // without truncation.
9992 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
9993 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
9994 QualType Scalar = LHSVecType ? RHSType : LHSType;
9995 QualType Vector = LHSVecType ? LHSType : RHSType;
9996 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
9997 Diag(Loc,
9998 diag::err_typecheck_vector_not_convertable_implict_truncation)
9999 << ScalarOrVector << Scalar << Vector;
10000
10001 return QualType();
10002 }
10003
10004 // Otherwise, use the generic diagnostic.
10005 Diag(Loc, DiagID)
10006 << LHSType << RHSType
10007 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10008 return QualType();
10009}
10010
10011// checkArithmeticNull - Detect when a NULL constant is used improperly in an
10012// expression. These are mainly cases where the null pointer is used as an
10013// integer instead of a pointer.
10014static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
10015 SourceLocation Loc, bool IsCompare) {
10016 // The canonical way to check for a GNU null is with isNullPointerConstant,
10017 // but we use a bit of a hack here for speed; this is a relatively
10018 // hot path, and isNullPointerConstant is slow.
10019 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10020 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10021
10022 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10023
10024 // Avoid analyzing cases where the result will either be invalid (and
10025 // diagnosed as such) or entirely valid and not something to warn about.
10026 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10027 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10028 return;
10029
10030 // Comparison operations would not make sense with a null pointer no matter
10031 // what the other expression is.
10032 if (!IsCompare) {
10033 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10034 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10035 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10036 return;
10037 }
10038
10039 // The rest of the operations only make sense with a null pointer
10040 // if the other expression is a pointer.
10041 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10042 NonNullType->canDecayToPointerType())
10043 return;
10044
10045 S.Diag(Loc, diag::warn_null_in_comparison_operation)
10046 << LHSNull /* LHS is NULL */ << NonNullType
10047 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10048}
10049
10050static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
10051 SourceLocation Loc) {
10052 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10053 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10054 if (!LUE || !RUE)
10055 return;
10056 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10057 RUE->getKind() != UETT_SizeOf)
10058 return;
10059
10060 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10061 QualType LHSTy = LHSArg->getType();
10062 QualType RHSTy;
10063
10064 if (RUE->isArgumentType())
10065 RHSTy = RUE->getArgumentType().getNonReferenceType();
10066 else
10067 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10068
10069 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10070 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10071 return;
10072
10073 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10074 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10075 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10076 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10077 << LHSArgDecl;
10078 }
10079 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10080 QualType ArrayElemTy = ArrayTy->getElementType();
10081 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10082 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10083 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10084 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10085 return;
10086 S.Diag(Loc, diag::warn_division_sizeof_array)
10087 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10088 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10089 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10090 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10091 << LHSArgDecl;
10092 }
10093
10094 S.Diag(Loc, diag::note_precedence_silence) << RHS;
10095 }
10096}
10097
10098static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
10099 ExprResult &RHS,
10100 SourceLocation Loc, bool IsDiv) {
10101 // Check for division/remainder by zero.
10102 Expr::EvalResult RHSValue;
10103 if (!RHS.get()->isValueDependent() &&
10104 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10105 RHSValue.Val.getInt() == 0)
10106 S.DiagRuntimeBehavior(Loc, RHS.get(),
10107 S.PDiag(diag::warn_remainder_division_by_zero)
10108 << IsDiv << RHS.get()->getSourceRange());
10109}
10110
10111QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
10112 SourceLocation Loc,
10113 bool IsCompAssign, bool IsDiv) {
10114 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10115
10116 if (LHS.get()->getType()->isVectorType() ||
10117 RHS.get()->getType()->isVectorType())
10118 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10119 /*AllowBothBool*/getLangOpts().AltiVec,
10120 /*AllowBoolConversions*/false);
10121 if (!IsDiv && (LHS.get()->getType()->isConstantMatrixType() ||
10122 RHS.get()->getType()->isConstantMatrixType()))
10123 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10124
10125 QualType compType = UsualArithmeticConversions(
10126 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10127 if (LHS.isInvalid() || RHS.isInvalid())
10128 return QualType();
10129
10130
10131 if (compType.isNull() || !compType->isArithmeticType())
10132 return InvalidOperands(Loc, LHS, RHS);
10133 if (IsDiv) {
10134 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10135 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10136 }
10137 return compType;
10138}
10139
10140QualType Sema::CheckRemainderOperands(
10141 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10142 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10143
10144 if (LHS.get()->getType()->isVectorType() ||
10145 RHS.get()->getType()->isVectorType()) {
10146 if (LHS.get()->getType()->hasIntegerRepresentation() &&
10147 RHS.get()->getType()->hasIntegerRepresentation())
10148 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10149 /*AllowBothBool*/getLangOpts().AltiVec,
10150 /*AllowBoolConversions*/false);
10151 return InvalidOperands(Loc, LHS, RHS);
10152 }
10153
10154 QualType compType = UsualArithmeticConversions(
10155 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10156 if (LHS.isInvalid() || RHS.isInvalid())
10157 return QualType();
10158
10159 if (compType.isNull() || !compType->isIntegerType())
10160 return InvalidOperands(Loc, LHS, RHS);
10161 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10162 return compType;
10163}
10164
10165/// Diagnose invalid arithmetic on two void pointers.
10166static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
10167 Expr *LHSExpr, Expr *RHSExpr) {
10168 S.Diag(Loc, S.getLangOpts().CPlusPlus
10169 ? diag::err_typecheck_pointer_arith_void_type
10170 : diag::ext_gnu_void_ptr)
10171 << 1 /* two pointers */ << LHSExpr->getSourceRange()
10172 << RHSExpr->getSourceRange();
10173}
10174
10175/// Diagnose invalid arithmetic on a void pointer.
10176static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
10177 Expr *Pointer) {
10178 S.Diag(Loc, S.getLangOpts().CPlusPlus
10179 ? diag::err_typecheck_pointer_arith_void_type
10180 : diag::ext_gnu_void_ptr)
10181 << 0 /* one pointer */ << Pointer->getSourceRange();
10182}
10183
10184/// Diagnose invalid arithmetic on a null pointer.
10185///
10186/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10187/// idiom, which we recognize as a GNU extension.
10188///
10189static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
10190 Expr *Pointer, bool IsGNUIdiom) {
10191 if (IsGNUIdiom)
10192 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10193 << Pointer->getSourceRange();
10194 else
10195 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10196 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10197}
10198
10199/// Diagnose invalid arithmetic on two function pointers.
10200static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
10201 Expr *LHS, Expr *RHS) {
10202 assert(LHS->getType()->isAnyPointerType())((LHS->getType()->isAnyPointerType()) ? static_cast<
void> (0) : __assert_fail ("LHS->getType()->isAnyPointerType()"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 10202, __PRETTY_FUNCTION__))
;
10203 assert(RHS->getType()->isAnyPointerType())((RHS->getType()->isAnyPointerType()) ? static_cast<
void> (0) : __assert_fail ("RHS->getType()->isAnyPointerType()"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 10203, __PRETTY_FUNCTION__))
;
10204 S.Diag(Loc, S.getLangOpts().CPlusPlus
10205 ? diag::err_typecheck_pointer_arith_function_type
10206 : diag::ext_gnu_ptr_func_arith)
10207 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10208 // We only show the second type if it differs from the first.
10209 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
10210 RHS->getType())
10211 << RHS->getType()->getPointeeType()
10212 << LHS->getSourceRange() << RHS->getSourceRange();
10213}
10214
10215/// Diagnose invalid arithmetic on a function pointer.
10216static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
10217 Expr *Pointer) {
10218 assert(Pointer->getType()->isAnyPointerType())((Pointer->getType()->isAnyPointerType()) ? static_cast
<void> (0) : __assert_fail ("Pointer->getType()->isAnyPointerType()"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 10218, __PRETTY_FUNCTION__))
;
10219 S.Diag(Loc, S.getLangOpts().CPlusPlus
10220 ? diag::err_typecheck_pointer_arith_function_type
10221 : diag::ext_gnu_ptr_func_arith)
10222 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10223 << 0 /* one pointer, so only one type */
10224 << Pointer->getSourceRange();
10225}
10226
10227/// Emit error if Operand is incomplete pointer type
10228///
10229/// \returns True if pointer has incomplete type
10230static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
10231 Expr *Operand) {
10232 QualType ResType = Operand->getType();
10233 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10234 ResType = ResAtomicType->getValueType();
10235
10236 assert(ResType->isAnyPointerType() && !ResType->isDependentType())((ResType->isAnyPointerType() && !ResType->isDependentType
()) ? static_cast<void> (0) : __assert_fail ("ResType->isAnyPointerType() && !ResType->isDependentType()"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 10236, __PRETTY_FUNCTION__))
;
10237 QualType PointeeTy = ResType->getPointeeType();
10238 return S.RequireCompleteSizedType(
10239 Loc, PointeeTy,
10240 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10241 Operand->getSourceRange());
10242}
10243
10244/// Check the validity of an arithmetic pointer operand.
10245///
10246/// If the operand has pointer type, this code will check for pointer types
10247/// which are invalid in arithmetic operations. These will be diagnosed
10248/// appropriately, including whether or not the use is supported as an
10249/// extension.
10250///
10251/// \returns True when the operand is valid to use (even if as an extension).
10252static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
10253 Expr *Operand) {
10254 QualType ResType = Operand->getType();
10255 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10256 ResType = ResAtomicType->getValueType();
10257
10258 if (!ResType->isAnyPointerType()) return true;
10259
10260 QualType PointeeTy = ResType->getPointeeType();
10261 if (PointeeTy->isVoidType()) {
10262 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
10263 return !S.getLangOpts().CPlusPlus;
10264 }
10265 if (PointeeTy->isFunctionType()) {
10266 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
10267 return !S.getLangOpts().CPlusPlus;
10268 }
10269
10270 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10271
10272 return true;
10273}
10274
10275/// Check the validity of a binary arithmetic operation w.r.t. pointer
10276/// operands.
10277///
10278/// This routine will diagnose any invalid arithmetic on pointer operands much
10279/// like \see checkArithmeticOpPointerOperand. However, it has special logic
10280/// for emitting a single diagnostic even for operations where both LHS and RHS
10281/// are (potentially problematic) pointers.
10282///
10283/// \returns True when the operand is valid to use (even if as an extension).
10284static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
10285 Expr *LHSExpr, Expr *RHSExpr) {
10286 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10287 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10288 if (!isLHSPointer && !isRHSPointer) return true;
10289
10290 QualType LHSPointeeTy, RHSPointeeTy;
10291 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10292 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10293
10294 // if both are pointers check if operation is valid wrt address spaces
10295 if (isLHSPointer && isRHSPointer) {
10296 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
10297 S.Diag(Loc,
10298 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10299 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10300 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10301 return false;
10302 }
10303 }
10304
10305 // Check for arithmetic on pointers to incomplete types.
10306 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10307 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10308 if (isLHSVoidPtr || isRHSVoidPtr) {
10309 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10310 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10311 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10312
10313 return !S.getLangOpts().CPlusPlus;
10314 }
10315
10316 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10317 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10318 if (isLHSFuncPtr || isRHSFuncPtr) {
10319 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10320 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10321 RHSExpr);
10322 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10323
10324 return !S.getLangOpts().CPlusPlus;
10325 }
10326
10327 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10328 return false;
10329 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10330 return false;
10331
10332 return true;
10333}
10334
10335/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10336/// literal.
10337static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
10338 Expr *LHSExpr, Expr *RHSExpr) {
10339 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10340 Expr* IndexExpr = RHSExpr;
10341 if (!StrExpr) {
10342 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10343 IndexExpr = LHSExpr;
10344 }
10345
10346 bool IsStringPlusInt = StrExpr &&
10347 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
10348 if (!IsStringPlusInt || IndexExpr->isValueDependent())
10349 return;
10350
10351 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10352 Self.Diag(OpLoc, diag::warn_string_plus_int)
10353 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10354
10355 // Only print a fixit for "str" + int, not for int + "str".
10356 if (IndexExpr == RHSExpr) {
10357 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10358 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10359 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10360 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10361 << FixItHint::CreateInsertion(EndLoc, "]");
10362 } else
10363 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10364}
10365
10366/// Emit a warning when adding a char literal to a string.
10367static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
10368 Expr *LHSExpr, Expr *RHSExpr) {
10369 const Expr *StringRefExpr = LHSExpr;
10370 const CharacterLiteral *CharExpr =
10371 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
10372
10373 if (!CharExpr) {
10374 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
10375 StringRefExpr = RHSExpr;
10376 }
10377
10378 if (!CharExpr || !StringRefExpr)
10379 return;
10380
10381 const QualType StringType = StringRefExpr->getType();
10382
10383 // Return if not a PointerType.
10384 if (!StringType->isAnyPointerType())
10385 return;
10386
10387 // Return if not a CharacterType.
10388 if (!StringType->getPointeeType()->isAnyCharacterType())
10389 return;
10390
10391 ASTContext &Ctx = Self.getASTContext();
10392 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10393
10394 const QualType CharType = CharExpr->getType();
10395 if (!CharType->isAnyCharacterType() &&
10396 CharType->isIntegerType() &&
10397 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
10398 Self.Diag(OpLoc, diag::warn_string_plus_char)
10399 << DiagRange << Ctx.CharTy;
10400 } else {
10401 Self.Diag(OpLoc, diag::warn_string_plus_char)
10402 << DiagRange << CharExpr->getType();
10403 }
10404
10405 // Only print a fixit for str + char, not for char + str.
10406 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
10407 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10408 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10409 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10410 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10411 << FixItHint::CreateInsertion(EndLoc, "]");
10412 } else {
10413 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10414 }
10415}
10416
10417/// Emit error when two pointers are incompatible.
10418static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
10419 Expr *LHSExpr, Expr *RHSExpr) {
10420 assert(LHSExpr->getType()->isAnyPointerType())((LHSExpr->getType()->isAnyPointerType()) ? static_cast
<void> (0) : __assert_fail ("LHSExpr->getType()->isAnyPointerType()"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 10420, __PRETTY_FUNCTION__))
;
10421 assert(RHSExpr->getType()->isAnyPointerType())((RHSExpr->getType()->isAnyPointerType()) ? static_cast
<void> (0) : __assert_fail ("RHSExpr->getType()->isAnyPointerType()"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 10421, __PRETTY_FUNCTION__))
;
10422 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
10423 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
10424 << RHSExpr->getSourceRange();
10425}
10426
10427// C99 6.5.6
10428QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
10429 SourceLocation Loc, BinaryOperatorKind Opc,
10430 QualType* CompLHSTy) {
10431 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10432
10433 if (LHS.get()->getType()->isVectorType() ||
10434 RHS.get()->getType()->isVectorType()) {
10435 QualType compType = CheckVectorOperands(
10436 LHS, RHS, Loc, CompLHSTy,
10437 /*AllowBothBool*/getLangOpts().AltiVec,
10438 /*AllowBoolConversions*/getLangOpts().ZVector);
10439 if (CompLHSTy) *CompLHSTy = compType;
10440 return compType;
10441 }
10442
10443 if (LHS.get()->getType()->isConstantMatrixType() ||
10444 RHS.get()->getType()->isConstantMatrixType()) {
10445 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10446 }
10447
10448 QualType compType = UsualArithmeticConversions(
10449 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10450 if (LHS.isInvalid() || RHS.isInvalid())
10451 return QualType();
10452
10453 // Diagnose "string literal" '+' int and string '+' "char literal".
10454 if (Opc == BO_Add) {
10455 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
10456 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
10457 }
10458
10459 // handle the common case first (both operands are arithmetic).
10460 if (!compType.isNull() && compType->isArithmeticType()) {
10461 if (CompLHSTy) *CompLHSTy = compType;
10462 return compType;
10463 }
10464
10465 // Type-checking. Ultimately the pointer's going to be in PExp;
10466 // note that we bias towards the LHS being the pointer.
10467 Expr *PExp = LHS.get(), *IExp = RHS.get();
10468
10469 bool isObjCPointer;
10470 if (PExp->getType()->isPointerType()) {
10471 isObjCPointer = false;
10472 } else if (PExp->getType()->isObjCObjectPointerType()) {
10473 isObjCPointer = true;
10474 } else {
10475 std::swap(PExp, IExp);
10476 if (PExp->getType()->isPointerType()) {
10477 isObjCPointer = false;
10478 } else if (PExp->getType()->isObjCObjectPointerType()) {
10479 isObjCPointer = true;
10480 } else {
10481 return InvalidOperands(Loc, LHS, RHS);
10482 }
10483 }
10484 assert(PExp->getType()->isAnyPointerType())((PExp->getType()->isAnyPointerType()) ? static_cast<
void> (0) : __assert_fail ("PExp->getType()->isAnyPointerType()"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 10484, __PRETTY_FUNCTION__))
;
10485
10486 if (!IExp->getType()->isIntegerType())
10487 return InvalidOperands(Loc, LHS, RHS);
10488
10489 // Adding to a null pointer results in undefined behavior.
10490 if (PExp->IgnoreParenCasts()->isNullPointerConstant(
10491 Context, Expr::NPC_ValueDependentIsNotNull)) {
10492 // In C++ adding zero to a null pointer is defined.
10493 Expr::EvalResult KnownVal;
10494 if (!getLangOpts().CPlusPlus ||
10495 (!IExp->isValueDependent() &&
10496 (!IExp->EvaluateAsInt(KnownVal, Context) ||
10497 KnownVal.Val.getInt() != 0))) {
10498 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
10499 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
10500 Context, BO_Add, PExp, IExp);
10501 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
10502 }
10503 }
10504
10505 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
10506 return QualType();
10507
10508 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
10509 return QualType();
10510
10511 // Check array bounds for pointer arithemtic
10512 CheckArrayAccess(PExp, IExp);
10513
10514 if (CompLHSTy) {
10515 QualType LHSTy = Context.isPromotableBitField(LHS.get());
10516 if (LHSTy.isNull()) {
10517 LHSTy = LHS.get()->getType();
10518 if (LHSTy->isPromotableIntegerType())
10519 LHSTy = Context.getPromotedIntegerType(LHSTy);
10520 }
10521 *CompLHSTy = LHSTy;
10522 }
10523
10524 return PExp->getType();
10525}
10526
10527// C99 6.5.6
10528QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
10529 SourceLocation Loc,
10530 QualType* CompLHSTy) {
10531 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10532
10533 if (LHS.get()->getType()->isVectorType() ||
10534 RHS.get()->getType()->isVectorType()) {
10535 QualType compType = CheckVectorOperands(
10536 LHS, RHS, Loc, CompLHSTy,
10537 /*AllowBothBool*/getLangOpts().AltiVec,
10538 /*AllowBoolConversions*/getLangOpts().ZVector);
10539 if (CompLHSTy) *CompLHSTy = compType;
10540 return compType;
10541 }
10542
10543 if (LHS.get()->getType()->isConstantMatrixType() ||
10544 RHS.get()->getType()->isConstantMatrixType()) {
10545 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10546 }
10547
10548 QualType compType = UsualArithmeticConversions(
10549 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10550 if (LHS.isInvalid() || RHS.isInvalid())
10551 return QualType();
10552
10553 // Enforce type constraints: C99 6.5.6p3.
10554
10555 // Handle the common case first (both operands are arithmetic).
10556 if (!compType.isNull() && compType->isArithmeticType()) {
10557 if (CompLHSTy) *CompLHSTy = compType;
10558 return compType;
10559 }
10560
10561 // Either ptr - int or ptr - ptr.
10562 if (LHS.get()->getType()->isAnyPointerType()) {
10563 QualType lpointee = LHS.get()->getType()->getPointeeType();
10564
10565 // Diagnose bad cases where we step over interface counts.
10566 if (LHS.get()->getType()->isObjCObjectPointerType() &&
10567 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
10568 return QualType();
10569
10570 // The result type of a pointer-int computation is the pointer type.
10571 if (RHS.get()->getType()->isIntegerType()) {
10572 // Subtracting from a null pointer should produce a warning.
10573 // The last argument to the diagnose call says this doesn't match the
10574 // GNU int-to-pointer idiom.
10575 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
10576 Expr::NPC_ValueDependentIsNotNull)) {
10577 // In C++ adding zero to a null pointer is defined.
10578 Expr::EvalResult KnownVal;
10579 if (!getLangOpts().CPlusPlus ||
10580 (!RHS.get()->isValueDependent() &&
10581 (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
10582 KnownVal.Val.getInt() != 0))) {
10583 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
10584 }
10585 }
10586
10587 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
10588 return QualType();
10589
10590 // Check array bounds for pointer arithemtic
10591 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
10592 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
10593
10594 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10595 return LHS.get()->getType();
10596 }
10597
10598 // Handle pointer-pointer subtractions.
10599 if (const PointerType *RHSPTy
10600 = RHS.get()->getType()->getAs<PointerType>()) {
10601 QualType rpointee = RHSPTy->getPointeeType();
10602
10603 if (getLangOpts().CPlusPlus) {
10604 // Pointee types must be the same: C++ [expr.add]
10605 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
10606 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10607 }
10608 } else {
10609 // Pointee types must be compatible C99 6.5.6p3
10610 if (!Context.typesAreCompatible(
10611 Context.getCanonicalType(lpointee).getUnqualifiedType(),
10612 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
10613 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10614 return QualType();
10615 }
10616 }
10617
10618 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
10619 LHS.get(), RHS.get()))
10620 return QualType();
10621
10622 // FIXME: Add warnings for nullptr - ptr.
10623
10624 // The pointee type may have zero size. As an extension, a structure or
10625 // union may have zero size or an array may have zero length. In this
10626 // case subtraction does not make sense.
10627 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
10628 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
10629 if (ElementSize.isZero()) {
10630 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
10631 << rpointee.getUnqualifiedType()
10632 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10633 }
10634 }
10635
10636 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10637 return Context.getPointerDiffType();
10638 }
10639 }
10640
10641 return InvalidOperands(Loc, LHS, RHS);
10642}
10643
10644static bool isScopedEnumerationType(QualType T) {
10645 if (const EnumType *ET = T->getAs<EnumType>())
10646 return ET->getDecl()->isScoped();
10647 return false;
10648}
10649
10650static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
10651 SourceLocation Loc, BinaryOperatorKind Opc,
10652 QualType LHSType) {
10653 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
10654 // so skip remaining warnings as we don't want to modify values within Sema.
10655 if (S.getLangOpts().OpenCL)
10656 return;
10657
10658 // Check right/shifter operand
10659 Expr::EvalResult RHSResult;
10660 if (RHS.get()->isValueDependent() ||
10661 !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
10662 return;
10663 llvm::APSInt Right = RHSResult.Val.getInt();
10664
10665 if (Right.isNegative()) {
10666 S.DiagRuntimeBehavior(Loc, RHS.get(),
10667 S.PDiag(diag::warn_shift_negative)
10668 << RHS.get()->getSourceRange());
10669 return;
10670 }
10671
10672 QualType LHSExprType = LHS.get()->getType();
10673 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
10674 if (LHSExprType->isExtIntType())
10675 LeftSize = S.Context.getIntWidth(LHSExprType);
10676 else if (LHSExprType->isFixedPointType()) {
10677 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
10678 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
10679 }
10680 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
10681 if (Right.uge(LeftBits)) {
10682 S.DiagRuntimeBehavior(Loc, RHS.get(),
10683 S.PDiag(diag::warn_shift_gt_typewidth)
10684 << RHS.get()->getSourceRange());
10685 return;
10686 }
10687
10688 // FIXME: We probably need to handle fixed point types specially here.
10689 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
10690 return;
10691
10692 // When left shifting an ICE which is signed, we can check for overflow which
10693 // according to C++ standards prior to C++2a has undefined behavior
10694 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
10695 // more than the maximum value representable in the result type, so never
10696 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
10697 // expression is still probably a bug.)
10698 Expr::EvalResult LHSResult;
10699 if (LHS.get()->isValueDependent() ||
10700 LHSType->hasUnsignedIntegerRepresentation() ||
10701 !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
10702 return;
10703 llvm::APSInt Left = LHSResult.Val.getInt();
10704
10705 // If LHS does not have a signed type and non-negative value
10706 // then, the behavior is undefined before C++2a. Warn about it.
10707 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
10708 !S.getLangOpts().CPlusPlus20) {
10709 S.DiagRuntimeBehavior(Loc, LHS.get(),
10710 S.PDiag(diag::warn_shift_lhs_negative)
10711 << LHS.get()->getSourceRange());
10712 return;
10713 }
10714
10715 llvm::APInt ResultBits =
10716 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
10717 if (LeftBits.uge(ResultBits))
10718 return;
10719 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
10720 Result = Result.shl(Right);
10721
10722 // Print the bit representation of the signed integer as an unsigned
10723 // hexadecimal number.
10724 SmallString<40> HexResult;
10725 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
10726
10727 // If we are only missing a sign bit, this is less likely to result in actual
10728 // bugs -- if the result is cast back to an unsigned type, it will have the
10729 // expected value. Thus we place this behind a different warning that can be
10730 // turned off separately if needed.
10731 if (LeftBits == ResultBits - 1) {
10732 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
10733 << HexResult << LHSType
10734 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10735 return;
10736 }
10737
10738 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
10739 << HexResult.str() << Result.getMinSignedBits() << LHSType
10740 << Left.getBitWidth() << LHS.get()->getSourceRange()
10741 << RHS.get()->getSourceRange();
10742}
10743
10744/// Return the resulting type when a vector is shifted
10745/// by a scalar or vector shift amount.
10746static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
10747 SourceLocation Loc, bool IsCompAssign) {
10748 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
10749 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
10750 !LHS.get()->getType()->isVectorType()) {
10751 S.Diag(Loc, diag::err_shift_rhs_only_vector)
10752 << RHS.get()->getType() << LHS.get()->getType()
10753 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10754 return QualType();
10755 }
10756
10757 if (!IsCompAssign) {
10758 LHS = S.UsualUnaryConversions(LHS.get());
10759 if (LHS.isInvalid()) return QualType();
10760 }
10761
10762 RHS = S.UsualUnaryConversions(RHS.get());
10763 if (RHS.isInvalid()) return QualType();
10764
10765 QualType LHSType = LHS.get()->getType();
10766 // Note that LHS might be a scalar because the routine calls not only in
10767 // OpenCL case.
10768 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
10769 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
10770
10771 // Note that RHS might not be a vector.
10772 QualType RHSType = RHS.get()->getType();
10773 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
10774 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
10775
10776 // The operands need to be integers.
10777 if (!LHSEleType->isIntegerType()) {
10778 S.Diag(Loc, diag::err_typecheck_expect_int)
10779 << LHS.get()->getType() << LHS.get()->getSourceRange();
10780 return QualType();
10781 }
10782
10783 if (!RHSEleType->isIntegerType()) {
10784 S.Diag(Loc, diag::err_typecheck_expect_int)
10785 << RHS.get()->getType() << RHS.get()->getSourceRange();
10786 return QualType();
10787 }
10788
10789 if (!LHSVecTy) {
10790 assert(RHSVecTy)((RHSVecTy) ? static_cast<void> (0) : __assert_fail ("RHSVecTy"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 10790, __PRETTY_FUNCTION__))
;
10791 if (IsCompAssign)
10792 return RHSType;
10793 if (LHSEleType != RHSEleType) {
10794 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
10795 LHSEleType = RHSEleType;
10796 }
10797 QualType VecTy =
10798 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
10799 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
10800 LHSType = VecTy;
10801 } else if (RHSVecTy) {
10802 // OpenCL v1.1 s6.3.j says that for vector types, the operators
10803 // are applied component-wise. So if RHS is a vector, then ensure
10804 // that the number of elements is the same as LHS...
10805 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
10806 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10807 << LHS.get()->getType() << RHS.get()->getType()
10808 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10809 return QualType();
10810 }
10811 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
10812 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
10813 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
10814 if (LHSBT != RHSBT &&
10815 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
10816 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
10817 << LHS.get()->getType() << RHS.get()->getType()
10818 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10819 }
10820 }
10821 } else {
10822 // ...else expand RHS to match the number of elements in LHS.
10823 QualType VecTy =
10824 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
10825 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
10826 }
10827
10828 return LHSType;
10829}
10830
10831// C99 6.5.7
10832QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
10833 SourceLocation Loc, BinaryOperatorKind Opc,
10834 bool IsCompAssign) {
10835 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10836
10837 // Vector shifts promote their scalar inputs to vector type.
10838 if (LHS.get()->getType()->isVectorType() ||
10839 RHS.get()->getType()->isVectorType()) {
10840 if (LangOpts.ZVector) {
10841 // The shift operators for the z vector extensions work basically
10842 // like general shifts, except that neither the LHS nor the RHS is
10843 // allowed to be a "vector bool".
10844 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
10845 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
10846 return InvalidOperands(Loc, LHS, RHS);
10847 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
10848 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10849 return InvalidOperands(Loc, LHS, RHS);
10850 }
10851 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
10852 }
10853
10854 // Shifts don't perform usual arithmetic conversions, they just do integer
10855 // promotions on each operand. C99 6.5.7p3
10856
10857 // For the LHS, do usual unary conversions, but then reset them away
10858 // if this is a compound assignment.
10859 ExprResult OldLHS = LHS;
10860 LHS = UsualUnaryConversions(LHS.get());
10861 if (LHS.isInvalid())
10862 return QualType();
10863 QualType LHSType = LHS.get()->getType();
10864 if (IsCompAssign) LHS = OldLHS;
10865
10866 // The RHS is simpler.
10867 RHS = UsualUnaryConversions(RHS.get());
10868 if (RHS.isInvalid())
10869 return QualType();
10870 QualType RHSType = RHS.get()->getType();
10871
10872 // C99 6.5.7p2: Each of the operands shall have integer type.
10873 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
10874 if ((!LHSType->isFixedPointOrIntegerType() &&
10875 !LHSType->hasIntegerRepresentation()) ||
10876 !RHSType->hasIntegerRepresentation())
10877 return InvalidOperands(Loc, LHS, RHS);
10878
10879 // C++0x: Don't allow scoped enums. FIXME: Use something better than
10880 // hasIntegerRepresentation() above instead of this.
10881 if (isScopedEnumerationType(LHSType) ||
10882 isScopedEnumerationType(RHSType)) {
10883 return InvalidOperands(Loc, LHS, RHS);
10884 }
10885 // Sanity-check shift operands
10886 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
10887
10888 // "The type of the result is that of the promoted left operand."
10889 return LHSType;
10890}
10891
10892/// Diagnose bad pointer comparisons.
10893static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
10894 ExprResult &LHS, ExprResult &RHS,
10895 bool IsError) {
10896 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
10897 : diag::ext_typecheck_comparison_of_distinct_pointers)
10898 << LHS.get()->getType() << RHS.get()->getType()
10899 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10900}
10901
10902/// Returns false if the pointers are converted to a composite type,
10903/// true otherwise.
10904static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
10905 ExprResult &LHS, ExprResult &RHS) {
10906 // C++ [expr.rel]p2:
10907 // [...] Pointer conversions (4.10) and qualification
10908 // conversions (4.4) are performed on pointer operands (or on
10909 // a pointer operand and a null pointer constant) to bring
10910 // them to their composite pointer type. [...]
10911 //
10912 // C++ [expr.eq]p1 uses the same notion for (in)equality
10913 // comparisons of pointers.
10914
10915 QualType LHSType = LHS.get()->getType();
10916 QualType RHSType = RHS.get()->getType();
10917 assert(LHSType->isPointerType() || RHSType->isPointerType() ||((LHSType->isPointerType() || RHSType->isPointerType() ||
LHSType->isMemberPointerType() || RHSType->isMemberPointerType
()) ? static_cast<void> (0) : __assert_fail ("LHSType->isPointerType() || RHSType->isPointerType() || LHSType->isMemberPointerType() || RHSType->isMemberPointerType()"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 10918, __PRETTY_FUNCTION__))
10918 LHSType->isMemberPointerType() || RHSType->isMemberPointerType())((LHSType->isPointerType() || RHSType->isPointerType() ||
LHSType->isMemberPointerType() || RHSType->isMemberPointerType
()) ? static_cast<void> (0) : __assert_fail ("LHSType->isPointerType() || RHSType->isPointerType() || LHSType->isMemberPointerType() || RHSType->isMemberPointerType()"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 10918, __PRETTY_FUNCTION__))
;
10919
10920 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
10921 if (T.isNull()) {
10922 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
10923 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
10924 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
10925 else
10926 S.InvalidOperands(Loc, LHS, RHS);
10927 return true;
10928 }
10929
10930 return false;
10931}
10932
10933static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
10934 ExprResult &LHS,
10935 ExprResult &RHS,
10936 bool IsError) {
10937 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
10938 : diag::ext_typecheck_comparison_of_fptr_to_void)
10939 << LHS.get()->getType() << RHS.get()->getType()
10940 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10941}
10942
10943static bool isObjCObjectLiteral(ExprResult &E) {
10944 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
10945 case Stmt::ObjCArrayLiteralClass:
10946 case Stmt::ObjCDictionaryLiteralClass:
10947 case Stmt::ObjCStringLiteralClass:
10948 case Stmt::ObjCBoxedExprClass:
10949 return true;
10950 default:
10951 // Note that ObjCBoolLiteral is NOT an object literal!
10952 return false;
10953 }
10954}
10955
10956static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
10957 const ObjCObjectPointerType *Type =
10958 LHS->getType()->getAs<ObjCObjectPointerType>();
10959
10960 // If this is not actually an Objective-C object, bail out.
10961 if (!Type)
10962 return false;
10963
10964 // Get the LHS object's interface type.
10965 QualType InterfaceType = Type->getPointeeType();
10966
10967 // If the RHS isn't an Objective-C object, bail out.
10968 if (!RHS->getType()->isObjCObjectPointerType())
10969 return false;
10970
10971 // Try to find the -isEqual: method.
10972 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
10973 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
10974 InterfaceType,
10975 /*IsInstance=*/true);
10976 if (!Method) {
10977 if (Type->isObjCIdType()) {
10978 // For 'id', just check the global pool.
10979 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
10980 /*receiverId=*/true);
10981 } else {
10982 // Check protocols.
10983 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
10984 /*IsInstance=*/true);
10985 }
10986 }
10987
10988 if (!Method)
10989 return false;
10990
10991 QualType T = Method->parameters()[0]->getType();
10992 if (!T->isObjCObjectPointerType())
10993 return false;
10994
10995 QualType R = Method->getReturnType();
10996 if (!R->isScalarType())
10997 return false;
10998
10999 return true;
11000}
11001
11002Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
11003 FromE = FromE->IgnoreParenImpCasts();
11004 switch (FromE->getStmtClass()) {
11005 default:
11006 break;
11007 case Stmt::ObjCStringLiteralClass:
11008 // "string literal"
11009 return LK_String;
11010 case Stmt::ObjCArrayLiteralClass:
11011 // "array literal"
11012 return LK_Array;
11013 case Stmt::ObjCDictionaryLiteralClass:
11014 // "dictionary literal"
11015 return LK_Dictionary;
11016 case Stmt::BlockExprClass:
11017 return LK_Block;
11018 case Stmt::ObjCBoxedExprClass: {
11019 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
11020 switch (Inner->getStmtClass()) {
11021 case Stmt::IntegerLiteralClass:
11022 case Stmt::FloatingLiteralClass:
11023 case Stmt::CharacterLiteralClass:
11024 case Stmt::ObjCBoolLiteralExprClass:
11025 case Stmt::CXXBoolLiteralExprClass:
11026 // "numeric literal"
11027 return LK_Numeric;
11028 case Stmt::ImplicitCastExprClass: {
11029 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
11030 // Boolean literals can be represented by implicit casts.
11031 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
11032 return LK_Numeric;
11033 break;
11034 }
11035 default:
11036 break;
11037 }
11038 return LK_Boxed;
11039 }
11040 }
11041 return LK_None;
11042}
11043
11044static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
11045 ExprResult &LHS, ExprResult &RHS,
11046 BinaryOperator::Opcode Opc){
11047 Expr *Literal;
11048 Expr *Other;
11049 if (isObjCObjectLiteral(LHS)) {
11050 Literal = LHS.get();
11051 Other = RHS.get();
11052 } else {
11053 Literal = RHS.get();
11054 Other = LHS.get();
11055 }
11056
11057 // Don't warn on comparisons against nil.
11058 Other = Other->IgnoreParenCasts();
11059 if (Other->isNullPointerConstant(S.getASTContext(),
11060 Expr::NPC_ValueDependentIsNotNull))
11061 return;
11062
11063 // This should be kept in sync with warn_objc_literal_comparison.
11064 // LK_String should always be after the other literals, since it has its own
11065 // warning flag.
11066 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
11067 assert(LiteralKind != Sema::LK_Block)((LiteralKind != Sema::LK_Block) ? static_cast<void> (0
) : __assert_fail ("LiteralKind != Sema::LK_Block", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 11067, __PRETTY_FUNCTION__))
;
11068 if (LiteralKind == Sema::LK_None) {
11069 llvm_unreachable("Unknown Objective-C object literal kind")::llvm::llvm_unreachable_internal("Unknown Objective-C object literal kind"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 11069)
;
11070 }
11071
11072 if (LiteralKind == Sema::LK_String)
11073 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
11074 << Literal->getSourceRange();
11075 else
11076 S.Diag(Loc, diag::warn_objc_literal_comparison)
11077 << LiteralKind << Literal->getSourceRange();
11078
11079 if (BinaryOperator::isEqualityOp(Opc) &&
11080 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11081 SourceLocation Start = LHS.get()->getBeginLoc();
11082 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
11083 CharSourceRange OpRange =
11084 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11085
11086 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11087 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11088 << FixItHint::CreateReplacement(OpRange, " isEqual:")
11089 << FixItHint::CreateInsertion(End, "]");
11090 }
11091}
11092
11093/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11094static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
11095 ExprResult &RHS, SourceLocation Loc,
11096 BinaryOperatorKind Opc) {
11097 // Check that left hand side is !something.
11098 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11099 if (!UO || UO->getOpcode() != UO_LNot) return;
11100
11101 // Only check if the right hand side is non-bool arithmetic type.
11102 if (RHS.get()->isKnownToHaveBooleanValue()) return;
11103
11104 // Make sure that the something in !something is not bool.
11105 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11106 if (SubExpr->isKnownToHaveBooleanValue()) return;
11107
11108 // Emit warning.
11109 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11110 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11111 << Loc << IsBitwiseOp;
11112
11113 // First note suggest !(x < y)
11114 SourceLocation FirstOpen = SubExpr->getBeginLoc();
11115 SourceLocation FirstClose = RHS.get()->getEndLoc();
11116 FirstClose = S.getLocForEndOfToken(FirstClose);
11117 if (FirstClose.isInvalid())
11118 FirstOpen = SourceLocation();
11119 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11120 << IsBitwiseOp
11121 << FixItHint::CreateInsertion(FirstOpen, "(")
11122 << FixItHint::CreateInsertion(FirstClose, ")");
11123
11124 // Second note suggests (!x) < y
11125 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11126 SourceLocation SecondClose = LHS.get()->getEndLoc();
11127 SecondClose = S.getLocForEndOfToken(SecondClose);
11128 if (SecondClose.isInvalid())
11129 SecondOpen = SourceLocation();
11130 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11131 << FixItHint::CreateInsertion(SecondOpen, "(")
11132 << FixItHint::CreateInsertion(SecondClose, ")");
11133}
11134
11135// Returns true if E refers to a non-weak array.
11136static bool checkForArray(const Expr *E) {
11137 const ValueDecl *D = nullptr;
11138 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11139 D = DR->getDecl();
11140 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11141 if (Mem->isImplicitAccess())
11142 D = Mem->getMemberDecl();
11143 }
11144 if (!D)
11145 return false;
11146 return D->getType()->isArrayType() && !D->isWeak();
11147}
11148
11149/// Diagnose some forms of syntactically-obvious tautological comparison.
11150static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
11151 Expr *LHS, Expr *RHS,
11152 BinaryOperatorKind Opc) {
11153 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11154 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11155
11156 QualType LHSType = LHS->getType();
11157 QualType RHSType = RHS->getType();
11158 if (LHSType->hasFloatingRepresentation() ||
11159 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11160 S.inTemplateInstantiation())
11161 return;
11162
11163 // Comparisons between two array types are ill-formed for operator<=>, so
11164 // we shouldn't emit any additional warnings about it.
11165 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11166 return;
11167
11168 // For non-floating point types, check for self-comparisons of the form
11169 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
11170 // often indicate logic errors in the program.
11171 //
11172 // NOTE: Don't warn about comparison expressions resulting from macro
11173 // expansion. Also don't warn about comparisons which are only self
11174 // comparisons within a template instantiation. The warnings should catch
11175 // obvious cases in the definition of the template anyways. The idea is to
11176 // warn when the typed comparison operator will always evaluate to the same
11177 // result.
11178
11179 // Used for indexing into %select in warn_comparison_always
11180 enum {
11181 AlwaysConstant,
11182 AlwaysTrue,
11183 AlwaysFalse,
11184 AlwaysEqual, // std::strong_ordering::equal from operator<=>
11185 };
11186
11187 // C++2a [depr.array.comp]:
11188 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11189 // operands of array type are deprecated.
11190 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
11191 RHSStripped->getType()->isArrayType()) {
11192 S.Diag(Loc, diag::warn_depr_array_comparison)
11193 << LHS->getSourceRange() << RHS->getSourceRange()
11194 << LHSStripped->getType() << RHSStripped->getType();
11195 // Carry on to produce the tautological comparison warning, if this
11196 // expression is potentially-evaluated, we can resolve the array to a
11197 // non-weak declaration, and so on.
11198 }
11199
11200 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11201 if (Expr::isSameComparisonOperand(LHS, RHS)) {
11202 unsigned Result;
11203 switch (Opc) {
11204 case BO_EQ:
11205 case BO_LE:
11206 case BO_GE:
11207 Result = AlwaysTrue;
11208 break;
11209 case BO_NE:
11210 case BO_LT:
11211 case BO_GT:
11212 Result = AlwaysFalse;
11213 break;
11214 case BO_Cmp:
11215 Result = AlwaysEqual;
11216 break;
11217 default:
11218 Result = AlwaysConstant;
11219 break;
11220 }
11221 S.DiagRuntimeBehavior(Loc, nullptr,
11222 S.PDiag(diag::warn_comparison_always)
11223 << 0 /*self-comparison*/
11224 << Result);
11225 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
11226 // What is it always going to evaluate to?
11227 unsigned Result;
11228 switch (Opc) {
11229 case BO_EQ: // e.g. array1 == array2
11230 Result = AlwaysFalse;
11231 break;
11232 case BO_NE: // e.g. array1 != array2
11233 Result = AlwaysTrue;
11234 break;
11235 default: // e.g. array1 <= array2
11236 // The best we can say is 'a constant'
11237 Result = AlwaysConstant;
11238 break;
11239 }
11240 S.DiagRuntimeBehavior(Loc, nullptr,
11241 S.PDiag(diag::warn_comparison_always)
11242 << 1 /*array comparison*/
11243 << Result);
11244 }
11245 }
11246
11247 if (isa<CastExpr>(LHSStripped))
11248 LHSStripped = LHSStripped->IgnoreParenCasts();
11249 if (isa<CastExpr>(RHSStripped))
11250 RHSStripped = RHSStripped->IgnoreParenCasts();
11251
11252 // Warn about comparisons against a string constant (unless the other
11253 // operand is null); the user probably wants string comparison function.
11254 Expr *LiteralString = nullptr;
11255 Expr *LiteralStringStripped = nullptr;
11256 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
11257 !RHSStripped->isNullPointerConstant(S.Context,
11258 Expr::NPC_ValueDependentIsNull)) {
11259 LiteralString = LHS;
11260 LiteralStringStripped = LHSStripped;
11261 } else if ((isa<StringLiteral>(RHSStripped) ||
11262 isa<ObjCEncodeExpr>(RHSStripped)) &&
11263 !LHSStripped->isNullPointerConstant(S.Context,
11264 Expr::NPC_ValueDependentIsNull)) {
11265 LiteralString = RHS;
11266 LiteralStringStripped = RHSStripped;
11267 }
11268
11269 if (LiteralString) {
11270 S.DiagRuntimeBehavior(Loc, nullptr,
11271 S.PDiag(diag::warn_stringcompare)
11272 << isa<ObjCEncodeExpr>(LiteralStringStripped)
11273 << LiteralString->getSourceRange());
11274 }
11275}
11276
11277static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
11278 switch (CK) {
11279 default: {
11280#ifndef NDEBUG
11281 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
11282 << "\n";
11283#endif
11284 llvm_unreachable("unhandled cast kind")::llvm::llvm_unreachable_internal("unhandled cast kind", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 11284)
;
11285 }
11286 case CK_UserDefinedConversion:
11287 return ICK_Identity;
11288 case CK_LValueToRValue:
11289 return ICK_Lvalue_To_Rvalue;
11290 case CK_ArrayToPointerDecay:
11291 return ICK_Array_To_Pointer;
11292 case CK_FunctionToPointerDecay:
11293 return ICK_Function_To_Pointer;
11294 case CK_IntegralCast:
11295 return ICK_Integral_Conversion;
11296 case CK_FloatingCast:
11297 return ICK_Floating_Conversion;
11298 case CK_IntegralToFloating:
11299 case CK_FloatingToIntegral:
11300 return ICK_Floating_Integral;
11301 case CK_IntegralComplexCast:
11302 case CK_FloatingComplexCast:
11303 case CK_FloatingComplexToIntegralComplex:
11304 case CK_IntegralComplexToFloatingComplex:
11305 return ICK_Complex_Conversion;
11306 case CK_FloatingComplexToReal:
11307 case CK_FloatingRealToComplex:
11308 case CK_IntegralComplexToReal:
11309 case CK_IntegralRealToComplex:
11310 return ICK_Complex_Real;
11311 }
11312}
11313
11314static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
11315 QualType FromType,
11316 SourceLocation Loc) {
11317 // Check for a narrowing implicit conversion.
11318 StandardConversionSequence SCS;
11319 SCS.setAsIdentityConversion();
11320 SCS.setToType(0, FromType);
11321 SCS.setToType(1, ToType);
11322 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
11323 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
11324
11325 APValue PreNarrowingValue;
11326 QualType PreNarrowingType;
11327 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
11328 PreNarrowingType,
11329 /*IgnoreFloatToIntegralConversion*/ true)) {
11330 case NK_Dependent_Narrowing:
11331 // Implicit conversion to a narrower type, but the expression is
11332 // value-dependent so we can't tell whether it's actually narrowing.
11333 case NK_Not_Narrowing:
11334 return false;
11335
11336 case NK_Constant_Narrowing:
11337 // Implicit conversion to a narrower type, and the value is not a constant
11338 // expression.
11339 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11340 << /*Constant*/ 1
11341 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
11342 return true;
11343
11344 case NK_Variable_Narrowing:
11345 // Implicit conversion to a narrower type, and the value is not a constant
11346 // expression.
11347 case NK_Type_Narrowing:
11348 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11349 << /*Constant*/ 0 << FromType << ToType;
11350 // TODO: It's not a constant expression, but what if the user intended it
11351 // to be? Can we produce notes to help them figure out why it isn't?
11352 return true;
11353 }
11354 llvm_unreachable("unhandled case in switch")::llvm::llvm_unreachable_internal("unhandled case in switch",
"/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 11354)
;
11355}
11356
11357static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
11358 ExprResult &LHS,
11359 ExprResult &RHS,
11360 SourceLocation Loc) {
11361 QualType LHSType = LHS.get()->getType();
11362 QualType RHSType = RHS.get()->getType();
11363 // Dig out the original argument type and expression before implicit casts
11364 // were applied. These are the types/expressions we need to check the
11365 // [expr.spaceship] requirements against.
11366 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
11367 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
11368 QualType LHSStrippedType = LHSStripped.get()->getType();
11369 QualType RHSStrippedType = RHSStripped.get()->getType();
11370
11371 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
11372 // other is not, the program is ill-formed.
11373 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
11374 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11375 return QualType();
11376 }
11377
11378 // FIXME: Consider combining this with checkEnumArithmeticConversions.
11379 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
11380 RHSStrippedType->isEnumeralType();
11381 if (NumEnumArgs == 1) {
11382 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
11383 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
11384 if (OtherTy->hasFloatingRepresentation()) {
11385 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11386 return QualType();
11387 }
11388 }
11389 if (NumEnumArgs == 2) {
11390 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
11391 // type E, the operator yields the result of converting the operands
11392 // to the underlying type of E and applying <=> to the converted operands.
11393 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
11394 S.InvalidOperands(Loc, LHS, RHS);
11395 return QualType();
11396 }
11397 QualType IntType =
11398 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
11399 assert(IntType->isArithmeticType())((IntType->isArithmeticType()) ? static_cast<void> (
0) : __assert_fail ("IntType->isArithmeticType()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 11399, __PRETTY_FUNCTION__))
;
11400
11401 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
11402 // promote the boolean type, and all other promotable integer types, to
11403 // avoid this.
11404 if (IntType->isPromotableIntegerType())
11405 IntType = S.Context.getPromotedIntegerType(IntType);
11406
11407 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
11408 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
11409 LHSType = RHSType = IntType;
11410 }
11411
11412 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
11413 // usual arithmetic conversions are applied to the operands.
11414 QualType Type =
11415 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11416 if (LHS.isInvalid() || RHS.isInvalid())
11417 return QualType();
11418 if (Type.isNull())
11419 return S.InvalidOperands(Loc, LHS, RHS);
11420
11421 Optional<ComparisonCategoryType> CCT =
11422 getComparisonCategoryForBuiltinCmp(Type);
11423 if (!CCT)
11424 return S.InvalidOperands(Loc, LHS, RHS);
11425
11426 bool HasNarrowing = checkThreeWayNarrowingConversion(
11427 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
11428 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
11429 RHS.get()->getBeginLoc());
11430 if (HasNarrowing)
11431 return QualType();
11432
11433 assert(!Type.isNull() && "composite type for <=> has not been set")((!Type.isNull() && "composite type for <=> has not been set"
) ? static_cast<void> (0) : __assert_fail ("!Type.isNull() && \"composite type for <=> has not been set\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 11433, __PRETTY_FUNCTION__))
;
11434
11435 return S.CheckComparisonCategoryType(
11436 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
11437}
11438
11439static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
11440 ExprResult &RHS,
11441 SourceLocation Loc,
11442 BinaryOperatorKind Opc) {
11443 if (Opc == BO_Cmp)
11444 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
11445
11446 // C99 6.5.8p3 / C99 6.5.9p4
11447 QualType Type =
11448 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11449 if (LHS.isInvalid() || RHS.isInvalid())
11450 return QualType();
11451 if (Type.isNull())
11452 return S.InvalidOperands(Loc, LHS, RHS);
11453 assert(Type->isArithmeticType() || Type->isEnumeralType())((Type->isArithmeticType() || Type->isEnumeralType()) ?
static_cast<void> (0) : __assert_fail ("Type->isArithmeticType() || Type->isEnumeralType()"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 11453, __PRETTY_FUNCTION__))
;
11454
11455 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
11456 return S.InvalidOperands(Loc, LHS, RHS);
11457
11458 // Check for comparisons of floating point operands using != and ==.
11459 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
11460 S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
11461
11462 // The result of comparisons is 'bool' in C++, 'int' in C.
11463 return S.Context.getLogicalOperationType();
11464}
11465
11466void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
11467 if (!NullE.get()->getType()->isAnyPointerType())
11468 return;
11469 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
11470 if (!E.get()->getType()->isAnyPointerType() &&
11471 E.get()->isNullPointerConstant(Context,
11472 Expr::NPC_ValueDependentIsNotNull) ==
11473 Expr::NPCK_ZeroExpression) {
11474 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
11475 if (CL->getValue() == 0)
11476 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11477 << NullValue
11478 << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11479 NullValue ? "NULL" : "(void *)0");
11480 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
11481 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
11482 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
11483 if (T == Context.CharTy)
11484 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11485 << NullValue
11486 << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11487 NullValue ? "NULL" : "(void *)0");
11488 }
11489 }
11490}
11491
11492// C99 6.5.8, C++ [expr.rel]
11493QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
11494 SourceLocation Loc,
11495 BinaryOperatorKind Opc) {
11496 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
11497 bool IsThreeWay = Opc == BO_Cmp;
11498 bool IsOrdered = IsRelational || IsThreeWay;
11499 auto IsAnyPointerType = [](ExprResult E) {
11500 QualType Ty = E.get()->getType();
11501 return Ty->isPointerType() || Ty->isMemberPointerType();
11502 };
11503
11504 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
11505 // type, array-to-pointer, ..., conversions are performed on both operands to
11506 // bring them to their composite type.
11507 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
11508 // any type-related checks.
11509 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
11510 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
11511 if (LHS.isInvalid())
11512 return QualType();
11513 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
11514 if (RHS.isInvalid())
11515 return QualType();
11516 } else {
11517 LHS = DefaultLvalueConversion(LHS.get());
11518 if (LHS.isInvalid())
11519 return QualType();
11520 RHS = DefaultLvalueConversion(RHS.get());
11521 if (RHS.isInvalid())
11522 return QualType();
11523 }
11524
11525 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
11526 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
11527 CheckPtrComparisonWithNullChar(LHS, RHS);
11528 CheckPtrComparisonWithNullChar(RHS, LHS);
11529 }
11530
11531 // Handle vector comparisons separately.
11532 if (LHS.get()->getType()->isVectorType() ||
11533 RHS.get()->getType()->isVectorType())
11534 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
11535
11536 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11537 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11538
11539 QualType LHSType = LHS.get()->getType();
11540 QualType RHSType = RHS.get()->getType();
11541 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
11542 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
11543 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
11544
11545 const Expr::NullPointerConstantKind LHSNullKind =
11546 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11547 const Expr::NullPointerConstantKind RHSNullKind =
11548 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11549 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
11550 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
11551
11552 auto computeResultTy = [&]() {
11553 if (Opc != BO_Cmp)
11554 return Context.getLogicalOperationType();
11555 assert(getLangOpts().CPlusPlus)((getLangOpts().CPlusPlus) ? static_cast<void> (0) : __assert_fail
("getLangOpts().CPlusPlus", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 11555, __PRETTY_FUNCTION__))
;
11556 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()))((Context.hasSameType(LHS.get()->getType(), RHS.get()->
getType())) ? static_cast<void> (0) : __assert_fail ("Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 11556, __PRETTY_FUNCTION__))
;
11557
11558 QualType CompositeTy = LHS.get()->getType();
11559 assert(!CompositeTy->isReferenceType())((!CompositeTy->isReferenceType()) ? static_cast<void>
(0) : __assert_fail ("!CompositeTy->isReferenceType()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 11559, __PRETTY_FUNCTION__))
;
11560
11561 Optional<ComparisonCategoryType> CCT =
11562 getComparisonCategoryForBuiltinCmp(CompositeTy);
11563 if (!CCT)
11564 return InvalidOperands(Loc, LHS, RHS);
11565
11566 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
11567 // P0946R0: Comparisons between a null pointer constant and an object
11568 // pointer result in std::strong_equality, which is ill-formed under
11569 // P1959R0.
11570 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
11571 << (LHSIsNull ? LHS.get()->getSourceRange()
11572 : RHS.get()->getSourceRange());
11573 return QualType();
11574 }
11575
11576 return CheckComparisonCategoryType(
11577 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
11578 };
11579
11580 if (!IsOrdered && LHSIsNull != RHSIsNull) {
11581 bool IsEquality = Opc == BO_EQ;
11582 if (RHSIsNull)
11583 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
11584 RHS.get()->getSourceRange());
11585 else
11586 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
11587 LHS.get()->getSourceRange());
11588 }
11589
11590 if ((LHSType->isIntegerType() && !LHSIsNull) ||
11591 (RHSType->isIntegerType() && !RHSIsNull)) {
11592 // Skip normal pointer conversion checks in this case; we have better
11593 // diagnostics for this below.
11594 } else if (getLangOpts().CPlusPlus) {
11595 // Equality comparison of a function pointer to a void pointer is invalid,
11596 // but we allow it as an extension.
11597 // FIXME: If we really want to allow this, should it be part of composite
11598 // pointer type computation so it works in conditionals too?
11599 if (!IsOrdered &&
11600 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
11601 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
11602 // This is a gcc extension compatibility comparison.
11603 // In a SFINAE context, we treat this as a hard error to maintain
11604 // conformance with the C++ standard.
11605 diagnoseFunctionPointerToVoidComparison(
11606 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
11607
11608 if (isSFINAEContext())
11609 return QualType();
11610
11611 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11612 return computeResultTy();
11613 }
11614
11615 // C++ [expr.eq]p2:
11616 // If at least one operand is a pointer [...] bring them to their
11617 // composite pointer type.
11618 // C++ [expr.spaceship]p6
11619 // If at least one of the operands is of pointer type, [...] bring them
11620 // to their composite pointer type.
11621 // C++ [expr.rel]p2:
11622 // If both operands are pointers, [...] bring them to their composite
11623 // pointer type.
11624 // For <=>, the only valid non-pointer types are arrays and functions, and
11625 // we already decayed those, so this is really the same as the relational
11626 // comparison rule.
11627 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
11628 (IsOrdered ? 2 : 1) &&
11629 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
11630 RHSType->isObjCObjectPointerType()))) {
11631 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11632 return QualType();
11633 return computeResultTy();
11634 }
11635 } else if (LHSType->isPointerType() &&
11636 RHSType->isPointerType()) { // C99 6.5.8p2
11637 // All of the following pointer-related warnings are GCC extensions, except
11638 // when handling null pointer constants.
11639 QualType LCanPointeeTy =
11640 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11641 QualType RCanPointeeTy =
11642 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11643
11644 // C99 6.5.9p2 and C99 6.5.8p2
11645 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
11646 RCanPointeeTy.getUnqualifiedType())) {
11647 if (IsRelational) {
11648 // Pointers both need to point to complete or incomplete types
11649 if ((LCanPointeeTy->isIncompleteType() !=
11650 RCanPointeeTy->isIncompleteType()) &&
11651 !getLangOpts().C11) {
11652 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
11653 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
11654 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
11655 << RCanPointeeTy->isIncompleteType();
11656 }
11657 if (LCanPointeeTy->isFunctionType()) {
11658 // Valid unless a relational comparison of function pointers
11659 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
11660 << LHSType << RHSType << LHS.get()->getSourceRange()
11661 << RHS.get()->getSourceRange();
11662 }
11663 }
11664 } else if (!IsRelational &&
11665 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
11666 // Valid unless comparison between non-null pointer and function pointer
11667 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
11668 && !LHSIsNull && !RHSIsNull)
11669 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
11670 /*isError*/false);
11671 } else {
11672 // Invalid
11673 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
11674 }
11675 if (LCanPointeeTy != RCanPointeeTy) {
11676 // Treat NULL constant as a special case in OpenCL.
11677 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
11678 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
11679 Diag(Loc,
11680 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11681 << LHSType << RHSType << 0 /* comparison */
11682 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11683 }
11684 }
11685 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
11686 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
11687 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
11688 : CK_BitCast;
11689 if (LHSIsNull && !RHSIsNull)
11690 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
11691 else
11692 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
11693 }
11694 return computeResultTy();
11695 }
11696
11697 if (getLangOpts().CPlusPlus) {
11698 // C++ [expr.eq]p4:
11699 // Two operands of type std::nullptr_t or one operand of type
11700 // std::nullptr_t and the other a null pointer constant compare equal.
11701 if (!IsOrdered && LHSIsNull && RHSIsNull) {
11702 if (LHSType->isNullPtrType()) {
11703 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11704 return computeResultTy();
11705 }
11706 if (RHSType->isNullPtrType()) {
11707 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11708 return computeResultTy();
11709 }
11710 }
11711
11712 // Comparison of Objective-C pointers and block pointers against nullptr_t.
11713 // These aren't covered by the composite pointer type rules.
11714 if (!IsOrdered && RHSType->isNullPtrType() &&
11715 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
11716 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11717 return computeResultTy();
11718 }
11719 if (!IsOrdered && LHSType->isNullPtrType() &&
11720 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
11721 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11722 return computeResultTy();
11723 }
11724
11725 if (IsRelational &&
11726 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
11727 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
11728 // HACK: Relational comparison of nullptr_t against a pointer type is
11729 // invalid per DR583, but we allow it within std::less<> and friends,
11730 // since otherwise common uses of it break.
11731 // FIXME: Consider removing this hack once LWG fixes std::less<> and
11732 // friends to have std::nullptr_t overload candidates.
11733 DeclContext *DC = CurContext;
11734 if (isa<FunctionDecl>(DC))
11735 DC = DC->getParent();
11736 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
11737 if (CTSD->isInStdNamespace() &&
11738 llvm::StringSwitch<bool>(CTSD->getName())
11739 .Cases("less", "less_equal", "greater", "greater_equal", true)
11740 .Default(false)) {
11741 if (RHSType->isNullPtrType())
11742 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11743 else
11744 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11745 return computeResultTy();
11746 }
11747 }
11748 }
11749
11750 // C++ [expr.eq]p2:
11751 // If at least one operand is a pointer to member, [...] bring them to
11752 // their composite pointer type.
11753 if (!IsOrdered &&
11754 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
11755 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11756 return QualType();
11757 else
11758 return computeResultTy();
11759 }
11760 }
11761
11762 // Handle block pointer types.
11763 if (!IsOrdered && LHSType->isBlockPointerType() &&
11764 RHSType->isBlockPointerType()) {
11765 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
11766 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
11767
11768 if (!LHSIsNull && !RHSIsNull &&
11769 !Context.typesAreCompatible(lpointee, rpointee)) {
11770 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11771 << LHSType << RHSType << LHS.get()->getSourceRange()
11772 << RHS.get()->getSourceRange();
11773 }
11774 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11775 return computeResultTy();
11776 }
11777
11778 // Allow block pointers to be compared with null pointer constants.
11779 if (!IsOrdered
11780 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
11781 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
11782 if (!LHSIsNull && !RHSIsNull) {
11783 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
11784 ->getPointeeType()->isVoidType())
11785 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
11786 ->getPointeeType()->isVoidType())))
11787 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11788 << LHSType << RHSType << LHS.get()->getSourceRange()
11789 << RHS.get()->getSourceRange();
11790 }
11791 if (LHSIsNull && !RHSIsNull)
11792 LHS = ImpCastExprToType(LHS.get(), RHSType,
11793 RHSType->isPointerType() ? CK_BitCast
11794 : CK_AnyPointerToBlockPointerCast);
11795 else
11796 RHS = ImpCastExprToType(RHS.get(), LHSType,
11797 LHSType->isPointerType() ? CK_BitCast
11798 : CK_AnyPointerToBlockPointerCast);
11799 return computeResultTy();
11800 }
11801
11802 if (LHSType->isObjCObjectPointerType() ||
11803 RHSType->isObjCObjectPointerType()) {
11804 const PointerType *LPT = LHSType->getAs<PointerType>();
11805 const PointerType *RPT = RHSType->getAs<PointerType>();
11806 if (LPT || RPT) {
11807 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
11808 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
11809
11810 if (!LPtrToVoid && !RPtrToVoid &&
11811 !Context.typesAreCompatible(LHSType, RHSType)) {
11812 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11813 /*isError*/false);
11814 }
11815 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
11816 // the RHS, but we have test coverage for this behavior.
11817 // FIXME: Consider using convertPointersToCompositeType in C++.
11818 if (LHSIsNull && !RHSIsNull) {
11819 Expr *E = LHS.get();
11820 if (getLangOpts().ObjCAutoRefCount)
11821 CheckObjCConversion(SourceRange(), RHSType, E,
11822 CCK_ImplicitConversion);
11823 LHS = ImpCastExprToType(E, RHSType,
11824 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11825 }
11826 else {
11827 Expr *E = RHS.get();
11828 if (getLangOpts().ObjCAutoRefCount)
11829 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
11830 /*Diagnose=*/true,
11831 /*DiagnoseCFAudited=*/false, Opc);
11832 RHS = ImpCastExprToType(E, LHSType,
11833 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11834 }
11835 return computeResultTy();
11836 }
11837 if (LHSType->isObjCObjectPointerType() &&
11838 RHSType->isObjCObjectPointerType()) {
11839 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
11840 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11841 /*isError*/false);
11842 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
11843 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
11844
11845 if (LHSIsNull && !RHSIsNull)
11846 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
11847 else
11848 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11849 return computeResultTy();
11850 }
11851
11852 if (!IsOrdered && LHSType->isBlockPointerType() &&
11853 RHSType->isBlockCompatibleObjCPointerType(Context)) {
11854 LHS = ImpCastExprToType(LHS.get(), RHSType,
11855 CK_BlockPointerToObjCPointerCast);
11856 return computeResultTy();
11857 } else if (!IsOrdered &&
11858 LHSType->isBlockCompatibleObjCPointerType(Context) &&
11859 RHSType->isBlockPointerType()) {
11860 RHS = ImpCastExprToType(RHS.get(), LHSType,
11861 CK_BlockPointerToObjCPointerCast);
11862 return computeResultTy();
11863 }
11864 }
11865 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
11866 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
11867 unsigned DiagID = 0;
11868 bool isError = false;
11869 if (LangOpts.DebuggerSupport) {
11870 // Under a debugger, allow the comparison of pointers to integers,
11871 // since users tend to want to compare addresses.
11872 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
11873 (RHSIsNull && RHSType->isIntegerType())) {
11874 if (IsOrdered) {
11875 isError = getLangOpts().CPlusPlus;
11876 DiagID =
11877 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
11878 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
11879 }
11880 } else if (getLangOpts().CPlusPlus) {
11881 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
11882 isError = true;
11883 } else if (IsOrdered)
11884 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
11885 else
11886 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
11887
11888 if (DiagID) {
11889 Diag(Loc, DiagID)
11890 << LHSType << RHSType << LHS.get()->getSourceRange()
11891 << RHS.get()->getSourceRange();
11892 if (isError)
11893 return QualType();
11894 }
11895
11896 if (LHSType->isIntegerType())
11897 LHS = ImpCastExprToType(LHS.get(), RHSType,
11898 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11899 else
11900 RHS = ImpCastExprToType(RHS.get(), LHSType,
11901 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11902 return computeResultTy();
11903 }
11904
11905 // Handle block pointers.
11906 if (!IsOrdered && RHSIsNull
11907 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
11908 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11909 return computeResultTy();
11910 }
11911 if (!IsOrdered && LHSIsNull
11912 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
11913 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11914 return computeResultTy();
11915 }
11916
11917 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
11918 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
11919 return computeResultTy();
11920 }
11921
11922 if (LHSType->isQueueT() && RHSType->isQueueT()) {
11923 return computeResultTy();
11924 }
11925
11926 if (LHSIsNull && RHSType->isQueueT()) {
11927 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11928 return computeResultTy();
11929 }
11930
11931 if (LHSType->isQueueT() && RHSIsNull) {
11932 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11933 return computeResultTy();
11934 }
11935 }
11936
11937 return InvalidOperands(Loc, LHS, RHS);
11938}
11939
11940// Return a signed ext_vector_type that is of identical size and number of
11941// elements. For floating point vectors, return an integer type of identical
11942// size and number of elements. In the non ext_vector_type case, search from
11943// the largest type to the smallest type to avoid cases where long long == long,
11944// where long gets picked over long long.
11945QualType Sema::GetSignedVectorType(QualType V) {
11946 const VectorType *VTy = V->castAs<VectorType>();
11947 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
11948
11949 if (isa<ExtVectorType>(VTy)) {
11950 if (TypeSize == Context.getTypeSize(Context.CharTy))
11951 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
11952 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11953 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
11954 else if (TypeSize == Context.getTypeSize(Context.IntTy))
11955 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
11956 else if (TypeSize == Context.getTypeSize(Context.LongTy))
11957 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
11958 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&((TypeSize == Context.getTypeSize(Context.LongLongTy) &&
"Unhandled vector element size in vector compare") ? static_cast
<void> (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.LongLongTy) && \"Unhandled vector element size in vector compare\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 11959, __PRETTY_FUNCTION__))
11959 "Unhandled vector element size in vector compare")((TypeSize == Context.getTypeSize(Context.LongLongTy) &&
"Unhandled vector element size in vector compare") ? static_cast
<void> (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.LongLongTy) && \"Unhandled vector element size in vector compare\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 11959, __PRETTY_FUNCTION__))
;
11960 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
11961 }
11962
11963 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
11964 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
11965 VectorType::GenericVector);
11966 else if (TypeSize == Context.getTypeSize(Context.LongTy))
11967 return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
11968 VectorType::GenericVector);
11969 else if (TypeSize == Context.getTypeSize(Context.IntTy))
11970 return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
11971 VectorType::GenericVector);
11972 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11973 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
11974 VectorType::GenericVector);
11975 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&((TypeSize == Context.getTypeSize(Context.CharTy) && "Unhandled vector element size in vector compare"
) ? static_cast<void> (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.CharTy) && \"Unhandled vector element size in vector compare\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 11976, __PRETTY_FUNCTION__))
11976 "Unhandled vector element size in vector compare")((TypeSize == Context.getTypeSize(Context.CharTy) && "Unhandled vector element size in vector compare"
) ? static_cast<void> (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.CharTy) && \"Unhandled vector element size in vector compare\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 11976, __PRETTY_FUNCTION__))
;
11977 return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
11978 VectorType::GenericVector);
11979}
11980
11981/// CheckVectorCompareOperands - vector comparisons are a clang extension that
11982/// operates on extended vector types. Instead of producing an IntTy result,
11983/// like a scalar comparison, a vector comparison produces a vector of integer
11984/// types.
11985QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
11986 SourceLocation Loc,
11987 BinaryOperatorKind Opc) {
11988 if (Opc == BO_Cmp) {
11989 Diag(Loc, diag::err_three_way_vector_comparison);
11990 return QualType();
11991 }
11992
11993 // Check to make sure we're operating on vectors of the same type and width,
11994 // Allowing one side to be a scalar of element type.
11995 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
11996 /*AllowBothBool*/true,
11997 /*AllowBoolConversions*/getLangOpts().ZVector);
11998 if (vType.isNull())
11999 return vType;
12000
12001 QualType LHSType = LHS.get()->getType();
12002
12003 // If AltiVec, the comparison results in a numeric type, i.e.
12004 // bool for C++, int for C
12005 if (getLangOpts().AltiVec &&
12006 vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
12007 return Context.getLogicalOperationType();
12008
12009 // For non-floating point types, check for self-comparisons of the form
12010 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12011 // often indicate logic errors in the program.
12012 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12013
12014 // Check for comparisons of floating point operands using != and ==.
12015 if (BinaryOperator::isEqualityOp(Opc) &&
12016 LHSType->hasFloatingRepresentation()) {
12017 assert(RHS.get()->getType()->hasFloatingRepresentation())((RHS.get()->getType()->hasFloatingRepresentation()) ? static_cast
<void> (0) : __assert_fail ("RHS.get()->getType()->hasFloatingRepresentation()"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 12017, __PRETTY_FUNCTION__))
;
12018 CheckFloatComparison(Loc, LHS.get(), RHS.get());
12019 }
12020
12021 // Return a signed type for the vector.
12022 return GetSignedVectorType(vType);
12023}
12024
12025static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
12026 const ExprResult &XorRHS,
12027 const SourceLocation Loc) {
12028 // Do not diagnose macros.
12029 if (Loc.isMacroID())
12030 return;
12031
12032 bool Negative = false;
12033 bool ExplicitPlus = false;
12034 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
12035 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
12036
12037 if (!LHSInt)
12038 return;
12039 if (!RHSInt) {
12040 // Check negative literals.
12041 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
12042 UnaryOperatorKind Opc = UO->getOpcode();
12043 if (Opc != UO_Minus && Opc != UO_Plus)
12044 return;
12045 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
12046 if (!RHSInt)
12047 return;
12048 Negative = (Opc == UO_Minus);
12049 ExplicitPlus = !Negative;
12050 } else {
12051 return;
12052 }
12053 }
12054
12055 const llvm::APInt &LeftSideValue = LHSInt->getValue();
12056 llvm::APInt RightSideValue = RHSInt->getValue();
12057 if (LeftSideValue != 2 && LeftSideValue != 10)
12058 return;
12059
12060 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
12061 return;
12062
12063 CharSourceRange ExprRange = CharSourceRange::getCharRange(
12064 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
12065 llvm::StringRef ExprStr =
12066 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
12067
12068 CharSourceRange XorRange =
12069 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
12070 llvm::StringRef XorStr =
12071 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
12072 // Do not diagnose if xor keyword/macro is used.
12073 if (XorStr == "xor")
12074 return;
12075
12076 std::string LHSStr = std::string(Lexer::getSourceText(
12077 CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
12078 S.getSourceManager(), S.getLangOpts()));
12079 std::string RHSStr = std::string(Lexer::getSourceText(
12080 CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
12081 S.getSourceManager(), S.getLangOpts()));
12082
12083 if (Negative) {
12084 RightSideValue = -RightSideValue;
12085 RHSStr = "-" + RHSStr;
12086 } else if (ExplicitPlus) {
12087 RHSStr = "+" + RHSStr;
12088 }
12089
12090 StringRef LHSStrRef = LHSStr;
12091 StringRef RHSStrRef = RHSStr;
12092 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12093 // literals.
12094 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
12095 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
12096 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
12097 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
12098 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
12099 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
12100 LHSStrRef.find('\'') != StringRef::npos ||
12101 RHSStrRef.find('\'') != StringRef::npos)
12102 return;
12103
12104 bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12105 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12106 int64_t RightSideIntValue = RightSideValue.getSExtValue();
12107 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
12108 std::string SuggestedExpr = "1 << " + RHSStr;
12109 bool Overflow = false;
12110 llvm::APInt One = (LeftSideValue - 1);
12111 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
12112 if (Overflow) {
12113 if (RightSideIntValue < 64)
12114 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12115 << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr)
12116 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
12117 else if (RightSideIntValue == 64)
12118 S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true);
12119 else
12120 return;
12121 } else {
12122 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
12123 << ExprStr << XorValue.toString(10, true) << SuggestedExpr
12124 << PowValue.toString(10, true)
12125 << FixItHint::CreateReplacement(
12126 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
12127 }
12128
12129 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor;
12130 } else if (LeftSideValue == 10) {
12131 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
12132 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12133 << ExprStr << XorValue.toString(10, true) << SuggestedValue
12134 << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
12135 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor;
12136 }
12137}
12138
12139QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12140 SourceLocation Loc) {
12141 // Ensure that either both operands are of the same vector type, or
12142 // one operand is of a vector type and the other is of its element type.
12143 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
12144 /*AllowBothBool*/true,
12145 /*AllowBoolConversions*/false);
12146 if (vType.isNull())
12147 return InvalidOperands(Loc, LHS, RHS);
12148 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
12149 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
12150 return InvalidOperands(Loc, LHS, RHS);
12151 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
12152 // usage of the logical operators && and || with vectors in C. This
12153 // check could be notionally dropped.
12154 if (!getLangOpts().CPlusPlus &&
12155 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
12156 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
12157
12158 return GetSignedVectorType(LHS.get()->getType());
12159}
12160
12161QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
12162 SourceLocation Loc,
12163 bool IsCompAssign) {
12164 if (!IsCompAssign) {
12165 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12166 if (LHS.isInvalid())
12167 return QualType();
12168 }
12169 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12170 if (RHS.isInvalid())
12171 return QualType();
12172
12173 // For conversion purposes, we ignore any qualifiers.
12174 // For example, "const float" and "float" are equivalent.
12175 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
12176 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
12177
12178 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
12179 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
12180 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix")(((LHSMatType || RHSMatType) && "At least one operand must be a matrix"
) ? static_cast<void> (0) : __assert_fail ("(LHSMatType || RHSMatType) && \"At least one operand must be a matrix\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 12180, __PRETTY_FUNCTION__))
;
12181
12182 if (Context.hasSameType(LHSType, RHSType))
12183 return LHSType;
12184
12185 // Type conversion may change LHS/RHS. Keep copies to the original results, in
12186 // case we have to return InvalidOperands.
12187 ExprResult OriginalLHS = LHS;
12188 ExprResult OriginalRHS = RHS;
12189 if (LHSMatType && !RHSMatType) {
12190 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
12191 if (!RHS.isInvalid())
12192 return LHSType;
12193
12194 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12195 }
12196
12197 if (!LHSMatType && RHSMatType) {
12198 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
12199 if (!LHS.isInvalid())
12200 return RHSType;
12201 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12202 }
12203
12204 return InvalidOperands(Loc, LHS, RHS);
12205}
12206
12207QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
12208 SourceLocation Loc,
12209 bool IsCompAssign) {
12210 if (!IsCompAssign) {
12211 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12212 if (LHS.isInvalid())
12213 return QualType();
12214 }
12215 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12216 if (RHS.isInvalid())
12217 return QualType();
12218
12219 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
12220 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
12221 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix")(((LHSMatType || RHSMatType) && "At least one operand must be a matrix"
) ? static_cast<void> (0) : __assert_fail ("(LHSMatType || RHSMatType) && \"At least one operand must be a matrix\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 12221, __PRETTY_FUNCTION__))
;
12222
12223 if (LHSMatType && RHSMatType) {
12224 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
12225 return InvalidOperands(Loc, LHS, RHS);
12226
12227 if (!Context.hasSameType(LHSMatType->getElementType(),
12228 RHSMatType->getElementType()))
12229 return InvalidOperands(Loc, LHS, RHS);
12230
12231 return Context.getConstantMatrixType(LHSMatType->getElementType(),
12232 LHSMatType->getNumRows(),
12233 RHSMatType->getNumColumns());
12234 }
12235 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
12236}
12237
12238inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
12239 SourceLocation Loc,
12240 BinaryOperatorKind Opc) {
12241 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12242
12243 bool IsCompAssign =
12244 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
12245
12246 if (LHS.get()->getType()->isVectorType() ||
12247 RHS.get()->getType()->isVectorType()) {
12248 if (LHS.get()->getType()->hasIntegerRepresentation() &&
12249 RHS.get()->getType()->hasIntegerRepresentation())
12250 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
12251 /*AllowBothBool*/true,
12252 /*AllowBoolConversions*/getLangOpts().ZVector);
12253 return InvalidOperands(Loc, LHS, RHS);
12254 }
12255
12256 if (Opc == BO_And)
12257 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12258
12259 if (LHS.get()->getType()->hasFloatingRepresentation() ||
12260 RHS.get()->getType()->hasFloatingRepresentation())
12261 return InvalidOperands(Loc, LHS, RHS);
12262
12263 ExprResult LHSResult = LHS, RHSResult = RHS;
12264 QualType compType = UsualArithmeticConversions(
12265 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
12266 if (LHSResult.isInvalid() || RHSResult.isInvalid())
12267 return QualType();
12268 LHS = LHSResult.get();
12269 RHS = RHSResult.get();
12270
12271 if (Opc == BO_Xor)
12272 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
12273
12274 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
12275 return compType;
12276 return InvalidOperands(Loc, LHS, RHS);
12277}
12278
12279// C99 6.5.[13,14]
12280inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12281 SourceLocation Loc,
12282 BinaryOperatorKind Opc) {
12283 // Check vector operands differently.
12284 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
12285 return CheckVectorLogicalOperands(LHS, RHS, Loc);
12286
12287 bool EnumConstantInBoolContext = false;
12288 for (const ExprResult &HS : {LHS, RHS}) {
12289 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
12290 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
12291 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
12292 EnumConstantInBoolContext = true;
12293 }
12294 }
12295
12296 if (EnumConstantInBoolContext)
12297 Diag(Loc, diag::warn_enum_constant_in_bool_context);
12298
12299 // Diagnose cases where the user write a logical and/or but probably meant a
12300 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
12301 // is a constant.
12302 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
12303 !LHS.get()->getType()->isBooleanType() &&
12304 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
12305 // Don't warn in macros or template instantiations.
12306 !Loc.isMacroID() && !inTemplateInstantiation()) {
12307 // If the RHS can be constant folded, and if it constant folds to something
12308 // that isn't 0 or 1 (which indicate a potential logical operation that
12309 // happened to fold to true/false) then warn.
12310 // Parens on the RHS are ignored.
12311 Expr::EvalResult EVResult;
12312 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
12313 llvm::APSInt Result = EVResult.Val.getInt();
12314 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
12315 !RHS.get()->getExprLoc().isMacroID()) ||
12316 (Result != 0 && Result != 1)) {
12317 Diag(Loc, diag::warn_logical_instead_of_bitwise)
12318 << RHS.get()->getSourceRange()
12319 << (Opc == BO_LAnd ? "&&" : "||");
12320 // Suggest replacing the logical operator with the bitwise version
12321 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
12322 << (Opc == BO_LAnd ? "&" : "|")
12323 << FixItHint::CreateReplacement(SourceRange(
12324 Loc, getLocForEndOfToken(Loc)),
12325 Opc == BO_LAnd ? "&" : "|");
12326 if (Opc == BO_LAnd)
12327 // Suggest replacing "Foo() && kNonZero" with "Foo()"
12328 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
12329 << FixItHint::CreateRemoval(
12330 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
12331 RHS.get()->getEndLoc()));
12332 }
12333 }
12334 }
12335
12336 if (!Context.getLangOpts().CPlusPlus) {
12337 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
12338 // not operate on the built-in scalar and vector float types.
12339 if (Context.getLangOpts().OpenCL &&
12340 Context.getLangOpts().OpenCLVersion < 120) {
12341 if (LHS.get()->getType()->isFloatingType() ||
12342 RHS.get()->getType()->isFloatingType())
12343 return InvalidOperands(Loc, LHS, RHS);
12344 }
12345
12346 LHS = UsualUnaryConversions(LHS.get());
12347 if (LHS.isInvalid())
12348 return QualType();
12349
12350 RHS = UsualUnaryConversions(RHS.get());
12351 if (RHS.isInvalid())
12352 return QualType();
12353
12354 if (!LHS.get()->getType()->isScalarType() ||
12355 !RHS.get()->getType()->isScalarType())
12356 return InvalidOperands(Loc, LHS, RHS);
12357
12358 return Context.IntTy;
12359 }
12360
12361 // The following is safe because we only use this method for
12362 // non-overloadable operands.
12363
12364 // C++ [expr.log.and]p1
12365 // C++ [expr.log.or]p1
12366 // The operands are both contextually converted to type bool.
12367 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
12368 if (LHSRes.isInvalid())
12369 return InvalidOperands(Loc, LHS, RHS);
12370 LHS = LHSRes;
12371
12372 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
12373 if (RHSRes.isInvalid())
12374 return InvalidOperands(Loc, LHS, RHS);
12375 RHS = RHSRes;
12376
12377 // C++ [expr.log.and]p2
12378 // C++ [expr.log.or]p2
12379 // The result is a bool.
12380 return Context.BoolTy;
12381}
12382
12383static bool IsReadonlyMessage(Expr *E, Sema &S) {
12384 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12385 if (!ME) return false;
12386 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
12387 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
12388 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
12389 if (!Base) return false;
12390 return Base->getMethodDecl() != nullptr;
12391}
12392
12393/// Is the given expression (which must be 'const') a reference to a
12394/// variable which was originally non-const, but which has become
12395/// 'const' due to being captured within a block?
12396enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
12397static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
12398 assert(E->isLValue() && E->getType().isConstQualified())((E->isLValue() && E->getType().isConstQualified
()) ? static_cast<void> (0) : __assert_fail ("E->isLValue() && E->getType().isConstQualified()"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 12398, __PRETTY_FUNCTION__))
;
12399 E = E->IgnoreParens();
12400
12401 // Must be a reference to a declaration from an enclosing scope.
12402 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
12403 if (!DRE) return NCCK_None;
12404 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
12405
12406 // The declaration must be a variable which is not declared 'const'.
12407 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
12408 if (!var) return NCCK_None;
12409 if (var->getType().isConstQualified()) return NCCK_None;
12410 assert(var->hasLocalStorage() && "capture added 'const' to non-local?")((var->hasLocalStorage() && "capture added 'const' to non-local?"
) ? static_cast<void> (0) : __assert_fail ("var->hasLocalStorage() && \"capture added 'const' to non-local?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 12410, __PRETTY_FUNCTION__))
;
12411
12412 // Decide whether the first capture was for a block or a lambda.
12413 DeclContext *DC = S.CurContext, *Prev = nullptr;
12414 // Decide whether the first capture was for a block or a lambda.
12415 while (DC) {
12416 // For init-capture, it is possible that the variable belongs to the
12417 // template pattern of the current context.
12418 if (auto *FD = dyn_cast<FunctionDecl>(DC))
12419 if (var->isInitCapture() &&
12420 FD->getTemplateInstantiationPattern() == var->getDeclContext())
12421 break;
12422 if (DC == var->getDeclContext())
12423 break;
12424 Prev = DC;
12425 DC = DC->getParent();
12426 }
12427 // Unless we have an init-capture, we've gone one step too far.
12428 if (!var->isInitCapture())
12429 DC = Prev;
12430 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
12431}
12432
12433static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
12434 Ty = Ty.getNonReferenceType();
12435 if (IsDereference && Ty->isPointerType())
12436 Ty = Ty->getPointeeType();
12437 return !Ty.isConstQualified();
12438}
12439
12440// Update err_typecheck_assign_const and note_typecheck_assign_const
12441// when this enum is changed.
12442enum {
12443 ConstFunction,
12444 ConstVariable,
12445 ConstMember,
12446 ConstMethod,
12447 NestedConstMember,
12448 ConstUnknown, // Keep as last element
12449};
12450
12451/// Emit the "read-only variable not assignable" error and print notes to give
12452/// more information about why the variable is not assignable, such as pointing
12453/// to the declaration of a const variable, showing that a method is const, or
12454/// that the function is returning a const reference.
12455static void DiagnoseConstAssignment(Sema &S, const Expr *E,
12456 SourceLocation Loc) {
12457 SourceRange ExprRange = E->getSourceRange();
12458
12459 // Only emit one error on the first const found. All other consts will emit
12460 // a note to the error.
12461 bool DiagnosticEmitted = false;
12462
12463 // Track if the current expression is the result of a dereference, and if the
12464 // next checked expression is the result of a dereference.
12465 bool IsDereference = false;
12466 bool NextIsDereference = false;
12467
12468 // Loop to process MemberExpr chains.
12469 while (true) {
12470 IsDereference = NextIsDereference;
12471
12472 E = E->IgnoreImplicit()->IgnoreParenImpCasts();
12473 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12474 NextIsDereference = ME->isArrow();
12475 const ValueDecl *VD = ME->getMemberDecl();
12476 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
12477 // Mutable fields can be modified even if the class is const.
12478 if (Field->isMutable()) {
12479 assert(DiagnosticEmitted && "Expected diagnostic not emitted.")((DiagnosticEmitted && "Expected diagnostic not emitted."
) ? static_cast<void> (0) : __assert_fail ("DiagnosticEmitted && \"Expected diagnostic not emitted.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 12479, __PRETTY_FUNCTION__))
;
12480 break;
12481 }
12482
12483 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
12484 if (!DiagnosticEmitted) {
12485 S.Diag(Loc, diag::err_typecheck_assign_const)
12486 << ExprRange << ConstMember << false /*static*/ << Field
12487 << Field->getType();
12488 DiagnosticEmitted = true;
12489 }
12490 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12491 << ConstMember << false /*static*/ << Field << Field->getType()
12492 << Field->getSourceRange();
12493 }
12494 E = ME->getBase();
12495 continue;
12496 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
12497 if (VDecl->getType().isConstQualified()) {
12498 if (!DiagnosticEmitted) {
12499 S.Diag(Loc, diag::err_typecheck_assign_const)
12500 << ExprRange << ConstMember << true /*static*/ << VDecl
12501 << VDecl->getType();
12502 DiagnosticEmitted = true;
12503 }
12504 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12505 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
12506 << VDecl->getSourceRange();
12507 }
12508 // Static fields do not inherit constness from parents.
12509 break;
12510 }
12511 break; // End MemberExpr
12512 } else if (const ArraySubscriptExpr *ASE =
12513 dyn_cast<ArraySubscriptExpr>(E)) {
12514 E = ASE->getBase()->IgnoreParenImpCasts();
12515 continue;
12516 } else if (const ExtVectorElementExpr *EVE =
12517 dyn_cast<ExtVectorElementExpr>(E)) {
12518 E = EVE->getBase()->IgnoreParenImpCasts();
12519 continue;
12520 }
12521 break;
12522 }
12523
12524 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
12525 // Function calls
12526 const FunctionDecl *FD = CE->getDirectCallee();
12527 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
12528 if (!DiagnosticEmitted) {
12529 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12530 << ConstFunction << FD;
12531 DiagnosticEmitted = true;
12532 }
12533 S.Diag(FD->getReturnTypeSourceRange().getBegin(),
12534 diag::note_typecheck_assign_const)
12535 << ConstFunction << FD << FD->getReturnType()
12536 << FD->getReturnTypeSourceRange();
12537 }
12538 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12539 // Point to variable declaration.
12540 if (const ValueDecl *VD = DRE->getDecl()) {
12541 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
12542 if (!DiagnosticEmitted) {
12543 S.Diag(Loc, diag::err_typecheck_assign_const)
12544 << ExprRange << ConstVariable << VD << VD->getType();
12545 DiagnosticEmitted = true;
12546 }
12547 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12548 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
12549 }
12550 }
12551 } else if (isa<CXXThisExpr>(E)) {
12552 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
12553 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
12554 if (MD->isConst()) {
12555 if (!DiagnosticEmitted) {
12556 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12557 << ConstMethod << MD;
12558 DiagnosticEmitted = true;
12559 }
12560 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
12561 << ConstMethod << MD << MD->getSourceRange();
12562 }
12563 }
12564 }
12565 }
12566
12567 if (DiagnosticEmitted)
12568 return;
12569
12570 // Can't determine a more specific message, so display the generic error.
12571 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
12572}
12573
12574enum OriginalExprKind {
12575 OEK_Variable,
12576 OEK_Member,
12577 OEK_LValue
12578};
12579
12580static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
12581 const RecordType *Ty,
12582 SourceLocation Loc, SourceRange Range,
12583 OriginalExprKind OEK,
12584 bool &DiagnosticEmitted) {
12585 std::vector<const RecordType *> RecordTypeList;
12586 RecordTypeList.push_back(Ty);
12587 unsigned NextToCheckIndex = 0;
12588 // We walk the record hierarchy breadth-first to ensure that we print
12589 // diagnostics in field nesting order.
12590 while (RecordTypeList.size() > NextToCheckIndex) {
12591 bool IsNested = NextToCheckIndex > 0;
12592 for (const FieldDecl *Field :
12593 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
12594 // First, check every field for constness.
12595 QualType FieldTy = Field->getType();
12596 if (FieldTy.isConstQualified()) {
12597 if (!DiagnosticEmitted) {
12598 S.Diag(Loc, diag::err_typecheck_assign_const)
12599 << Range << NestedConstMember << OEK << VD
12600 << IsNested << Field;
12601 DiagnosticEmitted = true;
12602 }
12603 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
12604 << NestedConstMember << IsNested << Field
12605 << FieldTy << Field->getSourceRange();
12606 }
12607
12608 // Then we append it to the list to check next in order.
12609 FieldTy = FieldTy.getCanonicalType();
12610 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
12611 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
12612 RecordTypeList.push_back(FieldRecTy);
12613 }
12614 }
12615 ++NextToCheckIndex;
12616 }
12617}
12618
12619/// Emit an error for the case where a record we are trying to assign to has a
12620/// const-qualified field somewhere in its hierarchy.
12621static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
12622 SourceLocation Loc) {
12623 QualType Ty = E->getType();
12624 assert(Ty->isRecordType() && "lvalue was not record?")((Ty->isRecordType() && "lvalue was not record?") ?
static_cast<void> (0) : __assert_fail ("Ty->isRecordType() && \"lvalue was not record?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 12624, __PRETTY_FUNCTION__))
;
12625 SourceRange Range = E->getSourceRange();
12626 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
12627 bool DiagEmitted = false;
12628
12629 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
12630 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
12631 Range, OEK_Member, DiagEmitted);
12632 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12633 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
12634 Range, OEK_Variable, DiagEmitted);
12635 else
12636 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
12637 Range, OEK_LValue, DiagEmitted);
12638 if (!DiagEmitted)
12639 DiagnoseConstAssignment(S, E, Loc);
12640}
12641
12642/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
12643/// emit an error and return true. If so, return false.
12644static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
12645 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject))((!E->hasPlaceholderType(BuiltinType::PseudoObject)) ? static_cast
<void> (0) : __assert_fail ("!E->hasPlaceholderType(BuiltinType::PseudoObject)"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 12645, __PRETTY_FUNCTION__))
;
12646
12647 S.CheckShadowingDeclModification(E, Loc);
12648
12649 SourceLocation OrigLoc = Loc;
12650 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
12651 &Loc);
12652 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
12653 IsLV = Expr::MLV_InvalidMessageExpression;
12654 if (IsLV == Expr::MLV_Valid)
12655 return false;
12656
12657 unsigned DiagID = 0;
12658 bool NeedType = false;
12659 switch (IsLV) { // C99 6.5.16p2
12660 case Expr::MLV_ConstQualified:
12661 // Use a specialized diagnostic when we're assigning to an object
12662 // from an enclosing function or block.
12663 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
12664 if (NCCK == NCCK_Block)
12665 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
12666 else
12667 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
12668 break;
12669 }
12670
12671 // In ARC, use some specialized diagnostics for occasions where we
12672 // infer 'const'. These are always pseudo-strong variables.
12673 if (S.getLangOpts().ObjCAutoRefCount) {
12674 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
12675 if (declRef && isa<VarDecl>(declRef->getDecl())) {
12676 VarDecl *var = cast<VarDecl>(declRef->getDecl());
12677
12678 // Use the normal diagnostic if it's pseudo-__strong but the
12679 // user actually wrote 'const'.
12680 if (var->isARCPseudoStrong() &&
12681 (!var->getTypeSourceInfo() ||
12682 !var->getTypeSourceInfo()->getType().isConstQualified())) {
12683 // There are three pseudo-strong cases:
12684 // - self
12685 ObjCMethodDecl *method = S.getCurMethodDecl();
12686 if (method && var == method->getSelfDecl()) {
12687 DiagID = method->isClassMethod()
12688 ? diag::err_typecheck_arc_assign_self_class_method
12689 : diag::err_typecheck_arc_assign_self;
12690
12691 // - Objective-C externally_retained attribute.
12692 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
12693 isa<ParmVarDecl>(var)) {
12694 DiagID = diag::err_typecheck_arc_assign_externally_retained;
12695
12696 // - fast enumeration variables
12697 } else {
12698 DiagID = diag::err_typecheck_arr_assign_enumeration;
12699 }
12700
12701 SourceRange Assign;
12702 if (Loc != OrigLoc)
12703 Assign = SourceRange(OrigLoc, OrigLoc);
12704 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12705 // We need to preserve the AST regardless, so migration tool
12706 // can do its job.
12707 return false;
12708 }
12709 }
12710 }
12711
12712 // If none of the special cases above are triggered, then this is a
12713 // simple const assignment.
12714 if (DiagID == 0) {
12715 DiagnoseConstAssignment(S, E, Loc);
12716 return true;
12717 }
12718
12719 break;
12720 case Expr::MLV_ConstAddrSpace:
12721 DiagnoseConstAssignment(S, E, Loc);
12722 return true;
12723 case Expr::MLV_ConstQualifiedField:
12724 DiagnoseRecursiveConstFields(S, E, Loc);
12725 return true;
12726 case Expr::MLV_ArrayType:
12727 case Expr::MLV_ArrayTemporary:
12728 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
12729 NeedType = true;
12730 break;
12731 case Expr::MLV_NotObjectType:
12732 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
12733 NeedType = true;
12734 break;
12735 case Expr::MLV_LValueCast:
12736 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
12737 break;
12738 case Expr::MLV_Valid:
12739 llvm_unreachable("did not take early return for MLV_Valid")::llvm::llvm_unreachable_internal("did not take early return for MLV_Valid"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 12739)
;
12740 case Expr::MLV_InvalidExpression:
12741 case Expr::MLV_MemberFunction:
12742 case Expr::MLV_ClassTemporary:
12743 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
12744 break;
12745 case Expr::MLV_IncompleteType:
12746 case Expr::MLV_IncompleteVoidType:
12747 return S.RequireCompleteType(Loc, E->getType(),
12748 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
12749 case Expr::MLV_DuplicateVectorComponents:
12750 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
12751 break;
12752 case Expr::MLV_NoSetterProperty:
12753 llvm_unreachable("readonly properties should be processed differently")::llvm::llvm_unreachable_internal("readonly properties should be processed differently"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 12753)
;
12754 case Expr::MLV_InvalidMessageExpression:
12755 DiagID = diag::err_readonly_message_assignment;
12756 break;
12757 case Expr::MLV_SubObjCPropertySetting:
12758 DiagID = diag::err_no_subobject_property_setting;
12759 break;
12760 }
12761
12762 SourceRange Assign;
12763 if (Loc != OrigLoc)
12764 Assign = SourceRange(OrigLoc, OrigLoc);
12765 if (NeedType)
12766 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
12767 else
12768 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12769 return true;
12770}
12771
12772static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
12773 SourceLocation Loc,
12774 Sema &Sema) {
12775 if (Sema.inTemplateInstantiation())
12776 return;
12777 if (Sema.isUnevaluatedContext())
12778 return;
12779 if (Loc.isInvalid() || Loc.isMacroID())
12780 return;
12781 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
12782 return;
12783
12784 // C / C++ fields
12785 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
12786 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
12787 if (ML && MR) {
12788 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
12789 return;
12790 const ValueDecl *LHSDecl =
12791 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
12792 const ValueDecl *RHSDecl =
12793 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
12794 if (LHSDecl != RHSDecl)
12795 return;
12796 if (LHSDecl->getType().isVolatileQualified())
12797 return;
12798 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12799 if (RefTy->getPointeeType().isVolatileQualified())
12800 return;
12801
12802 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
12803 }
12804
12805 // Objective-C instance variables
12806 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
12807 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
12808 if (OL && OR && OL->getDecl() == OR->getDecl()) {
12809 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
12810 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
12811 if (RL && RR && RL->getDecl() == RR->getDecl())
12812 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
12813 }
12814}
12815
12816// C99 6.5.16.1
12817QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
12818 SourceLocation Loc,
12819 QualType CompoundType) {
12820 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject))((!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject))
? static_cast<void> (0) : __assert_fail ("!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 12820, __PRETTY_FUNCTION__))
;
12821
12822 // Verify that LHS is a modifiable lvalue, and emit error if not.
12823 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
12824 return QualType();
12825
12826 QualType LHSType = LHSExpr->getType();
12827 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
12828 CompoundType;
12829 // OpenCL v1.2 s6.1.1.1 p2:
12830 // The half data type can only be used to declare a pointer to a buffer that
12831 // contains half values
12832 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
12833 LHSType->isHalfType()) {
12834 Diag(Loc, diag::err_opencl_half_load_store) << 1
12835 << LHSType.getUnqualifiedType();
12836 return QualType();
12837 }
12838
12839 AssignConvertType ConvTy;
12840 if (CompoundType.isNull()) {
12841 Expr *RHSCheck = RHS.get();
12842
12843 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
12844
12845 QualType LHSTy(LHSType);
12846 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
12847 if (RHS.isInvalid())
12848 return QualType();
12849 // Special case of NSObject attributes on c-style pointer types.
12850 if (ConvTy == IncompatiblePointer &&
12851 ((Context.isObjCNSObjectType(LHSType) &&
12852 RHSType->isObjCObjectPointerType()) ||
12853 (Context.isObjCNSObjectType(RHSType) &&
12854 LHSType->isObjCObjectPointerType())))
12855 ConvTy = Compatible;
12856
12857 if (ConvTy == Compatible &&
12858 LHSType->isObjCObjectType())
12859 Diag(Loc, diag::err_objc_object_assignment)
12860 << LHSType;
12861
12862 // If the RHS is a unary plus or minus, check to see if they = and + are
12863 // right next to each other. If so, the user may have typo'd "x =+ 4"
12864 // instead of "x += 4".
12865 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
12866 RHSCheck = ICE->getSubExpr();
12867 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
12868 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
12869 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
12870 // Only if the two operators are exactly adjacent.
12871 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
12872 // And there is a space or other character before the subexpr of the
12873 // unary +/-. We don't want to warn on "x=-1".
12874 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
12875 UO->getSubExpr()->getBeginLoc().isFileID()) {
12876 Diag(Loc, diag::warn_not_compound_assign)
12877 << (UO->getOpcode() == UO_Plus ? "+" : "-")
12878 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
12879 }
12880 }
12881
12882 if (ConvTy == Compatible) {
12883 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
12884 // Warn about retain cycles where a block captures the LHS, but
12885 // not if the LHS is a simple variable into which the block is
12886 // being stored...unless that variable can be captured by reference!
12887 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
12888 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
12889 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
12890 checkRetainCycles(LHSExpr, RHS.get());
12891 }
12892
12893 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
12894 LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
12895 // It is safe to assign a weak reference into a strong variable.
12896 // Although this code can still have problems:
12897 // id x = self.weakProp;
12898 // id y = self.weakProp;
12899 // we do not warn to warn spuriously when 'x' and 'y' are on separate
12900 // paths through the function. This should be revisited if
12901 // -Wrepeated-use-of-weak is made flow-sensitive.
12902 // For ObjCWeak only, we do not warn if the assign is to a non-weak
12903 // variable, which will be valid for the current autorelease scope.
12904 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12905 RHS.get()->getBeginLoc()))
12906 getCurFunction()->markSafeWeakUse(RHS.get());
12907
12908 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
12909 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
12910 }
12911 }
12912 } else {
12913 // Compound assignment "x += y"
12914 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
12915 }
12916
12917 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
12918 RHS.get(), AA_Assigning))
12919 return QualType();
12920
12921 CheckForNullPointerDereference(*this, LHSExpr);
12922
12923 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
12924 if (CompoundType.isNull()) {
12925 // C++2a [expr.ass]p5:
12926 // A simple-assignment whose left operand is of a volatile-qualified
12927 // type is deprecated unless the assignment is either a discarded-value
12928 // expression or an unevaluated operand
12929 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
12930 } else {
12931 // C++2a [expr.ass]p6:
12932 // [Compound-assignment] expressions are deprecated if E1 has
12933 // volatile-qualified type
12934 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
12935 }
12936 }
12937
12938 // C99 6.5.16p3: The type of an assignment expression is the type of the
12939 // left operand unless the left operand has qualified type, in which case
12940 // it is the unqualified version of the type of the left operand.
12941 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
12942 // is converted to the type of the assignment expression (above).
12943 // C++ 5.17p1: the type of the assignment expression is that of its left
12944 // operand.
12945 return (getLangOpts().CPlusPlus
12946 ? LHSType : LHSType.getUnqualifiedType());
12947}
12948
12949// Only ignore explicit casts to void.
12950static bool IgnoreCommaOperand(const Expr *E) {
12951 E = E->IgnoreParens();
12952
12953 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
12954 if (CE->getCastKind() == CK_ToVoid) {
12955 return true;
12956 }
12957
12958 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
12959 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
12960 CE->getSubExpr()->getType()->isDependentType()) {
12961 return true;
12962 }
12963 }
12964
12965 return false;
12966}
12967
12968// Look for instances where it is likely the comma operator is confused with
12969// another operator. There is an explicit list of acceptable expressions for
12970// the left hand side of the comma operator, otherwise emit a warning.
12971void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
12972 // No warnings in macros
12973 if (Loc.isMacroID())
12974 return;
12975
12976 // Don't warn in template instantiations.
12977 if (inTemplateInstantiation())
12978 return;
12979
12980 // Scope isn't fine-grained enough to explicitly list the specific cases, so
12981 // instead, skip more than needed, then call back into here with the
12982 // CommaVisitor in SemaStmt.cpp.
12983 // The listed locations are the initialization and increment portions
12984 // of a for loop. The additional checks are on the condition of
12985 // if statements, do/while loops, and for loops.
12986 // Differences in scope flags for C89 mode requires the extra logic.
12987 const unsigned ForIncrementFlags =
12988 getLangOpts().C99 || getLangOpts().CPlusPlus
12989 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
12990 : Scope::ContinueScope | Scope::BreakScope;
12991 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
12992 const unsigned ScopeFlags = getCurScope()->getFlags();
12993 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
12994 (ScopeFlags & ForInitFlags) == ForInitFlags)
12995 return;
12996
12997 // If there are multiple comma operators used together, get the RHS of the
12998 // of the comma operator as the LHS.
12999 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
13000 if (BO->getOpcode() != BO_Comma)
13001 break;
13002 LHS = BO->getRHS();
13003 }
13004
13005 // Only allow some expressions on LHS to not warn.
13006 if (IgnoreCommaOperand(LHS))
13007 return;
13008
13009 Diag(Loc, diag::warn_comma_operator);
13010 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
13011 << LHS->getSourceRange()
13012 << FixItHint::CreateInsertion(LHS->getBeginLoc(),
13013 LangOpts.CPlusPlus ? "static_cast<void>("
13014 : "(void)(")
13015 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
13016 ")");
13017}
13018
13019// C99 6.5.17
13020static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
13021 SourceLocation Loc) {
13022 LHS = S.CheckPlaceholderExpr(LHS.get());
13023 RHS = S.CheckPlaceholderExpr(RHS.get());
13024 if (LHS.isInvalid() || RHS.isInvalid())
13025 return QualType();
13026
13027 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
13028 // operands, but not unary promotions.
13029 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
13030
13031 // So we treat the LHS as a ignored value, and in C++ we allow the
13032 // containing site to determine what should be done with the RHS.
13033 LHS = S.IgnoredValueConversions(LHS.get());
13034 if (LHS.isInvalid())
13035 return QualType();
13036
13037 S.DiagnoseUnusedExprResult(LHS.get());
13038
13039 if (!S.getLangOpts().CPlusPlus) {
13040 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
13041 if (RHS.isInvalid())
13042 return QualType();
13043 if (!RHS.get()->getType()->isVoidType())
13044 S.RequireCompleteType(Loc, RHS.get()->getType(),
13045 diag::err_incomplete_type);
13046 }
13047
13048 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
13049 S.DiagnoseCommaOperator(LHS.get(), Loc);
13050
13051 return RHS.get()->getType();
13052}
13053
13054/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
13055/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
13056static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
13057 ExprValueKind &VK,
13058 ExprObjectKind &OK,
13059 SourceLocation OpLoc,
13060 bool IsInc, bool IsPrefix) {
13061 if (Op->isTypeDependent())
13062 return S.Context.DependentTy;
13063
13064 QualType ResType = Op->getType();
13065 // Atomic types can be used for increment / decrement where the non-atomic
13066 // versions can, so ignore the _Atomic() specifier for the purpose of
13067 // checking.
13068 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
13069 ResType = ResAtomicType->getValueType();
13070
13071 assert(!ResType.isNull() && "no type for increment/decrement expression")((!ResType.isNull() && "no type for increment/decrement expression"
) ? static_cast<void> (0) : __assert_fail ("!ResType.isNull() && \"no type for increment/decrement expression\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 13071, __PRETTY_FUNCTION__))
;
13072
13073 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
13074 // Decrement of bool is not allowed.
13075 if (!IsInc) {
13076 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
13077 return QualType();
13078 }
13079 // Increment of bool sets it to true, but is deprecated.
13080 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
13081 : diag::warn_increment_bool)
13082 << Op->getSourceRange();
13083 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
13084 // Error on enum increments and decrements in C++ mode
13085 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
13086 return QualType();
13087 } else if (ResType->isRealType()) {
13088 // OK!
13089 } else if (ResType->isPointerType()) {
13090 // C99 6.5.2.4p2, 6.5.6p2
13091 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
13092 return QualType();
13093 } else if (ResType->isObjCObjectPointerType()) {
13094 // On modern runtimes, ObjC pointer arithmetic is forbidden.
13095 // Otherwise, we just need a complete type.
13096 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
13097 checkArithmeticOnObjCPointer(S, OpLoc, Op))
13098 return QualType();
13099 } else if (ResType->isAnyComplexType()) {
13100 // C99 does not support ++/-- on complex types, we allow as an extension.
13101 S.Diag(OpLoc, diag::ext_integer_increment_complex)
13102 << ResType << Op->getSourceRange();
13103 } else if (ResType->isPlaceholderType()) {
13104 ExprResult PR = S.CheckPlaceholderExpr(Op);
13105 if (PR.isInvalid()) return QualType();
13106 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
13107 IsInc, IsPrefix);
13108 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
13109 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
13110 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
13111 (ResType->castAs<VectorType>()->getVectorKind() !=
13112 VectorType::AltiVecBool)) {
13113 // The z vector extensions allow ++ and -- for non-bool vectors.
13114 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
13115 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
13116 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
13117 } else {
13118 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
13119 << ResType << int(IsInc) << Op->getSourceRange();
13120 return QualType();
13121 }
13122 // At this point, we know we have a real, complex or pointer type.
13123 // Now make sure the operand is a modifiable lvalue.
13124 if (CheckForModifiableLvalue(Op, OpLoc, S))
13125 return QualType();
13126 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
13127 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
13128 // An operand with volatile-qualified type is deprecated
13129 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
13130 << IsInc << ResType;
13131 }
13132 // In C++, a prefix increment is the same type as the operand. Otherwise
13133 // (in C or with postfix), the increment is the unqualified type of the
13134 // operand.
13135 if (IsPrefix && S.getLangOpts().CPlusPlus) {
13136 VK = VK_LValue;
13137 OK = Op->getObjectKind();
13138 return ResType;
13139 } else {
13140 VK = VK_RValue;
13141 return ResType.getUnqualifiedType();
13142 }
13143}
13144
13145
13146/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
13147/// This routine allows us to typecheck complex/recursive expressions
13148/// where the declaration is needed for type checking. We only need to
13149/// handle cases when the expression references a function designator
13150/// or is an lvalue. Here are some examples:
13151/// - &(x) => x
13152/// - &*****f => f for f a function designator.
13153/// - &s.xx => s
13154/// - &s.zz[1].yy -> s, if zz is an array
13155/// - *(x + 1) -> x, if x is an array
13156/// - &"123"[2] -> 0
13157/// - & __real__ x -> x
13158///
13159/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
13160/// members.
13161static ValueDecl *getPrimaryDecl(Expr *E) {
13162 switch (E->getStmtClass()) {
13163 case Stmt::DeclRefExprClass:
13164 return cast<DeclRefExpr>(E)->getDecl();
13165 case Stmt::MemberExprClass:
13166 // If this is an arrow operator, the address is an offset from
13167 // the base's value, so the object the base refers to is
13168 // irrelevant.
13169 if (cast<MemberExpr>(E)->isArrow())
13170 return nullptr;
13171 // Otherwise, the expression refers to a part of the base
13172 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
13173 case Stmt::ArraySubscriptExprClass: {
13174 // FIXME: This code shouldn't be necessary! We should catch the implicit
13175 // promotion of register arrays earlier.
13176 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
13177 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
13178 if (ICE->getSubExpr()->getType()->isArrayType())
13179 return getPrimaryDecl(ICE->getSubExpr());
13180 }
13181 return nullptr;
13182 }
13183 case Stmt::UnaryOperatorClass: {
13184 UnaryOperator *UO = cast<UnaryOperator>(E);
13185
13186 switch(UO->getOpcode()) {
13187 case UO_Real:
13188 case UO_Imag:
13189 case UO_Extension:
13190 return getPrimaryDecl(UO->getSubExpr());
13191 default:
13192 return nullptr;
13193 }
13194 }
13195 case Stmt::ParenExprClass:
13196 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
13197 case Stmt::ImplicitCastExprClass:
13198 // If the result of an implicit cast is an l-value, we care about
13199 // the sub-expression; otherwise, the result here doesn't matter.
13200 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
13201 case Stmt::CXXUuidofExprClass:
13202 return cast<CXXUuidofExpr>(E)->getGuidDecl();
13203 default:
13204 return nullptr;
13205 }
13206}
13207
13208namespace {
13209enum {
13210 AO_Bit_Field = 0,
13211 AO_Vector_Element = 1,
13212 AO_Property_Expansion = 2,
13213 AO_Register_Variable = 3,
13214 AO_Matrix_Element = 4,
13215 AO_No_Error = 5
13216};
13217}
13218/// Diagnose invalid operand for address of operations.
13219///
13220/// \param Type The type of operand which cannot have its address taken.
13221static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
13222 Expr *E, unsigned Type) {
13223 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
13224}
13225
13226/// CheckAddressOfOperand - The operand of & must be either a function
13227/// designator or an lvalue designating an object. If it is an lvalue, the
13228/// object cannot be declared with storage class register or be a bit field.
13229/// Note: The usual conversions are *not* applied to the operand of the &
13230/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
13231/// In C++, the operand might be an overloaded function name, in which case
13232/// we allow the '&' but retain the overloaded-function type.
13233QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
13234 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
13235 if (PTy->getKind() == BuiltinType::Overload) {
13236 Expr *E = OrigOp.get()->IgnoreParens();
13237 if (!isa<OverloadExpr>(E)) {
13238 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf)((cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) ?
static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 13238, __PRETTY_FUNCTION__))
;
13239 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
13240 << OrigOp.get()->getSourceRange();
13241 return QualType();
13242 }
13243
13244 OverloadExpr *Ovl = cast<OverloadExpr>(E);
13245 if (isa<UnresolvedMemberExpr>(Ovl))
13246 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
13247 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13248 << OrigOp.get()->getSourceRange();
13249 return QualType();
13250 }
13251
13252 return Context.OverloadTy;
13253 }
13254
13255 if (PTy->getKind() == BuiltinType::UnknownAny)
13256 return Context.UnknownAnyTy;
13257
13258 if (PTy->getKind() == BuiltinType::BoundMember) {
13259 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13260 << OrigOp.get()->getSourceRange();
13261 return QualType();
13262 }
13263
13264 OrigOp = CheckPlaceholderExpr(OrigOp.get());
13265 if (OrigOp.isInvalid()) return QualType();
13266 }
13267
13268 if (OrigOp.get()->isTypeDependent())
13269 return Context.DependentTy;
13270
13271 assert(!OrigOp.get()->getType()->isPlaceholderType())((!OrigOp.get()->getType()->isPlaceholderType()) ? static_cast
<void> (0) : __assert_fail ("!OrigOp.get()->getType()->isPlaceholderType()"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 13271, __PRETTY_FUNCTION__))
;
13272
13273 // Make sure to ignore parentheses in subsequent checks
13274 Expr *op = OrigOp.get()->IgnoreParens();
13275
13276 // In OpenCL captures for blocks called as lambda functions
13277 // are located in the private address space. Blocks used in
13278 // enqueue_kernel can be located in a different address space
13279 // depending on a vendor implementation. Thus preventing
13280 // taking an address of the capture to avoid invalid AS casts.
13281 if (LangOpts.OpenCL) {
13282 auto* VarRef = dyn_cast<DeclRefExpr>(op);
13283 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
13284 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
13285 return QualType();
13286 }
13287 }
13288
13289 if (getLangOpts().C99) {
13290 // Implement C99-only parts of addressof rules.
13291 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
13292 if (uOp->getOpcode() == UO_Deref)
13293 // Per C99 6.5.3.2, the address of a deref always returns a valid result
13294 // (assuming the deref expression is valid).
13295 return uOp->getSubExpr()->getType();
13296 }
13297 // Technically, there should be a check for array subscript
13298 // expressions here, but the result of one is always an lvalue anyway.
13299 }
13300 ValueDecl *dcl = getPrimaryDecl(op);
13301
13302 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
13303 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13304 op->getBeginLoc()))
13305 return QualType();
13306
13307 Expr::LValueClassification lval = op->ClassifyLValue(Context);
13308 unsigned AddressOfError = AO_No_Error;
13309
13310 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
13311 bool sfinae = (bool)isSFINAEContext();
13312 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
13313 : diag::ext_typecheck_addrof_temporary)
13314 << op->getType() << op->getSourceRange();
13315 if (sfinae)
13316 return QualType();
13317 // Materialize the temporary as an lvalue so that we can take its address.
13318 OrigOp = op =
13319 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
13320 } else if (isa<ObjCSelectorExpr>(op)) {
13321 return Context.getPointerType(op->getType());
13322 } else if (lval == Expr::LV_MemberFunction) {
13323 // If it's an instance method, make a member pointer.
13324 // The expression must have exactly the form &A::foo.
13325
13326 // If the underlying expression isn't a decl ref, give up.
13327 if (!isa<DeclRefExpr>(op)) {
13328 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13329 << OrigOp.get()->getSourceRange();
13330 return QualType();
13331 }
13332 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
13333 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
13334
13335 // The id-expression was parenthesized.
13336 if (OrigOp.get() != DRE) {
13337 Diag(OpLoc, diag::err_parens_pointer_member_function)
13338 << OrigOp.get()->getSourceRange();
13339
13340 // The method was named without a qualifier.
13341 } else if (!DRE->getQualifier()) {
13342 if (MD->getParent()->getName().empty())
13343 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13344 << op->getSourceRange();
13345 else {
13346 SmallString<32> Str;
13347 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
13348 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13349 << op->getSourceRange()
13350 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
13351 }
13352 }
13353
13354 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
13355 if (isa<CXXDestructorDecl>(MD))
13356 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
13357
13358 QualType MPTy = Context.getMemberPointerType(
13359 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
13360 // Under the MS ABI, lock down the inheritance model now.
13361 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13362 (void)isCompleteType(OpLoc, MPTy);
13363 return MPTy;
13364 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
13365 // C99 6.5.3.2p1
13366 // The operand must be either an l-value or a function designator
13367 if (!op->getType()->isFunctionType()) {
13368 // Use a special diagnostic for loads from property references.
13369 if (isa<PseudoObjectExpr>(op)) {
13370 AddressOfError = AO_Property_Expansion;
13371 } else {
13372 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
13373 << op->getType() << op->getSourceRange();
13374 return QualType();
13375 }
13376 }
13377 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
13378 // The operand cannot be a bit-field
13379 AddressOfError = AO_Bit_Field;
13380 } else if (op->getObjectKind() == OK_VectorComponent) {
13381 // The operand cannot be an element of a vector
13382 AddressOfError = AO_Vector_Element;
13383 } else if (op->getObjectKind() == OK_MatrixComponent) {
13384 // The operand cannot be an element of a matrix.
13385 AddressOfError = AO_Matrix_Element;
13386 } else if (dcl) { // C99 6.5.3.2p1
13387 // We have an lvalue with a decl. Make sure the decl is not declared
13388 // with the register storage-class specifier.
13389 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
13390 // in C++ it is not error to take address of a register
13391 // variable (c++03 7.1.1P3)
13392 if (vd->getStorageClass() == SC_Register &&
13393 !getLangOpts().CPlusPlus) {
13394 AddressOfError = AO_Register_Variable;
13395 }
13396 } else if (isa<MSPropertyDecl>(dcl)) {
13397 AddressOfError = AO_Property_Expansion;
13398 } else if (isa<FunctionTemplateDecl>(dcl)) {
13399 return Context.OverloadTy;
13400 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
13401 // Okay: we can take the address of a field.
13402 // Could be a pointer to member, though, if there is an explicit
13403 // scope qualifier for the class.
13404 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
13405 DeclContext *Ctx = dcl->getDeclContext();
13406 if (Ctx && Ctx->isRecord()) {
13407 if (dcl->getType()->isReferenceType()) {
13408 Diag(OpLoc,
13409 diag::err_cannot_form_pointer_to_member_of_reference_type)
13410 << dcl->getDeclName() << dcl->getType();
13411 return QualType();
13412 }
13413
13414 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
13415 Ctx = Ctx->getParent();
13416
13417 QualType MPTy = Context.getMemberPointerType(
13418 op->getType(),
13419 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
13420 // Under the MS ABI, lock down the inheritance model now.
13421 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13422 (void)isCompleteType(OpLoc, MPTy);
13423 return MPTy;
13424 }
13425 }
13426 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
13427 !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl))
13428 llvm_unreachable("Unknown/unexpected decl type")::llvm::llvm_unreachable_internal("Unknown/unexpected decl type"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 13428)
;
13429 }
13430
13431 if (AddressOfError != AO_No_Error) {
13432 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
13433 return QualType();
13434 }
13435
13436 if (lval == Expr::LV_IncompleteVoidType) {
13437 // Taking the address of a void variable is technically illegal, but we
13438 // allow it in cases which are otherwise valid.
13439 // Example: "extern void x; void* y = &x;".
13440 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
13441 }
13442
13443 // If the operand has type "type", the result has type "pointer to type".
13444 if (op->getType()->isObjCObjectType())
13445 return Context.getObjCObjectPointerType(op->getType());
13446
13447 CheckAddressOfPackedMember(op);
13448
13449 return Context.getPointerType(op->getType());
13450}
13451
13452static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
13453 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
13454 if (!DRE)
13455 return;
13456 const Decl *D = DRE->getDecl();
13457 if (!D)
13458 return;
13459 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
13460 if (!Param)
13461 return;
13462 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
13463 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
13464 return;
13465 if (FunctionScopeInfo *FD = S.getCurFunction())
13466 if (!FD->ModifiedNonNullParams.count(Param))
13467 FD->ModifiedNonNullParams.insert(Param);
13468}
13469
13470/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
13471static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
13472 SourceLocation OpLoc) {
13473 if (Op->isTypeDependent())
13474 return S.Context.DependentTy;
13475
13476 ExprResult ConvResult = S.UsualUnaryConversions(Op);
13477 if (ConvResult.isInvalid())
13478 return QualType();
13479 Op = ConvResult.get();
13480 QualType OpTy = Op->getType();
13481 QualType Result;
13482
13483 if (isa<CXXReinterpretCastExpr>(Op)) {
13484 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
13485 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
13486 Op->getSourceRange());
13487 }
13488
13489 if (const PointerType *PT = OpTy->getAs<PointerType>())
13490 {
13491 Result = PT->getPointeeType();
13492 }
13493 else if (const ObjCObjectPointerType *OPT =
13494 OpTy->getAs<ObjCObjectPointerType>())
13495 Result = OPT->getPointeeType();
13496 else {
13497 ExprResult PR = S.CheckPlaceholderExpr(Op);
13498 if (PR.isInvalid()) return QualType();
13499 if (PR.get() != Op)
13500 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
13501 }
13502
13503 if (Result.isNull()) {
13504 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
13505 << OpTy << Op->getSourceRange();
13506 return QualType();
13507 }
13508
13509 // Note that per both C89 and C99, indirection is always legal, even if Result
13510 // is an incomplete type or void. It would be possible to warn about
13511 // dereferencing a void pointer, but it's completely well-defined, and such a
13512 // warning is unlikely to catch any mistakes. In C++, indirection is not valid
13513 // for pointers to 'void' but is fine for any other pointer type:
13514 //
13515 // C++ [expr.unary.op]p1:
13516 // [...] the expression to which [the unary * operator] is applied shall
13517 // be a pointer to an object type, or a pointer to a function type
13518 if (S.getLangOpts().CPlusPlus && Result->isVoidType())
13519 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
13520 << OpTy << Op->getSourceRange();
13521
13522 // Dereferences are usually l-values...
13523 VK = VK_LValue;
13524
13525 // ...except that certain expressions are never l-values in C.
13526 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
13527 VK = VK_RValue;
13528
13529 return Result;
13530}
13531
13532BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
13533 BinaryOperatorKind Opc;
13534 switch (Kind) {
13535 default: llvm_unreachable("Unknown binop!")::llvm::llvm_unreachable_internal("Unknown binop!", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 13535)
;
13536 case tok::periodstar: Opc = BO_PtrMemD; break;
13537 case tok::arrowstar: Opc = BO_PtrMemI; break;
13538 case tok::star: Opc = BO_Mul; break;
13539 case tok::slash: Opc = BO_Div; break;
13540 case tok::percent: Opc = BO_Rem; break;
13541 case tok::plus: Opc = BO_Add; break;
13542 case tok::minus: Opc = BO_Sub; break;
13543 case tok::lessless: Opc = BO_Shl; break;
13544 case tok::greatergreater: Opc = BO_Shr; break;
13545 case tok::lessequal: Opc = BO_LE; break;
13546 case tok::less: Opc = BO_LT; break;
13547 case tok::greaterequal: Opc = BO_GE; break;
13548 case tok::greater: Opc = BO_GT; break;
13549 case tok::exclaimequal: Opc = BO_NE; break;
13550 case tok::equalequal: Opc = BO_EQ; break;
13551 case tok::spaceship: Opc = BO_Cmp; break;
13552 case tok::amp: Opc = BO_And; break;
13553 case tok::caret: Opc = BO_Xor; break;
13554 case tok::pipe: Opc = BO_Or; break;
13555 case tok::ampamp: Opc = BO_LAnd; break;
13556 case tok::pipepipe: Opc = BO_LOr; break;
13557 case tok::equal: Opc = BO_Assign; break;
13558 case tok::starequal: Opc = BO_MulAssign; break;
13559 case tok::slashequal: Opc = BO_DivAssign; break;
13560 case tok::percentequal: Opc = BO_RemAssign; break;
13561 case tok::plusequal: Opc = BO_AddAssign; break;
13562 case tok::minusequal: Opc = BO_SubAssign; break;
13563 case tok::lesslessequal: Opc = BO_ShlAssign; break;
13564 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
13565 case tok::ampequal: Opc = BO_AndAssign; break;
13566 case tok::caretequal: Opc = BO_XorAssign; break;
13567 case tok::pipeequal: Opc = BO_OrAssign; break;
13568 case tok::comma: Opc = BO_Comma; break;
13569 }
13570 return Opc;
13571}
13572
13573static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
13574 tok::TokenKind Kind) {
13575 UnaryOperatorKind Opc;
13576 switch (Kind) {
13577 default: llvm_unreachable("Unknown unary op!")::llvm::llvm_unreachable_internal("Unknown unary op!", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 13577)
;
13578 case tok::plusplus: Opc = UO_PreInc; break;
13579 case tok::minusminus: Opc = UO_PreDec; break;
13580 case tok::amp: Opc = UO_AddrOf; break;
13581 case tok::star: Opc = UO_Deref; break;
13582 case tok::plus: Opc = UO_Plus; break;
13583 case tok::minus: Opc = UO_Minus; break;
13584 case tok::tilde: Opc = UO_Not; break;
13585 case tok::exclaim: Opc = UO_LNot; break;
13586 case tok::kw___real: Opc = UO_Real; break;
13587 case tok::kw___imag: Opc = UO_Imag; break;
13588 case tok::kw___extension__: Opc = UO_Extension; break;
13589 }
13590 return Opc;
13591}
13592
13593/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
13594/// This warning suppressed in the event of macro expansions.
13595static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
13596 SourceLocation OpLoc, bool IsBuiltin) {
13597 if (S.inTemplateInstantiation())
13598 return;
13599 if (S.isUnevaluatedContext())
13600 return;
13601 if (OpLoc.isInvalid() || OpLoc.isMacroID())
13602 return;
13603 LHSExpr = LHSExpr->IgnoreParenImpCasts();
13604 RHSExpr = RHSExpr->IgnoreParenImpCasts();
13605 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13606 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13607 if (!LHSDeclRef || !RHSDeclRef ||
13608 LHSDeclRef->getLocation().isMacroID() ||
13609 RHSDeclRef->getLocation().isMacroID())
13610 return;
13611 const ValueDecl *LHSDecl =
13612 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
13613 const ValueDecl *RHSDecl =
13614 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
13615 if (LHSDecl != RHSDecl)
13616 return;
13617 if (LHSDecl->getType().isVolatileQualified())
13618 return;
13619 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13620 if (RefTy->getPointeeType().isVolatileQualified())
13621 return;
13622
13623 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
13624 : diag::warn_self_assignment_overloaded)
13625 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
13626 << RHSExpr->getSourceRange();
13627}
13628
13629/// Check if a bitwise-& is performed on an Objective-C pointer. This
13630/// is usually indicative of introspection within the Objective-C pointer.
13631static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
13632 SourceLocation OpLoc) {
13633 if (!S.getLangOpts().ObjC)
13634 return;
13635
13636 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
13637 const Expr *LHS = L.get();
13638 const Expr *RHS = R.get();
13639
13640 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13641 ObjCPointerExpr = LHS;
13642 OtherExpr = RHS;
13643 }
13644 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13645 ObjCPointerExpr = RHS;
13646 OtherExpr = LHS;
13647 }
13648
13649 // This warning is deliberately made very specific to reduce false
13650 // positives with logic that uses '&' for hashing. This logic mainly
13651 // looks for code trying to introspect into tagged pointers, which
13652 // code should generally never do.
13653 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
13654 unsigned Diag = diag::warn_objc_pointer_masking;
13655 // Determine if we are introspecting the result of performSelectorXXX.
13656 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
13657 // Special case messages to -performSelector and friends, which
13658 // can return non-pointer values boxed in a pointer value.
13659 // Some clients may wish to silence warnings in this subcase.
13660 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
13661 Selector S = ME->getSelector();
13662 StringRef SelArg0 = S.getNameForSlot(0);
13663 if (SelArg0.startswith("performSelector"))
13664 Diag = diag::warn_objc_pointer_masking_performSelector;
13665 }
13666
13667 S.Diag(OpLoc, Diag)
13668 << ObjCPointerExpr->getSourceRange();
13669 }
13670}
13671
13672static NamedDecl *getDeclFromExpr(Expr *E) {
13673 if (!E)
13674 return nullptr;
13675 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
13676 return DRE->getDecl();
13677 if (auto *ME = dyn_cast<MemberExpr>(E))
13678 return ME->getMemberDecl();
13679 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
13680 return IRE->getDecl();
13681 return nullptr;
13682}
13683
13684// This helper function promotes a binary operator's operands (which are of a
13685// half vector type) to a vector of floats and then truncates the result to
13686// a vector of either half or short.
13687static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
13688 BinaryOperatorKind Opc, QualType ResultTy,
13689 ExprValueKind VK, ExprObjectKind OK,
13690 bool IsCompAssign, SourceLocation OpLoc,
13691 FPOptionsOverride FPFeatures) {
13692 auto &Context = S.getASTContext();
13693 assert((isVector(ResultTy, Context.HalfTy) ||(((isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context
.ShortTy)) && "Result must be a vector of half or short"
) ? static_cast<void> (0) : __assert_fail ("(isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context.ShortTy)) && \"Result must be a vector of half or short\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 13695, __PRETTY_FUNCTION__))
13694 isVector(ResultTy, Context.ShortTy)) &&(((isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context
.ShortTy)) && "Result must be a vector of half or short"
) ? static_cast<void> (0) : __assert_fail ("(isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context.ShortTy)) && \"Result must be a vector of half or short\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 13695, __PRETTY_FUNCTION__))
13695 "Result must be a vector of half or short")(((isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context
.ShortTy)) && "Result must be a vector of half or short"
) ? static_cast<void> (0) : __assert_fail ("(isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context.ShortTy)) && \"Result must be a vector of half or short\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 13695, __PRETTY_FUNCTION__))
;
13696 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&((isVector(LHS.get()->getType(), Context.HalfTy) &&
isVector(RHS.get()->getType(), Context.HalfTy) &&
"both operands expected to be a half vector") ? static_cast<
void> (0) : __assert_fail ("isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && \"both operands expected to be a half vector\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 13698, __PRETTY_FUNCTION__))
13697 isVector(RHS.get()->getType(), Context.HalfTy) &&((isVector(LHS.get()->getType(), Context.HalfTy) &&
isVector(RHS.get()->getType(), Context.HalfTy) &&
"both operands expected to be a half vector") ? static_cast<
void> (0) : __assert_fail ("isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && \"both operands expected to be a half vector\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 13698, __PRETTY_FUNCTION__))
13698 "both operands expected to be a half vector")((isVector(LHS.get()->getType(), Context.HalfTy) &&
isVector(RHS.get()->getType(), Context.HalfTy) &&
"both operands expected to be a half vector") ? static_cast<
void> (0) : __assert_fail ("isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && \"both operands expected to be a half vector\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 13698, __PRETTY_FUNCTION__))
;
13699
13700 RHS = convertVector(RHS.get(), Context.FloatTy, S);
13701 QualType BinOpResTy = RHS.get()->getType();
13702
13703 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
13704 // change BinOpResTy to a vector of ints.
13705 if (isVector(ResultTy, Context.ShortTy))
13706 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
13707
13708 if (IsCompAssign)
13709 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13710 ResultTy, VK, OK, OpLoc, FPFeatures,
13711 BinOpResTy, BinOpResTy);
13712
13713 LHS = convertVector(LHS.get(), Context.FloatTy, S);
13714 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13715 BinOpResTy, VK, OK, OpLoc, FPFeatures);
13716 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
13717}
13718
13719static std::pair<ExprResult, ExprResult>
13720CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
13721 Expr *RHSExpr) {
13722 ExprResult LHS = LHSExpr, RHS = RHSExpr;
13723 if (!S.Context.isDependenceAllowed()) {
13724 // C cannot handle TypoExpr nodes on either side of a binop because it
13725 // doesn't handle dependent types properly, so make sure any TypoExprs have
13726 // been dealt with before checking the operands.
13727 LHS = S.CorrectDelayedTyposInExpr(LHS);
13728 RHS = S.CorrectDelayedTyposInExpr(
13729 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
13730 [Opc, LHS](Expr *E) {
13731 if (Opc != BO_Assign)
13732 return ExprResult(E);
13733 // Avoid correcting the RHS to the same Expr as the LHS.
13734 Decl *D = getDeclFromExpr(E);
13735 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
13736 });
13737 }
13738 return std::make_pair(LHS, RHS);
13739}
13740
13741/// Returns true if conversion between vectors of halfs and vectors of floats
13742/// is needed.
13743static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
13744 Expr *E0, Expr *E1 = nullptr) {
13745 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
13746 Ctx.getTargetInfo().useFP16ConversionIntrinsics())
13747 return false;
13748
13749 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
13750 QualType Ty = E->IgnoreImplicit()->getType();
13751
13752 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
13753 // to vectors of floats. Although the element type of the vectors is __fp16,
13754 // the vectors shouldn't be treated as storage-only types. See the
13755 // discussion here: https://reviews.llvm.org/rG825235c140e7
13756 if (const VectorType *VT = Ty->getAs<VectorType>()) {
13757 if (VT->getVectorKind() == VectorType::NeonVector)
13758 return false;
13759 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
13760 }
13761 return false;
13762 };
13763
13764 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
13765}
13766
13767/// CreateBuiltinBinOp - Creates a new built-in binary operation with
13768/// operator @p Opc at location @c TokLoc. This routine only supports
13769/// built-in operations; ActOnBinOp handles overloaded operators.
13770ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
13771 BinaryOperatorKind Opc,
13772 Expr *LHSExpr, Expr *RHSExpr) {
13773 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
13774 // The syntax only allows initializer lists on the RHS of assignment,
13775 // so we don't need to worry about accepting invalid code for
13776 // non-assignment operators.
13777 // C++11 5.17p9:
13778 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
13779 // of x = {} is x = T().
13780 InitializationKind Kind = InitializationKind::CreateDirectList(
13781 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13782 InitializedEntity Entity =
13783 InitializedEntity::InitializeTemporary(LHSExpr->getType());
13784 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
13785 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
13786 if (Init.isInvalid())
13787 return Init;
13788 RHSExpr = Init.get();
13789 }
13790
13791 ExprResult LHS = LHSExpr, RHS = RHSExpr;
13792 QualType ResultTy; // Result type of the binary operator.
13793 // The following two variables are used for compound assignment operators
13794 QualType CompLHSTy; // Type of LHS after promotions for computation
13795 QualType CompResultTy; // Type of computation result
13796 ExprValueKind VK = VK_RValue;
13797 ExprObjectKind OK = OK_Ordinary;
13798 bool ConvertHalfVec = false;
13799
13800 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
13801 if (!LHS.isUsable() || !RHS.isUsable())
13802 return ExprError();
13803
13804 if (getLangOpts().OpenCL) {
13805 QualType LHSTy = LHSExpr->getType();
13806 QualType RHSTy = RHSExpr->getType();
13807 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
13808 // the ATOMIC_VAR_INIT macro.
13809 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
13810 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13811 if (BO_Assign == Opc)
13812 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
13813 else
13814 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13815 return ExprError();
13816 }
13817
13818 // OpenCL special types - image, sampler, pipe, and blocks are to be used
13819 // only with a builtin functions and therefore should be disallowed here.
13820 if (LHSTy->isImageType() || RHSTy->isImageType() ||
13821 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
13822 LHSTy->isPipeType() || RHSTy->isPipeType() ||
13823 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
13824 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13825 return ExprError();
13826 }
13827 }
13828
13829 switch (Opc) {
13830 case BO_Assign:
13831 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
13832 if (getLangOpts().CPlusPlus &&
13833 LHS.get()->getObjectKind() != OK_ObjCProperty) {
13834 VK = LHS.get()->getValueKind();
13835 OK = LHS.get()->getObjectKind();
13836 }
13837 if (!ResultTy.isNull()) {
13838 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13839 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
13840
13841 // Avoid copying a block to the heap if the block is assigned to a local
13842 // auto variable that is declared in the same scope as the block. This
13843 // optimization is unsafe if the local variable is declared in an outer
13844 // scope. For example:
13845 //
13846 // BlockTy b;
13847 // {
13848 // b = ^{...};
13849 // }
13850 // // It is unsafe to invoke the block here if it wasn't copied to the
13851 // // heap.
13852 // b();
13853
13854 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
13855 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
13856 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
13857 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
13858 BE->getBlockDecl()->setCanAvoidCopyToHeap();
13859
13860 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
13861 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
13862 NTCUC_Assignment, NTCUK_Copy);
13863 }
13864 RecordModifiableNonNullParam(*this, LHS.get());
13865 break;
13866 case BO_PtrMemD:
13867 case BO_PtrMemI:
13868 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
13869 Opc == BO_PtrMemI);
13870 break;
13871 case BO_Mul:
13872 case BO_Div:
13873 ConvertHalfVec = true;
13874 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
13875 Opc == BO_Div);
13876 break;
13877 case BO_Rem:
13878 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
13879 break;
13880 case BO_Add:
13881 ConvertHalfVec = true;
13882 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
13883 break;
13884 case BO_Sub:
13885 ConvertHalfVec = true;
13886 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
13887 break;
13888 case BO_Shl:
13889 case BO_Shr:
13890 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
13891 break;
13892 case BO_LE:
13893 case BO_LT:
13894 case BO_GE:
13895 case BO_GT:
13896 ConvertHalfVec = true;
13897 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13898 break;
13899 case BO_EQ:
13900 case BO_NE:
13901 ConvertHalfVec = true;
13902 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13903 break;
13904 case BO_Cmp:
13905 ConvertHalfVec = true;
13906 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13907 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl())((ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()) ? static_cast
<void> (0) : __assert_fail ("ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 13907, __PRETTY_FUNCTION__))
;
13908 break;
13909 case BO_And:
13910 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
13911 LLVM_FALLTHROUGH[[gnu::fallthrough]];
13912 case BO_Xor:
13913 case BO_Or:
13914 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13915 break;
13916 case BO_LAnd:
13917 case BO_LOr:
13918 ConvertHalfVec = true;
13919 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
13920 break;
13921 case BO_MulAssign:
13922 case BO_DivAssign:
13923 ConvertHalfVec = true;
13924 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
13925 Opc == BO_DivAssign);
13926 CompLHSTy = CompResultTy;
13927 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13928 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13929 break;
13930 case BO_RemAssign:
13931 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
13932 CompLHSTy = CompResultTy;
13933 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13934 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13935 break;
13936 case BO_AddAssign:
13937 ConvertHalfVec = true;
13938 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
13939 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13940 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13941 break;
13942 case BO_SubAssign:
13943 ConvertHalfVec = true;
13944 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
13945 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13946 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13947 break;
13948 case BO_ShlAssign:
13949 case BO_ShrAssign:
13950 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
13951 CompLHSTy = CompResultTy;
13952 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13953 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13954 break;
13955 case BO_AndAssign:
13956 case BO_OrAssign: // fallthrough
13957 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13958 LLVM_FALLTHROUGH[[gnu::fallthrough]];
13959 case BO_XorAssign:
13960 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13961 CompLHSTy = CompResultTy;
13962 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13963 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13964 break;
13965 case BO_Comma:
13966 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
13967 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
13968 VK = RHS.get()->getValueKind();
13969 OK = RHS.get()->getObjectKind();
13970 }
13971 break;
13972 }
13973 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
13974 return ExprError();
13975
13976 // Some of the binary operations require promoting operands of half vector to
13977 // float vectors and truncating the result back to half vector. For now, we do
13978 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
13979 // arm64).
13980 assert((((Opc == BO_Comma || isVector(RHS.get()->getType(), Context
.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy)
) && "both sides are half vectors or neither sides are"
) ? static_cast<void> (0) : __assert_fail ("(Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy)) && \"both sides are half vectors or neither sides are\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 13983, __PRETTY_FUNCTION__))
13981 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==(((Opc == BO_Comma || isVector(RHS.get()->getType(), Context
.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy)
) && "both sides are half vectors or neither sides are"
) ? static_cast<void> (0) : __assert_fail ("(Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy)) && \"both sides are half vectors or neither sides are\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 13983, __PRETTY_FUNCTION__))
13982 isVector(LHS.get()->getType(), Context.HalfTy)) &&(((Opc == BO_Comma || isVector(RHS.get()->getType(), Context
.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy)
) && "both sides are half vectors or neither sides are"
) ? static_cast<void> (0) : __assert_fail ("(Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy)) && \"both sides are half vectors or neither sides are\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 13983, __PRETTY_FUNCTION__))
13983 "both sides are half vectors or neither sides are")(((Opc == BO_Comma || isVector(RHS.get()->getType(), Context
.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy)
) && "both sides are half vectors or neither sides are"
) ? static_cast<void> (0) : __assert_fail ("(Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy)) && \"both sides are half vectors or neither sides are\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 13983, __PRETTY_FUNCTION__))
;
13984 ConvertHalfVec =
13985 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
13986
13987 // Check for array bounds violations for both sides of the BinaryOperator
13988 CheckArrayAccess(LHS.get());
13989 CheckArrayAccess(RHS.get());
13990
13991 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
13992 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
13993 &Context.Idents.get("object_setClass"),
13994 SourceLocation(), LookupOrdinaryName);
13995 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
13996 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
13997 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
13998 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
13999 "object_setClass(")
14000 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
14001 ",")
14002 << FixItHint::CreateInsertion(RHSLocEnd, ")");
14003 }
14004 else
14005 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
14006 }
14007 else if (const ObjCIvarRefExpr *OIRE =
14008 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
14009 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
14010
14011 // Opc is not a compound assignment if CompResultTy is null.
14012 if (CompResultTy.isNull()) {
14013 if (ConvertHalfVec)
14014 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
14015 OpLoc, CurFPFeatureOverrides());
14016 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
14017 VK, OK, OpLoc, CurFPFeatureOverrides());
14018 }
14019
14020 // Handle compound assignments.
14021 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
14022 OK_ObjCProperty) {
14023 VK = VK_LValue;
14024 OK = LHS.get()->getObjectKind();
14025 }
14026
14027 // The LHS is not converted to the result type for fixed-point compound
14028 // assignment as the common type is computed on demand. Reset the CompLHSTy
14029 // to the LHS type we would have gotten after unary conversions.
14030 if (CompResultTy->isFixedPointType())
14031 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
14032
14033 if (ConvertHalfVec)
14034 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
14035 OpLoc, CurFPFeatureOverrides());
14036
14037 return CompoundAssignOperator::Create(
14038 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
14039 CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
14040}
14041
14042/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
14043/// operators are mixed in a way that suggests that the programmer forgot that
14044/// comparison operators have higher precedence. The most typical example of
14045/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
14046static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
14047 SourceLocation OpLoc, Expr *LHSExpr,
14048 Expr *RHSExpr) {
14049 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
14050 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
14051
14052 // Check that one of the sides is a comparison operator and the other isn't.
14053 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
14054 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
14055 if (isLeftComp == isRightComp)
14056 return;
14057
14058 // Bitwise operations are sometimes used as eager logical ops.
14059 // Don't diagnose this.
14060 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
14061 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
14062 if (isLeftBitwise || isRightBitwise)
14063 return;
14064
14065 SourceRange DiagRange = isLeftComp
14066 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
14067 : SourceRange(OpLoc, RHSExpr->getEndLoc());
14068 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
14069 SourceRange ParensRange =
14070 isLeftComp
14071 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
14072 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
14073
14074 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
14075 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
14076 SuggestParentheses(Self, OpLoc,
14077 Self.PDiag(diag::note_precedence_silence) << OpStr,
14078 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
14079 SuggestParentheses(Self, OpLoc,
14080 Self.PDiag(diag::note_precedence_bitwise_first)
14081 << BinaryOperator::getOpcodeStr(Opc),
14082 ParensRange);
14083}
14084
14085/// It accepts a '&&' expr that is inside a '||' one.
14086/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
14087/// in parentheses.
14088static void
14089EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
14090 BinaryOperator *Bop) {
14091 assert(Bop->getOpcode() == BO_LAnd)((Bop->getOpcode() == BO_LAnd) ? static_cast<void> (
0) : __assert_fail ("Bop->getOpcode() == BO_LAnd", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 14091, __PRETTY_FUNCTION__))
;
14092 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
14093 << Bop->getSourceRange() << OpLoc;
14094 SuggestParentheses(Self, Bop->getOperatorLoc(),
14095 Self.PDiag(diag::note_precedence_silence)
14096 << Bop->getOpcodeStr(),
14097 Bop->getSourceRange());
14098}
14099
14100/// Returns true if the given expression can be evaluated as a constant
14101/// 'true'.
14102static bool EvaluatesAsTrue(Sema &S, Expr *E) {
14103 bool Res;
14104 return !E->isValueDependent() &&
14105 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
14106}
14107
14108/// Returns true if the given expression can be evaluated as a constant
14109/// 'false'.
14110static bool EvaluatesAsFalse(Sema &S, Expr *E) {
14111 bool Res;
14112 return !E->isValueDependent() &&
14113 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
14114}
14115
14116/// Look for '&&' in the left hand of a '||' expr.
14117static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
14118 Expr *LHSExpr, Expr *RHSExpr) {
14119 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
14120 if (Bop->getOpcode() == BO_LAnd) {
14121 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
14122 if (EvaluatesAsFalse(S, RHSExpr))
14123 return;
14124 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
14125 if (!EvaluatesAsTrue(S, Bop->getLHS()))
14126 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14127 } else if (Bop->getOpcode() == BO_LOr) {
14128 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
14129 // If it's "a || b && 1 || c" we didn't warn earlier for
14130 // "a || b && 1", but warn now.
14131 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
14132 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
14133 }
14134 }
14135 }
14136}
14137
14138/// Look for '&&' in the right hand of a '||' expr.
14139static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
14140 Expr *LHSExpr, Expr *RHSExpr) {
14141 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
14142 if (Bop->getOpcode() == BO_LAnd) {
14143 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
14144 if (EvaluatesAsFalse(S, LHSExpr))
14145 return;
14146 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
14147 if (!EvaluatesAsTrue(S, Bop->getRHS()))
14148 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14149 }
14150 }
14151}
14152
14153/// Look for bitwise op in the left or right hand of a bitwise op with
14154/// lower precedence and emit a diagnostic together with a fixit hint that wraps
14155/// the '&' expression in parentheses.
14156static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
14157 SourceLocation OpLoc, Expr *SubExpr) {
14158 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14159 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
14160 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
14161 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
14162 << Bop->getSourceRange() << OpLoc;
14163 SuggestParentheses(S, Bop->getOperatorLoc(),
14164 S.PDiag(diag::note_precedence_silence)
14165 << Bop->getOpcodeStr(),
14166 Bop->getSourceRange());
14167 }
14168 }
14169}
14170
14171static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
14172 Expr *SubExpr, StringRef Shift) {
14173 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14174 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
14175 StringRef Op = Bop->getOpcodeStr();
14176 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
14177 << Bop->getSourceRange() << OpLoc << Shift << Op;
14178 SuggestParentheses(S, Bop->getOperatorLoc(),
14179 S.PDiag(diag::note_precedence_silence) << Op,
14180 Bop->getSourceRange());
14181 }
14182 }
14183}
14184
14185static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
14186 Expr *LHSExpr, Expr *RHSExpr) {
14187 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
14188 if (!OCE)
14189 return;
14190
14191 FunctionDecl *FD = OCE->getDirectCallee();
14192 if (!FD || !FD->isOverloadedOperator())
14193 return;
14194
14195 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
14196 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
14197 return;
14198
14199 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
14200 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
14201 << (Kind == OO_LessLess);
14202 SuggestParentheses(S, OCE->getOperatorLoc(),
14203 S.PDiag(diag::note_precedence_silence)
14204 << (Kind == OO_LessLess ? "<<" : ">>"),
14205 OCE->getSourceRange());
14206 SuggestParentheses(
14207 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
14208 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
14209}
14210
14211/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
14212/// precedence.
14213static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
14214 SourceLocation OpLoc, Expr *LHSExpr,
14215 Expr *RHSExpr){
14216 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
14217 if (BinaryOperator::isBitwiseOp(Opc))
14218 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
14219
14220 // Diagnose "arg1 & arg2 | arg3"
14221 if ((Opc == BO_Or || Opc == BO_Xor) &&
14222 !OpLoc.isMacroID()/* Don't warn in macros. */) {
14223 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
14224 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
14225 }
14226
14227 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
14228 // We don't warn for 'assert(a || b && "bad")' since this is safe.
14229 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
14230 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
14231 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
14232 }
14233
14234 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
14235 || Opc == BO_Shr) {
14236 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
14237 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
14238 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
14239 }
14240
14241 // Warn on overloaded shift operators and comparisons, such as:
14242 // cout << 5 == 4;
14243 if (BinaryOperator::isComparisonOp(Opc))
14244 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
14245}
14246
14247// Binary Operators. 'Tok' is the token for the operator.
14248ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
14249 tok::TokenKind Kind,
14250 Expr *LHSExpr, Expr *RHSExpr) {
14251 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
14252 assert(LHSExpr && "ActOnBinOp(): missing left expression")((LHSExpr && "ActOnBinOp(): missing left expression")
? static_cast<void> (0) : __assert_fail ("LHSExpr && \"ActOnBinOp(): missing left expression\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 14252, __PRETTY_FUNCTION__))
;
14253 assert(RHSExpr && "ActOnBinOp(): missing right expression")((RHSExpr && "ActOnBinOp(): missing right expression"
) ? static_cast<void> (0) : __assert_fail ("RHSExpr && \"ActOnBinOp(): missing right expression\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 14253, __PRETTY_FUNCTION__))
;
14254
14255 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
14256 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
14257
14258 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
14259}
14260
14261void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
14262 UnresolvedSetImpl &Functions) {
14263 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
14264 if (OverOp != OO_None && OverOp != OO_Equal)
14265 LookupOverloadedOperatorName(OverOp, S, Functions);
14266
14267 // In C++20 onwards, we may have a second operator to look up.
14268 if (getLangOpts().CPlusPlus20) {
14269 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
14270 LookupOverloadedOperatorName(ExtraOp, S, Functions);
14271 }
14272}
14273
14274/// Build an overloaded binary operator expression in the given scope.
14275static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
14276 BinaryOperatorKind Opc,
14277 Expr *LHS, Expr *RHS) {
14278 switch (Opc) {
14279 case BO_Assign:
14280 case BO_DivAssign:
14281 case BO_RemAssign:
14282 case BO_SubAssign:
14283 case BO_AndAssign:
14284 case BO_OrAssign:
14285 case BO_XorAssign:
14286 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
14287 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
14288 break;
14289 default:
14290 break;
14291 }
14292
14293 // Find all of the overloaded operators visible from this point.
14294 UnresolvedSet<16> Functions;
14295 S.LookupBinOp(Sc, OpLoc, Opc, Functions);
14296
14297 // Build the (potentially-overloaded, potentially-dependent)
14298 // binary operation.
14299 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
14300}
14301
14302ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
14303 BinaryOperatorKind Opc,
14304 Expr *LHSExpr, Expr *RHSExpr) {
14305 ExprResult LHS, RHS;
14306 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14307 if (!LHS.isUsable() || !RHS.isUsable())
14308 return ExprError();
14309 LHSExpr = LHS.get();
14310 RHSExpr = RHS.get();
14311
14312 // We want to end up calling one of checkPseudoObjectAssignment
14313 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
14314 // both expressions are overloadable or either is type-dependent),
14315 // or CreateBuiltinBinOp (in any other case). We also want to get
14316 // any placeholder types out of the way.
14317
14318 // Handle pseudo-objects in the LHS.
14319 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
14320 // Assignments with a pseudo-object l-value need special analysis.
14321 if (pty->getKind() == BuiltinType::PseudoObject &&
14322 BinaryOperator::isAssignmentOp(Opc))
14323 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
14324
14325 // Don't resolve overloads if the other type is overloadable.
14326 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
14327 // We can't actually test that if we still have a placeholder,
14328 // though. Fortunately, none of the exceptions we see in that
14329 // code below are valid when the LHS is an overload set. Note
14330 // that an overload set can be dependently-typed, but it never
14331 // instantiates to having an overloadable type.
14332 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14333 if (resolvedRHS.isInvalid()) return ExprError();
14334 RHSExpr = resolvedRHS.get();
14335
14336 if (RHSExpr->isTypeDependent() ||
14337 RHSExpr->getType()->isOverloadableType())
14338 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14339 }
14340
14341 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
14342 // template, diagnose the missing 'template' keyword instead of diagnosing
14343 // an invalid use of a bound member function.
14344 //
14345 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
14346 // to C++1z [over.over]/1.4, but we already checked for that case above.
14347 if (Opc == BO_LT && inTemplateInstantiation() &&
14348 (pty->getKind() == BuiltinType::BoundMember ||
14349 pty->getKind() == BuiltinType::Overload)) {
14350 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
14351 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
14352 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
14353 return isa<FunctionTemplateDecl>(ND);
14354 })) {
14355 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
14356 : OE->getNameLoc(),
14357 diag::err_template_kw_missing)
14358 << OE->getName().getAsString() << "";
14359 return ExprError();
14360 }
14361 }
14362
14363 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
14364 if (LHS.isInvalid()) return ExprError();
14365 LHSExpr = LHS.get();
14366 }
14367
14368 // Handle pseudo-objects in the RHS.
14369 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
14370 // An overload in the RHS can potentially be resolved by the type
14371 // being assigned to.
14372 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
14373 if (getLangOpts().CPlusPlus &&
14374 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
14375 LHSExpr->getType()->isOverloadableType()))
14376 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14377
14378 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14379 }
14380
14381 // Don't resolve overloads if the other type is overloadable.
14382 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
14383 LHSExpr->getType()->isOverloadableType())
14384 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14385
14386 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14387 if (!resolvedRHS.isUsable()) return ExprError();
14388 RHSExpr = resolvedRHS.get();
14389 }
14390
14391 if (getLangOpts().CPlusPlus) {
14392 // If either expression is type-dependent, always build an
14393 // overloaded op.
14394 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
14395 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14396
14397 // Otherwise, build an overloaded op if either expression has an
14398 // overloadable type.
14399 if (LHSExpr->getType()->isOverloadableType() ||
14400 RHSExpr->getType()->isOverloadableType())
14401 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14402 }
14403
14404 if (getLangOpts().RecoveryAST &&
14405 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
14406 assert(!getLangOpts().CPlusPlus)((!getLangOpts().CPlusPlus) ? static_cast<void> (0) : __assert_fail
("!getLangOpts().CPlusPlus", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 14406, __PRETTY_FUNCTION__))
;
14407 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&(((LHSExpr->containsErrors() || RHSExpr->containsErrors
()) && "Should only occur in error-recovery path.") ?
static_cast<void> (0) : __assert_fail ("(LHSExpr->containsErrors() || RHSExpr->containsErrors()) && \"Should only occur in error-recovery path.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 14408, __PRETTY_FUNCTION__))
14408 "Should only occur in error-recovery path.")(((LHSExpr->containsErrors() || RHSExpr->containsErrors
()) && "Should only occur in error-recovery path.") ?
static_cast<void> (0) : __assert_fail ("(LHSExpr->containsErrors() || RHSExpr->containsErrors()) && \"Should only occur in error-recovery path.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 14408, __PRETTY_FUNCTION__))
;
14409 if (BinaryOperator::isCompoundAssignmentOp(Opc))
14410 // C [6.15.16] p3:
14411 // An assignment expression has the value of the left operand after the
14412 // assignment, but is not an lvalue.
14413 return CompoundAssignOperator::Create(
14414 Context, LHSExpr, RHSExpr, Opc,
14415 LHSExpr->getType().getUnqualifiedType(), VK_RValue, OK_Ordinary,
14416 OpLoc, CurFPFeatureOverrides());
14417 QualType ResultType;
14418 switch (Opc) {
14419 case BO_Assign:
14420 ResultType = LHSExpr->getType().getUnqualifiedType();
14421 break;
14422 case BO_LT:
14423 case BO_GT:
14424 case BO_LE:
14425 case BO_GE:
14426 case BO_EQ:
14427 case BO_NE:
14428 case BO_LAnd:
14429 case BO_LOr:
14430 // These operators have a fixed result type regardless of operands.
14431 ResultType = Context.IntTy;
14432 break;
14433 case BO_Comma:
14434 ResultType = RHSExpr->getType();
14435 break;
14436 default:
14437 ResultType = Context.DependentTy;
14438 break;
14439 }
14440 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
14441 VK_RValue, OK_Ordinary, OpLoc,
14442 CurFPFeatureOverrides());
14443 }
14444
14445 // Build a built-in binary operation.
14446 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14447}
14448
14449static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
14450 if (T.isNull() || T->isDependentType())
14451 return false;
14452
14453 if (!T->isPromotableIntegerType())
14454 return true;
14455
14456 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
14457}
14458
14459ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
14460 UnaryOperatorKind Opc,
14461 Expr *InputExpr) {
14462 ExprResult Input = InputExpr;
14463 ExprValueKind VK = VK_RValue;
14464 ExprObjectKind OK = OK_Ordinary;
14465 QualType resultType;
14466 bool CanOverflow = false;
14467
14468 bool ConvertHalfVec = false;
14469 if (getLangOpts().OpenCL) {
14470 QualType Ty = InputExpr->getType();
14471 // The only legal unary operation for atomics is '&'.
14472 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
14473 // OpenCL special types - image, sampler, pipe, and blocks are to be used
14474 // only with a builtin functions and therefore should be disallowed here.
14475 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
14476 || Ty->isBlockPointerType())) {
14477 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14478 << InputExpr->getType()
14479 << Input.get()->getSourceRange());
14480 }
14481 }
14482
14483 switch (Opc) {
14484 case UO_PreInc:
14485 case UO_PreDec:
14486 case UO_PostInc:
14487 case UO_PostDec:
14488 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
14489 OpLoc,
14490 Opc == UO_PreInc ||
14491 Opc == UO_PostInc,
14492 Opc == UO_PreInc ||
14493 Opc == UO_PreDec);
14494 CanOverflow = isOverflowingIntegerType(Context, resultType);
14495 break;
14496 case UO_AddrOf:
14497 resultType = CheckAddressOfOperand(Input, OpLoc);
14498 CheckAddressOfNoDeref(InputExpr);
14499 RecordModifiableNonNullParam(*this, InputExpr);
14500 break;
14501 case UO_Deref: {
14502 Input = DefaultFunctionArrayLvalueConversion(Input.get());
14503 if (Input.isInvalid()) return ExprError();
14504 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
14505 break;
14506 }
14507 case UO_Plus:
14508 case UO_Minus:
14509 CanOverflow = Opc == UO_Minus &&
14510 isOverflowingIntegerType(Context, Input.get()->getType());
14511 Input = UsualUnaryConversions(Input.get());
14512 if (Input.isInvalid()) return ExprError();
14513 // Unary plus and minus require promoting an operand of half vector to a
14514 // float vector and truncating the result back to a half vector. For now, we
14515 // do this only when HalfArgsAndReturns is set (that is, when the target is
14516 // arm or arm64).
14517 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
14518
14519 // If the operand is a half vector, promote it to a float vector.
14520 if (ConvertHalfVec)
14521 Input = convertVector(Input.get(), Context.FloatTy, *this);
14522 resultType = Input.get()->getType();
14523 if (resultType->isDependentType())
14524 break;
14525 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
14526 break;
14527 else if (resultType->isVectorType() &&
14528 // The z vector extensions don't allow + or - with bool vectors.
14529 (!Context.getLangOpts().ZVector ||
14530 resultType->castAs<VectorType>()->getVectorKind() !=
14531 VectorType::AltiVecBool))
14532 break;
14533 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
14534 Opc == UO_Plus &&
14535 resultType->isPointerType())
14536 break;
14537
14538 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14539 << resultType << Input.get()->getSourceRange());
14540
14541 case UO_Not: // bitwise complement
14542 Input = UsualUnaryConversions(Input.get());
14543 if (Input.isInvalid())
14544 return ExprError();
14545 resultType = Input.get()->getType();
14546 if (resultType->isDependentType())
14547 break;
14548 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
14549 if (resultType->isComplexType() || resultType->isComplexIntegerType())
14550 // C99 does not support '~' for complex conjugation.
14551 Diag(OpLoc, diag::ext_integer_complement_complex)
14552 << resultType << Input.get()->getSourceRange();
14553 else if (resultType->hasIntegerRepresentation())
14554 break;
14555 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
14556 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
14557 // on vector float types.
14558 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14559 if (!T->isIntegerType())
14560 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14561 << resultType << Input.get()->getSourceRange());
14562 } else {
14563 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14564 << resultType << Input.get()->getSourceRange());
14565 }
14566 break;
14567
14568 case UO_LNot: // logical negation
14569 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
14570 Input = DefaultFunctionArrayLvalueConversion(Input.get());
14571 if (Input.isInvalid()) return ExprError();
14572 resultType = Input.get()->getType();
14573
14574 // Though we still have to promote half FP to float...
14575 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
14576 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
14577 resultType = Context.FloatTy;
14578 }
14579
14580 if (resultType->isDependentType())
14581 break;
14582 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
14583 // C99 6.5.3.3p1: ok, fallthrough;
14584 if (Context.getLangOpts().CPlusPlus) {
14585 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
14586 // operand contextually converted to bool.
14587 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
14588 ScalarTypeToBooleanCastKind(resultType));
14589 } else if (Context.getLangOpts().OpenCL &&
14590 Context.getLangOpts().OpenCLVersion < 120) {
14591 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14592 // operate on scalar float types.
14593 if (!resultType->isIntegerType() && !resultType->isPointerType())
14594 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14595 << resultType << Input.get()->getSourceRange());
14596 }
14597 } else if (resultType->isExtVectorType()) {
14598 if (Context.getLangOpts().OpenCL &&
14599 Context.getLangOpts().OpenCLVersion < 120 &&
14600 !Context.getLangOpts().OpenCLCPlusPlus) {
14601 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14602 // operate on vector float types.
14603 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14604 if (!T->isIntegerType())
14605 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14606 << resultType << Input.get()->getSourceRange());
14607 }
14608 // Vector logical not returns the signed variant of the operand type.
14609 resultType = GetSignedVectorType(resultType);
14610 break;
14611 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
14612 const VectorType *VTy = resultType->castAs<VectorType>();
14613 if (VTy->getVectorKind() != VectorType::GenericVector)
14614 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14615 << resultType << Input.get()->getSourceRange());
14616
14617 // Vector logical not returns the signed variant of the operand type.
14618 resultType = GetSignedVectorType(resultType);
14619 break;
14620 } else {
14621 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14622 << resultType << Input.get()->getSourceRange());
14623 }
14624
14625 // LNot always has type int. C99 6.5.3.3p5.
14626 // In C++, it's bool. C++ 5.3.1p8
14627 resultType = Context.getLogicalOperationType();
14628 break;
14629 case UO_Real:
14630 case UO_Imag:
14631 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
14632 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
14633 // complex l-values to ordinary l-values and all other values to r-values.
14634 if (Input.isInvalid()) return ExprError();
14635 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
14636 if (Input.get()->getValueKind() != VK_RValue &&
14637 Input.get()->getObjectKind() == OK_Ordinary)
14638 VK = Input.get()->getValueKind();
14639 } else if (!getLangOpts().CPlusPlus) {
14640 // In C, a volatile scalar is read by __imag. In C++, it is not.
14641 Input = DefaultLvalueConversion(Input.get());
14642 }
14643 break;
14644 case UO_Extension:
14645 resultType = Input.get()->getType();
14646 VK = Input.get()->getValueKind();
14647 OK = Input.get()->getObjectKind();
14648 break;
14649 case UO_Coawait:
14650 // It's unnecessary to represent the pass-through operator co_await in the
14651 // AST; just return the input expression instead.
14652 assert(!Input.get()->getType()->isDependentType() &&((!Input.get()->getType()->isDependentType() &&
"the co_await expression must be non-dependant before " "building operator co_await"
) ? static_cast<void> (0) : __assert_fail ("!Input.get()->getType()->isDependentType() && \"the co_await expression must be non-dependant before \" \"building operator co_await\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 14654, __PRETTY_FUNCTION__))
14653 "the co_await expression must be non-dependant before "((!Input.get()->getType()->isDependentType() &&
"the co_await expression must be non-dependant before " "building operator co_await"
) ? static_cast<void> (0) : __assert_fail ("!Input.get()->getType()->isDependentType() && \"the co_await expression must be non-dependant before \" \"building operator co_await\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 14654, __PRETTY_FUNCTION__))
14654 "building operator co_await")((!Input.get()->getType()->isDependentType() &&
"the co_await expression must be non-dependant before " "building operator co_await"
) ? static_cast<void> (0) : __assert_fail ("!Input.get()->getType()->isDependentType() && \"the co_await expression must be non-dependant before \" \"building operator co_await\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 14654, __PRETTY_FUNCTION__))
;
14655 return Input;
14656 }
14657 if (resultType.isNull() || Input.isInvalid())
14658 return ExprError();
14659
14660 // Check for array bounds violations in the operand of the UnaryOperator,
14661 // except for the '*' and '&' operators that have to be handled specially
14662 // by CheckArrayAccess (as there are special cases like &array[arraysize]
14663 // that are explicitly defined as valid by the standard).
14664 if (Opc != UO_AddrOf && Opc != UO_Deref)
14665 CheckArrayAccess(Input.get());
14666
14667 auto *UO =
14668 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
14669 OpLoc, CanOverflow, CurFPFeatureOverrides());
14670
14671 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
14672 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
14673 !isUnevaluatedContext())
14674 ExprEvalContexts.back().PossibleDerefs.insert(UO);
14675
14676 // Convert the result back to a half vector.
14677 if (ConvertHalfVec)
14678 return convertVector(UO, Context.HalfTy, *this);
14679 return UO;
14680}
14681
14682/// Determine whether the given expression is a qualified member
14683/// access expression, of a form that could be turned into a pointer to member
14684/// with the address-of operator.
14685bool Sema::isQualifiedMemberAccess(Expr *E) {
14686 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14687 if (!DRE->getQualifier())
14688 return false;
14689
14690 ValueDecl *VD = DRE->getDecl();
14691 if (!VD->isCXXClassMember())
14692 return false;
14693
14694 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
14695 return true;
14696 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
14697 return Method->isInstance();
14698
14699 return false;
14700 }
14701
14702 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
14703 if (!ULE->getQualifier())
14704 return false;
14705
14706 for (NamedDecl *D : ULE->decls()) {
14707 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
14708 if (Method->isInstance())
14709 return true;
14710 } else {
14711 // Overload set does not contain methods.
14712 break;
14713 }
14714 }
14715
14716 return false;
14717 }
14718
14719 return false;
14720}
14721
14722ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
14723 UnaryOperatorKind Opc, Expr *Input) {
14724 // First things first: handle placeholders so that the
14725 // overloaded-operator check considers the right type.
14726 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
14727 // Increment and decrement of pseudo-object references.
14728 if (pty->getKind() == BuiltinType::PseudoObject &&
14729 UnaryOperator::isIncrementDecrementOp(Opc))
14730 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
14731
14732 // extension is always a builtin operator.
14733 if (Opc == UO_Extension)
14734 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14735
14736 // & gets special logic for several kinds of placeholder.
14737 // The builtin code knows what to do.
14738 if (Opc == UO_AddrOf &&
14739 (pty->getKind() == BuiltinType::Overload ||
14740 pty->getKind() == BuiltinType::UnknownAny ||
14741 pty->getKind() == BuiltinType::BoundMember))
14742 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14743
14744 // Anything else needs to be handled now.
14745 ExprResult Result = CheckPlaceholderExpr(Input);
14746 if (Result.isInvalid()) return ExprError();
14747 Input = Result.get();
14748 }
14749
14750 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
14751 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
14752 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
14753 // Find all of the overloaded operators visible from this point.
14754 UnresolvedSet<16> Functions;
14755 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
14756 if (S && OverOp != OO_None)
14757 LookupOverloadedOperatorName(OverOp, S, Functions);
14758
14759 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
14760 }
14761
14762 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14763}
14764
14765// Unary Operators. 'Tok' is the token for the operator.
14766ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
14767 tok::TokenKind Op, Expr *Input) {
14768 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
14769}
14770
14771/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
14772ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
14773 LabelDecl *TheDecl) {
14774 TheDecl->markUsed(Context);
14775 // Create the AST node. The address of a label always has type 'void*'.
14776 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
14777 Context.getPointerType(Context.VoidTy));
14778}
14779
14780void Sema::ActOnStartStmtExpr() {
14781 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14782}
14783
14784void Sema::ActOnStmtExprError() {
14785 // Note that function is also called by TreeTransform when leaving a
14786 // StmtExpr scope without rebuilding anything.
14787
14788 DiscardCleanupsInEvaluationContext();
14789 PopExpressionEvaluationContext();
14790}
14791
14792ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
14793 SourceLocation RPLoc) {
14794 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
14795}
14796
14797ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
14798 SourceLocation RPLoc, unsigned TemplateDepth) {
14799 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!")((SubStmt && isa<CompoundStmt>(SubStmt) &&
"Invalid action invocation!") ? static_cast<void> (0) :
__assert_fail ("SubStmt && isa<CompoundStmt>(SubStmt) && \"Invalid action invocation!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 14799, __PRETTY_FUNCTION__))
;
14800 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
14801
14802 if (hasAnyUnrecoverableErrorsInThisFunction())
14803 DiscardCleanupsInEvaluationContext();
14804 assert(!Cleanup.exprNeedsCleanups() &&((!Cleanup.exprNeedsCleanups() && "cleanups within StmtExpr not correctly bound!"
) ? static_cast<void> (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within StmtExpr not correctly bound!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 14805, __PRETTY_FUNCTION__))
14805 "cleanups within StmtExpr not correctly bound!")((!Cleanup.exprNeedsCleanups() && "cleanups within StmtExpr not correctly bound!"
) ? static_cast<void> (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within StmtExpr not correctly bound!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 14805, __PRETTY_FUNCTION__))
;
14806 PopExpressionEvaluationContext();
14807
14808 // FIXME: there are a variety of strange constraints to enforce here, for
14809 // example, it is not possible to goto into a stmt expression apparently.
14810 // More semantic analysis is needed.
14811
14812 // If there are sub-stmts in the compound stmt, take the type of the last one
14813 // as the type of the stmtexpr.
14814 QualType Ty = Context.VoidTy;
14815 bool StmtExprMayBindToTemp = false;
14816 if (!Compound->body_empty()) {
14817 // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
14818 if (const auto *LastStmt =
14819 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
14820 if (const Expr *Value = LastStmt->getExprStmt()) {
14821 StmtExprMayBindToTemp = true;
14822 Ty = Value->getType();
14823 }
14824 }
14825 }
14826
14827 // FIXME: Check that expression type is complete/non-abstract; statement
14828 // expressions are not lvalues.
14829 Expr *ResStmtExpr =
14830 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
14831 if (StmtExprMayBindToTemp)
14832 return MaybeBindToTemporary(ResStmtExpr);
14833 return ResStmtExpr;
14834}
14835
14836ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
14837 if (ER.isInvalid())
14838 return ExprError();
14839
14840 // Do function/array conversion on the last expression, but not
14841 // lvalue-to-rvalue. However, initialize an unqualified type.
14842 ER = DefaultFunctionArrayConversion(ER.get());
14843 if (ER.isInvalid())
14844 return ExprError();
14845 Expr *E = ER.get();
14846
14847 if (E->isTypeDependent())
14848 return E;
14849
14850 // In ARC, if the final expression ends in a consume, splice
14851 // the consume out and bind it later. In the alternate case
14852 // (when dealing with a retainable type), the result
14853 // initialization will create a produce. In both cases the
14854 // result will be +1, and we'll need to balance that out with
14855 // a bind.
14856 auto *Cast = dyn_cast<ImplicitCastExpr>(E);
14857 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
14858 return Cast->getSubExpr();
14859
14860 // FIXME: Provide a better location for the initialization.
14861 return PerformCopyInitialization(
14862 InitializedEntity::InitializeStmtExprResult(
14863 E->getBeginLoc(), E->getType().getUnqualifiedType()),
14864 SourceLocation(), E);
14865}
14866
14867ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
14868 TypeSourceInfo *TInfo,
14869 ArrayRef<OffsetOfComponent> Components,
14870 SourceLocation RParenLoc) {
14871 QualType ArgTy = TInfo->getType();
14872 bool Dependent = ArgTy->isDependentType();
14873 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
14874
14875 // We must have at least one component that refers to the type, and the first
14876 // one is known to be a field designator. Verify that the ArgTy represents
14877 // a struct/union/class.
14878 if (!Dependent && !ArgTy->isRecordType())
14879 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
14880 << ArgTy << TypeRange);
14881
14882 // Type must be complete per C99 7.17p3 because a declaring a variable
14883 // with an incomplete type would be ill-formed.
14884 if (!Dependent
14885 && RequireCompleteType(BuiltinLoc, ArgTy,
14886 diag::err_offsetof_incomplete_type, TypeRange))
14887 return ExprError();
14888
14889 bool DidWarnAboutNonPOD = false;
14890 QualType CurrentType = ArgTy;
14891 SmallVector<OffsetOfNode, 4> Comps;
14892 SmallVector<Expr*, 4> Exprs;
14893 for (const OffsetOfComponent &OC : Components) {
14894 if (OC.isBrackets) {
14895 // Offset of an array sub-field. TODO: Should we allow vector elements?
14896 if (!CurrentType->isDependentType()) {
14897 const ArrayType *AT = Context.getAsArrayType(CurrentType);
14898 if(!AT)
14899 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
14900 << CurrentType);
14901 CurrentType = AT->getElementType();
14902 } else
14903 CurrentType = Context.DependentTy;
14904
14905 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
14906 if (IdxRval.isInvalid())
14907 return ExprError();
14908 Expr *Idx = IdxRval.get();
14909
14910 // The expression must be an integral expression.
14911 // FIXME: An integral constant expression?
14912 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
14913 !Idx->getType()->isIntegerType())
14914 return ExprError(
14915 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
14916 << Idx->getSourceRange());
14917
14918 // Record this array index.
14919 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
14920 Exprs.push_back(Idx);
14921 continue;
14922 }
14923
14924 // Offset of a field.
14925 if (CurrentType->isDependentType()) {
14926 // We have the offset of a field, but we can't look into the dependent
14927 // type. Just record the identifier of the field.
14928 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
14929 CurrentType = Context.DependentTy;
14930 continue;
14931 }
14932
14933 // We need to have a complete type to look into.
14934 if (RequireCompleteType(OC.LocStart, CurrentType,
14935 diag::err_offsetof_incomplete_type))
14936 return ExprError();
14937
14938 // Look for the designated field.
14939 const RecordType *RC = CurrentType->getAs<RecordType>();
14940 if (!RC)
14941 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
14942 << CurrentType);
14943 RecordDecl *RD = RC->getDecl();
14944
14945 // C++ [lib.support.types]p5:
14946 // The macro offsetof accepts a restricted set of type arguments in this
14947 // International Standard. type shall be a POD structure or a POD union
14948 // (clause 9).
14949 // C++11 [support.types]p4:
14950 // If type is not a standard-layout class (Clause 9), the results are
14951 // undefined.
14952 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14953 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
14954 unsigned DiagID =
14955 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
14956 : diag::ext_offsetof_non_pod_type;
14957
14958 if (!IsSafe && !DidWarnAboutNonPOD &&
14959 DiagRuntimeBehavior(BuiltinLoc, nullptr,
14960 PDiag(DiagID)
14961 << SourceRange(Components[0].LocStart, OC.LocEnd)
14962 << CurrentType))
14963 DidWarnAboutNonPOD = true;
14964 }
14965
14966 // Look for the field.
14967 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
14968 LookupQualifiedName(R, RD);
14969 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
14970 IndirectFieldDecl *IndirectMemberDecl = nullptr;
14971 if (!MemberDecl) {
14972 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
14973 MemberDecl = IndirectMemberDecl->getAnonField();
14974 }
14975
14976 if (!MemberDecl)
14977 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
14978 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
14979 OC.LocEnd));
14980
14981 // C99 7.17p3:
14982 // (If the specified member is a bit-field, the behavior is undefined.)
14983 //
14984 // We diagnose this as an error.
14985 if (MemberDecl->isBitField()) {
14986 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
14987 << MemberDecl->getDeclName()
14988 << SourceRange(BuiltinLoc, RParenLoc);
14989 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
14990 return ExprError();
14991 }
14992
14993 RecordDecl *Parent = MemberDecl->getParent();
14994 if (IndirectMemberDecl)
14995 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
14996
14997 // If the member was found in a base class, introduce OffsetOfNodes for
14998 // the base class indirections.
14999 CXXBasePaths Paths;
15000 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
15001 Paths)) {
15002 if (Paths.getDetectedVirtual()) {
15003 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
15004 << MemberDecl->getDeclName()
15005 << SourceRange(BuiltinLoc, RParenLoc);
15006 return ExprError();
15007 }
15008
15009 CXXBasePath &Path = Paths.front();
15010 for (const CXXBasePathElement &B : Path)
15011 Comps.push_back(OffsetOfNode(B.Base));
15012 }
15013
15014 if (IndirectMemberDecl) {
15015 for (auto *FI : IndirectMemberDecl->chain()) {
15016 assert(isa<FieldDecl>(FI))((isa<FieldDecl>(FI)) ? static_cast<void> (0) : __assert_fail
("isa<FieldDecl>(FI)", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 15016, __PRETTY_FUNCTION__))
;
15017 Comps.push_back(OffsetOfNode(OC.LocStart,
15018 cast<FieldDecl>(FI), OC.LocEnd));
15019 }
15020 } else
15021 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
15022
15023 CurrentType = MemberDecl->getType().getNonReferenceType();
15024 }
15025
15026 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
15027 Comps, Exprs, RParenLoc);
15028}
15029
15030ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
15031 SourceLocation BuiltinLoc,
15032 SourceLocation TypeLoc,
15033 ParsedType ParsedArgTy,
15034 ArrayRef<OffsetOfComponent> Components,
15035 SourceLocation RParenLoc) {
15036
15037 TypeSourceInfo *ArgTInfo;
15038 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
15039 if (ArgTy.isNull())
15040 return ExprError();
15041
15042 if (!ArgTInfo)
15043 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
15044
15045 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
15046}
15047
15048
15049ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
15050 Expr *CondExpr,
15051 Expr *LHSExpr, Expr *RHSExpr,
15052 SourceLocation RPLoc) {
15053 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)")(((CondExpr && LHSExpr && RHSExpr) &&
"Missing type argument(s)") ? static_cast<void> (0) : __assert_fail
("(CondExpr && LHSExpr && RHSExpr) && \"Missing type argument(s)\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 15053, __PRETTY_FUNCTION__))
;
15054
15055 ExprValueKind VK = VK_RValue;
15056 ExprObjectKind OK = OK_Ordinary;
15057 QualType resType;
15058 bool CondIsTrue = false;
15059 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
15060 resType = Context.DependentTy;
15061 } else {
15062 // The conditional expression is required to be a constant expression.
15063 llvm::APSInt condEval(32);
15064 ExprResult CondICE = VerifyIntegerConstantExpression(
15065 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
15066 if (CondICE.isInvalid())
15067 return ExprError();
15068 CondExpr = CondICE.get();
15069 CondIsTrue = condEval.getZExtValue();
15070
15071 // If the condition is > zero, then the AST type is the same as the LHSExpr.
15072 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
15073
15074 resType = ActiveExpr->getType();
15075 VK = ActiveExpr->getValueKind();
15076 OK = ActiveExpr->getObjectKind();
15077 }
15078
15079 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
15080 resType, VK, OK, RPLoc, CondIsTrue);
15081}
15082
15083//===----------------------------------------------------------------------===//
15084// Clang Extensions.
15085//===----------------------------------------------------------------------===//
15086
15087/// ActOnBlockStart - This callback is invoked when a block literal is started.
15088void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
15089 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
15090
15091 if (LangOpts.CPlusPlus) {
15092 MangleNumberingContext *MCtx;
15093 Decl *ManglingContextDecl;
15094 std::tie(MCtx, ManglingContextDecl) =
15095 getCurrentMangleNumberContext(Block->getDeclContext());
15096 if (MCtx) {
15097 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
15098 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
15099 }
15100 }
15101
15102 PushBlockScope(CurScope, Block);
15103 CurContext->addDecl(Block);
15104 if (CurScope)
15105 PushDeclContext(CurScope, Block);
15106 else
15107 CurContext = Block;
15108
15109 getCurBlock()->HasImplicitReturnType = true;
15110
15111 // Enter a new evaluation context to insulate the block from any
15112 // cleanups from the enclosing full-expression.
15113 PushExpressionEvaluationContext(
15114 ExpressionEvaluationContext::PotentiallyEvaluated);
15115}
15116
15117void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
15118 Scope *CurScope) {
15119 assert(ParamInfo.getIdentifier() == nullptr &&((ParamInfo.getIdentifier() == nullptr && "block-id should have no identifier!"
) ? static_cast<void> (0) : __assert_fail ("ParamInfo.getIdentifier() == nullptr && \"block-id should have no identifier!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 15120, __PRETTY_FUNCTION__))
15120 "block-id should have no identifier!")((ParamInfo.getIdentifier() == nullptr && "block-id should have no identifier!"
) ? static_cast<void> (0) : __assert_fail ("ParamInfo.getIdentifier() == nullptr && \"block-id should have no identifier!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 15120, __PRETTY_FUNCTION__))
;
15121 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral)((ParamInfo.getContext() == DeclaratorContext::BlockLiteral) ?
static_cast<void> (0) : __assert_fail ("ParamInfo.getContext() == DeclaratorContext::BlockLiteral"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 15121, __PRETTY_FUNCTION__))
;
15122 BlockScopeInfo *CurBlock = getCurBlock();
15123
15124 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
15125 QualType T = Sig->getType();
15126
15127 // FIXME: We should allow unexpanded parameter packs here, but that would,
15128 // in turn, make the block expression contain unexpanded parameter packs.
15129 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
15130 // Drop the parameters.
15131 FunctionProtoType::ExtProtoInfo EPI;
15132 EPI.HasTrailingReturn = false;
15133 EPI.TypeQuals.addConst();
15134 T = Context.getFunctionType(Context.DependentTy, None, EPI);
15135 Sig = Context.getTrivialTypeSourceInfo(T);
15136 }
15137
15138 // GetTypeForDeclarator always produces a function type for a block
15139 // literal signature. Furthermore, it is always a FunctionProtoType
15140 // unless the function was written with a typedef.
15141 assert(T->isFunctionType() &&((T->isFunctionType() && "GetTypeForDeclarator made a non-function block signature"
) ? static_cast<void> (0) : __assert_fail ("T->isFunctionType() && \"GetTypeForDeclarator made a non-function block signature\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 15142, __PRETTY_FUNCTION__))
15142 "GetTypeForDeclarator made a non-function block signature")((T->isFunctionType() && "GetTypeForDeclarator made a non-function block signature"
) ? static_cast<void> (0) : __assert_fail ("T->isFunctionType() && \"GetTypeForDeclarator made a non-function block signature\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 15142, __PRETTY_FUNCTION__))
;
15143
15144 // Look for an explicit signature in that function type.
15145 FunctionProtoTypeLoc ExplicitSignature;
15146
15147 if ((ExplicitSignature = Sig->getTypeLoc()
15148 .getAsAdjusted<FunctionProtoTypeLoc>())) {
15149
15150 // Check whether that explicit signature was synthesized by
15151 // GetTypeForDeclarator. If so, don't save that as part of the
15152 // written signature.
15153 if (ExplicitSignature.getLocalRangeBegin() ==
15154 ExplicitSignature.getLocalRangeEnd()) {
15155 // This would be much cheaper if we stored TypeLocs instead of
15156 // TypeSourceInfos.
15157 TypeLoc Result = ExplicitSignature.getReturnLoc();
15158 unsigned Size = Result.getFullDataSize();
15159 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
15160 Sig->getTypeLoc().initializeFullCopy(Result, Size);
15161
15162 ExplicitSignature = FunctionProtoTypeLoc();
15163 }
15164 }
15165
15166 CurBlock->TheDecl->setSignatureAsWritten(Sig);
15167 CurBlock->FunctionType = T;
15168
15169 const FunctionType *Fn = T->getAs<FunctionType>();
15170 QualType RetTy = Fn->getReturnType();
15171 bool isVariadic =
15172 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
15173
15174 CurBlock->TheDecl->setIsVariadic(isVariadic);
15175
15176 // Context.DependentTy is used as a placeholder for a missing block
15177 // return type. TODO: what should we do with declarators like:
15178 // ^ * { ... }
15179 // If the answer is "apply template argument deduction"....
15180 if (RetTy != Context.DependentTy) {
15181 CurBlock->ReturnType = RetTy;
15182 CurBlock->TheDecl->setBlockMissingReturnType(false);
15183 CurBlock->HasImplicitReturnType = false;
15184 }
15185
15186 // Push block parameters from the declarator if we had them.
15187 SmallVector<ParmVarDecl*, 8> Params;
15188 if (ExplicitSignature) {
15189 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
15190 ParmVarDecl *Param = ExplicitSignature.getParam(I);
15191 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
15192 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
15193 // Diagnose this as an extension in C17 and earlier.
15194 if (!getLangOpts().C2x)
15195 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
15196 }
15197 Params.push_back(Param);
15198 }
15199
15200 // Fake up parameter variables if we have a typedef, like
15201 // ^ fntype { ... }
15202 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
15203 for (const auto &I : Fn->param_types()) {
15204 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
15205 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
15206 Params.push_back(Param);
15207 }
15208 }
15209
15210 // Set the parameters on the block decl.
15211 if (!Params.empty()) {
15212 CurBlock->TheDecl->setParams(Params);
15213 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
15214 /*CheckParameterNames=*/false);
15215 }
15216
15217 // Finally we can process decl attributes.
15218 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
15219
15220 // Put the parameter variables in scope.
15221 for (auto AI : CurBlock->TheDecl->parameters()) {
15222 AI->setOwningFunction(CurBlock->TheDecl);
15223
15224 // If this has an identifier, add it to the scope stack.
15225 if (AI->getIdentifier()) {
15226 CheckShadow(CurBlock->TheScope, AI);
15227
15228 PushOnScopeChains(AI, CurBlock->TheScope);
15229 }
15230 }
15231}
15232
15233/// ActOnBlockError - If there is an error parsing a block, this callback
15234/// is invoked to pop the information about the block from the action impl.
15235void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
15236 // Leave the expression-evaluation context.
15237 DiscardCleanupsInEvaluationContext();
15238 PopExpressionEvaluationContext();
15239
15240 // Pop off CurBlock, handle nested blocks.
15241 PopDeclContext();
15242 PopFunctionScopeInfo();
15243}
15244
15245/// ActOnBlockStmtExpr - This is called when the body of a block statement
15246/// literal was successfully completed. ^(int x){...}
15247ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
15248 Stmt *Body, Scope *CurScope) {
15249 // If blocks are disabled, emit an error.
15250 if (!LangOpts.Blocks)
15251 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
15252
15253 // Leave the expression-evaluation context.
15254 if (hasAnyUnrecoverableErrorsInThisFunction())
15255 DiscardCleanupsInEvaluationContext();
15256 assert(!Cleanup.exprNeedsCleanups() &&((!Cleanup.exprNeedsCleanups() && "cleanups within block not correctly bound!"
) ? static_cast<void> (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within block not correctly bound!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 15257, __PRETTY_FUNCTION__))
15257 "cleanups within block not correctly bound!")((!Cleanup.exprNeedsCleanups() && "cleanups within block not correctly bound!"
) ? static_cast<void> (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within block not correctly bound!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 15257, __PRETTY_FUNCTION__))
;
15258 PopExpressionEvaluationContext();
15259
15260 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
15261 BlockDecl *BD = BSI->TheDecl;
15262
15263 if (BSI->HasImplicitReturnType)
15264 deduceClosureReturnType(*BSI);
15265
15266 QualType RetTy = Context.VoidTy;
15267 if (!BSI->ReturnType.isNull())
15268 RetTy = BSI->ReturnType;
15269
15270 bool NoReturn = BD->hasAttr<NoReturnAttr>();
15271 QualType BlockTy;
15272
15273 // If the user wrote a function type in some form, try to use that.
15274 if (!BSI->FunctionType.isNull()) {
15275 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
15276
15277 FunctionType::ExtInfo Ext = FTy->getExtInfo();
15278 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
15279
15280 // Turn protoless block types into nullary block types.
15281 if (isa<FunctionNoProtoType>(FTy)) {
15282 FunctionProtoType::ExtProtoInfo EPI;
15283 EPI.ExtInfo = Ext;
15284 BlockTy = Context.getFunctionType(RetTy, None, EPI);
15285
15286 // Otherwise, if we don't need to change anything about the function type,
15287 // preserve its sugar structure.
15288 } else if (FTy->getReturnType() == RetTy &&
15289 (!NoReturn || FTy->getNoReturnAttr())) {
15290 BlockTy = BSI->FunctionType;
15291
15292 // Otherwise, make the minimal modifications to the function type.
15293 } else {
15294 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
15295 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
15296 EPI.TypeQuals = Qualifiers();
15297 EPI.ExtInfo = Ext;
15298 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
15299 }
15300
15301 // If we don't have a function type, just build one from nothing.
15302 } else {
15303 FunctionProtoType::ExtProtoInfo EPI;
15304 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
15305 BlockTy = Context.getFunctionType(RetTy, None, EPI);
15306 }
15307
15308 DiagnoseUnusedParameters(BD->parameters());
15309 BlockTy = Context.getBlockPointerType(BlockTy);
15310
15311 // If needed, diagnose invalid gotos and switches in the block.
15312 if (getCurFunction()->NeedsScopeChecking() &&
15313 !PP.isCodeCompletionEnabled())
15314 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
15315
15316 BD->setBody(cast<CompoundStmt>(Body));
15317
15318 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
15319 DiagnoseUnguardedAvailabilityViolations(BD);
15320
15321 // Try to apply the named return value optimization. We have to check again
15322 // if we can do this, though, because blocks keep return statements around
15323 // to deduce an implicit return type.
15324 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
15325 !BD->isDependentContext())
15326 computeNRVO(Body, BSI);
15327
15328 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
15329 RetTy.hasNonTrivialToPrimitiveCopyCUnion())
15330 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
15331 NTCUK_Destruct|NTCUK_Copy);
15332
15333 PopDeclContext();
15334
15335 // Pop the block scope now but keep it alive to the end of this function.
15336 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
15337 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
15338
15339 // Set the captured variables on the block.
15340 SmallVector<BlockDecl::Capture, 4> Captures;
15341 for (Capture &Cap : BSI->Captures) {
15342 if (Cap.isInvalid() || Cap.isThisCapture())
15343 continue;
15344
15345 VarDecl *Var = Cap.getVariable();
15346 Expr *CopyExpr = nullptr;
15347 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
15348 if (const RecordType *Record =
15349 Cap.getCaptureType()->getAs<RecordType>()) {
15350 // The capture logic needs the destructor, so make sure we mark it.
15351 // Usually this is unnecessary because most local variables have
15352 // their destructors marked at declaration time, but parameters are
15353 // an exception because it's technically only the call site that
15354 // actually requires the destructor.
15355 if (isa<ParmVarDecl>(Var))
15356 FinalizeVarWithDestructor(Var, Record);
15357
15358 // Enter a separate potentially-evaluated context while building block
15359 // initializers to isolate their cleanups from those of the block
15360 // itself.
15361 // FIXME: Is this appropriate even when the block itself occurs in an
15362 // unevaluated operand?
15363 EnterExpressionEvaluationContext EvalContext(
15364 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15365
15366 SourceLocation Loc = Cap.getLocation();
15367
15368 ExprResult Result = BuildDeclarationNameExpr(
15369 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
15370
15371 // According to the blocks spec, the capture of a variable from
15372 // the stack requires a const copy constructor. This is not true
15373 // of the copy/move done to move a __block variable to the heap.
15374 if (!Result.isInvalid() &&
15375 !Result.get()->getType().isConstQualified()) {
15376 Result = ImpCastExprToType(Result.get(),
15377 Result.get()->getType().withConst(),
15378 CK_NoOp, VK_LValue);
15379 }
15380
15381 if (!Result.isInvalid()) {
15382 Result = PerformCopyInitialization(
15383 InitializedEntity::InitializeBlock(Var->getLocation(),
15384 Cap.getCaptureType(), false),
15385 Loc, Result.get());
15386 }
15387
15388 // Build a full-expression copy expression if initialization
15389 // succeeded and used a non-trivial constructor. Recover from
15390 // errors by pretending that the copy isn't necessary.
15391 if (!Result.isInvalid() &&
15392 !cast<CXXConstructExpr>(Result.get())->getConstructor()
15393 ->isTrivial()) {
15394 Result = MaybeCreateExprWithCleanups(Result);
15395 CopyExpr = Result.get();
15396 }
15397 }
15398 }
15399
15400 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
15401 CopyExpr);
15402 Captures.push_back(NewCap);
15403 }
15404 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
15405
15406 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
15407
15408 // If the block isn't obviously global, i.e. it captures anything at
15409 // all, then we need to do a few things in the surrounding context:
15410 if (Result->getBlockDecl()->hasCaptures()) {
15411 // First, this expression has a new cleanup object.
15412 ExprCleanupObjects.push_back(Result->getBlockDecl());
15413 Cleanup.setExprNeedsCleanups(true);
15414
15415 // It also gets a branch-protected scope if any of the captured
15416 // variables needs destruction.
15417 for (const auto &CI : Result->getBlockDecl()->captures()) {
15418 const VarDecl *var = CI.getVariable();
15419 if (var->getType().isDestructedType() != QualType::DK_none) {
15420 setFunctionHasBranchProtectedScope();
15421 break;
15422 }
15423 }
15424 }
15425
15426 if (getCurFunction())
15427 getCurFunction()->addBlock(BD);
15428
15429 return Result;
15430}
15431
15432ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
15433 SourceLocation RPLoc) {
15434 TypeSourceInfo *TInfo;
15435 GetTypeFromParser(Ty, &TInfo);
15436 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
15437}
15438
15439ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
15440 Expr *E, TypeSourceInfo *TInfo,
15441 SourceLocation RPLoc) {
15442 Expr *OrigExpr = E;
15443 bool IsMS = false;
15444
15445 // CUDA device code does not support varargs.
15446 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
15447 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
15448 CUDAFunctionTarget T = IdentifyCUDATarget(F);
15449 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
15450 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
15451 }
15452 }
15453
15454 // NVPTX does not support va_arg expression.
15455 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
15456 Context.getTargetInfo().getTriple().isNVPTX())
15457 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
15458
15459 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
15460 // as Microsoft ABI on an actual Microsoft platform, where
15461 // __builtin_ms_va_list and __builtin_va_list are the same.)
15462 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
15463 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
15464 QualType MSVaListType = Context.getBuiltinMSVaListType();
15465 if (Context.hasSameType(MSVaListType, E->getType())) {
15466 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
15467 return ExprError();
15468 IsMS = true;
15469 }
15470 }
15471
15472 // Get the va_list type
15473 QualType VaListType = Context.getBuiltinVaListType();
15474 if (!IsMS) {
15475 if (VaListType->isArrayType()) {
15476 // Deal with implicit array decay; for example, on x86-64,
15477 // va_list is an array, but it's supposed to decay to
15478 // a pointer for va_arg.
15479 VaListType = Context.getArrayDecayedType(VaListType);
15480 // Make sure the input expression also decays appropriately.
15481 ExprResult Result = UsualUnaryConversions(E);
15482 if (Result.isInvalid())
15483 return ExprError();
15484 E = Result.get();
15485 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
15486 // If va_list is a record type and we are compiling in C++ mode,
15487 // check the argument using reference binding.
15488 InitializedEntity Entity = InitializedEntity::InitializeParameter(
15489 Context, Context.getLValueReferenceType(VaListType), false);
15490 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
15491 if (Init.isInvalid())
15492 return ExprError();
15493 E = Init.getAs<Expr>();
15494 } else {
15495 // Otherwise, the va_list argument must be an l-value because
15496 // it is modified by va_arg.
15497 if (!E->isTypeDependent() &&
15498 CheckForModifiableLvalue(E, BuiltinLoc, *this))
15499 return ExprError();
15500 }
15501 }
15502
15503 if (!IsMS && !E->isTypeDependent() &&
15504 !Context.hasSameType(VaListType, E->getType()))
15505 return ExprError(
15506 Diag(E->getBeginLoc(),
15507 diag::err_first_argument_to_va_arg_not_of_type_va_list)
15508 << OrigExpr->getType() << E->getSourceRange());
15509
15510 if (!TInfo->getType()->isDependentType()) {
15511 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
15512 diag::err_second_parameter_to_va_arg_incomplete,
15513 TInfo->getTypeLoc()))
15514 return ExprError();
15515
15516 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
15517 TInfo->getType(),
15518 diag::err_second_parameter_to_va_arg_abstract,
15519 TInfo->getTypeLoc()))
15520 return ExprError();
15521
15522 if (!TInfo->getType().isPODType(Context)) {
15523 Diag(TInfo->getTypeLoc().getBeginLoc(),
15524 TInfo->getType()->isObjCLifetimeType()
15525 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
15526 : diag::warn_second_parameter_to_va_arg_not_pod)
15527 << TInfo->getType()
15528 << TInfo->getTypeLoc().getSourceRange();
15529 }
15530
15531 // Check for va_arg where arguments of the given type will be promoted
15532 // (i.e. this va_arg is guaranteed to have undefined behavior).
15533 QualType PromoteType;
15534 if (TInfo->getType()->isPromotableIntegerType()) {
15535 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
15536 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
15537 PromoteType = QualType();
15538 }
15539 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
15540 PromoteType = Context.DoubleTy;
15541 if (!PromoteType.isNull())
15542 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
15543 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
15544 << TInfo->getType()
15545 << PromoteType
15546 << TInfo->getTypeLoc().getSourceRange());
15547 }
15548
15549 QualType T = TInfo->getType().getNonLValueExprType(Context);
15550 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
15551}
15552
15553ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
15554 // The type of __null will be int or long, depending on the size of
15555 // pointers on the target.
15556 QualType Ty;
15557 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
15558 if (pw == Context.getTargetInfo().getIntWidth())
15559 Ty = Context.IntTy;
15560 else if (pw == Context.getTargetInfo().getLongWidth())
15561 Ty = Context.LongTy;
15562 else if (pw == Context.getTargetInfo().getLongLongWidth())
15563 Ty = Context.LongLongTy;
15564 else {
15565 llvm_unreachable("I don't know size of pointer!")::llvm::llvm_unreachable_internal("I don't know size of pointer!"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 15565)
;
15566 }
15567
15568 return new (Context) GNUNullExpr(Ty, TokenLoc);
15569}
15570
15571ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
15572 SourceLocation BuiltinLoc,
15573 SourceLocation RPLoc) {
15574 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
15575}
15576
15577ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
15578 SourceLocation BuiltinLoc,
15579 SourceLocation RPLoc,
15580 DeclContext *ParentContext) {
15581 return new (Context)
15582 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
15583}
15584
15585bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
15586 bool Diagnose) {
15587 if (!getLangOpts().ObjC)
15588 return false;
15589
15590 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
15591 if (!PT)
15592 return false;
15593 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
15594
15595 // Ignore any parens, implicit casts (should only be
15596 // array-to-pointer decays), and not-so-opaque values. The last is
15597 // important for making this trigger for property assignments.
15598 Expr *SrcExpr = Exp->IgnoreParenImpCasts();
15599 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
15600 if (OV->getSourceExpr())
15601 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
15602
15603 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
15604 if (!PT->isObjCIdType() &&
15605 !(ID && ID->getIdentifier()->isStr("NSString")))
15606 return false;
15607 if (!SL->isAscii())
15608 return false;
15609
15610 if (Diagnose) {
15611 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
15612 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
15613 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
15614 }
15615 return true;
15616 }
15617
15618 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
15619 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
15620 isa<CXXBoolLiteralExpr>(SrcExpr)) &&
15621 !SrcExpr->isNullPointerConstant(
15622 getASTContext(), Expr::NPC_NeverValueDependent)) {
15623 if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
15624 return false;
15625 if (Diagnose) {
15626 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
15627 << /*number*/1
15628 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
15629 Expr *NumLit =
15630 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
15631 if (NumLit)
15632 Exp = NumLit;
15633 }
15634 return true;
15635 }
15636
15637 return false;
15638}
15639
15640static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
15641 const Expr *SrcExpr) {
15642 if (!DstType->isFunctionPointerType() ||
15643 !SrcExpr->getType()->isFunctionType())
15644 return false;
15645
15646 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
15647 if (!DRE)
15648 return false;
15649
15650 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
15651 if (!FD)
15652 return false;
15653
15654 return !S.checkAddressOfFunctionIsAvailable(FD,
15655 /*Complain=*/true,
15656 SrcExpr->getBeginLoc());
15657}
15658
15659bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
15660 SourceLocation Loc,
15661 QualType DstType, QualType SrcType,
15662 Expr *SrcExpr, AssignmentAction Action,
15663 bool *Complained) {
15664 if (Complained)
15665 *Complained = false;
15666
15667 // Decode the result (notice that AST's are still created for extensions).
15668 bool CheckInferredResultType = false;
15669 bool isInvalid = false;
15670 unsigned DiagKind = 0;
15671 ConversionFixItGenerator ConvHints;
15672 bool MayHaveConvFixit = false;
15673 bool MayHaveFunctionDiff = false;
15674 const ObjCInterfaceDecl *IFace = nullptr;
15675 const ObjCProtocolDecl *PDecl = nullptr;
15676
15677 switch (ConvTy) {
15678 case Compatible:
15679 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
15680 return false;
15681
15682 case PointerToInt:
15683 if (getLangOpts().CPlusPlus) {
15684 DiagKind = diag::err_typecheck_convert_pointer_int;
15685 isInvalid = true;
15686 } else {
15687 DiagKind = diag::ext_typecheck_convert_pointer_int;
15688 }
15689 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15690 MayHaveConvFixit = true;
15691 break;
15692 case IntToPointer:
15693 if (getLangOpts().CPlusPlus) {
15694 DiagKind = diag::err_typecheck_convert_int_pointer;
15695 isInvalid = true;
15696 } else {
15697 DiagKind = diag::ext_typecheck_convert_int_pointer;
15698 }
15699 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15700 MayHaveConvFixit = true;
15701 break;
15702 case IncompatibleFunctionPointer:
15703 if (getLangOpts().CPlusPlus) {
15704 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
15705 isInvalid = true;
15706 } else {
15707 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
15708 }
15709 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15710 MayHaveConvFixit = true;
15711 break;
15712 case IncompatiblePointer:
15713 if (Action == AA_Passing_CFAudited) {
15714 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
15715 } else if (getLangOpts().CPlusPlus) {
15716 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
15717 isInvalid = true;
15718 } else {
15719 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
15720 }
15721 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
15722 SrcType->isObjCObjectPointerType();
15723 if (!CheckInferredResultType) {
15724 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15725 } else if (CheckInferredResultType) {
15726 SrcType = SrcType.getUnqualifiedType();
15727 DstType = DstType.getUnqualifiedType();
15728 }
15729 MayHaveConvFixit = true;
15730 break;
15731 case IncompatiblePointerSign:
15732 if (getLangOpts().CPlusPlus) {
15733 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
15734 isInvalid = true;
15735 } else {
15736 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
15737 }
15738 break;
15739 case FunctionVoidPointer:
15740 if (getLangOpts().CPlusPlus) {
15741 DiagKind = diag::err_typecheck_convert_pointer_void_func;
15742 isInvalid = true;
15743 } else {
15744 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
15745 }
15746 break;
15747 case IncompatiblePointerDiscardsQualifiers: {
15748 // Perform array-to-pointer decay if necessary.
15749 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
15750
15751 isInvalid = true;
15752
15753 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
15754 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
15755 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
15756 DiagKind = diag::err_typecheck_incompatible_address_space;
15757 break;
15758
15759 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
15760 DiagKind = diag::err_typecheck_incompatible_ownership;
15761 break;
15762 }
15763
15764 llvm_unreachable("unknown error case for discarding qualifiers!")::llvm::llvm_unreachable_internal("unknown error case for discarding qualifiers!"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 15764)
;
15765 // fallthrough
15766 }
15767 case CompatiblePointerDiscardsQualifiers:
15768 // If the qualifiers lost were because we were applying the
15769 // (deprecated) C++ conversion from a string literal to a char*
15770 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
15771 // Ideally, this check would be performed in
15772 // checkPointerTypesForAssignment. However, that would require a
15773 // bit of refactoring (so that the second argument is an
15774 // expression, rather than a type), which should be done as part
15775 // of a larger effort to fix checkPointerTypesForAssignment for
15776 // C++ semantics.
15777 if (getLangOpts().CPlusPlus &&
15778 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
15779 return false;
15780 if (getLangOpts().CPlusPlus) {
15781 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
15782 isInvalid = true;
15783 } else {
15784 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
15785 }
15786
15787 break;
15788 case IncompatibleNestedPointerQualifiers:
15789 if (getLangOpts().CPlusPlus) {
15790 isInvalid = true;
15791 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
15792 } else {
15793 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
15794 }
15795 break;
15796 case IncompatibleNestedPointerAddressSpaceMismatch:
15797 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
15798 isInvalid = true;
15799 break;
15800 case IntToBlockPointer:
15801 DiagKind = diag::err_int_to_block_pointer;
15802 isInvalid = true;
15803 break;
15804 case IncompatibleBlockPointer:
15805 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
15806 isInvalid = true;
15807 break;
15808 case IncompatibleObjCQualifiedId: {
15809 if (SrcType->isObjCQualifiedIdType()) {
15810 const ObjCObjectPointerType *srcOPT =
15811 SrcType->castAs<ObjCObjectPointerType>();
15812 for (auto *srcProto : srcOPT->quals()) {
15813 PDecl = srcProto;
15814 break;
15815 }
15816 if (const ObjCInterfaceType *IFaceT =
15817 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
15818 IFace = IFaceT->getDecl();
15819 }
15820 else if (DstType->isObjCQualifiedIdType()) {
15821 const ObjCObjectPointerType *dstOPT =
15822 DstType->castAs<ObjCObjectPointerType>();
15823 for (auto *dstProto : dstOPT->quals()) {
15824 PDecl = dstProto;
15825 break;
15826 }
15827 if (const ObjCInterfaceType *IFaceT =
15828 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
15829 IFace = IFaceT->getDecl();
15830 }
15831 if (getLangOpts().CPlusPlus) {
15832 DiagKind = diag::err_incompatible_qualified_id;
15833 isInvalid = true;
15834 } else {
15835 DiagKind = diag::warn_incompatible_qualified_id;
15836 }
15837 break;
15838 }
15839 case IncompatibleVectors:
15840 if (getLangOpts().CPlusPlus) {
15841 DiagKind = diag::err_incompatible_vectors;
15842 isInvalid = true;
15843 } else {
15844 DiagKind = diag::warn_incompatible_vectors;
15845 }
15846 break;
15847 case IncompatibleObjCWeakRef:
15848 DiagKind = diag::err_arc_weak_unavailable_assign;
15849 isInvalid = true;
15850 break;
15851 case Incompatible:
15852 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
15853 if (Complained)
15854 *Complained = true;
15855 return true;
15856 }
15857
15858 DiagKind = diag::err_typecheck_convert_incompatible;
15859 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15860 MayHaveConvFixit = true;
15861 isInvalid = true;
15862 MayHaveFunctionDiff = true;
15863 break;
15864 }
15865
15866 QualType FirstType, SecondType;
15867 switch (Action) {
15868 case AA_Assigning:
15869 case AA_Initializing:
15870 // The destination type comes first.
15871 FirstType = DstType;
15872 SecondType = SrcType;
15873 break;
15874
15875 case AA_Returning:
15876 case AA_Passing:
15877 case AA_Passing_CFAudited:
15878 case AA_Converting:
15879 case AA_Sending:
15880 case AA_Casting:
15881 // The source type comes first.
15882 FirstType = SrcType;
15883 SecondType = DstType;
15884 break;
15885 }
15886
15887 PartialDiagnostic FDiag = PDiag(DiagKind);
15888 if (Action == AA_Passing_CFAudited)
15889 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
15890 else
15891 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
15892
15893 // If we can fix the conversion, suggest the FixIts.
15894 if (!ConvHints.isNull()) {
15895 for (FixItHint &H : ConvHints.Hints)
15896 FDiag << H;
15897 }
15898
15899 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
15900
15901 if (MayHaveFunctionDiff)
15902 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
15903
15904 Diag(Loc, FDiag);
15905 if ((DiagKind == diag::warn_incompatible_qualified_id ||
15906 DiagKind == diag::err_incompatible_qualified_id) &&
15907 PDecl && IFace && !IFace->hasDefinition())
15908 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
15909 << IFace << PDecl;
15910
15911 if (SecondType == Context.OverloadTy)
15912 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
15913 FirstType, /*TakingAddress=*/true);
15914
15915 if (CheckInferredResultType)
15916 EmitRelatedResultTypeNote(SrcExpr);
15917
15918 if (Action == AA_Returning && ConvTy == IncompatiblePointer)
15919 EmitRelatedResultTypeNoteForReturn(DstType);
15920
15921 if (Complained)
15922 *Complained = true;
15923 return isInvalid;
15924}
15925
15926ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
15927 llvm::APSInt *Result,
15928 AllowFoldKind CanFold) {
15929 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
15930 public:
15931 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
15932 QualType T) override {
15933 return S.Diag(Loc, diag::err_ice_not_integral)
15934 << T << S.LangOpts.CPlusPlus;
15935 }
15936 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
15937 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
15938 }
15939 } Diagnoser;
15940
15941 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
15942}
15943
15944ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
15945 llvm::APSInt *Result,
15946 unsigned DiagID,
15947 AllowFoldKind CanFold) {
15948 class IDDiagnoser : public VerifyICEDiagnoser {
15949 unsigned DiagID;
15950
15951 public:
15952 IDDiagnoser(unsigned DiagID)
15953 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
15954
15955 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
15956 return S.Diag(Loc, DiagID);
15957 }
15958 } Diagnoser(DiagID);
15959
15960 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
15961}
15962
15963Sema::SemaDiagnosticBuilder
15964Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
15965 QualType T) {
15966 return diagnoseNotICE(S, Loc);
15967}
15968
15969Sema::SemaDiagnosticBuilder
15970Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
15971 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
15972}
15973
15974ExprResult
15975Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
15976 VerifyICEDiagnoser &Diagnoser,
15977 AllowFoldKind CanFold) {
15978 SourceLocation DiagLoc = E->getBeginLoc();
15979
15980 if (getLangOpts().CPlusPlus11) {
15981 // C++11 [expr.const]p5:
15982 // If an expression of literal class type is used in a context where an
15983 // integral constant expression is required, then that class type shall
15984 // have a single non-explicit conversion function to an integral or
15985 // unscoped enumeration type
15986 ExprResult Converted;
15987 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
15988 VerifyICEDiagnoser &BaseDiagnoser;
15989 public:
15990 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
15991 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
15992 BaseDiagnoser.Suppress, true),
15993 BaseDiagnoser(BaseDiagnoser) {}
15994
15995 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
15996 QualType T) override {
15997 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
15998 }
15999
16000 SemaDiagnosticBuilder diagnoseIncomplete(
16001 Sema &S, SourceLocation Loc, QualType T) override {
16002 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
16003 }
16004
16005 SemaDiagnosticBuilder diagnoseExplicitConv(
16006 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16007 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
16008 }
16009
16010 SemaDiagnosticBuilder noteExplicitConv(
16011 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16012 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16013 << ConvTy->isEnumeralType() << ConvTy;
16014 }
16015
16016 SemaDiagnosticBuilder diagnoseAmbiguous(
16017 Sema &S, SourceLocation Loc, QualType T) override {
16018 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
16019 }
16020
16021 SemaDiagnosticBuilder noteAmbiguous(
16022 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16023 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16024 << ConvTy->isEnumeralType() << ConvTy;
16025 }
16026
16027 SemaDiagnosticBuilder diagnoseConversion(
16028 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16029 llvm_unreachable("conversion functions are permitted")::llvm::llvm_unreachable_internal("conversion functions are permitted"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 16029)
;
16030 }
16031 } ConvertDiagnoser(Diagnoser);
16032
16033 Converted = PerformContextualImplicitConversion(DiagLoc, E,
16034 ConvertDiagnoser);
16035 if (Converted.isInvalid())
16036 return Converted;
16037 E = Converted.get();
16038 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
16039 return ExprError();
16040 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
16041 // An ICE must be of integral or unscoped enumeration type.
16042 if (!Diagnoser.Suppress)
16043 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
16044 << E->getSourceRange();
16045 return ExprError();
16046 }
16047
16048 ExprResult RValueExpr = DefaultLvalueConversion(E);
16049 if (RValueExpr.isInvalid())
16050 return ExprError();
16051
16052 E = RValueExpr.get();
16053
16054 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
16055 // in the non-ICE case.
16056 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
16057 if (Result)
16058 *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
16059 if (!isa<ConstantExpr>(E))
16060 E = ConstantExpr::Create(Context, E);
16061 return E;
16062 }
16063
16064 Expr::EvalResult EvalResult;
16065 SmallVector<PartialDiagnosticAt, 8> Notes;
16066 EvalResult.Diag = &Notes;
16067
16068 // Try to evaluate the expression, and produce diagnostics explaining why it's
16069 // not a constant expression as a side-effect.
16070 bool Folded =
16071 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
16072 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
16073
16074 if (!isa<ConstantExpr>(E))
16075 E = ConstantExpr::Create(Context, E, EvalResult.Val);
16076
16077 // In C++11, we can rely on diagnostics being produced for any expression
16078 // which is not a constant expression. If no diagnostics were produced, then
16079 // this is a constant expression.
16080 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
16081 if (Result)
16082 *Result = EvalResult.Val.getInt();
16083 return E;
16084 }
16085
16086 // If our only note is the usual "invalid subexpression" note, just point
16087 // the caret at its location rather than producing an essentially
16088 // redundant note.
16089 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
16090 diag::note_invalid_subexpr_in_const_expr) {
16091 DiagLoc = Notes[0].first;
16092 Notes.clear();
16093 }
16094
16095 if (!Folded || !CanFold) {
16096 if (!Diagnoser.Suppress) {
16097 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
16098 for (const PartialDiagnosticAt &Note : Notes)
16099 Diag(Note.first, Note.second);
16100 }
16101
16102 return ExprError();
16103 }
16104
16105 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
16106 for (const PartialDiagnosticAt &Note : Notes)
16107 Diag(Note.first, Note.second);
16108
16109 if (Result)
16110 *Result = EvalResult.Val.getInt();
16111 return E;
16112}
16113
16114namespace {
16115 // Handle the case where we conclude a expression which we speculatively
16116 // considered to be unevaluated is actually evaluated.
16117 class TransformToPE : public TreeTransform<TransformToPE> {
16118 typedef TreeTransform<TransformToPE> BaseTransform;
16119
16120 public:
16121 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
16122
16123 // Make sure we redo semantic analysis
16124 bool AlwaysRebuild() { return true; }
16125 bool ReplacingOriginal() { return true; }
16126
16127 // We need to special-case DeclRefExprs referring to FieldDecls which
16128 // are not part of a member pointer formation; normal TreeTransforming
16129 // doesn't catch this case because of the way we represent them in the AST.
16130 // FIXME: This is a bit ugly; is it really the best way to handle this
16131 // case?
16132 //
16133 // Error on DeclRefExprs referring to FieldDecls.
16134 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16135 if (isa<FieldDecl>(E->getDecl()) &&
16136 !SemaRef.isUnevaluatedContext())
16137 return SemaRef.Diag(E->getLocation(),
16138 diag::err_invalid_non_static_member_use)
16139 << E->getDecl() << E->getSourceRange();
16140
16141 return BaseTransform::TransformDeclRefExpr(E);
16142 }
16143
16144 // Exception: filter out member pointer formation
16145 ExprResult TransformUnaryOperator(UnaryOperator *E) {
16146 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
16147 return E;
16148
16149 return BaseTransform::TransformUnaryOperator(E);
16150 }
16151
16152 // The body of a lambda-expression is in a separate expression evaluation
16153 // context so never needs to be transformed.
16154 // FIXME: Ideally we wouldn't transform the closure type either, and would
16155 // just recreate the capture expressions and lambda expression.
16156 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
16157 return SkipLambdaBody(E, Body);
16158 }
16159 };
16160}
16161
16162ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
16163 assert(isUnevaluatedContext() &&((isUnevaluatedContext() && "Should only transform unevaluated expressions"
) ? static_cast<void> (0) : __assert_fail ("isUnevaluatedContext() && \"Should only transform unevaluated expressions\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 16164, __PRETTY_FUNCTION__))
16164 "Should only transform unevaluated expressions")((isUnevaluatedContext() && "Should only transform unevaluated expressions"
) ? static_cast<void> (0) : __assert_fail ("isUnevaluatedContext() && \"Should only transform unevaluated expressions\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 16164, __PRETTY_FUNCTION__))
;
16165 ExprEvalContexts.back().Context =
16166 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
16167 if (isUnevaluatedContext())
16168 return E;
16169 return TransformToPE(*this).TransformExpr(E);
16170}
16171
16172void
16173Sema::PushExpressionEvaluationContext(
16174 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
16175 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16176 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
16177 LambdaContextDecl, ExprContext);
16178 Cleanup.reset();
16179 if (!MaybeODRUseExprs.empty())
16180 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
16181}
16182
16183void
16184Sema::PushExpressionEvaluationContext(
16185 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
16186 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16187 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
16188 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
16189}
16190
16191namespace {
16192
16193const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
16194 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
16195 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
16196 if (E->getOpcode() == UO_Deref)
16197 return CheckPossibleDeref(S, E->getSubExpr());
16198 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
16199 return CheckPossibleDeref(S, E->getBase());
16200 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
16201 return CheckPossibleDeref(S, E->getBase());
16202 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
16203 QualType Inner;
16204 QualType Ty = E->getType();
16205 if (const auto *Ptr = Ty->getAs<PointerType>())
16206 Inner = Ptr->getPointeeType();
16207 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
16208 Inner = Arr->getElementType();
16209 else
16210 return nullptr;
16211
16212 if (Inner->hasAttr(attr::NoDeref))
16213 return E;
16214 }
16215 return nullptr;
16216}
16217
16218} // namespace
16219
16220void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
16221 for (const Expr *E : Rec.PossibleDerefs) {
16222 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
16223 if (DeclRef) {
16224 const ValueDecl *Decl = DeclRef->getDecl();
16225 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
16226 << Decl->getName() << E->getSourceRange();
16227 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
16228 } else {
16229 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
16230 << E->getSourceRange();
16231 }
16232 }
16233 Rec.PossibleDerefs.clear();
16234}
16235
16236/// Check whether E, which is either a discarded-value expression or an
16237/// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
16238/// and if so, remove it from the list of volatile-qualified assignments that
16239/// we are going to warn are deprecated.
16240void Sema::CheckUnusedVolatileAssignment(Expr *E) {
16241 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
16242 return;
16243
16244 // Note: ignoring parens here is not justified by the standard rules, but
16245 // ignoring parentheses seems like a more reasonable approach, and this only
16246 // drives a deprecation warning so doesn't affect conformance.
16247 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
16248 if (BO->getOpcode() == BO_Assign) {
16249 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
16250 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()),
16251 LHSs.end());
16252 }
16253 }
16254}
16255
16256ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
16257 if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() ||
16258 RebuildingImmediateInvocation)
16259 return E;
16260
16261 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
16262 /// It's OK if this fails; we'll also remove this in
16263 /// HandleImmediateInvocations, but catching it here allows us to avoid
16264 /// walking the AST looking for it in simple cases.
16265 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
16266 if (auto *DeclRef =
16267 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
16268 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
16269
16270 E = MaybeCreateExprWithCleanups(E);
16271
16272 ConstantExpr *Res = ConstantExpr::Create(
16273 getASTContext(), E.get(),
16274 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
16275 getASTContext()),
16276 /*IsImmediateInvocation*/ true);
16277 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
16278 return Res;
16279}
16280
16281static void EvaluateAndDiagnoseImmediateInvocation(
16282 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
16283 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
16284 Expr::EvalResult Eval;
16285 Eval.Diag = &Notes;
16286 ConstantExpr *CE = Candidate.getPointer();
16287 bool Result = CE->EvaluateAsConstantExpr(
16288 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
16289 if (!Result || !Notes.empty()) {
16290 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
16291 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
16292 InnerExpr = FunctionalCast->getSubExpr();
16293 FunctionDecl *FD = nullptr;
16294 if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
16295 FD = cast<FunctionDecl>(Call->getCalleeDecl());
16296 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
16297 FD = Call->getConstructor();
16298 else
16299 llvm_unreachable("unhandled decl kind")::llvm::llvm_unreachable_internal("unhandled decl kind", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 16299)
;
16300 assert(FD->isConsteval())((FD->isConsteval()) ? static_cast<void> (0) : __assert_fail
("FD->isConsteval()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 16300, __PRETTY_FUNCTION__))
;
16301 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
16302 for (auto &Note : Notes)
16303 SemaRef.Diag(Note.first, Note.second);
16304 return;
16305 }
16306 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
16307}
16308
16309static void RemoveNestedImmediateInvocation(
16310 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
16311 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
16312 struct ComplexRemove : TreeTransform<ComplexRemove> {
16313 using Base = TreeTransform<ComplexRemove>;
16314 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16315 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
16316 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
16317 CurrentII;
16318 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
16319 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
16320 SmallVector<Sema::ImmediateInvocationCandidate,
16321 4>::reverse_iterator Current)
16322 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
16323 void RemoveImmediateInvocation(ConstantExpr* E) {
16324 auto It = std::find_if(CurrentII, IISet.rend(),
16325 [E](Sema::ImmediateInvocationCandidate Elem) {
16326 return Elem.getPointer() == E;
16327 });
16328 assert(It != IISet.rend() &&((It != IISet.rend() && "ConstantExpr marked IsImmediateInvocation should "
"be present") ? static_cast<void> (0) : __assert_fail (
"It != IISet.rend() && \"ConstantExpr marked IsImmediateInvocation should \" \"be present\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 16330, __PRETTY_FUNCTION__))
16329 "ConstantExpr marked IsImmediateInvocation should "((It != IISet.rend() && "ConstantExpr marked IsImmediateInvocation should "
"be present") ? static_cast<void> (0) : __assert_fail (
"It != IISet.rend() && \"ConstantExpr marked IsImmediateInvocation should \" \"be present\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 16330, __PRETTY_FUNCTION__))
16330 "be present")((It != IISet.rend() && "ConstantExpr marked IsImmediateInvocation should "
"be present") ? static_cast<void> (0) : __assert_fail (
"It != IISet.rend() && \"ConstantExpr marked IsImmediateInvocation should \" \"be present\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 16330, __PRETTY_FUNCTION__))
;
16331 It->setInt(1); // Mark as deleted
16332 }
16333 ExprResult TransformConstantExpr(ConstantExpr *E) {
16334 if (!E->isImmediateInvocation())
16335 return Base::TransformConstantExpr(E);
16336 RemoveImmediateInvocation(E);
16337 return Base::TransformExpr(E->getSubExpr());
16338 }
16339 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
16340 /// we need to remove its DeclRefExpr from the DRSet.
16341 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
16342 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
16343 return Base::TransformCXXOperatorCallExpr(E);
16344 }
16345 /// Base::TransformInitializer skip ConstantExpr so we need to visit them
16346 /// here.
16347 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
16348 if (!Init)
16349 return Init;
16350 /// ConstantExpr are the first layer of implicit node to be removed so if
16351 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
16352 if (auto *CE = dyn_cast<ConstantExpr>(Init))
16353 if (CE->isImmediateInvocation())
16354 RemoveImmediateInvocation(CE);
16355 return Base::TransformInitializer(Init, NotCopyInit);
16356 }
16357 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16358 DRSet.erase(E);
16359 return E;
16360 }
16361 bool AlwaysRebuild() { return false; }
16362 bool ReplacingOriginal() { return true; }
16363 bool AllowSkippingCXXConstructExpr() {
16364 bool Res = AllowSkippingFirstCXXConstructExpr;
16365 AllowSkippingFirstCXXConstructExpr = true;
16366 return Res;
16367 }
16368 bool AllowSkippingFirstCXXConstructExpr = true;
16369 } Transformer(SemaRef, Rec.ReferenceToConsteval,
16370 Rec.ImmediateInvocationCandidates, It);
16371
16372 /// CXXConstructExpr with a single argument are getting skipped by
16373 /// TreeTransform in some situtation because they could be implicit. This
16374 /// can only occur for the top-level CXXConstructExpr because it is used
16375 /// nowhere in the expression being transformed therefore will not be rebuilt.
16376 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
16377 /// skipping the first CXXConstructExpr.
16378 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
16379 Transformer.AllowSkippingFirstCXXConstructExpr = false;
16380
16381 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
16382 assert(Res.isUsable())((Res.isUsable()) ? static_cast<void> (0) : __assert_fail
("Res.isUsable()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 16382, __PRETTY_FUNCTION__))
;
16383 Res = SemaRef.MaybeCreateExprWithCleanups(Res);
16384 It->getPointer()->setSubExpr(Res.get());
16385}
16386
16387static void
16388HandleImmediateInvocations(Sema &SemaRef,
16389 Sema::ExpressionEvaluationContextRecord &Rec) {
16390 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
16391 Rec.ReferenceToConsteval.size() == 0) ||
16392 SemaRef.RebuildingImmediateInvocation)
16393 return;
16394
16395 /// When we have more then 1 ImmediateInvocationCandidates we need to check
16396 /// for nested ImmediateInvocationCandidates. when we have only 1 we only
16397 /// need to remove ReferenceToConsteval in the immediate invocation.
16398 if (Rec.ImmediateInvocationCandidates.size() > 1) {
16399
16400 /// Prevent sema calls during the tree transform from adding pointers that
16401 /// are already in the sets.
16402 llvm::SaveAndRestore<bool> DisableIITracking(
16403 SemaRef.RebuildingImmediateInvocation, true);
16404
16405 /// Prevent diagnostic during tree transfrom as they are duplicates
16406 Sema::TentativeAnalysisScope DisableDiag(SemaRef);
16407
16408 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
16409 It != Rec.ImmediateInvocationCandidates.rend(); It++)
16410 if (!It->getInt())
16411 RemoveNestedImmediateInvocation(SemaRef, Rec, It);
16412 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
16413 Rec.ReferenceToConsteval.size()) {
16414 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
16415 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16416 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
16417 bool VisitDeclRefExpr(DeclRefExpr *E) {
16418 DRSet.erase(E);
16419 return DRSet.size();
16420 }
16421 } Visitor(Rec.ReferenceToConsteval);
16422 Visitor.TraverseStmt(
16423 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
16424 }
16425 for (auto CE : Rec.ImmediateInvocationCandidates)
16426 if (!CE.getInt())
16427 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
16428 for (auto DR : Rec.ReferenceToConsteval) {
16429 auto *FD = cast<FunctionDecl>(DR->getDecl());
16430 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
16431 << FD;
16432 SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
16433 }
16434}
16435
16436void Sema::PopExpressionEvaluationContext() {
16437 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
16438 unsigned NumTypos = Rec.NumTypos;
16439
16440 if (!Rec.Lambdas.empty()) {
16441 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
16442 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
16443 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
16444 unsigned D;
16445 if (Rec.isUnevaluated()) {
16446 // C++11 [expr.prim.lambda]p2:
16447 // A lambda-expression shall not appear in an unevaluated operand
16448 // (Clause 5).
16449 D = diag::err_lambda_unevaluated_operand;
16450 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
16451 // C++1y [expr.const]p2:
16452 // A conditional-expression e is a core constant expression unless the
16453 // evaluation of e, following the rules of the abstract machine, would
16454 // evaluate [...] a lambda-expression.
16455 D = diag::err_lambda_in_constant_expression;
16456 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
16457 // C++17 [expr.prim.lamda]p2:
16458 // A lambda-expression shall not appear [...] in a template-argument.
16459 D = diag::err_lambda_in_invalid_context;
16460 } else
16461 llvm_unreachable("Couldn't infer lambda error message.")::llvm::llvm_unreachable_internal("Couldn't infer lambda error message."
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 16461)
;
16462
16463 for (const auto *L : Rec.Lambdas)
16464 Diag(L->getBeginLoc(), D);
16465 }
16466 }
16467
16468 WarnOnPendingNoDerefs(Rec);
16469 HandleImmediateInvocations(*this, Rec);
16470
16471 // Warn on any volatile-qualified simple-assignments that are not discarded-
16472 // value expressions nor unevaluated operands (those cases get removed from
16473 // this list by CheckUnusedVolatileAssignment).
16474 for (auto *BO : Rec.VolatileAssignmentLHSs)
16475 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
16476 << BO->getType();
16477
16478 // When are coming out of an unevaluated context, clear out any
16479 // temporaries that we may have created as part of the evaluation of
16480 // the expression in that context: they aren't relevant because they
16481 // will never be constructed.
16482 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
16483 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
16484 ExprCleanupObjects.end());
16485 Cleanup = Rec.ParentCleanup;
16486 CleanupVarDeclMarking();
16487 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
16488 // Otherwise, merge the contexts together.
16489 } else {
16490 Cleanup.mergeFrom(Rec.ParentCleanup);
16491 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
16492 Rec.SavedMaybeODRUseExprs.end());
16493 }
16494
16495 // Pop the current expression evaluation context off the stack.
16496 ExprEvalContexts.pop_back();
16497
16498 // The global expression evaluation context record is never popped.
16499 ExprEvalContexts.back().NumTypos += NumTypos;
16500}
16501
16502void Sema::DiscardCleanupsInEvaluationContext() {
16503 ExprCleanupObjects.erase(
16504 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
16505 ExprCleanupObjects.end());
16506 Cleanup.reset();
16507 MaybeODRUseExprs.clear();
16508}
16509
16510ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
16511 ExprResult Result = CheckPlaceholderExpr(E);
16512 if (Result.isInvalid())
16513 return ExprError();
16514 E = Result.get();
16515 if (!E->getType()->isVariablyModifiedType())
16516 return E;
16517 return TransformToPotentiallyEvaluated(E);
16518}
16519
16520/// Are we in a context that is potentially constant evaluated per C++20
16521/// [expr.const]p12?
16522static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
16523 /// C++2a [expr.const]p12:
16524 // An expression or conversion is potentially constant evaluated if it is
16525 switch (SemaRef.ExprEvalContexts.back().Context) {
16526 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16527 // -- a manifestly constant-evaluated expression,
16528 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16529 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16530 case Sema::ExpressionEvaluationContext::DiscardedStatement:
16531 // -- a potentially-evaluated expression,
16532 case Sema::ExpressionEvaluationContext::UnevaluatedList:
16533 // -- an immediate subexpression of a braced-init-list,
16534
16535 // -- [FIXME] an expression of the form & cast-expression that occurs
16536 // within a templated entity
16537 // -- a subexpression of one of the above that is not a subexpression of
16538 // a nested unevaluated operand.
16539 return true;
16540
16541 case Sema::ExpressionEvaluationContext::Unevaluated:
16542 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16543 // Expressions in this context are never evaluated.
16544 return false;
16545 }
16546 llvm_unreachable("Invalid context")::llvm::llvm_unreachable_internal("Invalid context", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 16546)
;
16547}
16548
16549/// Return true if this function has a calling convention that requires mangling
16550/// in the size of the parameter pack.
16551static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
16552 // These manglings don't do anything on non-Windows or non-x86 platforms, so
16553 // we don't need parameter type sizes.
16554 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
16555 if (!TT.isOSWindows() || !TT.isX86())
16556 return false;
16557
16558 // If this is C++ and this isn't an extern "C" function, parameters do not
16559 // need to be complete. In this case, C++ mangling will apply, which doesn't
16560 // use the size of the parameters.
16561 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
16562 return false;
16563
16564 // Stdcall, fastcall, and vectorcall need this special treatment.
16565 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16566 switch (CC) {
16567 case CC_X86StdCall:
16568 case CC_X86FastCall:
16569 case CC_X86VectorCall:
16570 return true;
16571 default:
16572 break;
16573 }
16574 return false;
16575}
16576
16577/// Require that all of the parameter types of function be complete. Normally,
16578/// parameter types are only required to be complete when a function is called
16579/// or defined, but to mangle functions with certain calling conventions, the
16580/// mangler needs to know the size of the parameter list. In this situation,
16581/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
16582/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
16583/// result in a linker error. Clang doesn't implement this behavior, and instead
16584/// attempts to error at compile time.
16585static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
16586 SourceLocation Loc) {
16587 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
16588 FunctionDecl *FD;
16589 ParmVarDecl *Param;
16590
16591 public:
16592 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
16593 : FD(FD), Param(Param) {}
16594
16595 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
16596 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16597 StringRef CCName;
16598 switch (CC) {
16599 case CC_X86StdCall:
16600 CCName = "stdcall";
16601 break;
16602 case CC_X86FastCall:
16603 CCName = "fastcall";
16604 break;
16605 case CC_X86VectorCall:
16606 CCName = "vectorcall";
16607 break;
16608 default:
16609 llvm_unreachable("CC does not need mangling")::llvm::llvm_unreachable_internal("CC does not need mangling"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 16609)
;
16610 }
16611
16612 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
16613 << Param->getDeclName() << FD->getDeclName() << CCName;
16614 }
16615 };
16616
16617 for (ParmVarDecl *Param : FD->parameters()) {
16618 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
16619 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
16620 }
16621}
16622
16623namespace {
16624enum class OdrUseContext {
16625 /// Declarations in this context are not odr-used.
16626 None,
16627 /// Declarations in this context are formally odr-used, but this is a
16628 /// dependent context.
16629 Dependent,
16630 /// Declarations in this context are odr-used but not actually used (yet).
16631 FormallyOdrUsed,
16632 /// Declarations in this context are used.
16633 Used
16634};
16635}
16636
16637/// Are we within a context in which references to resolved functions or to
16638/// variables result in odr-use?
16639static OdrUseContext isOdrUseContext(Sema &SemaRef) {
16640 OdrUseContext Result;
16641
16642 switch (SemaRef.ExprEvalContexts.back().Context) {
16643 case Sema::ExpressionEvaluationContext::Unevaluated:
16644 case Sema::ExpressionEvaluationContext::UnevaluatedList:
16645 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16646 return OdrUseContext::None;
16647
16648 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16649 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16650 Result = OdrUseContext::Used;
16651 break;
16652
16653 case Sema::ExpressionEvaluationContext::DiscardedStatement:
16654 Result = OdrUseContext::FormallyOdrUsed;
16655 break;
16656
16657 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16658 // A default argument formally results in odr-use, but doesn't actually
16659 // result in a use in any real sense until it itself is used.
16660 Result = OdrUseContext::FormallyOdrUsed;
16661 break;
16662 }
16663
16664 if (SemaRef.CurContext->isDependentContext())
16665 return OdrUseContext::Dependent;
16666
16667 return Result;
16668}
16669
16670static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
16671 if (!Func->isConstexpr())
16672 return false;
16673
16674 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
16675 return true;
16676 auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
16677 return CCD && CCD->getInheritedConstructor();
16678}
16679
16680/// Mark a function referenced, and check whether it is odr-used
16681/// (C++ [basic.def.odr]p2, C99 6.9p3)
16682void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
16683 bool MightBeOdrUse) {
16684 assert(Func && "No function?")((Func && "No function?") ? static_cast<void> (
0) : __assert_fail ("Func && \"No function?\"", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 16684, __PRETTY_FUNCTION__))
;
16685
16686 Func->setReferenced();
16687
16688 // Recursive functions aren't really used until they're used from some other
16689 // context.
16690 bool IsRecursiveCall = CurContext == Func;
16691
16692 // C++11 [basic.def.odr]p3:
16693 // A function whose name appears as a potentially-evaluated expression is
16694 // odr-used if it is the unique lookup result or the selected member of a
16695 // set of overloaded functions [...].
16696 //
16697 // We (incorrectly) mark overload resolution as an unevaluated context, so we
16698 // can just check that here.
16699 OdrUseContext OdrUse =
16700 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
16701 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
16702 OdrUse = OdrUseContext::FormallyOdrUsed;
16703
16704 // Trivial default constructors and destructors are never actually used.
16705 // FIXME: What about other special members?
16706 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
16707 OdrUse == OdrUseContext::Used) {
16708 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
16709 if (Constructor->isDefaultConstructor())
16710 OdrUse = OdrUseContext::FormallyOdrUsed;
16711 if (isa<CXXDestructorDecl>(Func))
16712 OdrUse = OdrUseContext::FormallyOdrUsed;
16713 }
16714
16715 // C++20 [expr.const]p12:
16716 // A function [...] is needed for constant evaluation if it is [...] a
16717 // constexpr function that is named by an expression that is potentially
16718 // constant evaluated
16719 bool NeededForConstantEvaluation =
16720 isPotentiallyConstantEvaluatedContext(*this) &&
16721 isImplicitlyDefinableConstexprFunction(Func);
16722
16723 // Determine whether we require a function definition to exist, per
16724 // C++11 [temp.inst]p3:
16725 // Unless a function template specialization has been explicitly
16726 // instantiated or explicitly specialized, the function template
16727 // specialization is implicitly instantiated when the specialization is
16728 // referenced in a context that requires a function definition to exist.
16729 // C++20 [temp.inst]p7:
16730 // The existence of a definition of a [...] function is considered to
16731 // affect the semantics of the program if the [...] function is needed for
16732 // constant evaluation by an expression
16733 // C++20 [basic.def.odr]p10:
16734 // Every program shall contain exactly one definition of every non-inline
16735 // function or variable that is odr-used in that program outside of a
16736 // discarded statement
16737 // C++20 [special]p1:
16738 // The implementation will implicitly define [defaulted special members]
16739 // if they are odr-used or needed for constant evaluation.
16740 //
16741 // Note that we skip the implicit instantiation of templates that are only
16742 // used in unused default arguments or by recursive calls to themselves.
16743 // This is formally non-conforming, but seems reasonable in practice.
16744 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
16745 NeededForConstantEvaluation);
16746
16747 // C++14 [temp.expl.spec]p6:
16748 // If a template [...] is explicitly specialized then that specialization
16749 // shall be declared before the first use of that specialization that would
16750 // cause an implicit instantiation to take place, in every translation unit
16751 // in which such a use occurs
16752 if (NeedDefinition &&
16753 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
16754 Func->getMemberSpecializationInfo()))
16755 checkSpecializationVisibility(Loc, Func);
16756
16757 if (getLangOpts().CUDA)
16758 CheckCUDACall(Loc, Func);
16759
16760 if (getLangOpts().SYCLIsDevice)
16761 checkSYCLDeviceFunction(Loc, Func);
16762
16763 // If we need a definition, try to create one.
16764 if (NeedDefinition && !Func->getBody()) {
16765 runWithSufficientStackSpace(Loc, [&] {
16766 if (CXXConstructorDecl *Constructor =
16767 dyn_cast<CXXConstructorDecl>(Func)) {
16768 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
16769 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
16770 if (Constructor->isDefaultConstructor()) {
16771 if (Constructor->isTrivial() &&
16772 !Constructor->hasAttr<DLLExportAttr>())
16773 return;
16774 DefineImplicitDefaultConstructor(Loc, Constructor);
16775 } else if (Constructor->isCopyConstructor()) {
16776 DefineImplicitCopyConstructor(Loc, Constructor);
16777 } else if (Constructor->isMoveConstructor()) {
16778 DefineImplicitMoveConstructor(Loc, Constructor);
16779 }
16780 } else if (Constructor->getInheritedConstructor()) {
16781 DefineInheritingConstructor(Loc, Constructor);
16782 }
16783 } else if (CXXDestructorDecl *Destructor =
16784 dyn_cast<CXXDestructorDecl>(Func)) {
16785 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
16786 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
16787 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
16788 return;
16789 DefineImplicitDestructor(Loc, Destructor);
16790 }
16791 if (Destructor->isVirtual() && getLangOpts().AppleKext)
16792 MarkVTableUsed(Loc, Destructor->getParent());
16793 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
16794 if (MethodDecl->isOverloadedOperator() &&
16795 MethodDecl->getOverloadedOperator() == OO_Equal) {
16796 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
16797 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
16798 if (MethodDecl->isCopyAssignmentOperator())
16799 DefineImplicitCopyAssignment(Loc, MethodDecl);
16800 else if (MethodDecl->isMoveAssignmentOperator())
16801 DefineImplicitMoveAssignment(Loc, MethodDecl);
16802 }
16803 } else if (isa<CXXConversionDecl>(MethodDecl) &&
16804 MethodDecl->getParent()->isLambda()) {
16805 CXXConversionDecl *Conversion =
16806 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
16807 if (Conversion->isLambdaToBlockPointerConversion())
16808 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
16809 else
16810 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
16811 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
16812 MarkVTableUsed(Loc, MethodDecl->getParent());
16813 }
16814
16815 if (Func->isDefaulted() && !Func->isDeleted()) {
16816 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
16817 if (DCK != DefaultedComparisonKind::None)
16818 DefineDefaultedComparison(Loc, Func, DCK);
16819 }
16820
16821 // Implicit instantiation of function templates and member functions of
16822 // class templates.
16823 if (Func->isImplicitlyInstantiable()) {
16824 TemplateSpecializationKind TSK =
16825 Func->getTemplateSpecializationKindForInstantiation();
16826 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
16827 bool FirstInstantiation = PointOfInstantiation.isInvalid();
16828 if (FirstInstantiation) {
16829 PointOfInstantiation = Loc;
16830 if (auto *MSI = Func->getMemberSpecializationInfo())
16831 MSI->setPointOfInstantiation(Loc);
16832 // FIXME: Notify listener.
16833 else
16834 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
16835 } else if (TSK != TSK_ImplicitInstantiation) {
16836 // Use the point of use as the point of instantiation, instead of the
16837 // point of explicit instantiation (which we track as the actual point
16838 // of instantiation). This gives better backtraces in diagnostics.
16839 PointOfInstantiation = Loc;
16840 }
16841
16842 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
16843 Func->isConstexpr()) {
16844 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
16845 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
16846 CodeSynthesisContexts.size())
16847 PendingLocalImplicitInstantiations.push_back(
16848 std::make_pair(Func, PointOfInstantiation));
16849 else if (Func->isConstexpr())
16850 // Do not defer instantiations of constexpr functions, to avoid the
16851 // expression evaluator needing to call back into Sema if it sees a
16852 // call to such a function.
16853 InstantiateFunctionDefinition(PointOfInstantiation, Func);
16854 else {
16855 Func->setInstantiationIsPending(true);
16856 PendingInstantiations.push_back(
16857 std::make_pair(Func, PointOfInstantiation));
16858 // Notify the consumer that a function was implicitly instantiated.
16859 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
16860 }
16861 }
16862 } else {
16863 // Walk redefinitions, as some of them may be instantiable.
16864 for (auto i : Func->redecls()) {
16865 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
16866 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
16867 }
16868 }
16869 });
16870 }
16871
16872 // C++14 [except.spec]p17:
16873 // An exception-specification is considered to be needed when:
16874 // - the function is odr-used or, if it appears in an unevaluated operand,
16875 // would be odr-used if the expression were potentially-evaluated;
16876 //
16877 // Note, we do this even if MightBeOdrUse is false. That indicates that the
16878 // function is a pure virtual function we're calling, and in that case the
16879 // function was selected by overload resolution and we need to resolve its
16880 // exception specification for a different reason.
16881 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
16882 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
16883 ResolveExceptionSpec(Loc, FPT);
16884
16885 // If this is the first "real" use, act on that.
16886 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
16887 // Keep track of used but undefined functions.
16888 if (!Func->isDefined()) {
16889 if (mightHaveNonExternalLinkage(Func))
16890 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16891 else if (Func->getMostRecentDecl()->isInlined() &&
16892 !LangOpts.GNUInline &&
16893 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
16894 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16895 else if (isExternalWithNoLinkageType(Func))
16896 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16897 }
16898
16899 // Some x86 Windows calling conventions mangle the size of the parameter
16900 // pack into the name. Computing the size of the parameters requires the
16901 // parameter types to be complete. Check that now.
16902 if (funcHasParameterSizeMangling(*this, Func))
16903 CheckCompleteParameterTypesForMangler(*this, Func, Loc);
16904
16905 // In the MS C++ ABI, the compiler emits destructor variants where they are
16906 // used. If the destructor is used here but defined elsewhere, mark the
16907 // virtual base destructors referenced. If those virtual base destructors
16908 // are inline, this will ensure they are defined when emitting the complete
16909 // destructor variant. This checking may be redundant if the destructor is
16910 // provided later in this TU.
16911 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16912 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
16913 CXXRecordDecl *Parent = Dtor->getParent();
16914 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
16915 CheckCompleteDestructorVariant(Loc, Dtor);
16916 }
16917 }
16918
16919 Func->markUsed(Context);
16920 }
16921}
16922
16923/// Directly mark a variable odr-used. Given a choice, prefer to use
16924/// MarkVariableReferenced since it does additional checks and then
16925/// calls MarkVarDeclODRUsed.
16926/// If the variable must be captured:
16927/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
16928/// - else capture it in the DeclContext that maps to the
16929/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
16930static void
16931MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
16932 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
16933 // Keep track of used but undefined variables.
16934 // FIXME: We shouldn't suppress this warning for static data members.
16935 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
16936 (!Var->isExternallyVisible() || Var->isInline() ||
16937 SemaRef.isExternalWithNoLinkageType(Var)) &&
16938 !(Var->isStaticDataMember() && Var->hasInit())) {
16939 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
16940 if (old.isInvalid())
16941 old = Loc;
16942 }
16943 QualType CaptureType, DeclRefType;
16944 if (SemaRef.LangOpts.OpenMP)
16945 SemaRef.tryCaptureOpenMPLambdas(Var);
16946 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
16947 /*EllipsisLoc*/ SourceLocation(),
16948 /*BuildAndDiagnose*/ true,
16949 CaptureType, DeclRefType,
16950 FunctionScopeIndexToStopAt);
16951
16952 Var->markUsed(SemaRef.Context);
16953}
16954
16955void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
16956 SourceLocation Loc,
16957 unsigned CapturingScopeIndex) {
16958 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
16959}
16960
16961static void
16962diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
16963 ValueDecl *var, DeclContext *DC) {
16964 DeclContext *VarDC = var->getDeclContext();
16965
16966 // If the parameter still belongs to the translation unit, then
16967 // we're actually just using one parameter in the declaration of
16968 // the next.
16969 if (isa<ParmVarDecl>(var) &&
16970 isa<TranslationUnitDecl>(VarDC))
16971 return;
16972
16973 // For C code, don't diagnose about capture if we're not actually in code
16974 // right now; it's impossible to write a non-constant expression outside of
16975 // function context, so we'll get other (more useful) diagnostics later.
16976 //
16977 // For C++, things get a bit more nasty... it would be nice to suppress this
16978 // diagnostic for certain cases like using a local variable in an array bound
16979 // for a member of a local class, but the correct predicate is not obvious.
16980 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
16981 return;
16982
16983 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
16984 unsigned ContextKind = 3; // unknown
16985 if (isa<CXXMethodDecl>(VarDC) &&
16986 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
16987 ContextKind = 2;
16988 } else if (isa<FunctionDecl>(VarDC)) {
16989 ContextKind = 0;
16990 } else if (isa<BlockDecl>(VarDC)) {
16991 ContextKind = 1;
16992 }
16993
16994 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
16995 << var << ValueKind << ContextKind << VarDC;
16996 S.Diag(var->getLocation(), diag::note_entity_declared_at)
16997 << var;
16998
16999 // FIXME: Add additional diagnostic info about class etc. which prevents
17000 // capture.
17001}
17002
17003
17004static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
17005 bool &SubCapturesAreNested,
17006 QualType &CaptureType,
17007 QualType &DeclRefType) {
17008 // Check whether we've already captured it.
17009 if (CSI->CaptureMap.count(Var)) {
17010 // If we found a capture, any subcaptures are nested.
17011 SubCapturesAreNested = true;
17012
17013 // Retrieve the capture type for this variable.
17014 CaptureType = CSI->getCapture(Var).getCaptureType();
17015
17016 // Compute the type of an expression that refers to this variable.
17017 DeclRefType = CaptureType.getNonReferenceType();
17018
17019 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
17020 // are mutable in the sense that user can change their value - they are
17021 // private instances of the captured declarations.
17022 const Capture &Cap = CSI->getCapture(Var);
17023 if (Cap.isCopyCapture() &&
17024 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
17025 !(isa<CapturedRegionScopeInfo>(CSI) &&
17026 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
17027 DeclRefType.addConst();
17028 return true;
17029 }
17030 return false;
17031}
17032
17033// Only block literals, captured statements, and lambda expressions can
17034// capture; other scopes don't work.
17035static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
17036 SourceLocation Loc,
17037 const bool Diagnose, Sema &S) {
17038 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
17039 return getLambdaAwareParentOfDeclContext(DC);
17040 else if (Var->hasLocalStorage()) {
17041 if (Diagnose)
17042 diagnoseUncapturableValueReference(S, Loc, Var, DC);
17043 }
17044 return nullptr;
17045}
17046
17047// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
17048// certain types of variables (unnamed, variably modified types etc.)
17049// so check for eligibility.
17050static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
17051 SourceLocation Loc,
17052 const bool Diagnose, Sema &S) {
17053
17054 bool IsBlock = isa<BlockScopeInfo>(CSI);
17055 bool IsLambda = isa<LambdaScopeInfo>(CSI);
17056
17057 // Lambdas are not allowed to capture unnamed variables
17058 // (e.g. anonymous unions).
17059 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
17060 // assuming that's the intent.
17061 if (IsLambda && !Var->getDeclName()) {
17062 if (Diagnose) {
17063 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
17064 S.Diag(Var->getLocation(), diag::note_declared_at);
17065 }
17066 return false;
17067 }
17068
17069 // Prohibit variably-modified types in blocks; they're difficult to deal with.
17070 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
17071 if (Diagnose) {
17072 S.Diag(Loc, diag::err_ref_vm_type);
17073 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17074 }
17075 return false;
17076 }
17077 // Prohibit structs with flexible array members too.
17078 // We cannot capture what is in the tail end of the struct.
17079 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
17080 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
17081 if (Diagnose) {
17082 if (IsBlock)
17083 S.Diag(Loc, diag::err_ref_flexarray_type);
17084 else
17085 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
17086 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17087 }
17088 return false;
17089 }
17090 }
17091 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17092 // Lambdas and captured statements are not allowed to capture __block
17093 // variables; they don't support the expected semantics.
17094 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
17095 if (Diagnose) {
17096 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
17097 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17098 }
17099 return false;
17100 }
17101 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
17102 if (S.getLangOpts().OpenCL && IsBlock &&
17103 Var->getType()->isBlockPointerType()) {
17104 if (Diagnose)
17105 S.Diag(Loc, diag::err_opencl_block_ref_block);
17106 return false;
17107 }
17108
17109 return true;
17110}
17111
17112// Returns true if the capture by block was successful.
17113static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
17114 SourceLocation Loc,
17115 const bool BuildAndDiagnose,
17116 QualType &CaptureType,
17117 QualType &DeclRefType,
17118 const bool Nested,
17119 Sema &S, bool Invalid) {
17120 bool ByRef = false;
17121
17122 // Blocks are not allowed to capture arrays, excepting OpenCL.
17123 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
17124 // (decayed to pointers).
17125 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
17126 if (BuildAndDiagnose) {
17127 S.Diag(Loc, diag::err_ref_array_type);
17128 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17129 Invalid = true;
17130 } else {
17131 return false;
17132 }
17133 }
17134
17135 // Forbid the block-capture of autoreleasing variables.
17136 if (!Invalid &&
17137 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17138 if (BuildAndDiagnose) {
17139 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
17140 << /*block*/ 0;
17141 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17142 Invalid = true;
17143 } else {
17144 return false;
17145 }
17146 }
17147
17148 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
17149 if (const auto *PT = CaptureType->getAs<PointerType>()) {
17150 QualType PointeeTy = PT->getPointeeType();
17151
17152 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
17153 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
17154 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
17155 if (BuildAndDiagnose) {
17156 SourceLocation VarLoc = Var->getLocation();
17157 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
17158 S.Diag(VarLoc, diag::note_declare_parameter_strong);
17159 }
17160 }
17161 }
17162
17163 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17164 if (HasBlocksAttr || CaptureType->isReferenceType() ||
17165 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
17166 // Block capture by reference does not change the capture or
17167 // declaration reference types.
17168 ByRef = true;
17169 } else {
17170 // Block capture by copy introduces 'const'.
17171 CaptureType = CaptureType.getNonReferenceType().withConst();
17172 DeclRefType = CaptureType;
17173 }
17174
17175 // Actually capture the variable.
17176 if (BuildAndDiagnose)
17177 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
17178 CaptureType, Invalid);
17179
17180 return !Invalid;
17181}
17182
17183
17184/// Capture the given variable in the captured region.
17185static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
17186 VarDecl *Var,
17187 SourceLocation Loc,
17188 const bool BuildAndDiagnose,
17189 QualType &CaptureType,
17190 QualType &DeclRefType,
17191 const bool RefersToCapturedVariable,
17192 Sema &S, bool Invalid) {
17193 // By default, capture variables by reference.
17194 bool ByRef = true;
17195 // Using an LValue reference type is consistent with Lambdas (see below).
17196 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
17197 if (S.isOpenMPCapturedDecl(Var)) {
17198 bool HasConst = DeclRefType.isConstQualified();
17199 DeclRefType = DeclRefType.getUnqualifiedType();
17200 // Don't lose diagnostics about assignments to const.
17201 if (HasConst)
17202 DeclRefType.addConst();
17203 }
17204 // Do not capture firstprivates in tasks.
17205 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
17206 OMPC_unknown)
17207 return true;
17208 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
17209 RSI->OpenMPCaptureLevel);
17210 }
17211
17212 if (ByRef)
17213 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17214 else
17215 CaptureType = DeclRefType;
17216
17217 // Actually capture the variable.
17218 if (BuildAndDiagnose)
17219 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
17220 Loc, SourceLocation(), CaptureType, Invalid);
17221
17222 return !Invalid;
17223}
17224
17225/// Capture the given variable in the lambda.
17226static bool captureInLambda(LambdaScopeInfo *LSI,
17227 VarDecl *Var,
17228 SourceLocation Loc,
17229 const bool BuildAndDiagnose,
17230 QualType &CaptureType,
17231 QualType &DeclRefType,
17232 const bool RefersToCapturedVariable,
17233 const Sema::TryCaptureKind Kind,
17234 SourceLocation EllipsisLoc,
17235 const bool IsTopScope,
17236 Sema &S, bool Invalid) {
17237 // Determine whether we are capturing by reference or by value.
17238 bool ByRef = false;
17239 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
17240 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
17241 } else {
17242 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
17243 }
17244
17245 // Compute the type of the field that will capture this variable.
17246 if (ByRef) {
17247 // C++11 [expr.prim.lambda]p15:
17248 // An entity is captured by reference if it is implicitly or
17249 // explicitly captured but not captured by copy. It is
17250 // unspecified whether additional unnamed non-static data
17251 // members are declared in the closure type for entities
17252 // captured by reference.
17253 //
17254 // FIXME: It is not clear whether we want to build an lvalue reference
17255 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
17256 // to do the former, while EDG does the latter. Core issue 1249 will
17257 // clarify, but for now we follow GCC because it's a more permissive and
17258 // easily defensible position.
17259 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17260 } else {
17261 // C++11 [expr.prim.lambda]p14:
17262 // For each entity captured by copy, an unnamed non-static
17263 // data member is declared in the closure type. The
17264 // declaration order of these members is unspecified. The type
17265 // of such a data member is the type of the corresponding
17266 // captured entity if the entity is not a reference to an
17267 // object, or the referenced type otherwise. [Note: If the
17268 // captured entity is a reference to a function, the
17269 // corresponding data member is also a reference to a
17270 // function. - end note ]
17271 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
17272 if (!RefType->getPointeeType()->isFunctionType())
17273 CaptureType = RefType->getPointeeType();
17274 }
17275
17276 // Forbid the lambda copy-capture of autoreleasing variables.
17277 if (!Invalid &&
17278 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17279 if (BuildAndDiagnose) {
17280 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
17281 S.Diag(Var->getLocation(), diag::note_previous_decl)
17282 << Var->getDeclName();
17283 Invalid = true;
17284 } else {
17285 return false;
17286 }
17287 }
17288
17289 // Make sure that by-copy captures are of a complete and non-abstract type.
17290 if (!Invalid && BuildAndDiagnose) {
17291 if (!CaptureType->isDependentType() &&
17292 S.RequireCompleteSizedType(
17293 Loc, CaptureType,
17294 diag::err_capture_of_incomplete_or_sizeless_type,
17295 Var->getDeclName()))
17296 Invalid = true;
17297 else if (S.RequireNonAbstractType(Loc, CaptureType,
17298 diag::err_capture_of_abstract_type))
17299 Invalid = true;
17300 }
17301 }
17302
17303 // Compute the type of a reference to this captured variable.
17304 if (ByRef)
17305 DeclRefType = CaptureType.getNonReferenceType();
17306 else {
17307 // C++ [expr.prim.lambda]p5:
17308 // The closure type for a lambda-expression has a public inline
17309 // function call operator [...]. This function call operator is
17310 // declared const (9.3.1) if and only if the lambda-expression's
17311 // parameter-declaration-clause is not followed by mutable.
17312 DeclRefType = CaptureType.getNonReferenceType();
17313 if (!LSI->Mutable && !CaptureType->isReferenceType())
17314 DeclRefType.addConst();
17315 }
17316
17317 // Add the capture.
17318 if (BuildAndDiagnose)
17319 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
17320 Loc, EllipsisLoc, CaptureType, Invalid);
17321
17322 return !Invalid;
17323}
17324
17325bool Sema::tryCaptureVariable(
17326 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
17327 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
17328 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
17329 // An init-capture is notionally from the context surrounding its
17330 // declaration, but its parent DC is the lambda class.
17331 DeclContext *VarDC = Var->getDeclContext();
17332 if (Var->isInitCapture())
17333 VarDC = VarDC->getParent();
17334
17335 DeclContext *DC = CurContext;
17336 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
17337 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
17338 // We need to sync up the Declaration Context with the
17339 // FunctionScopeIndexToStopAt
17340 if (FunctionScopeIndexToStopAt) {
17341 unsigned FSIndex = FunctionScopes.size() - 1;
17342 while (FSIndex != MaxFunctionScopesIndex) {
17343 DC = getLambdaAwareParentOfDeclContext(DC);
17344 --FSIndex;
17345 }
17346 }
17347
17348
17349 // If the variable is declared in the current context, there is no need to
17350 // capture it.
17351 if (VarDC == DC) return true;
17352
17353 // Capture global variables if it is required to use private copy of this
17354 // variable.
17355 bool IsGlobal = !Var->hasLocalStorage();
17356 if (IsGlobal &&
17357 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
17358 MaxFunctionScopesIndex)))
17359 return true;
17360 Var = Var->getCanonicalDecl();
17361
17362 // Walk up the stack to determine whether we can capture the variable,
17363 // performing the "simple" checks that don't depend on type. We stop when
17364 // we've either hit the declared scope of the variable or find an existing
17365 // capture of that variable. We start from the innermost capturing-entity
17366 // (the DC) and ensure that all intervening capturing-entities
17367 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
17368 // declcontext can either capture the variable or have already captured
17369 // the variable.
17370 CaptureType = Var->getType();
17371 DeclRefType = CaptureType.getNonReferenceType();
17372 bool Nested = false;
17373 bool Explicit = (Kind != TryCapture_Implicit);
17374 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
17375 do {
17376 // Only block literals, captured statements, and lambda expressions can
17377 // capture; other scopes don't work.
17378 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
17379 ExprLoc,
17380 BuildAndDiagnose,
17381 *this);
17382 // We need to check for the parent *first* because, if we *have*
17383 // private-captured a global variable, we need to recursively capture it in
17384 // intermediate blocks, lambdas, etc.
17385 if (!ParentDC) {
17386 if (IsGlobal) {
17387 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
17388 break;
17389 }
17390 return true;
17391 }
17392
17393 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
17394 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
17395
17396
17397 // Check whether we've already captured it.
17398 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
17399 DeclRefType)) {
17400 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
17401 break;
17402 }
17403 // If we are instantiating a generic lambda call operator body,
17404 // we do not want to capture new variables. What was captured
17405 // during either a lambdas transformation or initial parsing
17406 // should be used.
17407 if (isGenericLambdaCallOperatorSpecialization(DC)) {
17408 if (BuildAndDiagnose) {
17409 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17410 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
17411 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
17412 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17413 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
17414 } else
17415 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
17416 }
17417 return true;
17418 }
17419
17420 // Try to capture variable-length arrays types.
17421 if (Var->getType()->isVariablyModifiedType()) {
17422 // We're going to walk down into the type and look for VLA
17423 // expressions.
17424 QualType QTy = Var->getType();
17425 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17426 QTy = PVD->getOriginalType();
17427 captureVariablyModifiedType(Context, QTy, CSI);
17428 }
17429
17430 if (getLangOpts().OpenMP) {
17431 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17432 // OpenMP private variables should not be captured in outer scope, so
17433 // just break here. Similarly, global variables that are captured in a
17434 // target region should not be captured outside the scope of the region.
17435 if (RSI->CapRegionKind == CR_OpenMP) {
17436 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
17437 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
17438 // If the variable is private (i.e. not captured) and has variably
17439 // modified type, we still need to capture the type for correct
17440 // codegen in all regions, associated with the construct. Currently,
17441 // it is captured in the innermost captured region only.
17442 if (IsOpenMPPrivateDecl != OMPC_unknown &&
17443 Var->getType()->isVariablyModifiedType()) {
17444 QualType QTy = Var->getType();
17445 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17446 QTy = PVD->getOriginalType();
17447 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
17448 I < E; ++I) {
17449 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
17450 FunctionScopes[FunctionScopesIndex - I]);
17451 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&((RSI->OpenMPLevel == OuterRSI->OpenMPLevel && "Wrong number of captured regions associated with the "
"OpenMP construct.") ? static_cast<void> (0) : __assert_fail
("RSI->OpenMPLevel == OuterRSI->OpenMPLevel && \"Wrong number of captured regions associated with the \" \"OpenMP construct.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 17453, __PRETTY_FUNCTION__))
17452 "Wrong number of captured regions associated with the "((RSI->OpenMPLevel == OuterRSI->OpenMPLevel && "Wrong number of captured regions associated with the "
"OpenMP construct.") ? static_cast<void> (0) : __assert_fail
("RSI->OpenMPLevel == OuterRSI->OpenMPLevel && \"Wrong number of captured regions associated with the \" \"OpenMP construct.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 17453, __PRETTY_FUNCTION__))
17453 "OpenMP construct.")((RSI->OpenMPLevel == OuterRSI->OpenMPLevel && "Wrong number of captured regions associated with the "
"OpenMP construct.") ? static_cast<void> (0) : __assert_fail
("RSI->OpenMPLevel == OuterRSI->OpenMPLevel && \"Wrong number of captured regions associated with the \" \"OpenMP construct.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 17453, __PRETTY_FUNCTION__))
;
17454 captureVariablyModifiedType(Context, QTy, OuterRSI);
17455 }
17456 }
17457 bool IsTargetCap =
17458 IsOpenMPPrivateDecl != OMPC_private &&
17459 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
17460 RSI->OpenMPCaptureLevel);
17461 // Do not capture global if it is not privatized in outer regions.
17462 bool IsGlobalCap =
17463 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
17464 RSI->OpenMPCaptureLevel);
17465
17466 // When we detect target captures we are looking from inside the
17467 // target region, therefore we need to propagate the capture from the
17468 // enclosing region. Therefore, the capture is not initially nested.
17469 if (IsTargetCap)
17470 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
17471
17472 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
17473 (IsGlobal && !IsGlobalCap)) {
17474 Nested = !IsTargetCap;
17475 bool HasConst = DeclRefType.isConstQualified();
17476 DeclRefType = DeclRefType.getUnqualifiedType();
17477 // Don't lose diagnostics about assignments to const.
17478 if (HasConst)
17479 DeclRefType.addConst();
17480 CaptureType = Context.getLValueReferenceType(DeclRefType);
17481 break;
17482 }
17483 }
17484 }
17485 }
17486 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
17487 // No capture-default, and this is not an explicit capture
17488 // so cannot capture this variable.
17489 if (BuildAndDiagnose) {
17490 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
17491 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17492 if (cast<LambdaScopeInfo>(CSI)->Lambda)
17493 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
17494 diag::note_lambda_decl);
17495 // FIXME: If we error out because an outer lambda can not implicitly
17496 // capture a variable that an inner lambda explicitly captures, we
17497 // should have the inner lambda do the explicit capture - because
17498 // it makes for cleaner diagnostics later. This would purely be done
17499 // so that the diagnostic does not misleadingly claim that a variable
17500 // can not be captured by a lambda implicitly even though it is captured
17501 // explicitly. Suggestion:
17502 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
17503 // at the function head
17504 // - cache the StartingDeclContext - this must be a lambda
17505 // - captureInLambda in the innermost lambda the variable.
17506 }
17507 return true;
17508 }
17509
17510 FunctionScopesIndex--;
17511 DC = ParentDC;
17512 Explicit = false;
17513 } while (!VarDC->Equals(DC));
17514
17515 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
17516 // computing the type of the capture at each step, checking type-specific
17517 // requirements, and adding captures if requested.
17518 // If the variable had already been captured previously, we start capturing
17519 // at the lambda nested within that one.
17520 bool Invalid = false;
17521 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
17522 ++I) {
17523 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
17524
17525 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
17526 // certain types of variables (unnamed, variably modified types etc.)
17527 // so check for eligibility.
17528 if (!Invalid)
17529 Invalid =
17530 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
17531
17532 // After encountering an error, if we're actually supposed to capture, keep
17533 // capturing in nested contexts to suppress any follow-on diagnostics.
17534 if (Invalid && !BuildAndDiagnose)
17535 return true;
17536
17537 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
17538 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17539 DeclRefType, Nested, *this, Invalid);
17540 Nested = true;
17541 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17542 Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose,
17543 CaptureType, DeclRefType, Nested,
17544 *this, Invalid);
17545 Nested = true;
17546 } else {
17547 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17548 Invalid =
17549 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17550 DeclRefType, Nested, Kind, EllipsisLoc,
17551 /*IsTopScope*/ I == N - 1, *this, Invalid);
17552 Nested = true;
17553 }
17554
17555 if (Invalid && !BuildAndDiagnose)
17556 return true;
17557 }
17558 return Invalid;
17559}
17560
17561bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
17562 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
17563 QualType CaptureType;
17564 QualType DeclRefType;
17565 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
17566 /*BuildAndDiagnose=*/true, CaptureType,
17567 DeclRefType, nullptr);
17568}
17569
17570bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
17571 QualType CaptureType;
17572 QualType DeclRefType;
17573 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17574 /*BuildAndDiagnose=*/false, CaptureType,
17575 DeclRefType, nullptr);
17576}
17577
17578QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
17579 QualType CaptureType;
17580 QualType DeclRefType;
17581
17582 // Determine whether we can capture this variable.
17583 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17584 /*BuildAndDiagnose=*/false, CaptureType,
17585 DeclRefType, nullptr))
17586 return QualType();
17587
17588 return DeclRefType;
17589}
17590
17591namespace {
17592// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
17593// The produced TemplateArgumentListInfo* points to data stored within this
17594// object, so should only be used in contexts where the pointer will not be
17595// used after the CopiedTemplateArgs object is destroyed.
17596class CopiedTemplateArgs {
17597 bool HasArgs;
17598 TemplateArgumentListInfo TemplateArgStorage;
17599public:
17600 template<typename RefExpr>
17601 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
17602 if (HasArgs)
17603 E->copyTemplateArgumentsInto(TemplateArgStorage);
17604 }
17605 operator TemplateArgumentListInfo*()
17606#ifdef __has_cpp_attribute
17607#if0 __has_cpp_attribute(clang::lifetimebound)1
17608 [[clang::lifetimebound]]
17609#endif
17610#endif
17611 {
17612 return HasArgs ? &TemplateArgStorage : nullptr;
17613 }
17614};
17615}
17616
17617/// Walk the set of potential results of an expression and mark them all as
17618/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
17619///
17620/// \return A new expression if we found any potential results, ExprEmpty() if
17621/// not, and ExprError() if we diagnosed an error.
17622static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
17623 NonOdrUseReason NOUR) {
17624 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
17625 // an object that satisfies the requirements for appearing in a
17626 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
17627 // is immediately applied." This function handles the lvalue-to-rvalue
17628 // conversion part.
17629 //
17630 // If we encounter a node that claims to be an odr-use but shouldn't be, we
17631 // transform it into the relevant kind of non-odr-use node and rebuild the
17632 // tree of nodes leading to it.
17633 //
17634 // This is a mini-TreeTransform that only transforms a restricted subset of
17635 // nodes (and only certain operands of them).
17636
17637 // Rebuild a subexpression.
17638 auto Rebuild = [&](Expr *Sub) {
17639 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
17640 };
17641
17642 // Check whether a potential result satisfies the requirements of NOUR.
17643 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
17644 // Any entity other than a VarDecl is always odr-used whenever it's named
17645 // in a potentially-evaluated expression.
17646 auto *VD = dyn_cast<VarDecl>(D);
17647 if (!VD)
17648 return true;
17649
17650 // C++2a [basic.def.odr]p4:
17651 // A variable x whose name appears as a potentially-evalauted expression
17652 // e is odr-used by e unless
17653 // -- x is a reference that is usable in constant expressions, or
17654 // -- x is a variable of non-reference type that is usable in constant
17655 // expressions and has no mutable subobjects, and e is an element of
17656 // the set of potential results of an expression of
17657 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
17658 // conversion is applied, or
17659 // -- x is a variable of non-reference type, and e is an element of the
17660 // set of potential results of a discarded-value expression to which
17661 // the lvalue-to-rvalue conversion is not applied
17662 //
17663 // We check the first bullet and the "potentially-evaluated" condition in
17664 // BuildDeclRefExpr. We check the type requirements in the second bullet
17665 // in CheckLValueToRValueConversionOperand below.
17666 switch (NOUR) {
17667 case NOUR_None:
17668 case NOUR_Unevaluated:
17669 llvm_unreachable("unexpected non-odr-use-reason")::llvm::llvm_unreachable_internal("unexpected non-odr-use-reason"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 17669)
;
17670
17671 case NOUR_Constant:
17672 // Constant references were handled when they were built.
17673 if (VD->getType()->isReferenceType())
17674 return true;
17675 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
17676 if (RD->hasMutableFields())
17677 return true;
17678 if (!VD->isUsableInConstantExpressions(S.Context))
17679 return true;
17680 break;
17681
17682 case NOUR_Discarded:
17683 if (VD->getType()->isReferenceType())
17684 return true;
17685 break;
17686 }
17687 return false;
17688 };
17689
17690 // Mark that this expression does not constitute an odr-use.
17691 auto MarkNotOdrUsed = [&] {
17692 S.MaybeODRUseExprs.remove(E);
17693 if (LambdaScopeInfo *LSI = S.getCurLambda())
17694 LSI->markVariableExprAsNonODRUsed(E);
17695 };
17696
17697 // C++2a [basic.def.odr]p2:
17698 // The set of potential results of an expression e is defined as follows:
17699 switch (E->getStmtClass()) {
17700 // -- If e is an id-expression, ...
17701 case Expr::DeclRefExprClass: {
17702 auto *DRE = cast<DeclRefExpr>(E);
17703 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
17704 break;
17705
17706 // Rebuild as a non-odr-use DeclRefExpr.
17707 MarkNotOdrUsed();
17708 return DeclRefExpr::Create(
17709 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
17710 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
17711 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
17712 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
17713 }
17714
17715 case Expr::FunctionParmPackExprClass: {
17716 auto *FPPE = cast<FunctionParmPackExpr>(E);
17717 // If any of the declarations in the pack is odr-used, then the expression
17718 // as a whole constitutes an odr-use.
17719 for (VarDecl *D : *FPPE)
17720 if (IsPotentialResultOdrUsed(D))
17721 return ExprEmpty();
17722
17723 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
17724 // nothing cares about whether we marked this as an odr-use, but it might
17725 // be useful for non-compiler tools.
17726 MarkNotOdrUsed();
17727 break;
17728 }
17729
17730 // -- If e is a subscripting operation with an array operand...
17731 case Expr::ArraySubscriptExprClass: {
17732 auto *ASE = cast<ArraySubscriptExpr>(E);
17733 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
17734 if (!OldBase->getType()->isArrayType())
17735 break;
17736 ExprResult Base = Rebuild(OldBase);
17737 if (!Base.isUsable())
17738 return Base;
17739 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
17740 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
17741 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
17742 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
17743 ASE->getRBracketLoc());
17744 }
17745
17746 case Expr::MemberExprClass: {
17747 auto *ME = cast<MemberExpr>(E);
17748 // -- If e is a class member access expression [...] naming a non-static
17749 // data member...
17750 if (isa<FieldDecl>(ME->getMemberDecl())) {
17751 ExprResult Base = Rebuild(ME->getBase());
17752 if (!Base.isUsable())
17753 return Base;
17754 return MemberExpr::Create(
17755 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
17756 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
17757 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
17758 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
17759 ME->getObjectKind(), ME->isNonOdrUse());
17760 }
17761
17762 if (ME->getMemberDecl()->isCXXInstanceMember())
17763 break;
17764
17765 // -- If e is a class member access expression naming a static data member,
17766 // ...
17767 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
17768 break;
17769
17770 // Rebuild as a non-odr-use MemberExpr.
17771 MarkNotOdrUsed();
17772 return MemberExpr::Create(
17773 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
17774 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
17775 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
17776 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
17777 return ExprEmpty();
17778 }
17779
17780 case Expr::BinaryOperatorClass: {
17781 auto *BO = cast<BinaryOperator>(E);
17782 Expr *LHS = BO->getLHS();
17783 Expr *RHS = BO->getRHS();
17784 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
17785 if (BO->getOpcode() == BO_PtrMemD) {
17786 ExprResult Sub = Rebuild(LHS);
17787 if (!Sub.isUsable())
17788 return Sub;
17789 LHS = Sub.get();
17790 // -- If e is a comma expression, ...
17791 } else if (BO->getOpcode() == BO_Comma) {
17792 ExprResult Sub = Rebuild(RHS);
17793 if (!Sub.isUsable())
17794 return Sub;
17795 RHS = Sub.get();
17796 } else {
17797 break;
17798 }
17799 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
17800 LHS, RHS);
17801 }
17802
17803 // -- If e has the form (e1)...
17804 case Expr::ParenExprClass: {
17805 auto *PE = cast<ParenExpr>(E);
17806 ExprResult Sub = Rebuild(PE->getSubExpr());
17807 if (!Sub.isUsable())
17808 return Sub;
17809 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
17810 }
17811
17812 // -- If e is a glvalue conditional expression, ...
17813 // We don't apply this to a binary conditional operator. FIXME: Should we?
17814 case Expr::ConditionalOperatorClass: {
17815 auto *CO = cast<ConditionalOperator>(E);
17816 ExprResult LHS = Rebuild(CO->getLHS());
17817 if (LHS.isInvalid())
17818 return ExprError();
17819 ExprResult RHS = Rebuild(CO->getRHS());
17820 if (RHS.isInvalid())
17821 return ExprError();
17822 if (!LHS.isUsable() && !RHS.isUsable())
17823 return ExprEmpty();
17824 if (!LHS.isUsable())
17825 LHS = CO->getLHS();
17826 if (!RHS.isUsable())
17827 RHS = CO->getRHS();
17828 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
17829 CO->getCond(), LHS.get(), RHS.get());
17830 }
17831
17832 // [Clang extension]
17833 // -- If e has the form __extension__ e1...
17834 case Expr::UnaryOperatorClass: {
17835 auto *UO = cast<UnaryOperator>(E);
17836 if (UO->getOpcode() != UO_Extension)
17837 break;
17838 ExprResult Sub = Rebuild(UO->getSubExpr());
17839 if (!Sub.isUsable())
17840 return Sub;
17841 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
17842 Sub.get());
17843 }
17844
17845 // [Clang extension]
17846 // -- If e has the form _Generic(...), the set of potential results is the
17847 // union of the sets of potential results of the associated expressions.
17848 case Expr::GenericSelectionExprClass: {
17849 auto *GSE = cast<GenericSelectionExpr>(E);
17850
17851 SmallVector<Expr *, 4> AssocExprs;
17852 bool AnyChanged = false;
17853 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
17854 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
17855 if (AssocExpr.isInvalid())
17856 return ExprError();
17857 if (AssocExpr.isUsable()) {
17858 AssocExprs.push_back(AssocExpr.get());
17859 AnyChanged = true;
17860 } else {
17861 AssocExprs.push_back(OrigAssocExpr);
17862 }
17863 }
17864
17865 return AnyChanged ? S.CreateGenericSelectionExpr(
17866 GSE->getGenericLoc(), GSE->getDefaultLoc(),
17867 GSE->getRParenLoc(), GSE->getControllingExpr(),
17868 GSE->getAssocTypeSourceInfos(), AssocExprs)
17869 : ExprEmpty();
17870 }
17871
17872 // [Clang extension]
17873 // -- If e has the form __builtin_choose_expr(...), the set of potential
17874 // results is the union of the sets of potential results of the
17875 // second and third subexpressions.
17876 case Expr::ChooseExprClass: {
17877 auto *CE = cast<ChooseExpr>(E);
17878
17879 ExprResult LHS = Rebuild(CE->getLHS());
17880 if (LHS.isInvalid())
17881 return ExprError();
17882
17883 ExprResult RHS = Rebuild(CE->getLHS());
17884 if (RHS.isInvalid())
17885 return ExprError();
17886
17887 if (!LHS.get() && !RHS.get())
17888 return ExprEmpty();
17889 if (!LHS.isUsable())
17890 LHS = CE->getLHS();
17891 if (!RHS.isUsable())
17892 RHS = CE->getRHS();
17893
17894 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
17895 RHS.get(), CE->getRParenLoc());
17896 }
17897
17898 // Step through non-syntactic nodes.
17899 case Expr::ConstantExprClass: {
17900 auto *CE = cast<ConstantExpr>(E);
17901 ExprResult Sub = Rebuild(CE->getSubExpr());
17902 if (!Sub.isUsable())
17903 return Sub;
17904 return ConstantExpr::Create(S.Context, Sub.get());
17905 }
17906
17907 // We could mostly rely on the recursive rebuilding to rebuild implicit
17908 // casts, but not at the top level, so rebuild them here.
17909 case Expr::ImplicitCastExprClass: {
17910 auto *ICE = cast<ImplicitCastExpr>(E);
17911 // Only step through the narrow set of cast kinds we expect to encounter.
17912 // Anything else suggests we've left the region in which potential results
17913 // can be found.
17914 switch (ICE->getCastKind()) {
17915 case CK_NoOp:
17916 case CK_DerivedToBase:
17917 case CK_UncheckedDerivedToBase: {
17918 ExprResult Sub = Rebuild(ICE->getSubExpr());
17919 if (!Sub.isUsable())
17920 return Sub;
17921 CXXCastPath Path(ICE->path());
17922 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
17923 ICE->getValueKind(), &Path);
17924 }
17925
17926 default:
17927 break;
17928 }
17929 break;
17930 }
17931
17932 default:
17933 break;
17934 }
17935
17936 // Can't traverse through this node. Nothing to do.
17937 return ExprEmpty();
17938}
17939
17940ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
17941 // Check whether the operand is or contains an object of non-trivial C union
17942 // type.
17943 if (E->getType().isVolatileQualified() &&
17944 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
17945 E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
17946 checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
17947 Sema::NTCUC_LValueToRValueVolatile,
17948 NTCUK_Destruct|NTCUK_Copy);
17949
17950 // C++2a [basic.def.odr]p4:
17951 // [...] an expression of non-volatile-qualified non-class type to which
17952 // the lvalue-to-rvalue conversion is applied [...]
17953 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
17954 return E;
17955
17956 ExprResult Result =
17957 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
17958 if (Result.isInvalid())
17959 return ExprError();
17960 return Result.get() ? Result : E;
17961}
17962
17963ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
17964 Res = CorrectDelayedTyposInExpr(Res);
17965
17966 if (!Res.isUsable())
17967 return Res;
17968
17969 // If a constant-expression is a reference to a variable where we delay
17970 // deciding whether it is an odr-use, just assume we will apply the
17971 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
17972 // (a non-type template argument), we have special handling anyway.
17973 return CheckLValueToRValueConversionOperand(Res.get());
17974}
17975
17976void Sema::CleanupVarDeclMarking() {
17977 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
17978 // call.
17979 MaybeODRUseExprSet LocalMaybeODRUseExprs;
17980 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
17981
17982 for (Expr *E : LocalMaybeODRUseExprs) {
17983 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
17984 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
17985 DRE->getLocation(), *this);
17986 } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
17987 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
17988 *this);
17989 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
17990 for (VarDecl *VD : *FP)
17991 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
17992 } else {
17993 llvm_unreachable("Unexpected expression")::llvm::llvm_unreachable_internal("Unexpected expression", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 17993)
;
17994 }
17995 }
17996
17997 assert(MaybeODRUseExprs.empty() &&((MaybeODRUseExprs.empty() && "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"
) ? static_cast<void> (0) : __assert_fail ("MaybeODRUseExprs.empty() && \"MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 17998, __PRETTY_FUNCTION__))
17998 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?")((MaybeODRUseExprs.empty() && "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"
) ? static_cast<void> (0) : __assert_fail ("MaybeODRUseExprs.empty() && \"MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 17998, __PRETTY_FUNCTION__))
;
17999}
18000
18001static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
18002 VarDecl *Var, Expr *E) {
18003 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||(((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E
) || isa<FunctionParmPackExpr>(E)) && "Invalid Expr argument to DoMarkVarDeclReferenced"
) ? static_cast<void> (0) : __assert_fail ("(!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>(E)) && \"Invalid Expr argument to DoMarkVarDeclReferenced\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 18005, __PRETTY_FUNCTION__))
18004 isa<FunctionParmPackExpr>(E)) &&(((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E
) || isa<FunctionParmPackExpr>(E)) && "Invalid Expr argument to DoMarkVarDeclReferenced"
) ? static_cast<void> (0) : __assert_fail ("(!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>(E)) && \"Invalid Expr argument to DoMarkVarDeclReferenced\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 18005, __PRETTY_FUNCTION__))
18005 "Invalid Expr argument to DoMarkVarDeclReferenced")(((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E
) || isa<FunctionParmPackExpr>(E)) && "Invalid Expr argument to DoMarkVarDeclReferenced"
) ? static_cast<void> (0) : __assert_fail ("(!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>(E)) && \"Invalid Expr argument to DoMarkVarDeclReferenced\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 18005, __PRETTY_FUNCTION__))
;
18006 Var->setReferenced();
18007
18008 if (Var->isInvalidDecl())
18009 return;
18010
18011 // Record a CUDA/HIP static device/constant variable if it is referenced
18012 // by host code. This is done conservatively, when the variable is referenced
18013 // in any of the following contexts:
18014 // - a non-function context
18015 // - a host function
18016 // - a host device function
18017 // This also requires the reference of the static device/constant variable by
18018 // host code to be visible in the device compilation for the compiler to be
18019 // able to externalize the static device/constant variable.
18020 if (SemaRef.getASTContext().mayExternalizeStaticVar(Var)) {
18021 auto *CurContext = SemaRef.CurContext;
18022 if (!CurContext || !isa<FunctionDecl>(CurContext) ||
18023 cast<FunctionDecl>(CurContext)->hasAttr<CUDAHostAttr>() ||
18024 (!cast<FunctionDecl>(CurContext)->hasAttr<CUDADeviceAttr>() &&
18025 !cast<FunctionDecl>(CurContext)->hasAttr<CUDAGlobalAttr>()))
18026 SemaRef.getASTContext().CUDAStaticDeviceVarReferencedByHost.insert(Var);
18027 }
18028
18029 auto *MSI = Var->getMemberSpecializationInfo();
18030 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
18031 : Var->getTemplateSpecializationKind();
18032
18033 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
18034 bool UsableInConstantExpr =
18035 Var->mightBeUsableInConstantExpressions(SemaRef.Context);
18036
18037 // C++20 [expr.const]p12:
18038 // A variable [...] is needed for constant evaluation if it is [...] a
18039 // variable whose name appears as a potentially constant evaluated
18040 // expression that is either a contexpr variable or is of non-volatile
18041 // const-qualified integral type or of reference type
18042 bool NeededForConstantEvaluation =
18043 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
18044
18045 bool NeedDefinition =
18046 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
18047
18048 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&((!isa<VarTemplatePartialSpecializationDecl>(Var) &&
"Can't instantiate a partial template specialization.") ? static_cast
<void> (0) : __assert_fail ("!isa<VarTemplatePartialSpecializationDecl>(Var) && \"Can't instantiate a partial template specialization.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 18049, __PRETTY_FUNCTION__))
18049 "Can't instantiate a partial template specialization.")((!isa<VarTemplatePartialSpecializationDecl>(Var) &&
"Can't instantiate a partial template specialization.") ? static_cast
<void> (0) : __assert_fail ("!isa<VarTemplatePartialSpecializationDecl>(Var) && \"Can't instantiate a partial template specialization.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 18049, __PRETTY_FUNCTION__))
;
18050
18051 // If this might be a member specialization of a static data member, check
18052 // the specialization is visible. We already did the checks for variable
18053 // template specializations when we created them.
18054 if (NeedDefinition && TSK != TSK_Undeclared &&
18055 !isa<VarTemplateSpecializationDecl>(Var))
18056 SemaRef.checkSpecializationVisibility(Loc, Var);
18057
18058 // Perform implicit instantiation of static data members, static data member
18059 // templates of class templates, and variable template specializations. Delay
18060 // instantiations of variable templates, except for those that could be used
18061 // in a constant expression.
18062 if (NeedDefinition && isTemplateInstantiation(TSK)) {
18063 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
18064 // instantiation declaration if a variable is usable in a constant
18065 // expression (among other cases).
18066 bool TryInstantiating =
18067 TSK == TSK_ImplicitInstantiation ||
18068 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
18069
18070 if (TryInstantiating) {
18071 SourceLocation PointOfInstantiation =
18072 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
18073 bool FirstInstantiation = PointOfInstantiation.isInvalid();
18074 if (FirstInstantiation) {
18075 PointOfInstantiation = Loc;
18076 if (MSI)
18077 MSI->setPointOfInstantiation(PointOfInstantiation);
18078 // FIXME: Notify listener.
18079 else
18080 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18081 }
18082
18083 if (UsableInConstantExpr) {
18084 // Do not defer instantiations of variables that could be used in a
18085 // constant expression.
18086 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
18087 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
18088 });
18089 } else if (FirstInstantiation ||
18090 isa<VarTemplateSpecializationDecl>(Var)) {
18091 // FIXME: For a specialization of a variable template, we don't
18092 // distinguish between "declaration and type implicitly instantiated"
18093 // and "implicit instantiation of definition requested", so we have
18094 // no direct way to avoid enqueueing the pending instantiation
18095 // multiple times.
18096 SemaRef.PendingInstantiations
18097 .push_back(std::make_pair(Var, PointOfInstantiation));
18098 }
18099 }
18100 }
18101
18102 // C++2a [basic.def.odr]p4:
18103 // A variable x whose name appears as a potentially-evaluated expression e
18104 // is odr-used by e unless
18105 // -- x is a reference that is usable in constant expressions
18106 // -- x is a variable of non-reference type that is usable in constant
18107 // expressions and has no mutable subobjects [FIXME], and e is an
18108 // element of the set of potential results of an expression of
18109 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
18110 // conversion is applied
18111 // -- x is a variable of non-reference type, and e is an element of the set
18112 // of potential results of a discarded-value expression to which the
18113 // lvalue-to-rvalue conversion is not applied [FIXME]
18114 //
18115 // We check the first part of the second bullet here, and
18116 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
18117 // FIXME: To get the third bullet right, we need to delay this even for
18118 // variables that are not usable in constant expressions.
18119
18120 // If we already know this isn't an odr-use, there's nothing more to do.
18121 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
18122 if (DRE->isNonOdrUse())
18123 return;
18124 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
18125 if (ME->isNonOdrUse())
18126 return;
18127
18128 switch (OdrUse) {
18129 case OdrUseContext::None:
18130 assert((!E || isa<FunctionParmPackExpr>(E)) &&(((!E || isa<FunctionParmPackExpr>(E)) && "missing non-odr-use marking for unevaluated decl ref"
) ? static_cast<void> (0) : __assert_fail ("(!E || isa<FunctionParmPackExpr>(E)) && \"missing non-odr-use marking for unevaluated decl ref\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 18131, __PRETTY_FUNCTION__))
18131 "missing non-odr-use marking for unevaluated decl ref")(((!E || isa<FunctionParmPackExpr>(E)) && "missing non-odr-use marking for unevaluated decl ref"
) ? static_cast<void> (0) : __assert_fail ("(!E || isa<FunctionParmPackExpr>(E)) && \"missing non-odr-use marking for unevaluated decl ref\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 18131, __PRETTY_FUNCTION__))
;
18132 break;
18133
18134 case OdrUseContext::FormallyOdrUsed:
18135 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
18136 // behavior.
18137 break;
18138
18139 case OdrUseContext::Used:
18140 // If we might later find that this expression isn't actually an odr-use,
18141 // delay the marking.
18142 if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
18143 SemaRef.MaybeODRUseExprs.insert(E);
18144 else
18145 MarkVarDeclODRUsed(Var, Loc, SemaRef);
18146 break;
18147
18148 case OdrUseContext::Dependent:
18149 // If this is a dependent context, we don't need to mark variables as
18150 // odr-used, but we may still need to track them for lambda capture.
18151 // FIXME: Do we also need to do this inside dependent typeid expressions
18152 // (which are modeled as unevaluated at this point)?
18153 const bool RefersToEnclosingScope =
18154 (SemaRef.CurContext != Var->getDeclContext() &&
18155 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
18156 if (RefersToEnclosingScope) {
18157 LambdaScopeInfo *const LSI =
18158 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
18159 if (LSI && (!LSI->CallOperator ||
18160 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
18161 // If a variable could potentially be odr-used, defer marking it so
18162 // until we finish analyzing the full expression for any
18163 // lvalue-to-rvalue
18164 // or discarded value conversions that would obviate odr-use.
18165 // Add it to the list of potential captures that will be analyzed
18166 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
18167 // unless the variable is a reference that was initialized by a constant
18168 // expression (this will never need to be captured or odr-used).
18169 //
18170 // FIXME: We can simplify this a lot after implementing P0588R1.
18171 assert(E && "Capture variable should be used in an expression.")((E && "Capture variable should be used in an expression."
) ? static_cast<void> (0) : __assert_fail ("E && \"Capture variable should be used in an expression.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 18171, __PRETTY_FUNCTION__))
;
18172 if (!Var->getType()->isReferenceType() ||
18173 !Var->isUsableInConstantExpressions(SemaRef.Context))
18174 LSI->addPotentialCapture(E->IgnoreParens());
18175 }
18176 }
18177 break;
18178 }
18179}
18180
18181/// Mark a variable referenced, and check whether it is odr-used
18182/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
18183/// used directly for normal expressions referring to VarDecl.
18184void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
18185 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
18186}
18187
18188static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
18189 Decl *D, Expr *E, bool MightBeOdrUse) {
18190 if (SemaRef.isInOpenMPDeclareTargetContext())
18191 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
18192
18193 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
18194 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
18195 return;
18196 }
18197
18198 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
18199
18200 // If this is a call to a method via a cast, also mark the method in the
18201 // derived class used in case codegen can devirtualize the call.
18202 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
18203 if (!ME)
18204 return;
18205 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
18206 if (!MD)
18207 return;
18208 // Only attempt to devirtualize if this is truly a virtual call.
18209 bool IsVirtualCall = MD->isVirtual() &&
18210 ME->performsVirtualDispatch(SemaRef.getLangOpts());
18211 if (!IsVirtualCall)
18212 return;
18213
18214 // If it's possible to devirtualize the call, mark the called function
18215 // referenced.
18216 CXXMethodDecl *DM = MD->getDevirtualizedMethod(
18217 ME->getBase(), SemaRef.getLangOpts().AppleKext);
18218 if (DM)
18219 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
18220}
18221
18222/// Perform reference-marking and odr-use handling for a DeclRefExpr.
18223void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
18224 // TODO: update this with DR# once a defect report is filed.
18225 // C++11 defect. The address of a pure member should not be an ODR use, even
18226 // if it's a qualified reference.
18227 bool OdrUse = true;
18228 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
18229 if (Method->isVirtual() &&
18230 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
18231 OdrUse = false;
18232
18233 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
18234 if (!isConstantEvaluated() && FD->isConsteval() &&
18235 !RebuildingImmediateInvocation)
18236 ExprEvalContexts.back().ReferenceToConsteval.insert(E);
18237 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
18238}
18239
18240/// Perform reference-marking and odr-use handling for a MemberExpr.
18241void Sema::MarkMemberReferenced(MemberExpr *E) {
18242 // C++11 [basic.def.odr]p2:
18243 // A non-overloaded function whose name appears as a potentially-evaluated
18244 // expression or a member of a set of candidate functions, if selected by
18245 // overload resolution when referred to from a potentially-evaluated
18246 // expression, is odr-used, unless it is a pure virtual function and its
18247 // name is not explicitly qualified.
18248 bool MightBeOdrUse = true;
18249 if (E->performsVirtualDispatch(getLangOpts())) {
18250 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
18251 if (Method->isPure())
18252 MightBeOdrUse = false;
18253 }
18254 SourceLocation Loc =
18255 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
18256 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
18257}
18258
18259/// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
18260void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
18261 for (VarDecl *VD : *E)
18262 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
18263}
18264
18265/// Perform marking for a reference to an arbitrary declaration. It
18266/// marks the declaration referenced, and performs odr-use checking for
18267/// functions and variables. This method should not be used when building a
18268/// normal expression which refers to a variable.
18269void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
18270 bool MightBeOdrUse) {
18271 if (MightBeOdrUse) {
18272 if (auto *VD = dyn_cast<VarDecl>(D)) {
18273 MarkVariableReferenced(Loc, VD);
18274 return;
18275 }
18276 }
18277 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
18278 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
18279 return;
18280 }
18281 D->setReferenced();
18282}
18283
18284namespace {
18285 // Mark all of the declarations used by a type as referenced.
18286 // FIXME: Not fully implemented yet! We need to have a better understanding
18287 // of when we're entering a context we should not recurse into.
18288 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
18289 // TreeTransforms rebuilding the type in a new context. Rather than
18290 // duplicating the TreeTransform logic, we should consider reusing it here.
18291 // Currently that causes problems when rebuilding LambdaExprs.
18292 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
18293 Sema &S;
18294 SourceLocation Loc;
18295
18296 public:
18297 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
18298
18299 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
18300
18301 bool TraverseTemplateArgument(const TemplateArgument &Arg);
18302 };
18303}
18304
18305bool MarkReferencedDecls::TraverseTemplateArgument(
18306 const TemplateArgument &Arg) {
18307 {
18308 // A non-type template argument is a constant-evaluated context.
18309 EnterExpressionEvaluationContext Evaluated(
18310 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
18311 if (Arg.getKind() == TemplateArgument::Declaration) {
18312 if (Decl *D = Arg.getAsDecl())
18313 S.MarkAnyDeclReferenced(Loc, D, true);
18314 } else if (Arg.getKind() == TemplateArgument::Expression) {
18315 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
18316 }
18317 }
18318
18319 return Inherited::TraverseTemplateArgument(Arg);
18320}
18321
18322void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
18323 MarkReferencedDecls Marker(*this, Loc);
18324 Marker.TraverseType(T);
18325}
18326
18327namespace {
18328/// Helper class that marks all of the declarations referenced by
18329/// potentially-evaluated subexpressions as "referenced".
18330class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
18331public:
18332 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
18333 bool SkipLocalVariables;
18334
18335 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
18336 : Inherited(S), SkipLocalVariables(SkipLocalVariables) {}
18337
18338 void visitUsedDecl(SourceLocation Loc, Decl *D) {
18339 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
18340 }
18341
18342 void VisitDeclRefExpr(DeclRefExpr *E) {
18343 // If we were asked not to visit local variables, don't.
18344 if (SkipLocalVariables) {
18345 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
18346 if (VD->hasLocalStorage())
18347 return;
18348 }
18349 S.MarkDeclRefReferenced(E);
18350 }
18351
18352 void VisitMemberExpr(MemberExpr *E) {
18353 S.MarkMemberReferenced(E);
18354 Visit(E->getBase());
18355 }
18356};
18357} // namespace
18358
18359/// Mark any declarations that appear within this expression or any
18360/// potentially-evaluated subexpressions as "referenced".
18361///
18362/// \param SkipLocalVariables If true, don't mark local variables as
18363/// 'referenced'.
18364void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
18365 bool SkipLocalVariables) {
18366 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
18367}
18368
18369/// Emit a diagnostic that describes an effect on the run-time behavior
18370/// of the program being compiled.
18371///
18372/// This routine emits the given diagnostic when the code currently being
18373/// type-checked is "potentially evaluated", meaning that there is a
18374/// possibility that the code will actually be executable. Code in sizeof()
18375/// expressions, code used only during overload resolution, etc., are not
18376/// potentially evaluated. This routine will suppress such diagnostics or,
18377/// in the absolutely nutty case of potentially potentially evaluated
18378/// expressions (C++ typeid), queue the diagnostic to potentially emit it
18379/// later.
18380///
18381/// This routine should be used for all diagnostics that describe the run-time
18382/// behavior of a program, such as passing a non-POD value through an ellipsis.
18383/// Failure to do so will likely result in spurious diagnostics or failures
18384/// during overload resolution or within sizeof/alignof/typeof/typeid.
18385bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
18386 const PartialDiagnostic &PD) {
18387 switch (ExprEvalContexts.back().Context) {
18388 case ExpressionEvaluationContext::Unevaluated:
18389 case ExpressionEvaluationContext::UnevaluatedList:
18390 case ExpressionEvaluationContext::UnevaluatedAbstract:
18391 case ExpressionEvaluationContext::DiscardedStatement:
18392 // The argument will never be evaluated, so don't complain.
18393 break;
18394
18395 case ExpressionEvaluationContext::ConstantEvaluated:
18396 // Relevant diagnostics should be produced by constant evaluation.
18397 break;
18398
18399 case ExpressionEvaluationContext::PotentiallyEvaluated:
18400 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18401 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
18402 FunctionScopes.back()->PossiblyUnreachableDiags.
18403 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
18404 return true;
18405 }
18406
18407 // The initializer of a constexpr variable or of the first declaration of a
18408 // static data member is not syntactically a constant evaluated constant,
18409 // but nonetheless is always required to be a constant expression, so we
18410 // can skip diagnosing.
18411 // FIXME: Using the mangling context here is a hack.
18412 if (auto *VD = dyn_cast_or_null<VarDecl>(
18413 ExprEvalContexts.back().ManglingContextDecl)) {
18414 if (VD->isConstexpr() ||
18415 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
18416 break;
18417 // FIXME: For any other kind of variable, we should build a CFG for its
18418 // initializer and check whether the context in question is reachable.
18419 }
18420
18421 Diag(Loc, PD);
18422 return true;
18423 }
18424
18425 return false;
18426}
18427
18428bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
18429 const PartialDiagnostic &PD) {
18430 return DiagRuntimeBehavior(
18431 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
18432}
18433
18434bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
18435 CallExpr *CE, FunctionDecl *FD) {
18436 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
18437 return false;
18438
18439 // If we're inside a decltype's expression, don't check for a valid return
18440 // type or construct temporaries until we know whether this is the last call.
18441 if (ExprEvalContexts.back().ExprContext ==
18442 ExpressionEvaluationContextRecord::EK_Decltype) {
18443 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
18444 return false;
18445 }
18446
18447 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
18448 FunctionDecl *FD;
18449 CallExpr *CE;
18450
18451 public:
18452 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
18453 : FD(FD), CE(CE) { }
18454
18455 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18456 if (!FD) {
18457 S.Diag(Loc, diag::err_call_incomplete_return)
18458 << T << CE->getSourceRange();
18459 return;
18460 }
18461
18462 S.Diag(Loc, diag::err_call_function_incomplete_return)
18463 << CE->getSourceRange() << FD << T;
18464 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
18465 << FD->getDeclName();
18466 }
18467 } Diagnoser(FD, CE);
18468
18469 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
18470 return true;
18471
18472 return false;
18473}
18474
18475// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
18476// will prevent this condition from triggering, which is what we want.
18477void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
18478 SourceLocation Loc;
18479
18480 unsigned diagnostic = diag::warn_condition_is_assignment;
18481 bool IsOrAssign = false;
18482
18483 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
18484 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
18485 return;
18486
18487 IsOrAssign = Op->getOpcode() == BO_OrAssign;
18488
18489 // Greylist some idioms by putting them into a warning subcategory.
18490 if (ObjCMessageExpr *ME
18491 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
18492 Selector Sel = ME->getSelector();
18493
18494 // self = [<foo> init...]
18495 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
18496 diagnostic = diag::warn_condition_is_idiomatic_assignment;
18497
18498 // <foo> = [<bar> nextObject]
18499 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
18500 diagnostic = diag::warn_condition_is_idiomatic_assignment;
18501 }
18502
18503 Loc = Op->getOperatorLoc();
18504 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
18505 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
18506 return;
18507
18508 IsOrAssign = Op->getOperator() == OO_PipeEqual;
18509 Loc = Op->getOperatorLoc();
18510 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
18511 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
18512 else {
18513 // Not an assignment.
18514 return;
18515 }
18516
18517 Diag(Loc, diagnostic) << E->getSourceRange();
18518
18519 SourceLocation Open = E->getBeginLoc();
18520 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
18521 Diag(Loc, diag::note_condition_assign_silence)
18522 << FixItHint::CreateInsertion(Open, "(")
18523 << FixItHint::CreateInsertion(Close, ")");
18524
18525 if (IsOrAssign)
18526 Diag(Loc, diag::note_condition_or_assign_to_comparison)
18527 << FixItHint::CreateReplacement(Loc, "!=");
18528 else
18529 Diag(Loc, diag::note_condition_assign_to_comparison)
18530 << FixItHint::CreateReplacement(Loc, "==");
18531}
18532
18533/// Redundant parentheses over an equality comparison can indicate
18534/// that the user intended an assignment used as condition.
18535void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
18536 // Don't warn if the parens came from a macro.
18537 SourceLocation parenLoc = ParenE->getBeginLoc();
18538 if (parenLoc.isInvalid() || parenLoc.isMacroID())
18539 return;
18540 // Don't warn for dependent expressions.
18541 if (ParenE->isTypeDependent())
18542 return;
18543
18544 Expr *E = ParenE->IgnoreParens();
18545
18546 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
18547 if (opE->getOpcode() == BO_EQ &&
18548 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
18549 == Expr::MLV_Valid) {
18550 SourceLocation Loc = opE->getOperatorLoc();
18551
18552 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
18553 SourceRange ParenERange = ParenE->getSourceRange();
18554 Diag(Loc, diag::note_equality_comparison_silence)
18555 << FixItHint::CreateRemoval(ParenERange.getBegin())
18556 << FixItHint::CreateRemoval(ParenERange.getEnd());
18557 Diag(Loc, diag::note_equality_comparison_to_assign)
18558 << FixItHint::CreateReplacement(Loc, "=");
18559 }
18560}
18561
18562ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
18563 bool IsConstexpr) {
18564 DiagnoseAssignmentAsCondition(E);
18565 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
18566 DiagnoseEqualityWithExtraParens(parenE);
18567
18568 ExprResult result = CheckPlaceholderExpr(E);
18569 if (result.isInvalid()) return ExprError();
18570 E = result.get();
18571
18572 if (!E->isTypeDependent()) {
18573 if (getLangOpts().CPlusPlus)
18574 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
18575
18576 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
18577 if (ERes.isInvalid())
18578 return ExprError();
18579 E = ERes.get();
18580
18581 QualType T = E->getType();
18582 if (!T->isScalarType()) { // C99 6.8.4.1p1
18583 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
18584 << T << E->getSourceRange();
18585 return ExprError();
18586 }
18587 CheckBoolLikeConversion(E, Loc);
18588 }
18589
18590 return E;
18591}
18592
18593Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
18594 Expr *SubExpr, ConditionKind CK) {
18595 // Empty conditions are valid in for-statements.
18596 if (!SubExpr)
18597 return ConditionResult();
18598
18599 ExprResult Cond;
18600 switch (CK) {
18601 case ConditionKind::Boolean:
18602 Cond = CheckBooleanCondition(Loc, SubExpr);
18603 break;
18604
18605 case ConditionKind::ConstexprIf:
18606 Cond = CheckBooleanCondition(Loc, SubExpr, true);
18607 break;
18608
18609 case ConditionKind::Switch:
18610 Cond = CheckSwitchCondition(Loc, SubExpr);
18611 break;
18612 }
18613 if (Cond.isInvalid()) {
18614 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
18615 {SubExpr});
18616 if (!Cond.get())
18617 return ConditionError();
18618 }
18619 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
18620 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
18621 if (!FullExpr.get())
18622 return ConditionError();
18623
18624 return ConditionResult(*this, nullptr, FullExpr,
18625 CK == ConditionKind::ConstexprIf);
18626}
18627
18628namespace {
18629 /// A visitor for rebuilding a call to an __unknown_any expression
18630 /// to have an appropriate type.
18631 struct RebuildUnknownAnyFunction
18632 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
18633
18634 Sema &S;
18635
18636 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
18637
18638 ExprResult VisitStmt(Stmt *S) {
18639 llvm_unreachable("unexpected statement!")::llvm::llvm_unreachable_internal("unexpected statement!", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 18639)
;
18640 }
18641
18642 ExprResult VisitExpr(Expr *E) {
18643 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
18644 << E->getSourceRange();
18645 return ExprError();
18646 }
18647
18648 /// Rebuild an expression which simply semantically wraps another
18649 /// expression which it shares the type and value kind of.
18650 template <class T> ExprResult rebuildSugarExpr(T *E) {
18651 ExprResult SubResult = Visit(E->getSubExpr());
18652 if (SubResult.isInvalid()) return ExprError();
18653
18654 Expr *SubExpr = SubResult.get();
18655 E->setSubExpr(SubExpr);
18656 E->setType(SubExpr->getType());
18657 E->setValueKind(SubExpr->getValueKind());
18658 assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void
> (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 18658, __PRETTY_FUNCTION__))
;
18659 return E;
18660 }
18661
18662 ExprResult VisitParenExpr(ParenExpr *E) {
18663 return rebuildSugarExpr(E);
18664 }
18665
18666 ExprResult VisitUnaryExtension(UnaryOperator *E) {
18667 return rebuildSugarExpr(E);
18668 }
18669
18670 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18671 ExprResult SubResult = Visit(E->getSubExpr());
18672 if (SubResult.isInvalid()) return ExprError();
18673
18674 Expr *SubExpr = SubResult.get();
18675 E->setSubExpr(SubExpr);
18676 E->setType(S.Context.getPointerType(SubExpr->getType()));
18677 assert(E->getValueKind() == VK_RValue)((E->getValueKind() == VK_RValue) ? static_cast<void>
(0) : __assert_fail ("E->getValueKind() == VK_RValue", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 18677, __PRETTY_FUNCTION__))
;
18678 assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void
> (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 18678, __PRETTY_FUNCTION__))
;
18679 return E;
18680 }
18681
18682 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
18683 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
18684
18685 E->setType(VD->getType());
18686
18687 assert(E->getValueKind() == VK_RValue)((E->getValueKind() == VK_RValue) ? static_cast<void>
(0) : __assert_fail ("E->getValueKind() == VK_RValue", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 18687, __PRETTY_FUNCTION__))
;
18688 if (S.getLangOpts().CPlusPlus &&
18689 !(isa<CXXMethodDecl>(VD) &&
18690 cast<CXXMethodDecl>(VD)->isInstance()))
18691 E->setValueKind(VK_LValue);
18692
18693 return E;
18694 }
18695
18696 ExprResult VisitMemberExpr(MemberExpr *E) {
18697 return resolveDecl(E, E->getMemberDecl());
18698 }
18699
18700 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18701 return resolveDecl(E, E->getDecl());
18702 }
18703 };
18704}
18705
18706/// Given a function expression of unknown-any type, try to rebuild it
18707/// to have a function type.
18708static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
18709 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
18710 if (Result.isInvalid()) return ExprError();
18711 return S.DefaultFunctionArrayConversion(Result.get());
18712}
18713
18714namespace {
18715 /// A visitor for rebuilding an expression of type __unknown_anytype
18716 /// into one which resolves the type directly on the referring
18717 /// expression. Strict preservation of the original source
18718 /// structure is not a goal.
18719 struct RebuildUnknownAnyExpr
18720 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
18721
18722 Sema &S;
18723
18724 /// The current destination type.
18725 QualType DestType;
18726
18727 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
18728 : S(S), DestType(CastType) {}
18729
18730 ExprResult VisitStmt(Stmt *S) {
18731 llvm_unreachable("unexpected statement!")::llvm::llvm_unreachable_internal("unexpected statement!", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 18731)
;
18732 }
18733
18734 ExprResult VisitExpr(Expr *E) {
18735 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
18736 << E->getSourceRange();
18737 return ExprError();
18738 }
18739
18740 ExprResult VisitCallExpr(CallExpr *E);
18741 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
18742
18743 /// Rebuild an expression which simply semantically wraps another
18744 /// expression which it shares the type and value kind of.
18745 template <class T> ExprResult rebuildSugarExpr(T *E) {
18746 ExprResult SubResult = Visit(E->getSubExpr());
18747 if (SubResult.isInvalid()) return ExprError();
18748 Expr *SubExpr = SubResult.get();
18749 E->setSubExpr(SubExpr);
18750 E->setType(SubExpr->getType());
18751 E->setValueKind(SubExpr->getValueKind());
18752 assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void
> (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 18752, __PRETTY_FUNCTION__))
;
18753 return E;
18754 }
18755
18756 ExprResult VisitParenExpr(ParenExpr *E) {
18757 return rebuildSugarExpr(E);
18758 }
18759
18760 ExprResult VisitUnaryExtension(UnaryOperator *E) {
18761 return rebuildSugarExpr(E);
18762 }
18763
18764 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18765 const PointerType *Ptr = DestType->getAs<PointerType>();
18766 if (!Ptr) {
18767 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
18768 << E->getSourceRange();
18769 return ExprError();
18770 }
18771
18772 if (isa<CallExpr>(E->getSubExpr())) {
18773 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
18774 << E->getSourceRange();
18775 return ExprError();
18776 }
18777
18778 assert(E->getValueKind() == VK_RValue)((E->getValueKind() == VK_RValue) ? static_cast<void>
(0) : __assert_fail ("E->getValueKind() == VK_RValue", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 18778, __PRETTY_FUNCTION__))
;
18779 assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void
> (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 18779, __PRETTY_FUNCTION__))
;
18780 E->setType(DestType);
18781
18782 // Build the sub-expression as if it were an object of the pointee type.
18783 DestType = Ptr->getPointeeType();
18784 ExprResult SubResult = Visit(E->getSubExpr());
18785 if (SubResult.isInvalid()) return ExprError();
18786 E->setSubExpr(SubResult.get());
18787 return E;
18788 }
18789
18790 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
18791
18792 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
18793
18794 ExprResult VisitMemberExpr(MemberExpr *E) {
18795 return resolveDecl(E, E->getMemberDecl());
18796 }
18797
18798 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18799 return resolveDecl(E, E->getDecl());
18800 }
18801 };
18802}
18803
18804/// Rebuilds a call expression which yielded __unknown_anytype.
18805ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
18806 Expr *CalleeExpr = E->getCallee();
18807
18808 enum FnKind {
18809 FK_MemberFunction,
18810 FK_FunctionPointer,
18811 FK_BlockPointer
18812 };
18813
18814 FnKind Kind;
18815 QualType CalleeType = CalleeExpr->getType();
18816 if (CalleeType == S.Context.BoundMemberTy) {
18817 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E))((isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr
>(E)) ? static_cast<void> (0) : __assert_fail ("isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 18817, __PRETTY_FUNCTION__))
;
18818 Kind = FK_MemberFunction;
18819 CalleeType = Expr::findBoundMemberType(CalleeExpr);
18820 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
18821 CalleeType = Ptr->getPointeeType();
18822 Kind = FK_FunctionPointer;
18823 } else {
18824 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
18825 Kind = FK_BlockPointer;
18826 }
18827 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
18828
18829 // Verify that this is a legal result type of a function.
18830 if (DestType->isArrayType() || DestType->isFunctionType()) {
18831 unsigned diagID = diag::err_func_returning_array_function;
18832 if (Kind == FK_BlockPointer)
18833 diagID = diag::err_block_returning_array_function;
18834
18835 S.Diag(E->getExprLoc(), diagID)
18836 << DestType->isFunctionType() << DestType;
18837 return ExprError();
18838 }
18839
18840 // Otherwise, go ahead and set DestType as the call's result.
18841 E->setType(DestType.getNonLValueExprType(S.Context));
18842 E->setValueKind(Expr::getValueKindForType(DestType));
18843 assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void
> (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 18843, __PRETTY_FUNCTION__))
;
18844
18845 // Rebuild the function type, replacing the result type with DestType.
18846 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
18847 if (Proto) {
18848 // __unknown_anytype(...) is a special case used by the debugger when
18849 // it has no idea what a function's signature is.
18850 //
18851 // We want to build this call essentially under the K&R
18852 // unprototyped rules, but making a FunctionNoProtoType in C++
18853 // would foul up all sorts of assumptions. However, we cannot
18854 // simply pass all arguments as variadic arguments, nor can we
18855 // portably just call the function under a non-variadic type; see
18856 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
18857 // However, it turns out that in practice it is generally safe to
18858 // call a function declared as "A foo(B,C,D);" under the prototype
18859 // "A foo(B,C,D,...);". The only known exception is with the
18860 // Windows ABI, where any variadic function is implicitly cdecl
18861 // regardless of its normal CC. Therefore we change the parameter
18862 // types to match the types of the arguments.
18863 //
18864 // This is a hack, but it is far superior to moving the
18865 // corresponding target-specific code from IR-gen to Sema/AST.
18866
18867 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
18868 SmallVector<QualType, 8> ArgTypes;
18869 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
18870 ArgTypes.reserve(E->getNumArgs());
18871 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
18872 Expr *Arg = E->getArg(i);
18873 QualType ArgType = Arg->getType();
18874 if (E->isLValue()) {
18875 ArgType = S.Context.getLValueReferenceType(ArgType);
18876 } else if (E->isXValue()) {
18877 ArgType = S.Context.getRValueReferenceType(ArgType);
18878 }
18879 ArgTypes.push_back(ArgType);
18880 }
18881 ParamTypes = ArgTypes;
18882 }
18883 DestType = S.Context.getFunctionType(DestType, ParamTypes,
18884 Proto->getExtProtoInfo());
18885 } else {
18886 DestType = S.Context.getFunctionNoProtoType(DestType,
18887 FnType->getExtInfo());
18888 }
18889
18890 // Rebuild the appropriate pointer-to-function type.
18891 switch (Kind) {
18892 case FK_MemberFunction:
18893 // Nothing to do.
18894 break;
18895
18896 case FK_FunctionPointer:
18897 DestType = S.Context.getPointerType(DestType);
18898 break;
18899
18900 case FK_BlockPointer:
18901 DestType = S.Context.getBlockPointerType(DestType);
18902 break;
18903 }
18904
18905 // Finally, we can recurse.
18906 ExprResult CalleeResult = Visit(CalleeExpr);
18907 if (!CalleeResult.isUsable()) return ExprError();
18908 E->setCallee(CalleeResult.get());
18909
18910 // Bind a temporary if necessary.
18911 return S.MaybeBindToTemporary(E);
18912}
18913
18914ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
18915 // Verify that this is a legal result type of a call.
18916 if (DestType->isArrayType() || DestType->isFunctionType()) {
18917 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
18918 << DestType->isFunctionType() << DestType;
18919 return ExprError();
18920 }
18921
18922 // Rewrite the method result type if available.
18923 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
18924 assert(Method->getReturnType() == S.Context.UnknownAnyTy)((Method->getReturnType() == S.Context.UnknownAnyTy) ? static_cast
<void> (0) : __assert_fail ("Method->getReturnType() == S.Context.UnknownAnyTy"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 18924, __PRETTY_FUNCTION__))
;
18925 Method->setReturnType(DestType);
18926 }
18927
18928 // Change the type of the message.
18929 E->setType(DestType.getNonReferenceType());
18930 E->setValueKind(Expr::getValueKindForType(DestType));
18931
18932 return S.MaybeBindToTemporary(E);
18933}
18934
18935ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
18936 // The only case we should ever see here is a function-to-pointer decay.
18937 if (E->getCastKind() == CK_FunctionToPointerDecay) {
18938 assert(E->getValueKind() == VK_RValue)((E->getValueKind() == VK_RValue) ? static_cast<void>
(0) : __assert_fail ("E->getValueKind() == VK_RValue", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 18938, __PRETTY_FUNCTION__))
;
18939 assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void
> (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 18939, __PRETTY_FUNCTION__))
;
18940
18941 E->setType(DestType);
18942
18943 // Rebuild the sub-expression as the pointee (function) type.
18944 DestType = DestType->castAs<PointerType>()->getPointeeType();
18945
18946 ExprResult Result = Visit(E->getSubExpr());
18947 if (!Result.isUsable()) return ExprError();
18948
18949 E->setSubExpr(Result.get());
18950 return E;
18951 } else if (E->getCastKind() == CK_LValueToRValue) {
18952 assert(E->getValueKind() == VK_RValue)((E->getValueKind() == VK_RValue) ? static_cast<void>
(0) : __assert_fail ("E->getValueKind() == VK_RValue", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 18952, __PRETTY_FUNCTION__))
;
18953 assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void
> (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 18953, __PRETTY_FUNCTION__))
;
18954
18955 assert(isa<BlockPointerType>(E->getType()))((isa<BlockPointerType>(E->getType())) ? static_cast
<void> (0) : __assert_fail ("isa<BlockPointerType>(E->getType())"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 18955, __PRETTY_FUNCTION__))
;
18956
18957 E->setType(DestType);
18958
18959 // The sub-expression has to be a lvalue reference, so rebuild it as such.
18960 DestType = S.Context.getLValueReferenceType(DestType);
18961
18962 ExprResult Result = Visit(E->getSubExpr());
18963 if (!Result.isUsable()) return ExprError();
18964
18965 E->setSubExpr(Result.get());
18966 return E;
18967 } else {
18968 llvm_unreachable("Unhandled cast type!")::llvm::llvm_unreachable_internal("Unhandled cast type!", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 18968)
;
18969 }
18970}
18971
18972ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
18973 ExprValueKind ValueKind = VK_LValue;
18974 QualType Type = DestType;
18975
18976 // We know how to make this work for certain kinds of decls:
18977
18978 // - functions
18979 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
18980 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
18981 DestType = Ptr->getPointeeType();
18982 ExprResult Result = resolveDecl(E, VD);
18983 if (Result.isInvalid()) return ExprError();
18984 return S.ImpCastExprToType(Result.get(), Type,
18985 CK_FunctionToPointerDecay, VK_RValue);
18986 }
18987
18988 if (!Type->isFunctionType()) {
18989 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
18990 << VD << E->getSourceRange();
18991 return ExprError();
18992 }
18993 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
18994 // We must match the FunctionDecl's type to the hack introduced in
18995 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
18996 // type. See the lengthy commentary in that routine.
18997 QualType FDT = FD->getType();
18998 const FunctionType *FnType = FDT->castAs<FunctionType>();
18999 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
19000 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
19001 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
19002 SourceLocation Loc = FD->getLocation();
19003 FunctionDecl *NewFD = FunctionDecl::Create(
19004 S.Context, FD->getDeclContext(), Loc, Loc,
19005 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
19006 SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
19007 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
19008
19009 if (FD->getQualifier())
19010 NewFD->setQualifierInfo(FD->getQualifierLoc());
19011
19012 SmallVector<ParmVarDecl*, 16> Params;
19013 for (const auto &AI : FT->param_types()) {
19014 ParmVarDecl *Param =
19015 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
19016 Param->setScopeInfo(0, Params.size());
19017 Params.push_back(Param);
19018 }
19019 NewFD->setParams(Params);
19020 DRE->setDecl(NewFD);
19021 VD = DRE->getDecl();
19022 }
19023 }
19024
19025 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
19026 if (MD->isInstance()) {
19027 ValueKind = VK_RValue;
19028 Type = S.Context.BoundMemberTy;
19029 }
19030
19031 // Function references aren't l-values in C.
19032 if (!S.getLangOpts().CPlusPlus)
19033 ValueKind = VK_RValue;
19034
19035 // - variables
19036 } else if (isa<VarDecl>(VD)) {
19037 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
19038 Type = RefTy->getPointeeType();
19039 } else if (Type->isFunctionType()) {
19040 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
19041 << VD << E->getSourceRange();
19042 return ExprError();
19043 }
19044
19045 // - nothing else
19046 } else {
19047 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
19048 << VD << E->getSourceRange();
19049 return ExprError();
19050 }
19051
19052 // Modifying the declaration like this is friendly to IR-gen but
19053 // also really dangerous.
19054 VD->setType(DestType);
19055 E->setType(Type);
19056 E->setValueKind(ValueKind);
19057 return E;
19058}
19059
19060/// Check a cast of an unknown-any type. We intentionally only
19061/// trigger this for C-style casts.
19062ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
19063 Expr *CastExpr, CastKind &CastKind,
19064 ExprValueKind &VK, CXXCastPath &Path) {
19065 // The type we're casting to must be either void or complete.
19066 if (!CastType->isVoidType() &&
19067 RequireCompleteType(TypeRange.getBegin(), CastType,
19068 diag::err_typecheck_cast_to_incomplete))
19069 return ExprError();
19070
19071 // Rewrite the casted expression from scratch.
19072 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
19073 if (!result.isUsable()) return ExprError();
19074
19075 CastExpr = result.get();
19076 VK = CastExpr->getValueKind();
19077 CastKind = CK_NoOp;
19078
19079 return CastExpr;
19080}
19081
19082ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
19083 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
19084}
19085
19086ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
19087 Expr *arg, QualType &paramType) {
19088 // If the syntactic form of the argument is not an explicit cast of
19089 // any sort, just do default argument promotion.
19090 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
19091 if (!castArg) {
19092 ExprResult result = DefaultArgumentPromotion(arg);
19093 if (result.isInvalid()) return ExprError();
19094 paramType = result.get()->getType();
19095 return result;
19096 }
19097
19098 // Otherwise, use the type that was written in the explicit cast.
19099 assert(!arg->hasPlaceholderType())((!arg->hasPlaceholderType()) ? static_cast<void> (0
) : __assert_fail ("!arg->hasPlaceholderType()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 19099, __PRETTY_FUNCTION__))
;
19100 paramType = castArg->getTypeAsWritten();
19101
19102 // Copy-initialize a parameter of that type.
19103 InitializedEntity entity =
19104 InitializedEntity::InitializeParameter(Context, paramType,
19105 /*consumed*/ false);
19106 return PerformCopyInitialization(entity, callLoc, arg);
19107}
19108
19109static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
19110 Expr *orig = E;
19111 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
19112 while (true) {
19113 E = E->IgnoreParenImpCasts();
19114 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
19115 E = call->getCallee();
19116 diagID = diag::err_uncasted_call_of_unknown_any;
19117 } else {
19118 break;
19119 }
19120 }
19121
19122 SourceLocation loc;
19123 NamedDecl *d;
19124 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
19125 loc = ref->getLocation();
19126 d = ref->getDecl();
19127 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
19128 loc = mem->getMemberLoc();
19129 d = mem->getMemberDecl();
19130 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
19131 diagID = diag::err_uncasted_call_of_unknown_any;
19132 loc = msg->getSelectorStartLoc();
19133 d = msg->getMethodDecl();
19134 if (!d) {
19135 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
19136 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
19137 << orig->getSourceRange();
19138 return ExprError();
19139 }
19140 } else {
19141 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
19142 << E->getSourceRange();
19143 return ExprError();
19144 }
19145
19146 S.Diag(loc, diagID) << d << orig->getSourceRange();
19147
19148 // Never recoverable.
19149 return ExprError();
19150}
19151
19152/// Check for operands with placeholder types and complain if found.
19153/// Returns ExprError() if there was an error and no recovery was possible.
19154ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
19155 if (!Context.isDependenceAllowed()) {
19156 // C cannot handle TypoExpr nodes on either side of a binop because it
19157 // doesn't handle dependent types properly, so make sure any TypoExprs have
19158 // been dealt with before checking the operands.
19159 ExprResult Result = CorrectDelayedTyposInExpr(E);
19160 if (!Result.isUsable()) return ExprError();
19161 E = Result.get();
19162 }
19163
19164 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
19165 if (!placeholderType) return E;
19166
19167 switch (placeholderType->getKind()) {
19168
19169 // Overloaded expressions.
19170 case BuiltinType::Overload: {
19171 // Try to resolve a single function template specialization.
19172 // This is obligatory.
19173 ExprResult Result = E;
19174 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
19175 return Result;
19176
19177 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
19178 // leaves Result unchanged on failure.
19179 Result = E;
19180 if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
19181 return Result;
19182
19183 // If that failed, try to recover with a call.
19184 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
19185 /*complain*/ true);
19186 return Result;
19187 }
19188
19189 // Bound member functions.
19190 case BuiltinType::BoundMember: {
19191 ExprResult result = E;
19192 const Expr *BME = E->IgnoreParens();
19193 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
19194 // Try to give a nicer diagnostic if it is a bound member that we recognize.
19195 if (isa<CXXPseudoDestructorExpr>(BME)) {
19196 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
19197 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
19198 if (ME->getMemberNameInfo().getName().getNameKind() ==
19199 DeclarationName::CXXDestructorName)
19200 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
19201 }
19202 tryToRecoverWithCall(result, PD,
19203 /*complain*/ true);
19204 return result;
19205 }
19206
19207 // ARC unbridged casts.
19208 case BuiltinType::ARCUnbridgedCast: {
19209 Expr *realCast = stripARCUnbridgedCast(E);
19210 diagnoseARCUnbridgedCast(realCast);
19211 return realCast;
19212 }
19213
19214 // Expressions of unknown type.
19215 case BuiltinType::UnknownAny:
19216 return diagnoseUnknownAnyExpr(*this, E);
19217
19218 // Pseudo-objects.
19219 case BuiltinType::PseudoObject:
19220 return checkPseudoObjectRValue(E);
19221
19222 case BuiltinType::BuiltinFn: {
19223 // Accept __noop without parens by implicitly converting it to a call expr.
19224 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
19225 if (DRE) {
19226 auto *FD = cast<FunctionDecl>(DRE->getDecl());
19227 if (FD->getBuiltinID() == Builtin::BI__noop) {
19228 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
19229 CK_BuiltinFnToFnPtr)
19230 .get();
19231 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
19232 VK_RValue, SourceLocation(),
19233 FPOptionsOverride());
19234 }
19235 }
19236
19237 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
19238 return ExprError();
19239 }
19240
19241 case BuiltinType::IncompleteMatrixIdx:
19242 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
19243 ->getRowIdx()
19244 ->getBeginLoc(),
19245 diag::err_matrix_incomplete_index);
19246 return ExprError();
19247
19248 // Expressions of unknown type.
19249 case BuiltinType::OMPArraySection:
19250 Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
19251 return ExprError();
19252
19253 // Expressions of unknown type.
19254 case BuiltinType::OMPArrayShaping:
19255 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
19256
19257 case BuiltinType::OMPIterator:
19258 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
19259
19260 // Everything else should be impossible.
19261#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
19262 case BuiltinType::Id:
19263#include "clang/Basic/OpenCLImageTypes.def"
19264#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
19265 case BuiltinType::Id:
19266#include "clang/Basic/OpenCLExtensionTypes.def"
19267#define SVE_TYPE(Name, Id, SingletonId) \
19268 case BuiltinType::Id:
19269#include "clang/Basic/AArch64SVEACLETypes.def"
19270#define PPC_MMA_VECTOR_TYPE(Name, Id, Size) \
19271 case BuiltinType::Id:
19272#include "clang/Basic/PPCTypes.def"
19273#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
19274#define PLACEHOLDER_TYPE(Id, SingletonId)
19275#include "clang/AST/BuiltinTypes.def"
19276 break;
19277 }
19278
19279 llvm_unreachable("invalid placeholder type!")::llvm::llvm_unreachable_internal("invalid placeholder type!"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 19279)
;
19280}
19281
19282bool Sema::CheckCaseExpression(Expr *E) {
19283 if (E->isTypeDependent())
19284 return true;
19285 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
19286 return E->getType()->isIntegralOrEnumerationType();
19287 return false;
19288}
19289
19290/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
19291ExprResult
19292Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
19293 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&(((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
"Unknown Objective-C Boolean value!") ? static_cast<void>
(0) : __assert_fail ("(Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && \"Unknown Objective-C Boolean value!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 19294, __PRETTY_FUNCTION__))
19294 "Unknown Objective-C Boolean value!")(((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
"Unknown Objective-C Boolean value!") ? static_cast<void>
(0) : __assert_fail ("(Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && \"Unknown Objective-C Boolean value!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp"
, 19294, __PRETTY_FUNCTION__))
;
19295 QualType BoolT = Context.ObjCBuiltinBoolTy;
19296 if (!Context.getBOOLDecl()) {
19297 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
19298 Sema::LookupOrdinaryName);
19299 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
19300 NamedDecl *ND = Result.getFoundDecl();
19301 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
19302 Context.setBOOLDecl(TD);
19303 }
19304 }
19305 if (Context.getBOOLDecl())
19306 BoolT = Context.getBOOLType();
19307 return new (Context)
19308 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
19309}
19310
19311ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
19312 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
19313 SourceLocation RParen) {
19314
19315 StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
19316
19317 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
19318 return Spec.getPlatform() == Platform;
19319 });
19320
19321 VersionTuple Version;
19322 if (Spec != AvailSpecs.end())
19323 Version = Spec->getVersion();
19324
19325 // The use of `@available` in the enclosing function should be analyzed to
19326 // warn when it's used inappropriately (i.e. not if(@available)).
19327 if (getCurFunctionOrMethodDecl())
19328 getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
19329 else if (getCurBlock() || getCurLambda())
19330 getCurFunction()->HasPotentialAvailabilityViolations = true;
19331
19332 return new (Context)
19333 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
19334}
19335
19336ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
19337 ArrayRef<Expr *> SubExprs, QualType T) {
19338 if (!Context.getLangOpts().RecoveryAST)
19339 return ExprError();
19340
19341 if (isSFINAEContext())
19342 return ExprError();
19343
19344 if (T.isNull() || !Context.getLangOpts().RecoveryASTType)
19345 // We don't know the concrete type, fallback to dependent type.
19346 T = Context.DependentTy;
19347 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
19348}

/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/Lex/LiteralSupport.h

1//===--- LiteralSupport.h ---------------------------------------*- 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 NumericLiteralParser, CharLiteralParser, and
10// StringLiteralParser interfaces.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_LEX_LITERALSUPPORT_H
15#define LLVM_CLANG_LEX_LITERALSUPPORT_H
16
17#include "clang/Basic/CharInfo.h"
18#include "clang/Basic/LLVM.h"
19#include "clang/Basic/TokenKinds.h"
20#include "llvm/ADT/APFloat.h"
21#include "llvm/ADT/ArrayRef.h"
22#include "llvm/ADT/SmallString.h"
23#include "llvm/ADT/StringRef.h"
24#include "llvm/Support/DataTypes.h"
25
26namespace clang {
27
28class DiagnosticsEngine;
29class Preprocessor;
30class Token;
31class SourceLocation;
32class TargetInfo;
33class SourceManager;
34class LangOptions;
35
36/// Copy characters from Input to Buf, expanding any UCNs.
37void expandUCNs(SmallVectorImpl<char> &Buf, StringRef Input);
38
39/// NumericLiteralParser - This performs strict semantic analysis of the content
40/// of a ppnumber, classifying it as either integer, floating, or erroneous,
41/// determines the radix of the value and can convert it to a useful value.
42class NumericLiteralParser {
43 const SourceManager &SM;
44 const LangOptions &LangOpts;
45 DiagnosticsEngine &Diags;
46
47 const char *const ThisTokBegin;
48 const char *const ThisTokEnd;
49 const char *DigitsBegin, *SuffixBegin; // markers
50 const char *s; // cursor
51
52 unsigned radix;
53
54 bool saw_exponent, saw_period, saw_ud_suffix, saw_fixed_point_suffix;
55
56 SmallString<32> UDSuffixBuf;
57
58public:
59 NumericLiteralParser(StringRef TokSpelling, SourceLocation TokLoc,
60 const SourceManager &SM, const LangOptions &LangOpts,
61 const TargetInfo &Target, DiagnosticsEngine &Diags);
62 bool hadError : 1;
63 bool isUnsigned : 1;
64 bool isLong : 1; // This is *not* set for long long.
65 bool isLongLong : 1;
66 bool isHalf : 1; // 1.0h
67 bool isFloat : 1; // 1.0f
68 bool isImaginary : 1; // 1.0i
69 bool isFloat16 : 1; // 1.0f16
70 bool isFloat128 : 1; // 1.0q
71 uint8_t MicrosoftInteger; // Microsoft suffix extension i8, i16, i32, or i64.
72
73 bool isFract : 1; // 1.0hr/r/lr/uhr/ur/ulr
74 bool isAccum : 1; // 1.0hk/k/lk/uhk/uk/ulk
75
76 bool isFixedPointLiteral() const {
77 return (saw_period || saw_exponent) && saw_fixed_point_suffix;
10
Assuming field 'saw_period' is true
11
Returning value, which participates in a condition later
78 }
79
80 bool isIntegerLiteral() const {
81 return !saw_period && !saw_exponent && !isFixedPointLiteral();
82 }
83 bool isFloatingLiteral() const {
84 return (saw_period
15.1
Field 'saw_period' is true
15.1
Field 'saw_period' is true
15.1
Field 'saw_period' is true
15.1
Field 'saw_period' is true
|| saw_exponent) && !isFixedPointLiteral()
;
16
Returning the value 1, which participates in a condition later
85 }
86
87 bool hasUDSuffix() const {
88 return saw_ud_suffix;
89 }
90 StringRef getUDSuffix() const {
91 assert(saw_ud_suffix)((saw_ud_suffix) ? static_cast<void> (0) : __assert_fail
("saw_ud_suffix", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/Lex/LiteralSupport.h"
, 91, __PRETTY_FUNCTION__))
;
92 return UDSuffixBuf;
93 }
94 unsigned getUDSuffixOffset() const {
95 assert(saw_ud_suffix)((saw_ud_suffix) ? static_cast<void> (0) : __assert_fail
("saw_ud_suffix", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/Lex/LiteralSupport.h"
, 95, __PRETTY_FUNCTION__))
;
96 return SuffixBegin - ThisTokBegin;
97 }
98
99 static bool isValidUDSuffix(const LangOptions &LangOpts, StringRef Suffix);
100
101 unsigned getRadix() const { return radix; }
102
103 /// GetIntegerValue - Convert this numeric literal value to an APInt that
104 /// matches Val's input width. If there is an overflow (i.e., if the unsigned
105 /// value read is larger than the APInt's bits will hold), set Val to the low
106 /// bits of the result and return true. Otherwise, return false.
107 bool GetIntegerValue(llvm::APInt &Val);
108
109 /// GetFloatValue - Convert this numeric literal to a floating value, using
110 /// the specified APFloat fltSemantics (specifying float, double, etc).
111 /// The optional bool isExact (passed-by-reference) has its value
112 /// set to true if the returned APFloat can represent the number in the
113 /// literal exactly, and false otherwise.
114 llvm::APFloat::opStatus GetFloatValue(llvm::APFloat &Result);
115
116 /// GetFixedPointValue - Convert this numeric literal value into a
117 /// scaled integer that represents this value. Returns true if an overflow
118 /// occurred when calculating the integral part of the scaled integer or
119 /// calculating the digit sequence of the exponent.
120 bool GetFixedPointValue(llvm::APInt &StoreVal, unsigned Scale);
121
122private:
123
124 void ParseNumberStartingWithZero(SourceLocation TokLoc);
125 void ParseDecimalOrOctalCommon(SourceLocation TokLoc);
126
127 static bool isDigitSeparator(char C) { return C == '\''; }
128
129 /// Determine whether the sequence of characters [Start, End) contains
130 /// any real digits (not digit separators).
131 bool containsDigits(const char *Start, const char *End) {
132 return Start != End && (Start + 1 != End || !isDigitSeparator(Start[0]));
133 }
134
135 enum CheckSeparatorKind { CSK_BeforeDigits, CSK_AfterDigits };
136
137 /// Ensure that we don't have a digit separator here.
138 void checkSeparator(SourceLocation TokLoc, const char *Pos,
139 CheckSeparatorKind IsAfterDigits);
140
141 /// SkipHexDigits - Read and skip over any hex digits, up to End.
142 /// Return a pointer to the first non-hex digit or End.
143 const char *SkipHexDigits(const char *ptr) {
144 while (ptr != ThisTokEnd && (isHexDigit(*ptr) || isDigitSeparator(*ptr)))
145 ptr++;
146 return ptr;
147 }
148
149 /// SkipOctalDigits - Read and skip over any octal digits, up to End.
150 /// Return a pointer to the first non-hex digit or End.
151 const char *SkipOctalDigits(const char *ptr) {
152 while (ptr != ThisTokEnd &&
153 ((*ptr >= '0' && *ptr <= '7') || isDigitSeparator(*ptr)))
154 ptr++;
155 return ptr;
156 }
157
158 /// SkipDigits - Read and skip over any digits, up to End.
159 /// Return a pointer to the first non-hex digit or End.
160 const char *SkipDigits(const char *ptr) {
161 while (ptr != ThisTokEnd && (isDigit(*ptr) || isDigitSeparator(*ptr)))
162 ptr++;
163 return ptr;
164 }
165
166 /// SkipBinaryDigits - Read and skip over any binary digits, up to End.
167 /// Return a pointer to the first non-binary digit or End.
168 const char *SkipBinaryDigits(const char *ptr) {
169 while (ptr != ThisTokEnd &&
170 (*ptr == '0' || *ptr == '1' || isDigitSeparator(*ptr)))
171 ptr++;
172 return ptr;
173 }
174
175};
176
177/// CharLiteralParser - Perform interpretation and semantic analysis of a
178/// character literal.
179class CharLiteralParser {
180 uint64_t Value;
181 tok::TokenKind Kind;
182 bool IsMultiChar;
183 bool HadError;
184 SmallString<32> UDSuffixBuf;
185 unsigned UDSuffixOffset;
186public:
187 CharLiteralParser(const char *begin, const char *end,
188 SourceLocation Loc, Preprocessor &PP,
189 tok::TokenKind kind);
190
191 bool hadError() const { return HadError; }
192 bool isAscii() const { return Kind == tok::char_constant; }
193 bool isWide() const { return Kind == tok::wide_char_constant; }
194 bool isUTF8() const { return Kind == tok::utf8_char_constant; }
195 bool isUTF16() const { return Kind == tok::utf16_char_constant; }
196 bool isUTF32() const { return Kind == tok::utf32_char_constant; }
197 bool isMultiChar() const { return IsMultiChar; }
198 uint64_t getValue() const { return Value; }
199 StringRef getUDSuffix() const { return UDSuffixBuf; }
200 unsigned getUDSuffixOffset() const {
201 assert(!UDSuffixBuf.empty() && "no ud-suffix")((!UDSuffixBuf.empty() && "no ud-suffix") ? static_cast
<void> (0) : __assert_fail ("!UDSuffixBuf.empty() && \"no ud-suffix\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/Lex/LiteralSupport.h"
, 201, __PRETTY_FUNCTION__))
;
202 return UDSuffixOffset;
203 }
204};
205
206/// StringLiteralParser - This decodes string escape characters and performs
207/// wide string analysis and Translation Phase #6 (concatenation of string
208/// literals) (C99 5.1.1.2p1).
209class StringLiteralParser {
210 const SourceManager &SM;
211 const LangOptions &Features;
212 const TargetInfo &Target;
213 DiagnosticsEngine *Diags;
214
215 unsigned MaxTokenLength;
216 unsigned SizeBound;
217 unsigned CharByteWidth;
218 tok::TokenKind Kind;
219 SmallString<512> ResultBuf;
220 char *ResultPtr; // cursor
221 SmallString<32> UDSuffixBuf;
222 unsigned UDSuffixToken;
223 unsigned UDSuffixOffset;
224public:
225 StringLiteralParser(ArrayRef<Token> StringToks,
226 Preprocessor &PP, bool Complain = true);
227 StringLiteralParser(ArrayRef<Token> StringToks,
228 const SourceManager &sm, const LangOptions &features,
229 const TargetInfo &target,
230 DiagnosticsEngine *diags = nullptr)
231 : SM(sm), Features(features), Target(target), Diags(diags),
232 MaxTokenLength(0), SizeBound(0), CharByteWidth(0), Kind(tok::unknown),
233 ResultPtr(ResultBuf.data()), hadError(false), Pascal(false) {
234 init(StringToks);
235 }
236
237
238 bool hadError;
239 bool Pascal;
240
241 StringRef GetString() const {
242 return StringRef(ResultBuf.data(), GetStringLength());
243 }
244 unsigned GetStringLength() const { return ResultPtr-ResultBuf.data(); }
245
246 unsigned GetNumStringChars() const {
247 return GetStringLength() / CharByteWidth;
248 }
249 /// getOffsetOfStringByte - This function returns the offset of the
250 /// specified byte of the string data represented by Token. This handles
251 /// advancing over escape sequences in the string.
252 ///
253 /// If the Diagnostics pointer is non-null, then this will do semantic
254 /// checking of the string literal and emit errors and warnings.
255 unsigned getOffsetOfStringByte(const Token &TheTok, unsigned ByteNo) const;
256
257 bool isAscii() const { return Kind == tok::string_literal; }
258 bool isWide() const { return Kind == tok::wide_string_literal; }
259 bool isUTF8() const { return Kind == tok::utf8_string_literal; }
260 bool isUTF16() const { return Kind == tok::utf16_string_literal; }
261 bool isUTF32() const { return Kind == tok::utf32_string_literal; }
262 bool isPascal() const { return Pascal; }
263
264 StringRef getUDSuffix() const { return UDSuffixBuf; }
265
266 /// Get the index of a token containing a ud-suffix.
267 unsigned getUDSuffixToken() const {
268 assert(!UDSuffixBuf.empty() && "no ud-suffix")((!UDSuffixBuf.empty() && "no ud-suffix") ? static_cast
<void> (0) : __assert_fail ("!UDSuffixBuf.empty() && \"no ud-suffix\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/Lex/LiteralSupport.h"
, 268, __PRETTY_FUNCTION__))
;
269 return UDSuffixToken;
270 }
271 /// Get the spelling offset of the first byte of the ud-suffix.
272 unsigned getUDSuffixOffset() const {
273 assert(!UDSuffixBuf.empty() && "no ud-suffix")((!UDSuffixBuf.empty() && "no ud-suffix") ? static_cast
<void> (0) : __assert_fail ("!UDSuffixBuf.empty() && \"no ud-suffix\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/Lex/LiteralSupport.h"
, 273, __PRETTY_FUNCTION__))
;
274 return UDSuffixOffset;
275 }
276
277 static bool isValidUDSuffix(const LangOptions &LangOpts, StringRef Suffix);
278
279private:
280 void init(ArrayRef<Token> StringToks);
281 bool CopyStringFragment(const Token &Tok, const char *TokBegin,
282 StringRef Fragment);
283 void DiagnoseLexingError(SourceLocation Loc);
284};
285
286} // end namespace clang
287
288#endif

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

/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/include/llvm/ADT/PointerIntPair.h

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